--- /dev/null
+Headway Base Installation
+http://headwaythemes.com/
+
+INSTALL:
+1. Upload Headway Base via FTP to your wp-content/themes/ directory.
+2. Go to your WordPress dashboard and select Appearance.
+3. Select Headway Base and click activate.
+
+SUPPORT & DOCUMENTATION:
+If you are looking for detailed documentation or theme support, please visit http://support.headwaythemes.com/
\ No newline at end of file
--- /dev/null
+ GNU GENERAL PUBLIC LICENSE
+ Version 2, June 1991
+
+ Copyright (C) 1989, 1991 Free Software Foundation, Inc.
+ 51 Franklin St, Fifth Floor, Boston, MA 02110, USA
+
+ Everyone is permitted to copy and distribute verbatim copies
+ of this license document, but changing it is not allowed.
+
+ Preamble
+
+ The licenses for most software are designed to take away your
+freedom to share and change it. By contrast, the GNU General Public
+License is intended to guarantee your freedom to share and change free
+software--to make sure the software is free for all its users. This
+General Public License applies to most of the Free Software
+Foundation's software and to any other program whose authors commit to
+using it. (Some other Free Software Foundation software is covered by
+the GNU Library General Public License instead.) You can apply it to
+your programs, too.
+
+ When we speak of free software, we are referring to freedom, not
+price. Our General Public Licenses are designed to make sure that you
+have the freedom to distribute copies of free software (and charge for
+this service if you wish), that you receive source code or can get it
+if you want it, that you can change the software or use pieces of it
+in new free programs; and that you know you can do these things.
+
+ To protect your rights, we need to make restrictions that forbid
+anyone to deny you these rights or to ask you to surrender the rights.
+These restrictions translate to certain responsibilities for you if you
+distribute copies of the software, or if you modify it.
+
+ For example, if you distribute copies of such a program, whether
+gratis or for a fee, you must give the recipients all the rights that
+you have. You must make sure that they, too, receive or can get the
+source code. And you must show them these terms so they know their
+rights.
+
+ We protect your rights with two steps: (1) copyright the software, and
+(2) offer you this license which gives you legal permission to copy,
+distribute and/or modify the software.
+
+ Also, for each author's protection and ours, we want to make certain
+that everyone understands that there is no warranty for this free
+software. If the software is modified by someone else and passed on, we
+want its recipients to know that what they have is not the original, so
+that any problems introduced by others will not reflect on the original
+authors' reputations.
+
+ Finally, any free program is threatened constantly by software
+patents. We wish to avoid the danger that redistributors of a free
+program will individually obtain patent licenses, in effect making the
+program proprietary. To prevent this, we have made it clear that any
+patent must be licensed for everyone's free use or not licensed at all.
+
+ The precise terms and conditions for copying, distribution and
+modification follow.
+
+ GNU GENERAL PUBLIC LICENSE
+ TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION
+
+ 0. This License applies to any program or other work which contains
+a notice placed by the copyright holder saying it may be distributed
+under the terms of this General Public License. The "Program", below,
+refers to any such program or work, and a "work based on the Program"
+means either the Program or any derivative work under copyright law:
+that is to say, a work containing the Program or a portion of it,
+either verbatim or with modifications and/or translated into another
+language. (Hereinafter, translation is included without limitation in
+the term "modification".) Each licensee is addressed as "you".
+
+Activities other than copying, distribution and modification are not
+covered by this License; they are outside its scope. The act of
+running the Program is not restricted, and the output from the Program
+is covered only if its contents constitute a work based on the
+Program (independent of having been made by running the Program).
+Whether that is true depends on what the Program does.
+
+ 1. You may copy and distribute verbatim copies of the Program's
+source code as you receive it, in any medium, provided that you
+conspicuously and appropriately publish on each copy an appropriate
+copyright notice and disclaimer of warranty; keep intact all the
+notices that refer to this License and to the absence of any warranty;
+and give any other recipients of the Program a copy of this License
+along with the Program.
+
+You may charge a fee for the physical act of transferring a copy, and
+you may at your option offer warranty protection in exchange for a fee.
+
+ 2. You may modify your copy or copies of the Program or any portion
+of it, thus forming a work based on the Program, and copy and
+distribute such modifications or work under the terms of Section 1
+above, provided that you also meet all of these conditions:
+
+ a) You must cause the modified files to carry prominent notices
+ stating that you changed the files and the date of any change.
+
+ b) You must cause any work that you distribute or publish, that in
+ whole or in part contains or is derived from the Program or any
+ part thereof, to be licensed as a whole at no charge to all third
+ parties under the terms of this License.
+
+ c) If the modified program normally reads commands interactively
+ when run, you must cause it, when started running for such
+ interactive use in the most ordinary way, to print or display an
+ announcement including an appropriate copyright notice and a
+ notice that there is no warranty (or else, saying that you provide
+ a warranty) and that users may redistribute the program under
+ these conditions, and telling the user how to view a copy of this
+ License. (Exception: if the Program itself is interactive but
+ does not normally print such an announcement, your work based on
+ the Program is not required to print an announcement.)
+
+These requirements apply to the modified work as a whole. If
+identifiable sections of that work are not derived from the Program,
+and can be reasonably considered independent and separate works in
+themselves, then this License, and its terms, do not apply to those
+sections when you distribute them as separate works. But when you
+distribute the same sections as part of a whole which is a work based
+on the Program, the distribution of the whole must be on the terms of
+this License, whose permissions for other licensees extend to the
+entire whole, and thus to each and every part regardless of who wrote it.
+Thus, it is not the intent of this section to claim rights or contest
+your rights to work written entirely by you; rather, the intent is to
+exercise the right to control the distribution of derivative or
+collective works based on the Program.
+
+In addition, mere aggregation of another work not based on the Program
+with the Program (or with a work based on the Program) on a volume of
+a storage or distribution medium does not bring the other work under
+the scope of this License.
+
+ 3. You may copy and distribute the Program (or a work based on it,
+under Section 2) in object code or executable form under the terms of
+Sections 1 and 2 above provided that you also do one of the following:
+
+ a) Accompany it with the complete corresponding machine-readable
+ source code, which must be distributed under the terms of Sections
+ 1 and 2 above on a medium customarily used for software interchange; or,
+
+ b) Accompany it with a written offer, valid for at least three
+ years, to give any third party, for a charge no more than your
+ cost of physically performing source distribution, a complete
+ machine-readable copy of the corresponding source code, to be
+ distributed under the terms of Sections 1 and 2 above on a medium
+ customarily used for software interchange; or,
+
+ c) Accompany it with the information you received as to the offer
+ to distribute corresponding source code. (This alternative is
+ allowed only for noncommercial distribution and only if you
+ received the program in object code or executable form with such
+ an offer, in accord with Subsection b above.)
+
+The source code for a work means the preferred form of the work for
+making modifications to it. For an executable work, complete source
+code means all the source code for all modules it contains, plus any
+associated interface definition files, plus the scripts used to
+control compilation and installation of the executable. However, as a
+special exception, the source code distributed need not include
+anything that is normally distributed (in either source or binary
+form) with the major components (compiler, kernel, and so on) of the
+operating system on which the executable runs, unless that component
+itself accompanies the executable.
+
+If distribution of executable or object code is made by offering
+access to copy from a designated place, then offering equivalent
+access to copy the source code from the same place counts as
+distribution of the source code, even though third parties are not
+compelled to copy the source along with the object code.
+
+ 4. You may not copy, modify, sublicense, or distribute the Program
+except as expressly provided under this License. Any attempt
+otherwise to copy, modify, sublicense or distribute the Program is
+void, and will automatically terminate your rights under this License.
+However, parties who have received copies, or rights, from you under
+this License will not have their licenses terminated so long as such
+parties remain in full compliance.
+
+ 5. You are not required to accept this License, since you have not
+signed it. However, nothing else grants you permission to modify or
+distribute the Program or its derivative works. These actions are
+prohibited by law if you do not accept this License. Therefore, by
+modifying or distributing the Program (or any work based on the
+Program), you indicate your acceptance of this License to do so, and
+all its terms and conditions for copying, distributing or modifying
+the Program or works based on it.
+
+ 6. Each time you redistribute the Program (or any work based on the
+Program), the recipient automatically receives a license from the
+original licensor to copy, distribute or modify the Program subject to
+these terms and conditions. You may not impose any further
+restrictions on the recipients' exercise of the rights granted herein.
+You are not responsible for enforcing compliance by third parties to
+this License.
+
+ 7. If, as a consequence of a court judgment or allegation of patent
+infringement or for any other reason (not limited to patent issues),
+conditions are imposed on you (whether by court order, agreement or
+otherwise) that contradict the conditions of this License, they do not
+excuse you from the conditions of this License. If you cannot
+distribute so as to satisfy simultaneously your obligations under this
+License and any other pertinent obligations, then as a consequence you
+may not distribute the Program at all. For example, if a patent
+license would not permit royalty-free redistribution of the Program by
+all those who receive copies directly or indirectly through you, then
+the only way you could satisfy both it and this License would be to
+refrain entirely from distribution of the Program.
+
+If any portion of this section is held invalid or unenforceable under
+any particular circumstance, the balance of the section is intended to
+apply and the section as a whole is intended to apply in other
+circumstances.
+
+It is not the purpose of this section to induce you to infringe any
+patents or other property right claims or to contest validity of any
+such claims; this section has the sole purpose of protecting the
+integrity of the free software distribution system, which is
+implemented by public license practices. Many people have made
+generous contributions to the wide range of software distributed
+through that system in reliance on consistent application of that
+system; it is up to the author/donor to decide if he or she is willing
+to distribute software through any other system and a licensee cannot
+impose that choice.
+
+This section is intended to make thoroughly clear what is believed to
+be a consequence of the rest of this License.
+
+ 8. If the distribution and/or use of the Program is restricted in
+certain countries either by patents or by copyrighted interfaces, the
+original copyright holder who places the Program under this License
+may add an explicit geographical distribution limitation excluding
+those countries, so that distribution is permitted only in or among
+countries not thus excluded. In such case, this License incorporates
+the limitation as if written in the body of this License.
+
+ 9. The Free Software Foundation may publish revised and/or new versions
+of the General Public License from time to time. Such new versions will
+be similar in spirit to the present version, but may differ in detail to
+address new problems or concerns.
+
+Each version is given a distinguishing version number. If the Program
+specifies a version number of this License which applies to it and "any
+later version", you have the option of following the terms and conditions
+either of that version or of any later version published by the Free
+Software Foundation. If the Program does not specify a version number of
+this License, you may choose any version ever published by the Free Software
+Foundation.
+
+ 10. If you wish to incorporate parts of the Program into other free
+programs whose distribution conditions are different, write to the author
+to ask for permission. For software which is copyrighted by the Free
+Software Foundation, write to the Free Software Foundation; we sometimes
+make exceptions for this. Our decision will be guided by the two goals
+of preserving the free status of all derivatives of our free software and
+of promoting the sharing and reuse of software generally.
+
+ NO WARRANTY
+
+ 11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY
+FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN
+OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES
+PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED
+OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
+MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS
+TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE
+PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING,
+REPAIR OR CORRECTION.
+
+ 12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
+WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR
+REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES,
+INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING
+OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED
+TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY
+YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER
+PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE
+POSSIBILITY OF SUCH DAMAGES.
+
+ END OF TERMS AND CONDITIONS
+
--- /dev/null
+TERMS & CONDITIONS
+
+This End User License Agreement is a binding legal agreement between you and Vesped, Inc, d/b/a Headway Themes, LLC (Company). Purchase, installation or use of Headway Themes (Service) provided on HeadwayThemes.com signifies that you have read, understood, and agreed to be bound by the terms outlined below.
+
+1. HEADWAY THEMES LICENSING
+
+HEADWAY THEMES GPL LICENSING
+
+All WordPress themes produced by Headway Themes, LLC (Company) are released under the GPL version 2.0 license (http://www.gnu.org/licenses/gpl-2.0.html GNU/GPLv2).
+
+THEME DELIVERY
+
+After your payment has been successfully received, you will receive download links and support forum registration information to the email address you provided during purchase. If you do not receive an email after this time period, contact at support@headwaythemes.com
+
+
+2. TERMS OF SERVICE FOR MEMBERSHIP
+
+A. SIMPLE VERSION
+
+As a paid customer of the Service, you are a member of the HeadwayThemes.com website community. This allows you to get upgraded versions of Headway Themes, support in the forums, quick access to new products, and other benefits of membership, all subject to the terms and conditions contained in this document.
+
+HEADWAY BASE:
+
+The Headway Base Plan entitles you access to Headway Members only support and product updates for a period of one (1) year. You may use Headway Base on an unlimited number of domains. You may remove the footer attribution linking to headwaythemes.com if you want.
+
+HEADWAY STANDARD:
+
+The Headway Standard Plan entitles you access to Headway Members only support and product updates for a period of one (1) year. You may use Headway Standard on an unlimited number of domains. You may remove the footer attribution linking to headwaythemes.com if you want. You also get access to 3 Headway Child Themes during your year of membership.
+
+HEADWAY ALL-ACCESS:
+
+The Headway All-Access Plan entitles you access to Headway Members only support and product updates for a period of one (1) year. You may use Headway All-Access on an unlimited number of domains. You may remove the footer attribution linking to headwaythemes.com if you want. You also get access to all Headway Child Themes during your year of membership. With the All-Access plan you also have access to early beta releases and exclusive developer webinars.
+
+* For the above plans, you get access to updates and support for a period of one (1) year. At that time you will be required to renew your membership to receive product updates and support for another year.
+
+HEADWAY LIFETIME PASS:
+
+The Headway Lifetime Pass Plan entitles you access to Headway Members only support and product updates for life. You may use Headway Lifetime Pass Plan on an unlimited number of domains. You may remove the footer attribution linking to headwaythemes.com if you want. You also get access to all Headway Child Themes released. With the All-Access plan you also have access to early beta releases and exclusive developer webinars.
+
+* Access to product updates and support is for lifetime.
+
+Use or distribution of Headway Themes in violation of the terms and conditions of membership contained in this document will result in termination of your membership, without refund. Also, please be civil and considerate when making use of the support forums, as bad behavior is also grounds for termination of your membership.
+
+B. LEGAL STUFF
+
+Use and enjoyment of services ("Service") from Headway Themes, LLC ("Headway Themes, LLC"), owned and operated by Vesped, Inc, d/b/a Headway Themes, LLC, is provided to you ("you" or "Member") under the Headway Themes Membership Terms and Conditions of Service ("Terms and Conditions of Service" or "Agreement").
+
+Headway Themes, LLC reserves the right to update and change the Terms and Conditions of Service from time to time without notice. Any new features that augment or enhance the current Service, including the release of new features and resources, shall be subject to the Terms and Conditions of Service. Continued use of the Service after any such changes shall constitute your consent to such changes. Members can review the most current version of the Terms and Conditions of Service at any time at this URL: http://headwaythemes.com/terms_of_service.txt
+
+Violation of any of the terms below will result in the termination of your Membership. You agree to use the Service at your own risk.
+
+MEMBERSHIP AND ACCOUNT TERMS
+
+HeadwayThemes.com is a membership website. Use of enjoyment of Membership benefits, such as product access, updates, support, training and other benefits of Membership are provided to paid Members in good standing only. You are responsible for updating your information, including contact names, addresses, telephone numbers and credit card information (as applicable) in a timely manner.
+
+* Members must be 18 years or older to use this Service.
+
+* Members are responsible for maintaining the security of accounts and passwords. Headway Themes, LLC cannot and will not be liable for any loss or damage from your failure to comply with this security obligation.
+
+* Members are responsible for all Content posted and activity that occurs under your account.
+
+* Members may not use the Service for any illegal or unauthorized purpose. You must not, in the use of the Service, violate any laws in your jurisdiction (including but not limited to copyright and trademark laws).
+
+LICENSE, ACKNOWLEDGMENTS AND WARRANTIES
+
+Headway Themes (Service) Members submitting content in forums grant Headway Themes, LLC the rights to distribute, display, reproduce, reformat, translate, archive, license, edit, modify and create derivative works and/or excerpts of any such material for purposes of distributing the material as part of Company's products and services (and the promotion of same).
+
+No Member Content submitted by Member shall contain any content that is obscene, libelous, slanderous or otherwise defamatory, false or misleading or which violates any copyright, right of privacy or publicity or other right of any person, and the Member Content will not contain any viruses, scripts, macros, or programs or links to macros, scripts, programs, or any code that alters, destroys or inhibits the operation of, or infiltrates, computer systems or data run through such computer systems. Member shall indemnify and hold harmless Headway Themes, LLC, its affiliates and agents, and those licensed or otherwise authorized by Headway Themes, LLC to process, transmit or distribute Member Content from and against any and all claims, losses, damages, liabilities, costs and expenses (including reasonable attorney's fees) arising out of or relating to any breach by Member of the foregoing representations and warranties or otherwise arising out of or relating to the contents or nature of the Member Content.
+
+MODIFICATION TO THE SERVICE AND PRICES
+
+Headway Themes, LLC reserves the right at any time and from time to time to modify or discontinue, temporarily or permanently, the Service (or any part thereof) with or without notice.
+
+Prices of all Services, including but not limited to upgrade packages and membership fees, are subject to change at anytime.
+
+Headway Themes, LLC shall not be liable to you or to any third party for any modification, price change, suspension or discontinuance of the Service.
+
+PAYMENTS AND REFUNDS
+
+Payment - A valid credit card or PayPal account is required for purchasing upgrades or additional products or services.
+
+Refunds - Headway Themes, LLC does not offer refunds.
+
+TERM
+
+Term of membership, with the exception of the Headway Lifetime Pass, is for a period of one year from date of purchase as long as Member continues to use Headway Themes, LLC services, or until such time as either party notifies the other to terminate with or without cause. These Terms and Conditions, including any revisions, remain in effect for the duration of membership.
+
+Term of membership for Headway Lifetime Pass is perpetual from date of purchase as long as Member continues to use Headway Themes, LLC services, or until such time as either party notifies the other to terminate with or without cause. These Terms and Conditions, including any revisions, remain in effect for the duration of membership.
+
+ACCESS
+
+During the Term, you are authorized to access the Service solely to manage your Headway Themes member account(s) or as otherwise authorized by Headway Themes, LLC in writing. You agree that you will not use the Service or any content therein or data obtained there from for any other purpose and that you will not disseminate any of this information. Your right to access your account with the Service (including, without limitation, any login or other access information) is personal to you, non-transferable and non-assignable, and is subject to any limits established by Headway Themes, LLC. You agree that you will not use any automated means, including, without limitation, agents, robots, scripts, or spiders, to access or manage your account with the Service or to monitor or copy the Service websites or the content contained therein except those automated means expressly made available by Headway Themes, LLC, if any, or authorized in advance and in writing by Headway Themes, LLC (for example, Headway Themes-approved third party tools and services). Without limitation to the foregoing, you further agree that you will not take any action that imposes an unreasonable or disproportionately large load on the Service as determined by Headway Themes, LLC.
+
+INDEMNITY AND LIMITATION OF LIABILITY
+
+Member will indemnify and hold harmless Headway Themes, LLC and its, affiliate and subsidiary companies, officers, directors, employees, licensees, successors and assigns, including those licensed or authorized by Headway Themes, LLC to transmit and distribute materials, from any and all liabilities, damages, judgments, claims, costs, losses, and expenses (including reasonable legal fees and costs) arising out of or related to any and all claims alleging conduct that would amount to a breach of any of Company's representations and warranties in the Membership Agreement, including these Terms and Conditions.
+
+HEADWAY THEMES, LLC SHALL NOT BE LIABLE TO MEMBER FOR ANY INDIRECT, INCIDENTAL, CONSEQUENTIAL, SPECIAL OR EXEMPLARY DAMAGES (EVEN IF HEADWAY THEMES, LLC HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES), ARISING FROM OR RELATED IN ANY WAY TO ANY PROVISION OF THIS AGREEMENT (INCLUDING SUCH DAMAGES INCURRED BY THIRD PARTIES), INCLUDING BUT NOT LIMITED TO LOSS OF REVENUE OR ANTICIPATED PROFITS OR LOST BUSINESS. IN NO EVENT SHALL HEADWAY THEMES BE LIABLE TO MEMBER FOR AN AMOUNT GREATER THAN THE PAYMENTS MADE BY MEMBER TO HEADWAY THEMES, LLC FOR PRODUCTS AND SERVICES PROVIDED PURSUANT TO THE TERMS OF THIS AGREEMENT. Some jurisdictions do not allow the exclusion of liability for incidental or consequential damages, so some or all of the above exclusions or limitations may not apply.
+
+CANCELLATION AND TERMINATION
+
+Headway Themes, LLC, in its sole discretion, has the right to suspend or terminate your account and refuse any and all current or future use of the Service, or any other Headway Themes, LLC service, for violation of these Member Terms of Service. Such termination of the Service will result in the deactivation or deletion of your Account or your access to your Account, and the forfeiture and relinquishment of all content in your account. Headway Themes, LLC reserves the right to refuse service to anyone for any reason at any time, and to refund your payment and terminate your account in the sole discretion of Headway Themes, LLC.
+
+If Member is dissatisfied with any aspect of the Service(s), your sole and exclusive remedy is to terminate the Agreement and/or the Service(s) Terms by requesting your account be closed.
+
+Reasons for Headway Themes, LLC's determination to so terminate, suspend or discontinue your account or participation may include, but is not limited to, if Headway Themes, LLC believes that you violated the Agreement or other policies or guidelines of the Service, a Third Party Product, or if Headway Themes, LLC believes Member conduct may be harmful to other consumers, members or licensees who participate in (or offer to its users) the Service Web Sites (and/or any part thereof).
+
+All decisions made by Headway Themes, LLC in this matter will be final and neither Headway Themes, LLC nor any of the Headway Themes, LLC Entities shall have any liability regarding such decisions.
+
+MAJEURE
+
+If Service is prevented or delayed in or from performing any of its obligations under the Agreement due to circumstances beyond its control, including but not limited to governmental acts, war, riots, strikes or trade disputes (including by and with our own employees), technical failure, general availability of the internet, power failure, communications failure, weather, flood, fire or explosion, natural or local emergency, Headway Themes, LLC shall not be liable for any resulting failure to provide services hereunder.
+
+NOTICES
+
+Any notices or communications under the agreement shall be by electronic mail or in writing and shall be deemed delivered upon receipt to the party to whom such communication is directed, at the addresses specified below. If to Headway Themes, LLC, such notices shall be addressed to support@headwaythemes.com or to Grant Griffiths, Headway Themes, LLC, 513 Prospect Street, Clay Center, Kansas 67432 , USA. If to Member, such notices shall be addressed to the electronic or mailing address specified in Members's service registration form, or such other address as either party may give the other by notice as provided in this section. It is the applicant's responsibility to provide an accurate address and to ensure that the Service is notified of any changes to applicant's address as specified in this section.
+
+GOVERNING LAW, VENUE AND ATTORNEYS FEES
+
+The Membership Agreement, including these Terms and Conditions, shall be governed by and construed in accordance with the laws of the United States and the State of Kansas. Any dispute arising under or related in any way to this Agreement shall be adjudicated in a court of competent jurisdiction in the County of Clay, Kansas. In the event of litigation to enforce any provision of the Membership Agreement, including these Terms and Conditions, the prevailing party will be entitled to recover from the other party its costs and fees, including reasonable legal fees.
+
+ELECTRONIC SIGNATURES EFFECTIVE
+
+The Agreement is an electronic contract that sets out the legally binding terms of your use of the Service's products and services, including, without limitation, the Service Web Sites. You indicate your acceptance of the Agreement and all of the terms and conditions contained or referenced in the Agreement and these Member Terms of Service and in any Programs Terms by clicking on the "I Accept" button in connection with your enrollment. This action creates an electronic signature that has the same legal force and effect as a handwritten signature. By clicking on the "I Accept" button, you accept the Agreement, including, without limitation, the Programs Terms and agree to the terms, conditions and notices contained or referenced therein. When you click on the "I Accept" button during enrollment, you also consent to have the Agreement provided to you in electronic form. You have the right to receive the Agreement in non-electronic form.
+
+In order to access and retain this electronic Agreement, you must have access to the World Wide Web, either directly or through devices that access web-based content, and pay any service fees associated with such access. In addition, you must use all equipment necessary to make such connection to the World Wide Web, including, without limitation, a computer and modem or other access device. Please print a copy of the Agreement for your records. To retain an electronic copy of the Agreement, you may save it into any word processing program. We will notify you of any changes in the hardware or software requirements needed to access and/or retain the Agreement that create a material risk that you will not be able to continue to access and/or retain the electronic Agreement.
+
+TRADEMARK INFORMATION
+
+All logos, product, and service name related to these TOS are trademarks of Headway Themes, LLC. Without Headway Themes, LLC's prior permission, you agree not to display or use in any manner the Headway Themes Trademarks.
+
+3. GENERAL CONDITIONS
+
+* Each Member uses the Service at Member's sole risk. The Service is provided on an "as is" and "as available" basis.
+Technical support is only available via the support forum
+
+* Member must not use any Headway Themes, LLC digital products in a manner not permitted by the terms of Member's membership level, and must not distribute any Headway Themes, LLC digital products to third parties by any means, including but not limited to posting download links at public or private forums, websites, peer-to-peer networks, torrents, or email lists. With the exception to those as authorized by the GPL version 2.0 license (http://www.gnu.org/licenses/gpl-2.0.html GNU/GPLv2). Headway Themes, LLC reserves all rights with respect to its intellectual property, and all remedies, in law and in equity.
+
+* Member must not modify, adapt or hack the Service or modify another website so as to falsely imply that it is associated with the Service, Headway Themes, LLC, or any other Headway Themes, LLC service.
+
+* Member agree not to reproduce, duplicate, copy, sell, resell or exploit any portion of the Service, use of the Service, or access to the Service without the express written permission by Headway Themes, LLC. With the exception to those as authorized by the GPL version 2.0 license (http://www.gnu.org/licenses/gpl-2.0.html GNU/GPLv2).
+Headway Themes, LLC may, but has no obligation to, remove Content and Accounts containing Content that we determine in our sole discretion are unlawful, offensive, threatening, libelous, defamatory, pornographic, obscene or otherwise objectionable or violates any party's intellectual property or these Terms of Service.
+
+* Verbal, physical, written or other abuse (including threats of abuse or retribution) of any Headway Themes, LLC customer, employee, member, or officer will result in immediate account termination.
+
+* Headway Themes, LLC does not warrant that (i) the service will meet your specific requirements, (ii) the service will be uninterrupted, timely, secure, or error-free, (iii) the results that may be obtained from the use of the service will be accurate or reliable, (iv) the quality of any products, services, information, or other material purchased or obtained by you through the service will meet your expectations, and (v) any errors in the Service will be corrected.
+
+* Member expressly understands and agrees that Headway Themes, LLC shall not be liable for any direct, indirect, incidental, special, consequential or exemplary damages, including but not limited to, damages for loss of profits, goodwill, use, data or other intangible losses (even if Headway Themes, LLC has been advised of the possibility of such damages), resulting from: (i) the use or the inability to use the Service; (ii) the cost of procurement of substitute goods and services resulting from any goods, data, information or services purchased or obtained or messages received or transactions entered into through or from the service; (iii) unauthorized access to or alteration of your transmissions or data; (iv) statements or conduct of any third party on the service; (v) or any other matter relating to the service. Headway Themes, LLC’s liability to you shall not, for any reason, exceed the amount actually paid by you to Headway Themes, LLC.
+
+* The failure of Headway Themes, LLC to exercise or enforce any right or provision of the Terms of Service shall not constitute a waiver of such right or provision. The Terms of Service constitutes the entire agreement between you and Headway Themes, LLC and govern your use of the Service, superseding any prior agreements between you and Headway Themes, LLC (including, but not limited to, any prior versions of the Terms of Service).
+
+Effective Date December 1st, 2011
--- /dev/null
+<?php
+/* Prevent direct access to this file */
+if ( !defined('WP_CONTENT_DIR') )
+ die('Please do not access this file directly.');
+
+/* WordPress and a lot of plugins require the function in this file, so I guess we have to use it :-(. */
+wp_footer();
+
+HeadwayDisplay::body_close();
+
+HeadwayDisplay::html_close();
\ No newline at end of file
--- /dev/null
+<?php
+/**
+ * Starts Headway
+ *
+ * @package Headway
+ * @author Clay Griffiths
+ */
+
+/* Prevent direct access to this file */
+if ( !defined('WP_CONTENT_DIR') )
+ die('Please do not access this file directly.');
+
+/* Make sure PHP 5.2 or newer is installed and WordPress 3.2 or newer is installed. */
+require_once get_template_directory() . '/library/common/compatibility-checks.php';
+
+/* Load Headway! */
+require_once get_template_directory() . '/library/common/functions.php';
+require_once get_template_directory() . '/library/common/application.php';
+
+Headway::init();
\ No newline at end of file
--- /dev/null
+<?php
+/* Prevent direct access to this file */
+if ( !defined('WP_CONTENT_DIR') )
+ die('Please do not access this file directly.');
+
+HeadwayDisplay::html_open();
+
+wp_head();
+
+HeadwayDisplay::body_open();
\ No newline at end of file
--- /dev/null
+<?php
+/**
+ * Main template file used for Headway.
+ *
+ * @author Clay Griffiths
+ * @package Headway
+ **/
+
+/* Prevent direct access to this file */
+if ( !defined('WP_CONTENT_DIR') )
+ die('Please do not access this file directly.');
+
+HeadwayDisplay::layout();
\ No newline at end of file
--- /dev/null
+<?php
+class HeadwayAdminBar {
+
+
+ public static function init() {
+
+ add_action('admin_bar_menu', array(__CLASS__, 'add_admin_bar_nodes'), 75);
+
+ }
+
+
+ public static function remove_admin_bar() {
+
+ show_admin_bar(false);
+ remove_action('wp_head', '_admin_bar_bump_cb');
+
+ }
+
+
+ public static function add_admin_bar_nodes() {
+
+ if ( !HeadwayCapabilities::can_user_visually_edit() )
+ return;
+
+ global $wp_admin_bar;
+
+ $default_visual_editor_mode = current_theme_supports('headway-grid') ? 'grid' : 'design';
+
+ //Headway Root
+ $wp_admin_bar->add_menu(array(
+ 'id' => 'headway',
+ 'title' => 'Headway',
+ 'href' => add_query_arg(array('visual-editor' => 'true', 'visual-editor-mode' => $default_visual_editor_mode, 've-layout' => HeadwayLayout::get_current()), home_url())
+ ));
+
+ //Visual Editor
+ $wp_admin_bar->add_menu(array(
+ 'parent' => 'headway',
+ 'id' => 'headway-ve',
+ 'title' => 'Visual Editor',
+ 'href' => add_query_arg(array('visual-editor' => 'true', 'visual-editor-mode' => $default_visual_editor_mode, 've-layout' => HeadwayLayout::get_current()), home_url())
+ ));
+
+ //Grid
+ if ( current_theme_supports('headway-grid') ) {
+
+ $wp_admin_bar->add_menu(array(
+ 'parent' => 'headway-ve',
+ 'id' => 'headway-ve-grid',
+ 'title' => 'Grid',
+ 'href' => add_query_arg(array('visual-editor' => 'true', 'visual-editor-mode' => 'grid', 've-layout' => HeadwayLayout::get_current()), home_url())
+ ));
+
+ }
+
+ //Design Editor
+ $wp_admin_bar->add_menu(array(
+ 'parent' => 'headway-ve',
+ 'id' => 'headway-ve-design',
+ 'title' => 'Design',
+ 'href' => add_query_arg(array('visual-editor' => 'true', 'visual-editor-mode' => 'design', 've-layout' => HeadwayLayout::get_current()), home_url())
+ ));
+
+ //Templates
+ $wp_admin_bar->add_menu(array(
+ 'parent' => 'headway',
+ 'id' => 'headway-admin-templates',
+ 'title' => 'Templates',
+ 'href' => admin_url('admin.php?page=headway-templates')
+ ));
+
+ //Admin Options
+ $wp_admin_bar->add_menu(array(
+ 'parent' => 'headway',
+ 'id' => 'headway-admin-options',
+ 'title' => 'Options',
+ 'href' => admin_url('admin.php?page=headway-options')
+ ));
+
+ $wp_admin_bar->add_menu(array(
+ 'parent' => 'headway-admin-options',
+ 'id' => 'headway-admin-options-general',
+ 'title' => 'General',
+ 'href' => admin_url('admin.php?page=headway-options#tab-general')
+ ));
+
+ $wp_admin_bar->add_menu(array(
+ 'parent' => 'headway-admin-options',
+ 'id' => 'headway-admin-options-seo',
+ 'title' => 'Search Engine Optimization',
+ 'href' => admin_url('admin.php?page=headway-options#tab-seo')
+ ));
+
+ $wp_admin_bar->add_menu(array(
+ 'parent' => 'headway-admin-options',
+ 'id' => 'headway-admin-options-scripts',
+ 'title' => 'Scripts/Analytics',
+ 'href' => admin_url('admin.php?page=headway-options#tab-scripts')
+ ));
+
+ $wp_admin_bar->add_menu(array(
+ 'parent' => 'headway-admin-options',
+ 'id' => 'headway-admin-options-visual-editor',
+ 'title' => 'Visual Editor',
+ 'href' => admin_url('admin.php?page=headway-options#tab-visual-editor')
+ ));
+
+ $wp_admin_bar->add_menu(array(
+ 'parent' => 'headway-admin-options',
+ 'id' => 'headway-admin-options-advanced',
+ 'title' => 'Advanced',
+ 'href' => admin_url('admin.php?page=headway-options#tab-advanced')
+ ));
+
+ //Admin Tools
+ $wp_admin_bar->add_menu(array(
+ 'parent' => 'headway',
+ 'id' => 'headway-admin-tools',
+ 'title' => 'Tools',
+ 'href' => admin_url('admin.php?page=headway-tools')
+ ));
+
+ $wp_admin_bar->add_menu(array(
+ 'parent' => 'headway-admin-tools',
+ 'id' => 'headway-admin-tools-system-info',
+ 'title' => 'System Info',
+ 'href' => admin_url('admin.php?page=headway-tools#tab-system-info')
+ ));
+
+ $wp_admin_bar->add_menu(array(
+ 'parent' => 'headway-admin-tools',
+ 'id' => 'headway-admin-tools-reset',
+ 'title' => 'Reset',
+ 'href' => admin_url('admin.php?page=headway-tools#tab-reset')
+ ));
+
+ }
+
+
+}
\ No newline at end of file
--- /dev/null
+<?php
+headway_register_admin_meta_box('HeadwayMetaBoxTemplate');
+class HeadwayMetaBoxTemplate extends HeadwayAdminMetaBoxAPI {
+
+ protected $id = 'template';
+
+ protected $name = 'Shared Layout';
+
+ protected $context = 'side';
+
+ protected $inputs = array(
+ 'template' => array(
+ 'id' => 'template',
+ 'type' => 'select',
+ 'options' => array(),
+ 'description' => 'Assign a shared layout to this entry. Shared layouts can be added and modified in the Headway Visual Editor.',
+ 'blank-option' => '– Do Not Use Shared Layout –'
+ )
+ );
+
+ protected function modify_arguments($post = false) {
+
+ $this->inputs['template']['options'] = HeadwayLayout::get_templates();
+
+ $post_type = get_post_type_object( $post->post_type );
+
+ $this->inputs['template']['description'] = str_replace('entry', strtolower($post_type->labels->singular_name), $this->inputs['template']['description']);
+
+ }
+
+}
+
+headway_register_admin_meta_box('HeadwayMetaBoxTitleControl');
+class HeadwayMetaBoxTitleControl extends HeadwayAdminMetaBoxAPI {
+
+ protected $id = 'alternate-title';
+
+ protected $name = 'Title Control';
+
+ protected $context = 'side';
+
+ protected $inputs = array(
+ 'hide-title' => array(
+ 'id' => 'hide-title',
+ 'name' => 'Hide Title',
+ 'type' => 'select',
+ 'blank-option' => '– Do Not Hide Title –',
+ 'options' => array(
+ 'singular' => 'Hide on Single View',
+ 'list' => 'Hide in Index and Archives',
+ 'both' => 'Hide on Single View, Index, and Archives'
+ ),
+ 'description' => 'Choose whether or not you would like to hide the title for this entry. This can be useful if you have advanced formatting in this entry.',
+ ),
+
+ 'alternate-title' => array(
+ 'id' => 'alternate-title',
+ 'name' => 'Alternate Title',
+ 'type' => 'text',
+ 'description' => 'Using the alternate page title, you can override the title that\'s displayed in the Content Block of the page. Doing this, you can have a shorter page title in the navigation menu and <code><title></code>, but have a longer and more descriptive title in the actual page content.'
+ )
+ );
+
+}
+
+
+headway_register_admin_meta_box('HeadwayMetaBoxDisplay');
+class HeadwayMetaBoxDisplay extends HeadwayAdminMetaBoxAPI {
+
+ protected $id = 'display';
+
+ protected $name = 'Display';
+
+ protected $inputs = array(
+ 'css-class' => array(
+ 'id' => 'css-class',
+ 'name' => 'Custom CSS Class(es)',
+ 'type' => 'text',
+ 'description' => 'If you are familiar with <a href="http://www.w3schools.com/css/" target="_blank">CSS</a> and would like to style this entry by targeting a certain CSS class (or classes), then you may enter them in here. The class will be added to the <strong>entry container\'s class</strong> along with the <strong>body class</strong> if only this entry is being viewed (e.g. single post or page view). Classes can be separated with spaces and/or commas.'
+ )
+ );
+
+}
+
+
+headway_register_admin_meta_box('HeadwayMetaBoxPostThumbnail');
+class HeadwayMetaBoxPostThumbnail extends HeadwayAdminMetaBoxAPI {
+
+ protected $id = 'post-thumbnail';
+
+ protected $name = 'Featured Image Position';
+
+ protected $context = 'side';
+
+ protected $priority = 'low';
+
+ protected $inputs = array(
+ 'position' => array(
+ 'id' => 'position',
+ 'name' => 'Featured Image Position',
+ 'type' => 'radio',
+ 'options' => array(
+ '' => 'Use Block Default',
+ 'left' => 'Left',
+ 'right' => 'Right',
+ 'above-title' => 'Above Title',
+ 'above-content' => 'Above Content'
+ ),
+ 'description' => 'Set the position of the featured image for this entry.',
+ 'default' => '',
+ 'group' => 'post-thumbnail'
+ ),
+ );
+
+}
+
+
+if ( !HeadwaySEO::plugin_active() )
+ headway_register_admin_meta_box('HeadwayMetaBoxSEO');
+class HeadwayMetaBoxSEO extends HeadwayAdminMetaBoxAPI {
+
+ protected $id = 'seo';
+
+ protected $name = 'Search Engine Optimization (SEO)';
+
+ protected $post_type_supports_id = 'headway-seo';
+
+ protected $priority = 'high';
+
+ protected $inputs = array(
+ 'seo-preview' => array(
+ 'id' => 'seo-preview',
+ 'type' => 'seo-preview'
+ ),
+
+ 'title' => array(
+ 'id' => 'title',
+ 'group' => 'seo',
+ 'name' => 'Title',
+ 'type' => 'text',
+ 'description' => 'Custom <code><title></code> tag'
+ ),
+
+ 'description' => array(
+ 'id' => 'description',
+ 'group' => 'seo',
+ 'name' => 'Description',
+ 'type' => 'textarea',
+ 'description' => 'Custom <code><meta></code> description'
+ ),
+
+ 'noindex' => array(
+ 'id' => 'noindex',
+ 'group' => 'seo',
+ 'name' => '<code>noindex</code> this entry.',
+ 'type' => 'checkbox',
+ 'description' => 'Index/NoIndex tells the engines whether the entry should be crawled and kept in the engines\' index for retrieval. If you check this box to opt for <code>noindex</code>, the entry will be excluded from the engines. <strong>Note:</strong> if you\'re not sure what this does, do not check this box.'
+ ),
+
+ 'nofollow' => array(
+ 'id' => 'nofollow',
+ 'group' => 'seo',
+ 'name' => '<code>nofollow</code> links in this entry.',
+ 'type' => 'checkbox',
+ 'description' => 'Follow/NoFollow tells the engines whether links on the entry should be crawled. If you check this box to employ "nofollow," the engines will disregard the links on the entry both for discovery and ranking purposes. <strong>Note:</strong> if you\'re not sure what this does, do not check this box.'
+ ),
+
+ 'noarchive' => array(
+ 'id' => 'noarchive',
+ 'group' => 'seo',
+ 'name' => '<code>noarchive</code> links in this entry.',
+ 'type' => 'checkbox',
+ 'description' => 'Noarchive is used to restrict search engines from saving a cached copy of the entry. By default, the engines will maintain visible copies of all pages they indexed, accessible to searchers through the "cached" link in the search results. Check this box to restrict search engines from storing cached copies of this entry.'
+ ),
+
+ 'nosnippet' => array(
+ 'id' => 'nosnippet',
+ 'group' => 'seo',
+ 'name' => '<code>nosnippet</code> links in this entry.',
+ 'type' => 'checkbox',
+ 'description' => 'Nosnippet informs the engines that they should refrain from displaying a descriptive block of text next to the entry\'s title and URL in the search results.'
+ ),
+
+ 'noodp' => array(
+ 'id' => 'noodp',
+ 'group' => 'seo',
+ 'name' => '<code>noodp</code> links in this entry.',
+ 'type' => 'checkbox',
+ 'description' => 'NoODP is a specialized tag telling the engines not to grab a descriptive snippet about a page from the Open Directory Project (DMOZ) for display in the search results.'
+ ),
+
+ 'noydir' => array(
+ 'id' => 'noydir',
+ 'group' => 'seo',
+ 'name' => '<code>noydir</code> links in this entry.',
+ 'type' => 'checkbox',
+ 'description' => 'NoYDir, like NoODP, is specific to Yahoo!, informing that engine not to use the Yahoo! Directory description of a page/site in the search results.'
+ ),
+
+ 'redirect-301' => array(
+ 'id' => 'redirect-301',
+ 'group' => 'seo',
+ 'name' => '301 Permanent Redirect',
+ 'type' => 'text',
+ 'description' => 'The 301 Permanent Redirect can be used to forward an old post or page to a new or different location. If you ever move a page or change a page\'s permalink, use this to forward your visitors to the new location.<br /><br /><em>Want more information? Read more about <a href="http://support.google.com/webmasters/bin/answer.py?hl=en&answer=93633" target="_blank">301 Redirects</a>.</em>'
+ ),
+
+ );
+
+
+ protected function input_seo_preview() {
+
+ global $post;
+
+ $date = get_the_time('M j, Y') ? get_the_time('M j, Y') : mktime('M j, Y');
+ $date_text = ( $post->post_type == 'post' ) ? $date . ' ... ' : null;
+
+ echo '<h4 id="seo-preview-title">Search Engine Result Preview</h4>';
+
+ echo '<div id="seo-preview">';
+
+ echo '<h4 title="Click To Edit">' . get_bloginfo('name') . '</h4>';
+ echo '<p id="seo-preview-description" title="Click To Edit">' . $date_text . '<span id="text"></span></p>';
+
+ echo '<p id="seo-preview-bottom"><span id="seo-preview-url">' . str_replace('http://', '', home_url()) . '</span> - <span>Cached</span> - <span>Similar</span></p>';
+
+ echo '</div><!-- #seo-preview -->';
+
+ echo '<small id="seo-preview-disclaimer">Remember, this is only a predicted search engine result preview. There is no guarantee that it will look exactly this way. However, it will look similar.</small>';
+
+ }
+
+
+ protected function input_text_with_counter($input) {
+
+ echo '
+ <tr class="label">
+ <th valign="top" scope="row">
+ <label for="' . $input['attr-id'] . '">' . $input['name'] . '</label>
+ </th>
+ </tr>
+
+ <tr>
+ <td>
+ <input type="text" value="' . esc_attr($input['value']) . '" id="' . $input['attr-id'] . '" name="' . $input['attr-name'] . '" />
+ </td>
+ </tr>
+
+ <tr class="character-counter">
+ <td>
+ <span>130</span><div class="character-counter-box"><div class="character-counter-inside"></div></div>
+ </td>
+ </tr>
+ ';
+
+ }
+
+
+ protected function modify_arguments($post = false) {
+
+ //Do not use this box if the page being edited is the front page since they can edit the setting in the configuration.
+ if ( get_option('page_on_front') == headway_get('post') && get_option('show_on_front') == 'page' ) {
+
+ $this->info = '<strong>Configure the SEO settings for this page (Front Page) in the Headway Search Engine Optimization settings tab in <a href="' . admin_url('admin.php?page=headway-options#tab-seo-content') . '" target="_blank">Headway » Configuration</a>.</strong>';
+
+ $this->inputs = array();
+
+ return;
+
+ }
+
+ //Setup the defaults for the title and checkboxes
+ $current_screen = get_current_screen();
+ $seo_templates_query = HeadwayOption::get('seo-templates', 'general', HeadwaySEO::output_layouts_and_defaults());
+ $seo_templates = headway_get('single-' . $current_screen->id, $seo_templates_query, array());
+
+ $title_template = str_replace(array('%sitename%', '%SITENAME%'), get_bloginfo('name'), headway_get('title', $seo_templates));
+
+ echo '<input type="hidden" id="title-seo-template" value="' . $title_template . '" />';
+
+ $this->inputs['noindex']['default'] = headway_get('noindex', $seo_templates);
+ $this->inputs['nofollow']['default'] = headway_get('nofollow', $seo_templates);
+ $this->inputs['noarchive']['default'] = headway_get('noarchive', $seo_templates);
+ $this->inputs['nosnippet']['default'] = headway_get('nosnippet', $seo_templates);
+ $this->inputs['noodp']['default'] = headway_get('noodp', $seo_templates);
+ $this->inputs['noydir']['default'] = headway_get('noydir', $seo_templates);
+
+
+ }
+
+}
\ No newline at end of file
--- /dev/null
+<?php
+class HeadwayAdminPages {
+
+
+ /**
+ * @see HeadwayAdmin::visual_editor_redirect
+ *
+ * This function is here strictly for backup. The PHP header location should replace all of this.
+ **/
+ public static function visual_editor() {
+
+ HeadwayAdmin::show_header('Headway Visual Editor');
+ echo '<p>You are now being redirected. If you are not redirected within 3 seconds, click <a href="' . home_url() . '/?visual-editor=true"><strong>here</strong></a>.</p>';
+ echo '<meta http-equiv="refresh" content="3;URL=' . home_url() . '/?visual-editor=true">';
+ HeadwayAdmin::show_footer();
+
+ }
+
+
+ public static function getting_started() {
+
+ HeadwayAdmin::show_header();
+
+ require_once HEADWAY_LIBRARY_DIR . '/admin/pages/getting-started.php';
+
+ HeadwayAdmin::show_footer();
+
+ }
+
+
+ public static function whats_new() {
+
+ require_once HEADWAY_LIBRARY_DIR . '/admin/pages/whats-new.php';
+
+ }
+
+
+ public static function templates() {
+
+ HeadwayAdmin::show_header();
+
+ require_once HEADWAY_LIBRARY_DIR . '/admin/pages/templates.php';
+
+ HeadwayAdmin::show_footer();
+
+ }
+
+
+ public static function options() {
+
+ HeadwayAdmin::show_header();
+
+ require_once HEADWAY_LIBRARY_DIR . '/admin/pages/options.php';
+
+ HeadwayAdmin::show_footer();
+
+ }
+
+
+ public static function tools() {
+
+ HeadwayAdmin::show_header();
+
+ require_once HEADWAY_LIBRARY_DIR . '/admin/pages/tools.php';
+
+ HeadwayAdmin::show_footer();
+
+ }
+
+
+}
\ No newline at end of file
--- /dev/null
+<?php
+class HeadwayAdminWrite {
+
+
+ public static function init() {
+
+ /* Load the default meta boxes */
+ Headway::load('admin/admin-meta-boxes');
+
+ add_action('delete_post', array(__CLASS__, 'delete_post'));
+
+ add_filter('get_sample_permalink_html', array(__CLASS__, 'open_in_visual_editor_button'), 10, 4);
+
+ }
+
+
+ public static function delete_post($postid) {
+
+ $post = get_post($postid);
+
+ /* If the post type is a revision then don't do anything. */
+ if ( $post->post_type == 'revision' )
+ return false;
+
+ /* Figure out the layout ID */
+ $layout_id = 'single-' . $post->post_type . '-' . $postid;
+
+ /* Delete everything from the layout including blocks, wrapper, design editor instances, and the wp_options rows */
+ HeadwayLayout::delete_layout($layout_id, false);
+
+ }
+
+
+ public static function open_in_visual_editor_button($return, $id, $new_title, $new_slug) {
+
+ global $post;
+
+ if ( !isset($post->ID) || !is_numeric($post->ID) || $post->post_status != 'publish' || !HeadwayCapabilities::can_user_visually_edit() )
+ return $return;
+
+ $layout_id = 'single' . HeadwayLayout::$sep . $post->post_type . HeadwayLayout::$sep . $post->ID;
+
+ if ( get_option('show_on_front') === 'page' ) {
+
+ if ( $post->ID == get_option('page_on_front') )
+ $layout_id = 'front_page';
+
+ if ( $post->ID == get_option('page_for_posts') )
+ $layout_id = 'index';
+
+ }
+
+ $visual_editor_url = home_url('/?visual-editor=true&ve-layout=' . urlencode($layout_id));
+
+ $return .= '<span id="headway-open-in-ve-btn" style="margin-right: 3px;"><a href="' . $visual_editor_url . '" class="button button-primary button-small" target="_blank">Open in Visual Editor</a></span>';
+
+ return $return;
+
+ }
+
+
+}
\ No newline at end of file
--- /dev/null
+<?php
+class HeadwayAdmin {
+
+
+ public static function init() {
+
+ self::setup_hooks();
+
+ Headway::load(array(
+ 'api/api-admin-meta-box',
+ 'admin/admin-write' => true,
+ 'admin/admin-pages',
+ 'admin/api-admin-inputs'
+ ));
+
+ }
+
+
+ public static function setup_hooks() {
+
+ /* Actions */
+ add_action('admin_init', array(__CLASS__, 'activation'), 1);
+ add_action('admin_init', array(__CLASS__, 'enqueue'));
+ add_action('admin_init', array(__CLASS__, 'visual_editor_redirect'), 12);
+
+ add_action('init', array(__CLASS__, 'form_action_save'), 12); // Init runs before admin_menu; admin_menu runs before admin_init
+ add_action('init', array(__CLASS__, 'form_action_licenses'), 12);
+ add_action('init', array(__CLASS__, 'form_action_reset'), 12);
+
+ add_action('admin_menu', array(__CLASS__, 'add_menus'));
+ add_action('admin_head', array(__CLASS__, 'remove_system_submenus'));
+
+ add_action('headway_admin_save_message', array(__CLASS__, 'save_message'));
+ add_action('headway_admin_save_error_message', array(__CLASS__, 'save_error_message'));
+
+ add_action('admin_notices', array(__CLASS__, 'notice_no_widgets_or_menus'));
+
+ add_filter('page_row_actions', array(__CLASS__, 'row_action_visual_editor'), 10, 2);
+ add_filter('post_row_actions', array(__CLASS__, 'row_action_visual_editor'), 10, 2);
+ add_filter('tag_row_actions', array(__CLASS__, 'row_action_visual_editor'), 10, 2);
+
+ }
+
+
+ public static function form_action_save() {
+
+ //Form action for all Headway configuration panels. Not in function/hook so it can load before everything else.
+ if ( !headway_post('headway-submit', false))
+ return false;
+
+ if ( !wp_verify_nonce(headway_post('headway-admin-nonce', false), 'headway-admin-nonce') ) {
+
+ global $headway_admin_save_message;
+ $headway_admin_save_message = 'Security nonce did not match.';
+
+ return false;
+
+ }
+
+ foreach ( headway_post('headway-admin-input', array()) as $option => $value ) {
+
+ HeadwayOption::set($option, $value);
+
+ }
+
+ global $headway_admin_save_message;
+ $headway_admin_save_message = 'Settings saved.';
+
+ return true;
+
+ }
+
+
+ public static function form_action_licenses() {
+
+ if ( !headway_post('headway-licenses', false))
+ return false;
+
+ if ( !wp_verify_nonce(headway_post('headway-admin-nonce', false), 'headway-admin-nonce') )
+ return false;
+
+ if ( !is_array(headway_post('headway-licenses')) )
+ return false;
+
+ global $headway_admin_save_message;
+ global $headway_admin_save_error_message;
+
+
+ /* Save and activations */
+ if ( $save_and_activations = headway_get('save-and-activate', headway_post('headway-licenses')) ) {
+
+ if ( is_array($save_and_activations) && count($save_and_activations) ) {
+
+ foreach ( $save_and_activations as $item_slug_to_activate => $submit_value ) {
+
+ HeadwayOption::set('license-key-' . $item_slug_to_activate, headway_get('license-key-' . $item_slug_to_activate, headway_post('headway-admin-input')));
+ $activation_request = headway_activate_license($item_slug_to_activate);
+
+ self::set_license_activation_message($activation_request);
+
+ }
+
+ }
+
+ }
+
+ /* Activations */
+ if ( $activations = headway_get('activate', headway_post('headway-licenses')) ) {
+
+ if ( is_array($activations) && count($activations) ) {
+
+ foreach ( headway_get('activate', headway_post('headway-licenses')) as $item_slug_to_activate => $submit_value ) {
+
+ $activation_request = headway_activate_license($item_slug_to_activate);
+
+ self::set_license_activation_message($activation_request);
+
+ }
+
+ }
+
+ }
+
+ /* Deactivations */
+ if ( $deactivations = headway_get('deactivate', headway_post('headway-licenses')) ) {
+
+ if ( is_array($deactivations) && count($deactivations) ) {
+
+ foreach ( headway_get('deactivate', headway_post('headway-licenses')) as $item_slug_to_deactivate => $submit_value ) {
+
+ $deactivation_request = headway_deactivate_license($item_slug_to_deactivate);
+
+ if ( $deactivation_request == 'deactivated' ) {
+
+ $headway_admin_save_message = 'License deactivated.';
+
+ } else if ( !is_wp_error($deactivation_request) ) {
+
+ $headway_admin_save_error_message = '<strong>Whoops!</strong> Could not deactivate license. Please check that you have entered your license correctly.';
+
+ } else {
+
+ $headway_admin_save_error_message = '
+ <strong>Error While Deactivating:</strong> (' . $deactivation_request->get_error_code() . ') ' . $deactivation_request->get_error_message() . '<br /><br />
+ ' . __('Please contact Headway Support if this error persists.', 'headway') . '
+ ';
+
+ }
+
+ }
+
+ }
+
+ }
+
+
+ return true;
+
+ }
+
+
+ public static function set_license_activation_message($activation_request) {
+
+ global $headway_admin_save_message;
+ global $headway_admin_save_error_message;
+
+ if ( $activation_request == 'active' || $activation_request == 'valid' ) {
+
+ $headway_admin_save_message = __('License saved and activated.', 'headway');
+
+ } else if ( $activation_request == 'invalid' || $activation_request == 'expired' ) {
+
+ $headway_admin_save_error_message = __('
+ <strong>Whoops!</strong> Could not activate license. Please check that you have entered your license correctly and that it has not expired.<br /><br />
+ Make sure you copied your license correctly from the <a href="http://headwaythemes.com/dashboard" target="_blank">Headway Dashboard</a>.
+ ', 'headway');
+
+ } else if ( is_wp_error($activation_request) ) {
+
+ $headway_admin_save_error_message = '
+ <strong>Error While Activating:</strong> (' . $activation_request->get_error_code() . ') ' . $activation_request->get_error_message() . '<br /><br />
+ ' . __('Please contact Headway Support if this error persists.', 'headway') . '
+ ';
+
+ }
+
+ }
+
+
+ public static function form_action_reset() {
+
+ global $wpdb;
+
+ if ( !defined('HEADWAY_ALLOW_RESET') || HEADWAY_ALLOW_RESET !== true )
+ return false;
+
+ //Form action for all Headway configuration panels. Not in function/hook so it can load before everything else.
+ if ( !headway_post('reset-headway', false) )
+ return false;
+
+ //Verify the nonce so other sites can't maliciously reset a Headway installation.
+ if ( !wp_verify_nonce(headway_post('headway-reset-nonce', false), 'headway-reset-nonce') ) {
+
+ $GLOBALS['headway_admin_save_message'] = 'Security nonce did not match.';
+
+ return false;
+
+ }
+
+ /* Loop through WordPress options and delete the skin options */
+ $wpdb->query( "DELETE FROM $wpdb->options WHERE option_name = 'headway'" );
+ $wpdb->query( "DELETE FROM $wpdb->options WHERE option_name LIKE 'headway_%'" );
+
+ $wpdb->query( "DELETE FROM $wpdb->options WHERE option_name LIKE '_transient_hw_%'" );
+
+ /* Remove Headway post meta */
+ $wpdb->query( "DELETE FROM $wpdb->postmeta WHERE meta_key LIKE '_hw_%'" );
+
+ /* Drop Headway tables */
+ Headway::mysql_drop_tables();
+
+ /* Flush WP cache */
+ wp_cache_flush();
+
+ do_action('headway_global_reset');
+
+ $GLOBALS['headway_admin_save_message'] = 'Headway was successfully reset.';
+
+ //This will hide the reset box if set to true.
+ $GLOBALS['headway_reset_success'] = true;
+
+ return true;
+
+ }
+
+
+ public static function activation() {
+
+ if ( !is_admin() || !headway_get('activated') )
+ return false;
+
+ global $pagenow;
+
+ if ( $pagenow !== 'themes.php' )
+ return false;
+
+ //Since they may be upgrading and files may change, let's clear the cache
+ do_action('headway_activation');
+
+ self::activation_redirect();
+
+ }
+
+
+ public static function activation_redirect() {
+
+ do_action('headway_activation_redirect');
+
+ //If a child theme has been activated rather than Headway, then don't redirect.
+ //Let the child theme developer redirect if they want by using the hook above.
+ if ( HEADWAY_CHILD_THEME_ACTIVE === true )
+ return false;
+
+ $parent_menu = self::parent_menu();
+
+ //If header were sent, then don't do the redirect
+ if ( headers_sent() )
+ return false;
+
+ //We're all good, redirect now
+ wp_safe_redirect(admin_url('admin.php?page=headway-' . $parent_menu['id']));
+ die();
+
+ }
+
+
+ public static function visual_editor_redirect() {
+
+ if ( isset($_GET['page']) && strpos($_GET['page'], 'headway-visual-editor') !== false && !headers_sent() )
+ wp_safe_redirect(home_url() . '/?visual-editor=true');
+
+ }
+
+
+ public static function add_admin_separator($position){
+
+ global $menu;
+
+ $menu[$position] = array('', 'read', 'separator-headway', '', 'wp-menu-separator headway-separator');
+
+ ksort($menu);
+
+ }
+
+
+ public static function add_admin_submenu($name, $id, $callback) {
+
+ $parent_menu = self::parent_menu();
+
+ return add_submenu_page('headway-' . $parent_menu['id'], $name, $name, 'manage_options', $id, $callback);
+
+ }
+
+
+ public static function add_menus(){
+
+ //If the hide menus constant is set to true, don't hide the menus!
+ if (defined('HEADWAY_HIDE_MENUS') && HEADWAY_HIDE_MENUS === true)
+ return false;
+
+ //If user cannot access the admin panels, then don't bother running these functions
+ if ( !HeadwayCapabilities::can_user_visually_edit() )
+ return false;
+
+ $menu_name = ( HeadwayOption::get('hide-menu-version-number', false, true) == true ) ? 'Headway' : 'Headway ' . HEADWAY_VERSION;
+
+ $icon = (version_compare($GLOBALS['wp_version'], '3.8', '>=') && get_user_option('admin_color') != 'light') ? 'headway-32-white.png' : 'headway-16.png';
+ $icon_url = headway_url() . '/library/admin/images/' . $icon;
+
+ $parent_menu = self::parent_menu();
+
+ self::add_admin_separator(48);
+
+ add_menu_page($parent_menu['name'], $menu_name, 'manage_options', 'headway-' . $parent_menu['id'], $parent_menu['callback'], $icon_url, 49);
+
+ switch ( $parent_menu['id'] ) {
+
+ case 'getting-started':
+ self::add_admin_submenu('Getting Started', 'headway-getting-started', array('HeadwayAdminPages', 'getting_started'));
+ self::add_admin_submenu('Visual Editor', 'headway-visual-editor', array('HeadwayAdminPages', 'visual_editor'));
+
+ self::add_admin_submenu('Templates', 'headway-templates', array('HeadwayAdminPages', 'templates'));
+ self::add_admin_submenu('Options', 'headway-options', array('HeadwayAdminPages', 'options'));
+ self::add_admin_submenu('Tools', 'headway-tools', array('HeadwayAdminPages', 'tools'));
+ break;
+
+ case 'visual-editor':
+ self::add_admin_submenu('Visual Editor', 'headway-visual-editor', array('HeadwayAdminPages', 'visual_editor'));
+
+ self::add_admin_submenu('Templates', 'headway-templates', array('HeadwayAdminPages', 'templates'));
+ self::add_admin_submenu('Options', 'headway-options', array('HeadwayAdminPages', 'options'));
+ self::add_admin_submenu('Tools', 'headway-tools', array('HeadwayAdminPages', 'tools'));
+ break;
+
+ case 'options':
+ self::add_admin_submenu('Options', 'headway-options', array('HeadwayAdminPages', 'options'));
+ self::add_admin_submenu('Visual Editor', 'headway-visual-editor', array('HeadwayAdminPages', 'visual_editor'));
+ self::add_admin_submenu('Templates', 'headway-templates', array('HeadwayAdminPages', 'templates'));
+ self::add_admin_submenu('Tools', 'headway-tools', array('HeadwayAdminPages', 'tools'));
+ break;
+
+ }
+
+ self::add_admin_submenu( 'What\'s New', 'headway-whats-new', array( 'HeadwayAdminPages', 'whats_new' ) );
+
+ }
+
+
+ public static function remove_system_submenus() {
+
+ $parent_menu = HeadwayAdmin::parent_menu();
+
+ remove_submenu_page( 'headway-' . $parent_menu['id'], 'headway-whats-new' );
+
+ }
+
+
+ public static function parent_menu() {
+
+ $menu_setup = HeadwayOption::get('menu-setup', false, 'getting-started');
+
+ /* Figure out the primary page */
+ switch ( $menu_setup ) {
+
+ case 'getting-started':
+ $parent_menu = array(
+ 'id' => 'getting-started',
+ 'name' => 'Getting Started',
+ 'callback' => array('HeadwayAdminPages', 'getting_started')
+ );
+ break;
+
+ case 'visual-editor':
+ $parent_menu = array(
+ 'id' => 'visual-editor',
+ 'name' => 'Visual Editor',
+ 'callback' => array('HeadwayAdminPages', 'visual_editor')
+ );
+ break;
+
+ case 'options':
+ $parent_menu = array(
+ 'id' => 'options',
+ 'name' => 'Options',
+ 'callback' => array('HeadwayAdminPages', 'options')
+ );
+ break;
+
+ }
+
+ return $parent_menu;
+
+ }
+
+
+ public static function enqueue() {
+
+ global $pagenow;
+
+ /* Scripts Path */
+ $script_folder = (defined('SCRIPT_DEBUG') && SCRIPT_DEBUG) ? 'scripts' : 'scripts-min';
+
+ /* Global */
+ wp_enqueue_style('headway_admin_global', headway_url() . '/library/admin/css/admin-headway-global.css');
+
+ /* General Headway admin CSS/JS */
+ if ( strpos(headway_get('page'), 'headway') !== false ) {
+
+ wp_enqueue_script('headway_jquery_scrollto', headway_url() . '/library/admin/js/jquery.scrollto.js', array('jquery'));
+ wp_enqueue_script('headway_jquery_tabby', headway_url() . '/library/admin/js/jquery.tabby.js', array('jquery'));
+ wp_enqueue_script('headway_jquery_qtip', headway_url() . '/library/admin/js/jquery.qtip.js', array('jquery'));
+ wp_enqueue_script('headway_admin_js', headway_url() . '/library/admin/js/admin-headway.js', array('jquery', 'headway_jquery_qtip'));
+
+ wp_enqueue_style('headway_admin', headway_url() . '/library/admin/css/admin-headway.css');
+ wp_enqueue_style('headway_alerts', headway_url() . '/library/media/css/alerts.css');
+
+ }
+
+ /* Templates */
+ if ( headway_get('page') == 'headway-templates' ) {
+
+ wp_enqueue_script('headway_knockout', headway_url() . '/library/admin/js/knockout.js', array('jquery'));
+ wp_enqueue_script('headway_admin_templates', headway_url() . '/library/admin/js/admin-templates.js', array('jquery'));
+
+ wp_localize_script('headway_admin_templates', 'Headway', array(
+ 'ajaxURL' => admin_url('admin-ajax.php'),
+ 'security' => wp_create_nonce('headway-visual-editor-ajax'),
+
+ 'templates' => HeadwayTemplates::get_all(),
+ 'templateActive' => HeadwayTemplates::get_active(),
+
+ 'viewModels' => array()
+ ));
+
+ add_thickbox();
+ wp_enqueue_media();
+
+ }
+
+ /* Meta Boxes */
+ wp_enqueue_style('headway_admin_write', headway_url() . '/library/admin/css/admin-write.css');
+ wp_enqueue_style('headway_alerts', headway_url() . '/library/media/css/alerts.css');
+ wp_enqueue_script('headway_admin_write', headway_url() . '/library/admin/js/admin-write.js', array('jquery'));
+
+ /* Auto Updater */
+ if ( $pagenow === 'update-core.php' ) {
+
+ wp_enqueue_script('headway_admin', headway_url() . '/library/admin/js/admin-headway.js', array('jquery'));
+ wp_enqueue_style('headway_admin', headway_url() . '/library/admin/css/admin-headway.css');
+ wp_enqueue_style('headway_alerts', headway_url() . '/library/media/css/alerts.css');
+
+ }
+
+ }
+
+
+ public static function save_message() {
+
+ global $headway_admin_save_message;
+
+ if ( !isset($headway_admin_save_message) || $headway_admin_save_message == false )
+ return false;
+
+ echo '<div id="setting-error-settings_updated" class="updated settings-error"><p>' . $headway_admin_save_message . '</p></div>';
+
+ }
+
+
+ public static function save_error_message() {
+
+ global $headway_admin_save_error_message;
+
+ if ( !isset($headway_admin_save_error_message) || $headway_admin_save_error_message == false )
+ return false;
+
+ echo '<div id="setting-error-settings_error" class="error settings-error"><p>' . $headway_admin_save_error_message . '</p></div>';
+
+ }
+
+
+ public static function notice_no_widgets_or_menus() {
+
+ global $pagenow;
+
+ if ( $pagenow != 'widgets.php' && $pagenow != 'nav-menus.php' )
+ return false;
+
+ $grid_mode_url = add_query_arg(array('visual-editor' => 'true', 'visual-editor-mode' => 'grid'), home_url());
+
+ //Show the widgets message if no widget blocks exist.
+ if ( $pagenow == 'widgets.php' ) {
+
+ $widget_area_blocks = HeadwayBlocksData::get_blocks_by_type('widget-area');
+
+ if ( !empty($widget_area_blocks) )
+ return;
+
+ if ( !current_theme_supports('headway-grid') )
+ return;
+
+ echo '<div class="updated" style="margin-top: 15px;">
+ <p>Headway has detected that you have no Widget Area blocks. If you wish to use the WordPress widgets system with Headway, please add a Widget Area block in the <a href="' . $grid_mode_url . '" target="_blank">Visual Editor: Grid</a>.</p>
+
+ <style type="text/css">
+ div.error.below-h2 { display: none; }
+ div.error.below-h2 + p { display: none; }
+ </style>
+ </div>';
+
+ }
+
+ //Show the navigation menus message if no navigation blocks exist.
+ if ( $pagenow == 'nav-menus.php' ) {
+
+ $navigation_blocks = HeadwayBlocksData::get_blocks_by_type('navigation');
+
+ if ( !empty($navigation_blocks) )
+ return;
+
+ if ( !current_theme_supports('headway-grid') )
+ return;
+
+ echo '<div class="updated">
+ <p>Headway has detected that you have no Navigation blocks. If you wish to use the WordPress menus system with Headway, please add a Navigation block in the <a href="' . $grid_mode_url . '" target="_blank">Visual Editor: Grid</a>.</p>
+ </div>';
+
+ }
+
+ }
+
+
+ public static function show_header($title = false) {
+
+ echo '<div class="wrap headway-page">';
+
+ if ( $title )
+ echo '<h2>' . $title . '</h2>';
+
+ }
+
+
+ public static function show_footer() {
+
+ echo '</div><!-- #wrapper -->';
+
+ }
+
+
+ public static function row_action_visual_editor($actions, $item) {
+
+ if ( !HeadwayCapabilities::can_user_visually_edit() )
+ return $actions;
+
+ /* Post */
+ if ( isset($item->post_status) ) {
+
+ if ( $item->post_status != 'publish' )
+ return $actions;
+
+ $post_type = get_post_type_object($item->post_type);
+
+ if ( !$post_type->public )
+ return $actions;
+
+ $layout_id = 'single' . HeadwayLayout::$sep . $item->post_type . HeadwayLayout::$sep . $item->ID;
+
+ if ( get_option('show_on_front') === 'page' ) {
+
+ if ( $item->ID == get_option('page_on_front') )
+ $layout_id = 'front_page';
+
+ if ( $item->ID == get_option('page_for_posts') )
+ $layout_id = 'index';
+
+ }
+
+ /* Category */
+ } elseif ( isset($item->term_id) && $item->taxonomy == 'category' ) {
+
+ $layout_id = 'archive' . HeadwayLayout::$sep . 'category' . HeadwayLayout::$sep . $item->term_id;
+
+ /* Post Tag */
+ } elseif ( isset($item->term_id) && $item->taxonomy == 'post_tag' ) {
+
+ $layout_id = 'archive' . HeadwayLayout::$sep . 'post_tag' . HeadwayLayout::$sep . $item->term_id;
+
+ /* Taxonomy */
+ } elseif ( isset($item->term_id) ) {
+
+ $layout_id = 'archive' . HeadwayLayout::$sep . 'taxonomy' . HeadwayLayout::$sep . $item->taxonomy . HeadwayLayout::$sep . $item->term_id;
+
+ }
+
+ $visual_editor_url = home_url('/?visual-editor=true&ve-layout=' . urlencode($layout_id));
+
+ $actions['hw-visual-editor'] = '<a href="' . $visual_editor_url . '" title="Open in Headway Visual Editor" rel="permalink" target="_blank">Open in Visual Editor</a>';
+
+ return $actions;
+
+ }
+
+
+}
\ No newline at end of file
--- /dev/null
+<?php
+class HeadwayAdminInputs {
+
+
+ public static function generate($inputs, $table_class = 'form-table') {
+
+ echo '<table class="' . $table_class . '">';
+
+ $row_count = 0;
+
+ foreach ( $inputs as $input ) {
+
+ $row_count++;
+
+ if ( !method_exists(__CLASS__, 'input_' . $input['type']) )
+ continue;
+
+ $tooltip = (isset($input['tooltip']) && $input['tooltip']) ? '<span class="label-tooltip" title="' . esc_attr($input['tooltip']) . '"></span>' : null;
+ $description = (isset($input['description']) && $input['description']) ? '<p class="description">' . $input['description'] . '</p>' : null;
+ $suffix = (isset($input['suffix']) && $input['suffix']) ? $input['suffix'] : null;
+
+ $id = isset($input['id']) ? $input['id'] : null;
+
+ $row_class = ( $row_count == count($inputs) ) ? ' class="no-bottom-border"' : null;
+
+ if ( headway_get('value', $input) && !is_int(headway_get('value', $input)) )
+ $input['value'] = stripslashes(esc_attr($input['value']));
+
+ echo '<tr valign="top"' . $row_class . '>
+ <th scope="row">
+ <label for="' . $id . '">' . $input['label'] . $tooltip . '</label>
+ </th>
+ <td>';
+
+ call_user_func(array(__CLASS__, 'input_' . $input['type']), $input);
+
+ echo $suffix . $description;
+
+ echo '</td>
+ </tr>';
+
+ }
+
+ echo '</table>';
+
+ }
+
+
+ public static function input_text($input) {
+
+ $defaults = array(
+ 'size' => 'medium',
+ 'value' => null,
+ 'unit' => null,
+ 'tooltip' => null,
+ 'description' => null,
+ 'no-submit' => false,
+ 'masked' => false
+ );
+
+ $input = array_merge($defaults, $input);
+
+ $name_attr = $input['no-submit'] ? null : ' name="headway-admin-input[' . $input['id'] . ']"';
+ $type_attr = $input['masked'] ? 'password' : 'text';
+
+ echo '<input type="' . $type_attr . '" class="' . $input['size'] . '-text" value="' . $input['value'] . '" id="' . $input['id'] . '"' . $name_attr . '> ' . $input['unit'];
+
+ }
+
+
+ public static function input_password($input) {
+
+ $defaults = array(
+ 'size' => 'medium',
+ 'value' => null,
+ 'tooltip' => null,
+ 'description' => null,
+ 'no-submit' => false
+ );
+
+ $input = array_merge($defaults, $input);
+
+ $name_attr = $input['no-submit'] ? null : ' name="headway-admin-input[' . $input['id'] . ']"';
+
+ echo '<input type="password" class="' . $input['size'] . '-text" value="' . $input['value'] . '" id="' . $input['id'] . '"' . $name_attr . '>';
+
+ }
+
+
+ public static function input_paragraph($input) {
+
+ $defaults = array(
+ 'cols' => 30,
+ 'rows' => 5,
+ 'value' => null,
+ 'allow-tabbing' => false,
+ 'no-submit' => false
+ );
+
+ $input = array_merge($defaults, $input);
+
+ $allow_tabbing_class = $input['allow-tabbing'] ? 'class="allow-tabbing" ' : null;
+
+ $name_attr = $input['no-submit'] ? null : ' name="headway-admin-input[' . $input['id'] . ']"';
+
+ echo '<textarea ' . $allow_tabbing_class . 'cols="' . $input['cols'] . '" rows="' . $input['rows'] . '" id="' . $input['id'] . '"' . $name_attr . '>' . $input['value'] . '</textarea>';
+
+ }
+
+
+ public static function input_checkbox($input) {
+
+ $defaults = array(
+ 'no-submit' => false
+ );
+
+ $input = array_merge($defaults, $input);
+
+ echo '<fieldset>';
+
+ //Initialize counter for adding <br />'s
+ $checkbox_count = 0;
+
+ echo '<legend class="screen-reader-text">
+ <span>' . $input['label']. '</span>
+ </legend>';
+
+ foreach($input['checkboxes'] as $checkbox) {
+
+ $checkbox_count++;
+ $checkbox_checked = ( isset($checkbox['checked']) && $checkbox['checked'] == true ) ? ' checked="checked"' : null;
+
+ $name_attr = $input['no-submit'] ? null : ' name="headway-admin-input[' . $checkbox['id'] . ']"';
+
+ echo '<label for="' . $checkbox['id'] . '">';
+
+ //The hidden input is not needed if the no-submit attribute is set
+ echo $input['no-submit'] ? null : '<input type="hidden" value="0"' . $name_attr . ' />';
+
+ echo '<input type="checkbox" ' . $checkbox_checked . 'value="1" id="' . $checkbox['id'] . '"' . $name_attr . ' />
+ ' . $checkbox['label'] .
+ '</label>';
+
+ //Add in <br /> if there are multiple checkboxes
+ if ( count($input['checkboxes']) > 1 && $checkbox_count < count($input['checkboxes']) )
+ echo '<br />';
+
+ }
+
+ echo '</fieldset>';
+
+ }
+
+
+ public static function input_checkboxes($input) {
+
+ self::input_checkbox($input);
+
+ }
+
+
+ public static function input_select($input) {
+
+ $defaults = array(
+ 'value' => null,
+ 'no-submit' => false,
+ 'multiple' => false
+ );
+
+ $input = array_merge($defaults, $input);
+
+ $name_multiple_array = $input['multiple'] ? '[]' : null;
+ $multiple_attr = $input['multiple'] ? ' multiple="multiple" size="10"' : null;
+ $name_attr = $input['no-submit'] ? null : ' name="headway-admin-input[' . $input['id'] . ']' . $name_multiple_array . '"';
+
+ //If there are options in the multiselect and then the user wants to remove all of the selected options, it will not save.
+ //This is the workaround.
+ if ( !$input['no-submit'] && $input['multiple'] )
+ echo '<input type="hidden" value="0" name="headway-admin-input[' . $input['id'] . ']" />';
+
+ echo '<select class="postform" id="' . $input['id'] . '"' . $name_attr . $multiple_attr . '>';
+
+ foreach($input['options'] as $value => $label) {
+
+ if ( !$input['multiple'] )
+ $selected = ( $value == $input['value'] ) ? ' selected="selected"' : null;
+ else
+ $selected = ( is_array($input['value']) && in_array($value, $input['value']) ) ? ' selected="selected"' : null;
+
+ echo '<option value="' . $value . '"' . $selected . '>' . $label . '</option>';
+
+ }
+
+ echo '</select>';
+
+ }
+
+
+ public static function input_radio($input) {
+
+ $defaults = array(
+ 'no-submit' => false
+ );
+
+ $input = array_merge($defaults, $input);
+
+ $name_attr = $input['no-submit'] ? null : ' name="headway-admin-input[' . $input['id'] . ']"';
+
+ echo '<fieldset>';
+
+ //Initialize counter for adding <br />'s
+ $radio_count = 0;
+
+ echo '<legend class="screen-reader-text">
+ <span>' . $input['label']. '</span>
+ </legend>';
+
+ foreach($input['radios'] as $radio) {
+
+ $radio_count++;
+ $radio_checked = ( $radio['value'] === $input['value'] ) ? ' checked="checked"' : null;
+
+ echo '
+ <label for="' . $radio['value'] . '" class="radio-label">
+ <input type="radio" ' . $radio_checked . 'value="' . $radio['value'] . '" id="' . $radio['value'] . '"' . $name_attr . ' />
+ ' . $radio['label'] .
+ '</label>';
+
+ }
+
+ echo '</fieldset>';
+
+ }
+
+
+}
\ No newline at end of file
--- /dev/null
+#adminmenu li[class*="toplevel_page_headway"] .wp-menu-image img {
+ width: 16px;
+ height: 16px;
+}
+
+#customize-current-theme-link {
+ display: none;
+}
+
+#headway-admin-notifications {
+ position: fixed;
+ top: 45px;
+ right: 20px;
+ z-index: 14;
+}
+
+#headway-admin-notifications div {
+ min-width: 200px;
+ max-width: 400px;
+}
\ No newline at end of file
--- /dev/null
+/* Important Stuff */
+ .wrap.headway-page h2 {
+ margin-bottom: 15px;
+ }
+
+/* Regular Elements */
+ abbr, acronym {
+ background: #eee;
+ cursor: help;
+ letter-spacing: 1px;
+ text-transform: uppercase;
+ }
+
+ div.hr {
+ background: transparent;
+ border-top: 1px solid #eaeaea;
+ clear: both;
+ height: 1px;
+ margin: 24px 0;
+ overflow: hidden;
+ display: block;
+ width: 100%;
+ }
+/* End Regular Elements */
+
+
+/* Messages */
+ /* Reset */
+ div.reset-alert {
+ width: 700px;
+ }
+
+ div.reset-alert input.alert-big-button {
+ color: #832525;
+ }
+ /* End Reset */
+
+ /* Alert Buttons */
+ input.alert-big-button, .wp-core-ui input.alert-big-button {
+ font-size: 15px !important;
+ width: 300px;
+ height: 34px;
+ position: relative;
+ margin: 15px 0 20px -158px;
+ left: 50%;
+ }
+ /* End Alert Buttons */
+/* End Messages */
+
+
+/* Wrapper */
+ div.headway-small-wrap {
+ max-width: 1000px;
+ }
+/* End Wrapper */
+
+
+/* Titles */
+ h3.title {
+ margin: 30px 0 15px;
+ }
+
+ h3.title code { font-size: 1em; }
+
+ h3.title-hr {
+ border-top: 1px solid #eee;
+ padding-top: 30px;
+ }
+/* End Titles */
+
+
+/* Tabs */
+ h2.big-tabs-tabs {
+ opacity: 0;
+ margin-bottom: 20px;
+ }
+
+ h2.big-tabs-tabs a.nav-tab-active { color: #D54E21; }
+ h2.big-tabs-tabs a:hover:not(.nav-tab-active) { color: #464646; }
+
+ h2.big-tabs-tabs a.nav-tab-inactive {
+ opacity: .4;
+ cursor: help;
+ color: #aaa !important;
+ }
+
+ div.big-tab {
+ max-width: 1100px;
+ display: none;
+ }
+
+ div.big-tab-fading {
+ z-index: 1;
+ }
+
+ div.big-tab-visible { }
+/* End Tabs */
+
+
+/* Inputs */
+ table.form-table tr {
+ border-bottom: 1px solid #f3f3f3;
+ }
+
+ table.form-table tr.no-bottom-border {
+ border-bottom: none;
+ }
+
+ table.form-table tr th, table.form-table tr td {
+ padding: 15px 10px;
+ }
+
+ table.form-table label {
+ user-select: none;
+ -webkit-user-select: none;
+ }
+
+ table.form-table textarea {
+ resize: none;
+ }
+
+ table.form-table select {
+ width: 150px;
+ }
+
+ label span.label-tooltip {
+ width: 14px;
+ height: 13px;
+ background: url(../images/help-grey.png);
+ display: inline-block;
+ text-indent: -9999px;
+ margin: 0 0 -1px 8px;
+ cursor: help;
+ opacity: .5;
+ }
+
+ label span.label-tooltip:hover { opacity: .9; }
+
+ label.radio-label {
+ margin-right: 15px;
+ }
+
+ div.hr-submit {
+ margin: 45px 0 20px;
+ }
+
+ p.submit {
+ padding-top: 0;
+ }
+
+ table.form-table input.large-text {
+ width: 350px !important;
+ }
+
+ input.headway-save {
+ width: 220px;
+ height: 28px !important;
+ }
+/* End Inputs */
+
+
+/* Input Descriptions and Tooltips */
+ p.description {
+ clear: both;
+ margin: 0;
+ }
+/* End Input Descripts and Tooltips */
+
+
+/* Getting Started Page */
+ h3.headway-sub-title {
+ color: #777;
+ font-size: 16px;
+ line-height: 25px;
+ font-weight: normal;
+ }
+
+ div#headway-getting-started-ve-link-container {
+ margin: 15px 0 15px -250px;
+ position: relative;
+ left: 50%;
+ float: left;
+ clear: both;
+ }
+
+ div#headway-getting-started-ve-link-container p { margin-left: 10px; }
+
+ div#headway-getting-started-license-notice {
+ font-size: 13px;
+ }
+
+ input.headway-big-button {
+ font-size: 18px !important;
+ width: 500px;
+ height: 50px !important;
+ }
+/* End Getting Started Page */
+
+
+/* Templates Page */
+ form#upload-skin {
+ display: none;
+ }
+
+ .headway-templates .headway-template .theme-actions .delete-template {
+ color: #A00;
+ text-decoration: none;
+ border-color: rgba(0, 0, 0, 0);
+ box-shadow: none;
+ background: rgba(0, 0, 0, 0);
+ }
+
+ .headway-templates .headway-template .theme-actions .delete-template:hover {
+ background: #D54E21;
+ color: #FFF;
+ border-color: #D54E21;
+ }
+
+ .headway-templates .headway-template.missing-image .theme-screenshot {
+ background: url(../../visual-editor/images/logo.png) no-repeat 50% 50% !important;
+ }
+
+ button#template-export-image-button {
+ padding-left: 5px;
+ }
+
+ button#template-export-image-button span {
+ line-height: 18px;
+ display: inline-block;
+ width: 18px;
+ height: 18px;
+ color: #888;
+ vertical-align: text-top;
+ margin: 0 2px;
+ }
+
+ button#template-export-image-button span::after {
+ font-family: 'dashicons';
+ content: "\f128";
+ font: normal 18px/1 'dashicons';
+ speak: none;
+ -webkit-font-smoothing: antialiased;
+ -moz-osx-font-smoothing: grayscale;
+ }
+
+ img#template-export-image-preview {
+ max-width: 340px;
+ margin-top: 15px;
+ border: 1px solid #ddd;
+ }
+
+ /* Loading indicator */
+ @-webkit-keyframes spin {
+ from {
+ -webkit-transform: rotate(0deg);
+ }
+ to {
+ -webkit-transform: rotate(360deg);
+ }
+ }
+
+ @-moz-keyframes spin {
+ from {
+ -moz-transform: rotate(0deg);
+ }
+ to {
+ -moz-transform: rotate(360deg);
+ }
+ }
+
+ @-ms-keyframes spin {
+ from {
+ -ms-transform: rotate(0deg);
+ }
+ to {
+ -ms-transform: rotate(360deg);
+ }
+ }
+
+ .template-installing .template-loading-indicator {
+ position: absolute;
+ display: block;
+ width: 80px;
+ height: 80px;
+ left: 50%;
+ top: 50%;
+ margin: -40px 0 0 -40px;
+ text-align: center;
+ -webkit-animation: spin 1500ms infinite linear;
+ -moz-animation: spin 1500ms infinite linear;
+ animation: spin 1500ms infinite linear;
+ background-image: url(data:image/svg+xml;base64,PHN2ZyB2ZXJzaW9uPSIxLjEiIHhtbG5zPSJodHRwOi8vd3d3LnczLm9yZy8yMDAwL3N2ZyIgZGF0YS1pY29uPSJjb2ciIHdpZHRoPSIxMjgiIGhlaWdodD0iMTI4IiBjbGFzcz0iaWNvbmljIGljb25pYy1jb2cgaWNvbmljLW9yaWVudGF0aW9uLXNxdWFyZSIgdmlld0JveD0iMCAwIDEyOCAxMjgiPgogIDxnIGRhdGEtd2lkdGg9IjEyOCIgZGF0YS1oZWlnaHQ9IjEyOCIgY2xhc3M9Imljb25pYy1sZyIgZGlzcGxheT0iaW5saW5lIj4KICAgIDxwYXRoIGQ9Ik0xMjggNzMuOXYtMTkuOWwtMTQuMy0zLjZjLTEuMi00LjItMi44LTguMy01LTEybDcuNS0xMi43LTE0LjEtMTQuMS0xMi43IDcuNmMtMy43LTIuMS03LjgtMy44LTEyLTVsLTMuNS0xNC4yaC0xOS45bC0zLjYgMTQuM2MtNC4yIDEuMi04LjMgMi44LTEyIDVsLTEyLjctNy41LTE0IDE0IDcuNiAxMi43Yy0yLjEgMy43LTMuOCA3LjgtNSAxMmwtMTQuMyAzLjZ2MTkuOWwxNC4zIDMuNmMxLjIgNC4yIDIuOCA4LjMgNSAxMmwtNy41IDEyLjcgMTQuMSAxNC4xIDEyLjctNy42YzMuNyAyLjEgNy44IDMuOCAxMiA1bDMuNyAxNC4zaDE5LjdsMy42LTE0LjNjNC4yLTEuMiA4LjMtMi44IDEyLTVsMTIuNyA3LjUgMTQuMS0xNC4xLTcuNi0xMi43YzIuMS0zLjcgMy44LTcuOCA1LTEybDE0LjItMy42em0tNjQgMjQuMWMtMTguOCAwLTM0LTE1LjItMzQtMzRzMTUuMi0zNCAzNC0zNCAzNCAxNS4yIDM0IDM0LTE1LjIgMzQtMzQgMzR6IgogICAgY2xhc3M9Imljb25pYy1jb2ctYm9keSBpY29uaWMtZWxlbWVudC1maWxsIiAvPgogIDwvZz4KPC9zdmc+);
+ background-size: 80px;
+ opacity: .6;
+ }
+
+ .headway-templates .headway-template.missing-image.template-installing div.theme-screenshot {
+ background: none !important;
+ }
+/* End Templates */
+
+
+/* Options Page */
+ /* SEO Tab */
+ h3#seo-templates-title {
+ margin: 30px 0 -25px 125px;
+ font-size: 1.3em;
+ }
+
+ div#seo-templates-header {
+ width: auto;
+ float: left;
+ border: 1px solid #e5e5e5;
+ padding: 5px;
+ border-bottom: none;
+ border-radius: 8px 8px 0 0;
+ background: #fff;
+ margin: 0 0 -1px 800px;
+ position: relative;
+ background: #fafafa;
+ }
+
+ div#seo-templates-header span {
+ top: 9px;
+ left: -140px;
+ position: absolute;
+ width: 130px;
+ text-align: right;
+ color: #999;
+ }
+
+ div#seo-templates-header select {
+ width: 150px;
+ }
+
+ div#seo-templates-inputs {
+ width: 850px;
+ padding: 15px;
+ border: 1px solid #e5e5e5;
+ border-radius: 8px;
+ clear: both;
+ margin: 0 0 0 110px;
+ background: #fafafa;
+ box-shadow: 1px 1px 0 #ddd;
+ }
+
+ div#seo-templates-inputs th {
+ width: 130px;
+ }
+
+ div#seo-templates-inputs input.large-text, div#seo-templates-inputs textarea {
+ width: 100%;
+ }
+
+ h3#seo-templates-advanced-options-title span {
+ cursor: pointer;
+ margin: 0 0 0 5px;
+ font-size: 11px;
+ font-weight: bold;
+ color: #21759B;
+ padding: 5px 10px;
+ background: #eee;
+ text-shadow: 1px 1px 0 #fff;
+ border-radius: 3px;
+ box-shadow: 1px 1px 0 #ddd;
+ }
+
+ h3#seo-templates-advanced-options-title span:hover {
+ color: #D54E21;
+ }
+
+ div#seo-templates-advanced-options {
+ display: none;
+ }
+
+ p#seo-description {
+ margin: 25px 0 -5px 0;
+ }
+ /* End SEO Tab */
+
+ /* License Validation */
+ div.license-key-input-table {
+ border: 1px solid #dadada;
+ border-radius: 5px;
+ background: #fff;
+ display: block;
+ padding: 0 30px 10px;
+
+ margin: 10px 0 -10px;
+ }
+
+ span.license-key-validation {
+ margin: 0 0 0 6px;
+ padding-bottom: 1px;
+ }
+
+ span.license-key-validation.red {
+ border-bottom: 1px dotted #900;
+ }
+ /* End License Validation */
+/* End Options Page */
+
+
+/* Tools */
+ /* System Info */
+ textarea#system-info-textarea {
+ font-family: 'courier new', monospace;
+ margin: 10px 0 0 0;
+ width: 900px;
+ height: 400px;
+ }
+
+/* End Tools */
+
+
+
+/* Updates */
+ .headway-update-backup-reminder {
+ width: 650px !important;
+ padding: 5px 20px !important;
+ }
+/* End Updates */
+
+
+/* Colored Text */
+ span.red {
+ color: #900;
+ }
+
+ span.green {
+ color: #090;
+ }
+/* End Colored Text */
+
+
+/* Obligatory stupid jQuery stuff */
+ .ui-helper-hidden {
+ display: none;
+ }
+
+ .ui-helper-hidden-accessible {
+ left: -9999px;
+ position: absolute;
+ }
+
+ .ui-helper-reset {
+ border: 0;
+ font-size: 100%;
+ line-height: 1.3;
+ list-style: none;
+ margin: 0;
+ outline: 0;
+ padding: 0;
+ text-decoration: none;
+ }
+
+ .ui-helper-clearfix:after {
+ clear: both;
+ content: ".";
+ display: block;
+ height: 0;
+ visibility: hidden;
+ }
+
+ .ui-helper-clearfix {
+ display: inline-block;
+ }
+
+ * html .ui-helper-clearfix {
+ height: 1%;
+ }
+
+ .ui-helper-clearfix {
+ display: block;
+ }
+
+ .ui-helper-zfix {
+ filter: alpha(opacity=0);
+ height: 100%;
+ left: 0;
+ opacity: 0;
+ position: absolute;
+ top: 0;
+ width: 100%;
+ }
+
+ .ui-widget-overlay {
+ height: 100%;
+ left: 0;
+ position: absolute;
+ top: 0;
+ width: 100%;
+ }
+
+/* Getting Started page */
+.headway-getting-started-wrap .headway-sub-title {
+ font-size: 18px;
+ margin: 20px 0;
+}
+
+.wrap .headway-getting-started-wrap h2 {
+ clear: both;
+ margin-top: 20px;
+ margin-bottom: 10px;
+ width: 100%;
+}
+
+.headway-sub-title img {
+ vertical-align: middle;
+ margin-right: 10px;
+}
+
+.headway-infobox-row {
+ margin-top: 3%;
+}
+
+.headway-infobox-row::after {
+ clear: both;
+ content: ".";
+ display: block;
+ height: 0;
+ visibility: hidden;
+}
+
+.headway-infobox {
+ background: #fdfdfd;
+ padding: 13px 25px;
+ min-height: 66px;
+ float: left;
+ width: 42%;
+ border: solid 1px #ccc;
+}
+
+.headway-infobox-icon {
+ width: 43%;
+ padding: 0 20px;
+ height: 76px;
+ line-height: 73px;
+}
+
+.headway-infobox.inrow {
+ margin-right: 3%;
+}
+
+.headway-infobox.big {
+ min-height: 150px;
+}
+
+.headway-infobox span.dashicons {
+ font-size: 46px;
+ color: #f36341;
+ margin-right: 10px;
+ width: 46px;
+ height: 76px;
+ line-height: 76px;
+ position: relative;
+ vertical-align: middle;
+ float: left;
+}
+
+.headway-infobox span.dashicons.bigfix {
+ font-size: 40px;
+}
+
+.headway-infobox a.big {
+ font-size: 22px;
+ text-decoration: none;
+}
+
+.headway-infobox a:hover {
+ text-decoration: underline;
+}
+
+.headway-infobox.big h3 {
+ font-size: 18px;
+ color: #555;
+ font-weight: normal;
+ margin-top: 10px;
+}
--- /dev/null
+/* ADMIN META BOXES */
+div.postbox tr.form-field input.check, tr.form-field input.radio { width: 16px; }
+div.postbox table.headway-admin-meta-box tr.label:first-child th { padding: 10px 10px 3px 10px; }
+div.postbox table.headway-admin-meta-box tr.label { margin-top: 15px; }
+div.postbox table.headway-admin-meta-box tr.label th { padding: 20px 10px 3px 10px; }
+div.postbox table.headway-admin-meta-box tr.label th label { font-weight: bold; font-size: 14px; color: #444; }
+div.postbox table.headway-admin-meta-box tr.description td { padding: 0 10px 10px; }
+div.postbox table.headway-admin-meta-box tr.description p { color: #777; font-size: 11.5px; margin: -3px 0 0 5px !important; }
+div.postbox table.headway-admin-meta-box label.selectit { font-size: 12px; color: #333; }
+div.postbox table.headway-admin-meta-box label.selectit input { margin: -4px 3px 0 0; }
+div.postbox table.headway-admin-meta-box input[type='text'], div.postbox table.headway-admin-meta-box textarea { width: 100% !important; }
+
+div.postbox table.headway-admin-meta-box select { width: 90%; }
+
+div.postbox table.headway-admin-meta-box {
+ margin-top: 10px;
+}
+
+div.postbox div.alert { margin: 15px 5px 0; }
+
+#poststuff div.postbox[id^="headway-admin-meta-box-"] h3.hndle {
+ background: url(../images/headway-32.png);
+ background-size: 16px;
+ background-repeat: no-repeat;
+ padding-left: 36px;
+ background-position: 12px 50%;
+}
+/* END ADMIN META BOXES */
+
+/* LIVE SEO PREVIEW */
+#seo-preview {
+ display: block;
+ background: #fff;
+ border: 1px solid #bbb;
+ margin: 10px 10px 0;
+ padding: 8px;
+ font-family: arial,sans-serif;
+ color: #000;
+ font-size: 13px;
+ width: 540px;
+ clear: both;
+}
+
+#seo-preview h4 {
+ text-decoration: underline;
+ color: #1111CC;
+ font-size: 16px;
+ font-weight: normal;
+ margin: 0;
+ cursor: pointer;
+}
+
+#seo-preview p#seo-preview-description {
+ line-height: 16px;
+ margin: 2px 0 0;
+ font-size: 13px;
+ display: block;
+ cursor: pointer;
+}
+
+#seo-preview p#seo-preview-bottom {
+ color: #767676;
+ margin: 0;
+ font-size: 13px;
+}
+
+ #seo-preview p#seo-preview-bottom span {
+ color: #4272DB;
+ }
+
+ #seo-preview p#seo-preview-bottom span#seo-preview-url {
+ color: #0E774A;
+ }
+
+h4#seo-preview-title {
+ color: #444;
+ font-size: 14px;
+ font-weight: bold;
+ margin: 15px 0 15px 10px;
+ display: block;
+ clear: both;
+ float: left;
+ vertical-align: middle;
+}
+
+small#seo-preview-disclaimer {
+ color:#777;
+ margin: 5px 0 4px 12px;
+ float:left;
+ font-style: italic;
+}
+/* END LIVE SEO PREVIEW */
\ No newline at end of file
--- /dev/null
+(function($) {
+$(document).ready(function() {
+
+ /* Big Tabs */
+ setupBigTabs = function() {
+
+ if ( $('h2.big-tabs-tabs').length === 0 )
+ return;
+
+ //Bind tab buttons
+ $('h2.big-tabs-tabs a.nav-tab').on('click', function(event){
+
+ var tabID = $(this).attr('href').replace('#tab-', '');
+
+ //Stop all other animations
+ $('div.big-tabs-container div.big-tab, div.hr-submit, p.submit').stop(true, true);
+
+ //Check to make sure tab exists
+ if ( $('div.big-tabs-container div#tab-' + tabID + '-content').length === 0 )
+ return false;
+
+ //Set tab as active
+ $(this).siblings('.nav-tab-active').removeClass('nav-tab-active');
+ $(this).addClass('nav-tab-active');
+
+ //Hide the submit button so it can be faded in later
+ $('div.hr-submit, p.submit').hide();
+
+ //Hide/show the tabs accordingly
+ $('div.big-tabs-container div.big-tab-visible')
+ .removeClass('big-tab-visible')
+ .hide();
+
+ $('div.big-tabs-container div#tab-' + tabID + '-content')
+ .addClass('big-tab-visible')
+ .addClass('big-tab-fading')
+ .fadeIn(200, function() {
+
+ $(this).removeClass('big-tab-fading');
+
+ $('div.hr-submit, p.submit').fadeIn(200);
+
+ });
+
+ });
+
+ //Setup display for tabs and tab containers
+ if ( window.location.hash.indexOf('tab-') !== -1 && $('div.big-tabs-container div#tab-' + window.location.hash.replace('#tab-', '') + '-content').length === 1 ) {
+
+ var tabID = window.location.hash.replace('#tab-', '');
+ var tab = $('h2.big-tabs-tabs a[href="#tab-' + tabID + '"]');
+
+ //Set tab as active
+ tab.addClass('nav-tab-active');
+
+ //Show tab's container
+ $('div.big-tabs-container div#tab-' + tabID + '-content').fadeIn(200, function() {
+ $(this).addClass('big-tab-visible');
+ });
+
+ } else {
+
+ var firstTab = $('h2.big-tabs-tabs a.nav-tab:first');
+ var tabID = firstTab.attr('href').replace('#tab-', '');
+
+ //Set the tab as active
+ firstTab.addClass('nav-tab-active');
+
+ //Show first tab's container
+ $('div.big-tabs-container div#tab-' + tabID + '-content').fadeIn(200, function() {
+ $(this).addClass('big-tab-visible');
+ });
+
+ }
+
+ //Show the tabs
+ $('h2.big-tabs-tabs').animate({opacity: 1}, 200);
+
+ //Show the submit HR and submit button
+ setTimeout(function(){
+ $('div.hr-submit, p.submit').fadeIn(200);
+ }, 300);
+
+ }
+
+ //Call the function now
+ setupBigTabs();
+ /* End Big Tabs */
+
+
+ /* Tooltips */
+ if ( typeof $().qtip === 'function' ) {
+
+ $('label span.label-tooltip').qtip({
+ style: {
+ classes: 'qtip-headway'
+ },
+ position: {
+ my: 'bottom left',
+ at: 'top right'
+ }
+ });
+
+ }
+ /* End Tooltips */
+
+
+ /* Textareas */
+ if ( $('textarea.allow-tabbing').length > 0 )
+ $('textarea.allow-tabbing').tabby();
+
+
+ /* System Info */
+ if ( $('textarea#system-info-textarea').length > 0 ) {
+
+ $('textarea#system-info-textarea').qtip({
+ style: {
+ classes: 'qtip-headway'
+ },
+ position: {
+ my: 'bottom center',
+ at: 'top center'
+ }
+ });
+
+ $('textarea#system-info-textarea').bind('mouseup', function() {
+
+ $(this)
+ .focus()
+ .select();
+
+ });
+
+ }
+
+
+ /* SEO Templates */
+ if ( $('div#seo-templates').length === 1 ) {
+
+ fetchSEOTemplateValues = function(currentPage) {
+
+ seoInputs.each(function() {
+
+ var value = $('input#seo-' + currentPage + '-' + $(this).attr('id')).val();
+
+ /*
+ Since checkboxes and traditional inputs are handled differently we have to either
+ set the value of regular inputs or set the checkbox as checked.
+ */
+ if ( $(this).attr('type') != 'checkbox' ) {
+
+ $(this).val(value);
+
+ } else {
+
+ if ( value == 1 ) {
+ $(this).attr('checked', true);
+ } else {
+ $(this).attr('checked', false);
+ }
+
+ }
+
+ });
+
+ }
+
+ /* Set Up Initial Values */
+ var currentPage = $('div#seo-templates-header select').val();
+ var seoInputs = $('div#seo-templates-inputs input, div#seo-templates-inputs textarea');
+
+ fetchSEOTemplateValues(currentPage);
+
+ /* Bind the page select */
+ $('div#seo-templates-header select').bind('change', function() {
+
+ currentPage = $(this).val();
+
+ fetchSEOTemplateValues(currentPage);
+
+ });
+
+ /* Bind the inputs */
+ seoInputs.bind('click blur', function() {
+
+ var hidden = $('input#seo-' + currentPage + '-' + $(this).attr('id'));
+
+ /*
+ Since checkboxes and traditional inputs are handled differently we have to either
+ set the value of regular inputs or set the checkbox as checked.
+ */
+ if ( $(this).attr('type') != 'checkbox' ) {
+
+ hidden.val($(this).val());
+
+ } else {
+
+ if ( $(this).is(':checked') ) {
+ hidden.val('1');
+ } else {
+ hidden.val('0');
+ }
+
+ }
+
+ });
+
+ /* Bind the advanced options toggle */
+ $('h3#seo-templates-advanced-options-title span').bind('click', function(event) {
+
+ if ( !$(this).hasClass('seo-advanced-visible') ) {
+
+ $('div#seo-templates-advanced-options').fadeIn(250);
+ $(this).html('Hide ↑').addClass('seo-advanced-visible');
+
+ jQuery.scrollTo($('h3#seo-templates-advanced-options-title'), 500, {
+ easing: 'swing',
+ offset: {top:-10}
+ });
+
+ } else {
+
+ $('div#seo-templates-advanced-options').fadeOut(200);
+ $(this).html('Show ↓').removeClass('seo-advanced-visible');
+
+ jQuery.scrollTo($('div#seo-templates'), 300, {
+ easing: 'swing',
+ offset: {top:-40}
+ });
+
+ }
+
+ });
+
+ }
+ /* End SEO Templates */
+
+
+ /* Reset */
+ if ( $('form#reset-headway').length === 1 ) {
+
+ $('input#reset-headway-submit').bind('click', function() {
+
+ return confirm('Warning! ALL existing Headway data, including, but not limited to: Blocks, Design Settings, and Headway Search Engine Optimization settings will be deleted. This cannot be undone. \'OK\' to delete, \'Cancel\' to stop');
+
+ });
+
+ }
+ /* End Reset */
+
+});
+})(jQuery);
\ No newline at end of file
--- /dev/null
+jQuery(document).ready(function($) {
+
+ showNotification = function(args) {
+
+ var notification = $('<div id="headway-notification-' + args.id + '" class="updated below-h2"><p>' + args.message + '</p></div>');
+
+ notification.appendTo('#headway-admin-notifications');
+
+ if ( typeof args.closeTimer != 'undefined' && args.closeTimer ) {
+
+ setTimeout(function() {
+ notification.fadeOut(1000, function() {
+ $(this).remove();
+ });
+ }, args.closeTimer);
+
+ }
+
+ return notification;
+
+ }
+
+ showErrorNotification = function(args) {
+
+ var notification = $('<div id="headway-notification-' + args.id + '" class="error below-h2"><p>' + args.message + '</p></div>');
+
+ notification.appendTo('#headway-admin-notifications');
+
+ return notification;
+
+ }
+
+ updateNotification = function(id, message) {
+
+ return $('#headway-notification-' + id).children('p').html(message);
+
+ }
+
+ hideNotification = function(id) {
+
+ $('#headway-notification-' + id).fadeOut(500);
+
+ }
+
+
+ var templates = {
+ init: function() {
+
+ templates.bind();
+ templates.setupViewModel();
+
+ },
+
+ setupViewModel: function() {
+
+ Headway.viewModels.templates = {
+ templates: ko.observableArray(Headway.templates),
+ active: ko.observable(Headway.templateActive),
+ activateSkin: function() {
+
+ var skin = this;
+
+ /* Don't try to activate if it's already activated */
+ if ( skin.id == Headway.viewModels.templates.active().id )
+ return;
+
+ /* Send AJAX Request to switch skins */
+ $.post(Headway.ajaxURL, {
+ security: Headway.security,
+ action: 'headway_visual_editor',
+ method: 'switch_skin',
+ skin: skin.id
+ }, function(response) {
+
+ /* Set this skin as the activated skin */
+ Headway.viewModels.templates.active(skin);
+
+ showNotification({
+ id: 'skin-switched',
+ message: skin.name + ' activated.',
+ closeTimer: 5000,
+ success: true
+ });
+
+ });
+
+ },
+ deleteSkin: function() {
+
+ var skin = this;
+
+ if ( !confirm('Are you sure you want to delete this template? All design settings, blocks, and layout settings for this template will be deleted.') )
+ return;
+
+ /* Send AJAX Request to switch skins */
+ $.post(Headway.ajaxURL, {
+ security: Headway.security,
+ action: 'headway_visual_editor',
+ method: 'delete_skin',
+ skin: skin.id
+ }, function(response) {
+
+ if ( response != 'success' ) {
+
+ return showErrorNotification({
+ id: 'unable-to-delete-skin',
+ message: 'Unable to delete template.',
+ });
+
+ } else {
+
+ showNotification({
+ id: 'skin-deleted',
+ message: skin.name + ' deleted.',
+ closeTimer: 5000,
+ success: true
+ });
+
+ }
+
+ Headway.viewModels.templates.templates.remove(skin);
+
+ });
+
+ }
+ }
+
+ ko.applyBindings(Headway.viewModels.templates, $('.headway-templates').get(0));
+
+ },
+
+ bind: function() {
+
+ /* Skin Upload button */
+ $('#install-template').on('click', function() {
+
+ if ( $(this).is('[disabled]') )
+ return;
+
+ $('#upload-skin input[type="file"]').first().trigger('click');
+
+ });
+
+
+ $('#upload-skin input[type="file"]').on('change', function(event) {
+
+ if ( event.target.files[0].name.split('.').slice(-1)[0] != 'json' )
+ return alert("Invalid template.\n\nPlease make sure that you have unzipped the Headway Template. You should be uploading a .json file.");
+
+ var skinFile = $(this).get(0).files[0];
+
+ if ( skinFile && typeof skinFile.name != 'undefined' && typeof skinFile.type != 'undefined' ) {
+
+ var skinReader = new FileReader();
+
+ skinReader.onload = function(e) {
+
+ var skinJSON = e.target.result;
+ var skin = JSON.parse(skinJSON);
+
+ /* Check to be sure that the JSON file is a layout */
+ if ( skin['data-type'] != 'skin' )
+ return alert('Cannot load template. Please insure that the file is a valid Headway Template.');
+
+ /* Deactivate install template button */
+ $('#install-template').attr('disabled', 'true');
+
+ showNotification({
+ id: 'installing-skin',
+ message: 'Installing Template: ' + skin['name'],
+ closeTimer: false,
+ closable: false
+ });
+
+ Headway.viewModels.templates.templates.push({
+ description: null,
+ name: 'Installing ' + skin['name'] + '...',
+ installing: true,
+ id: null,
+ author: null,
+ active: false,
+ version: null
+ });
+
+ installSkin(skin);
+
+ }
+
+ skinReader.readAsText(skinFile);
+
+ } else {
+
+ alert('Cannot load template. Please insure that the file is a valid Headway Template.');
+
+ }
+
+ });
+
+
+ installSkin = function(skin) {
+
+ if ( typeof skin['image-definitions'] == 'object' && Object.keys(skin['image-definitions']).length ) {
+
+ var numberOfImages = Object.keys(skin['image-definitions']).length;
+ var importedImages = {};
+
+ showNotification({
+ id: 'skin-importing-images',
+ message: 'Importing Images...',
+ closeTimer: false,
+ closable: false
+ });
+
+ var importSkinImage = function(imageID) {
+
+ /* Update notification for image import */
+ var imageIDInt = parseInt(imageID.replace('%%', '').replace('IMAGE_REPLACEMENT_', ''));
+
+ updateNotification('skin-importing-images', 'Importing Image (' + imageIDInt + '/' + numberOfImages + ')');
+
+ /* Do the AJAX request to upload the image */
+ var imageImportXhr = $.post(Headway.ajaxURL, {
+ security: Headway.security,
+ action: 'headway_visual_editor',
+ method: 'import_image',
+ imageID: imageID,
+ imageContents: skin['image-definitions'][imageID]
+ }, null, 'json')
+ .always(function(response) {
+
+ /* Update notification */
+
+ /* Check if error. If so, fire notification */
+ if ( typeof response['url'] == 'undefined' ) {
+ var response = 'ERROR';
+
+ showNotification({
+ id: 'skin-importing-images-error-' + imageIDInt,
+ message: 'Error Importing Image #' + imageIDInt,
+ closeTimer: 10000,
+ closable: true,
+ error: true
+ });
+ }
+
+ /* Store uploaded image URL */
+ importedImages[imageID] = response;
+
+ /* Check if there are more images to upload. If so, upload them. */
+ var nextImageID = '%%IMAGE_REPLACEMENT_' + (parseInt(imageID.replace('%%', '').replace('IMAGE_REPLACEMENT_', '')) + 1) + '%%';
+
+ if ( typeof skin['image-definitions'][nextImageID] != 'undefined' ) {
+
+ importSkinImage(nextImageID);
+
+ /* If not, finalize skin installation */
+ } else {
+
+ /* Hide notification since images are uploaded is complete */
+ hideNotification('skin-importing-images');
+
+ /* Finalize */
+ skin['imported-images'] = importedImages;
+
+ finalizeSkinInstallation(skin);
+
+ }
+
+ });
+ /* End doing AJAX request to upload image */
+
+ }
+
+ importSkinImage('%%IMAGE_REPLACEMENT_1%%');
+
+ } else {
+
+ finalizeSkinInstallation(skin);
+
+ }
+
+ }
+
+
+ finalizeSkinInstallation = function(skin) {
+
+ /* Remove image definitions from skin array since they've already been imported */
+ if ( typeof skin['image-definitions'] != 'undefined' )
+ delete skin['image-definitions'];
+
+ /* Do AJAX request to install skin */
+ return $.post(Headway.ajaxURL, {
+ security: Headway.security,
+ action: 'headway_visual_editor',
+ method: 'install_skin',
+ skin: JSON.stringify(skin)
+ }).done(function(data) {
+
+ var skin = data;
+
+ if ( typeof skin['error'] !== 'undefined' || typeof skin['name'] == 'undefined' ) {
+
+ if ( typeof skin['error'] == 'undefined' )
+ skin['error'] = 'Could not install template.';
+
+ return showNotification({
+ id: 'skin-not-installed',
+ message: 'Error: ' + skin['error'],
+ closable: true,
+ closeTimer: false,
+ error: true
+ });
+
+ }
+
+ hideNotification('installing-skin');
+
+ showNotification({
+ id: 'skin-installed',
+ message: skin['name'] + ' successfully installed.',
+ closeTimer: 5000,
+ success: true
+ });
+
+ /* Pop off the last skin which is going to be the loader */
+ Headway.viewModels.templates.templates.pop();
+ Headway.viewModels.templates.templates.push($.extend({}, {description: null}, skin));
+
+ /* Reactive install template button */
+ $('#install-template').removeAttr('disabled');
+
+ }).fail(function(data) {
+
+ showNotification({
+ id: 'skin-not-installed',
+ message: 'Error: Could not install template.',
+ closable: true,
+ closeTimer: false,
+ error: true
+ });
+
+ });
+
+ }
+
+ /* Skin Export */
+ $('#export-template-submit').on('click', function(event) {
+
+ event.preventDefault();
+
+ var params = {
+ 'security': Headway.security,
+ 'action': 'headway_visual_editor',
+ 'method': 'export_skin',
+ 'skin-info': $('#export-template-form').serialize()
+ }
+
+ var exportURL = Headway.ajaxURL + '?' + $.param(params);
+
+ return window.open(exportURL);
+
+ });
+
+ /* Export Template Image */
+ var HWTemplateExportImageFrame;
+
+ $('#template-export-image-button').on('click', function (event) {
+
+ event.preventDefault();
+
+ // If the media frame already exists, reopen it.
+ if (HWTemplateExportImageFrame) {
+ HWTemplateExportImageFrame.open();
+ return;
+ }
+
+ // Create the media frame.
+ HWTemplateExportImageFrame = wp.media.frames.file_frame = wp.media({
+ title: 'Select Image for Template',
+ button: {
+ text: 'Select Image',
+ },
+ multiple: false
+ });
+
+ // When an image is selected, run a callback.
+ HWTemplateExportImageFrame.on('select', function () {
+ attachment = HWTemplateExportImageFrame.state().get('selection').first().toJSON();
+
+ $('input#template-export-image').val(attachment.url);
+
+ $('img#template-export-image-preview')
+ .attr('src', attachment.url)
+ .show();
+
+ });
+
+ HWTemplateExportImageFrame.open();
+ });
+
+
+ /* Add Blank Skin */
+ $('#add-blank-template').on('click', function() {
+
+ var skinName = window.prompt('Please enter a name for the new template:' , 'Template Name');
+
+ if ( !skinName || $('#notification-adding-blank-skin').length )
+ return;
+
+ /* Perform AJAX request to create the skin and get the ID and name */
+ $.post(Headway.ajaxURL, {
+ security: Headway.security,
+ action: 'headway_visual_editor',
+ method: 'add_blank_skin',
+ skinName: skinName
+ }, function(response) {
+
+ var skinID = response['id'];
+ var skinName = response['name'];
+
+ showNotification({
+ id: 'added-blank-skin',
+ message: skinName + ' successfully added.',
+ closeTimer: 5000,
+ success: true
+ });
+
+ Headway.viewModels.templates.templates.push({
+ id: skinID,
+ name: skinName,
+ version: null,
+ author: null,
+ description: null
+ });
+
+ }, 'json');
+
+ });
+
+ }
+ }
+
+ templates.init();
+
+});
\ No newline at end of file
--- /dev/null
+(function($) {
+$(document).ready(function() {
+
+ /* SEO Live Preview */
+ if ( $('div#seo-preview').length == 1 ) {
+
+ //Insert content into preview
+ if ( $('textarea#headway-admin-meta-box-seo-description').val().length > 0 ) {
+
+ var description = $('textarea#headway-admin-meta-box-seo-description').val();
+
+ if(description.length > 150){
+ description = description.substr(0, 150) + ' ...';
+ }
+
+ $('div#seo-preview p#seo-preview-description span#text').text(description);
+
+ } else {
+
+ var excerpt = $('textarea#content').val().replace(/(<([^>]+)>)/ig, '');
+
+ if ( excerpt.length > 150 ) {
+ excerpt = excerpt.substr(0, 150) + ' ...';
+ }
+
+ $('div#seo-preview p#seo-preview-description span#text').text(excerpt);
+
+ }
+
+ if ( $('input#headway-admin-meta-box-seo-title').val().length > 0 ) {
+
+ $('div#seo-preview h4').text($('input#headway-admin-meta-box-seo-title').val());
+
+ } else if ( $('div#titlediv input#title').val().length > 0 ) {
+
+ $('div#seo-preview h4').text($('input#title-seo-template').val().replace('%title%', $('div#titlediv input#title').val()));
+
+ }
+
+ if ( $('span#seo-preview-url').text().length == 0 ) {
+
+ $('span#seo-preview-url').text($('span#sample-permalink').text().replace('http://', ''));
+
+ }
+
+ //Bind Inputs
+ $('input#headway-admin-meta-box-seo-title').bind('keyup blur', function() {
+
+ if ( $(this).val().length > 0 ) {
+
+ $('div#seo-preview h4').text($(this).val());
+
+ } else {
+
+ $('div#seo-preview h4').text($('input#title-seo-template').val().replace('%title%', $('div#titlediv input#title').val()));
+
+ }
+
+ });
+
+ $('textarea#headway-admin-meta-box-seo-description').bind('keyup blur', function() {
+
+ var description = $(this).val();
+
+ if ( description.length > 150 )
+ description = description.substr(0, 150) + ' ...';
+
+ if ( $(this).val().length == 0 ) {
+
+ var description = $('textarea#content').val().replace(/(<([^>]+)>)/ig, '');
+
+ if ( excerpt.length > 150 ) {
+ description = excerpt.substr(0, 150) + ' ...';
+ }
+
+ }
+
+ $('div#seo-preview p#seo-preview-description span#text').text(description);
+
+ });
+
+ $('div#titlediv input#title').bind('keyup blur', function() {
+
+ if ( $('input#headway-admin-meta-box-seo-title').val().length == 0 ) {
+
+ $('div#seo-preview h4').text($('input#title-seo-template').val().replace('%title%', $(this).val()));
+
+ }
+
+ });
+
+ //Periodically check for updates in the content
+ setInterval(function() {
+
+ if ( $('textarea#headway-admin-meta-box-seo-description').val().length > 0 )
+ return false;
+
+ if ( $('textarea#content').val() != undefined ){
+ var excerpt = $('textarea#content').val().replace(/(<([^>]+)>)/ig, '');
+ } else {
+ var excerpt = $('textarea#excerpt').val();
+ }
+
+ if ( excerpt.length > 150 )
+ excerpt = excerpt.substr(0, 150) + ' ...';
+
+ $('div#seo-preview p#seo-preview-description span#text').text(excerpt);
+
+ }, 4000);
+
+ //Bind Clickables
+ $('div#seo-preview h4').bind('click', function(event) {
+
+ if ( $('input#headway-admin-meta-box-seo-title').val().length == 0 )
+ $('input#headway-admin-meta-box-seo-title').val($(this).text());
+
+ $('input#headway-admin-meta-box-seo-title')
+ .focus()
+ .css({backgroundColor: '#FFF6BF'})
+ .animate({backgroundColor: '#fff'}, 400);
+
+ event.preventDefault();
+
+ });
+
+ $('div#seo-preview p#seo-preview-description').bind('click', function(event) {
+
+ $('textarea#headway-admin-meta-box-seo-description')
+ .focus()
+ .css({backgroundColor: '#FFF6BF'})
+ .animate({backgroundColor: '#fff'}, 400);
+
+ event.preventDefault();
+
+ });
+ }
+ /* End SEO Live Preview */
+
+});
+})(jQuery);
\ No newline at end of file
--- /dev/null
+/*!
+ * Masonry PACKAGED v3.1.5
+ * Cascading grid layout library
+ * http://masonry.desandro.com
+ * MIT License
+ * by David DeSandro
+ */
+
+!function(a){function b(){}function c(a){function c(b){b.prototype.option||(b.prototype.option=function(b){a.isPlainObject(b)&&(this.options=a.extend(!0,this.options,b))})}function e(b,c){a.fn[b]=function(e){if("string"==typeof e){for(var g=d.call(arguments,1),h=0,i=this.length;i>h;h++){var j=this[h],k=a.data(j,b);if(k)if(a.isFunction(k[e])&&"_"!==e.charAt(0)){var l=k[e].apply(k,g);if(void 0!==l)return l}else f("no such method '"+e+"' for "+b+" instance");else f("cannot call methods on "+b+" prior to initialization; attempted to call '"+e+"'")}return this}return this.each(function(){var d=a.data(this,b);d?(d.option(e),d._init()):(d=new c(this,e),a.data(this,b,d))})}}if(a){var f="undefined"==typeof console?b:function(a){console.error(a)};return a.bridget=function(a,b){c(b),e(a,b)},a.bridget}}var d=Array.prototype.slice;"function"==typeof define&&define.amd?define("jquery-bridget/jquery.bridget",["jquery"],c):c(a.jQuery)}(window),function(a){function b(b){var c=a.event;return c.target=c.target||c.srcElement||b,c}var c=document.documentElement,d=function(){};c.addEventListener?d=function(a,b,c){a.addEventListener(b,c,!1)}:c.attachEvent&&(d=function(a,c,d){a[c+d]=d.handleEvent?function(){var c=b(a);d.handleEvent.call(d,c)}:function(){var c=b(a);d.call(a,c)},a.attachEvent("on"+c,a[c+d])});var e=function(){};c.removeEventListener?e=function(a,b,c){a.removeEventListener(b,c,!1)}:c.detachEvent&&(e=function(a,b,c){a.detachEvent("on"+b,a[b+c]);try{delete a[b+c]}catch(d){a[b+c]=void 0}});var f={bind:d,unbind:e};"function"==typeof define&&define.amd?define("eventie/eventie",f):"object"==typeof exports?module.exports=f:a.eventie=f}(this),function(a){function b(a){"function"==typeof a&&(b.isReady?a():f.push(a))}function c(a){var c="readystatechange"===a.type&&"complete"!==e.readyState;if(!b.isReady&&!c){b.isReady=!0;for(var d=0,g=f.length;g>d;d++){var h=f[d];h()}}}function d(d){return d.bind(e,"DOMContentLoaded",c),d.bind(e,"readystatechange",c),d.bind(a,"load",c),b}var e=a.document,f=[];b.isReady=!1,"function"==typeof define&&define.amd?(b.isReady="function"==typeof requirejs,define("doc-ready/doc-ready",["eventie/eventie"],d)):a.docReady=d(a.eventie)}(this),function(){function a(){}function b(a,b){for(var c=a.length;c--;)if(a[c].listener===b)return c;return-1}function c(a){return function(){return this[a].apply(this,arguments)}}var d=a.prototype,e=this,f=e.EventEmitter;d.getListeners=function(a){var b,c,d=this._getEvents();if(a instanceof RegExp){b={};for(c in d)d.hasOwnProperty(c)&&a.test(c)&&(b[c]=d[c])}else b=d[a]||(d[a]=[]);return b},d.flattenListeners=function(a){var b,c=[];for(b=0;b<a.length;b+=1)c.push(a[b].listener);return c},d.getListenersAsObject=function(a){var b,c=this.getListeners(a);return c instanceof Array&&(b={},b[a]=c),b||c},d.addListener=function(a,c){var d,e=this.getListenersAsObject(a),f="object"==typeof c;for(d in e)e.hasOwnProperty(d)&&-1===b(e[d],c)&&e[d].push(f?c:{listener:c,once:!1});return this},d.on=c("addListener"),d.addOnceListener=function(a,b){return this.addListener(a,{listener:b,once:!0})},d.once=c("addOnceListener"),d.defineEvent=function(a){return this.getListeners(a),this},d.defineEvents=function(a){for(var b=0;b<a.length;b+=1)this.defineEvent(a[b]);return this},d.removeListener=function(a,c){var d,e,f=this.getListenersAsObject(a);for(e in f)f.hasOwnProperty(e)&&(d=b(f[e],c),-1!==d&&f[e].splice(d,1));return this},d.off=c("removeListener"),d.addListeners=function(a,b){return this.manipulateListeners(!1,a,b)},d.removeListeners=function(a,b){return this.manipulateListeners(!0,a,b)},d.manipulateListeners=function(a,b,c){var d,e,f=a?this.removeListener:this.addListener,g=a?this.removeListeners:this.addListeners;if("object"!=typeof b||b instanceof RegExp)for(d=c.length;d--;)f.call(this,b,c[d]);else for(d in b)b.hasOwnProperty(d)&&(e=b[d])&&("function"==typeof e?f.call(this,d,e):g.call(this,d,e));return this},d.removeEvent=function(a){var b,c=typeof a,d=this._getEvents();if("string"===c)delete d[a];else if(a instanceof RegExp)for(b in d)d.hasOwnProperty(b)&&a.test(b)&&delete d[b];else delete this._events;return this},d.removeAllListeners=c("removeEvent"),d.emitEvent=function(a,b){var c,d,e,f,g=this.getListenersAsObject(a);for(e in g)if(g.hasOwnProperty(e))for(d=g[e].length;d--;)c=g[e][d],c.once===!0&&this.removeListener(a,c.listener),f=c.listener.apply(this,b||[]),f===this._getOnceReturnValue()&&this.removeListener(a,c.listener);return this},d.trigger=c("emitEvent"),d.emit=function(a){var b=Array.prototype.slice.call(arguments,1);return this.emitEvent(a,b)},d.setOnceReturnValue=function(a){return this._onceReturnValue=a,this},d._getOnceReturnValue=function(){return this.hasOwnProperty("_onceReturnValue")?this._onceReturnValue:!0},d._getEvents=function(){return this._events||(this._events={})},a.noConflict=function(){return e.EventEmitter=f,a},"function"==typeof define&&define.amd?define("eventEmitter/EventEmitter",[],function(){return a}):"object"==typeof module&&module.exports?module.exports=a:this.EventEmitter=a}.call(this),function(a){function b(a){if(a){if("string"==typeof d[a])return a;a=a.charAt(0).toUpperCase()+a.slice(1);for(var b,e=0,f=c.length;f>e;e++)if(b=c[e]+a,"string"==typeof d[b])return b}}var c="Webkit Moz ms Ms O".split(" "),d=document.documentElement.style;"function"==typeof define&&define.amd?define("get-style-property/get-style-property",[],function(){return b}):"object"==typeof exports?module.exports=b:a.getStyleProperty=b}(window),function(a){function b(a){var b=parseFloat(a),c=-1===a.indexOf("%")&&!isNaN(b);return c&&b}function c(){for(var a={width:0,height:0,innerWidth:0,innerHeight:0,outerWidth:0,outerHeight:0},b=0,c=g.length;c>b;b++){var d=g[b];a[d]=0}return a}function d(a){function d(a){if("string"==typeof a&&(a=document.querySelector(a)),a&&"object"==typeof a&&a.nodeType){var d=f(a);if("none"===d.display)return c();var e={};e.width=a.offsetWidth,e.height=a.offsetHeight;for(var k=e.isBorderBox=!(!j||!d[j]||"border-box"!==d[j]),l=0,m=g.length;m>l;l++){var n=g[l],o=d[n];o=h(a,o);var p=parseFloat(o);e[n]=isNaN(p)?0:p}var q=e.paddingLeft+e.paddingRight,r=e.paddingTop+e.paddingBottom,s=e.marginLeft+e.marginRight,t=e.marginTop+e.marginBottom,u=e.borderLeftWidth+e.borderRightWidth,v=e.borderTopWidth+e.borderBottomWidth,w=k&&i,x=b(d.width);x!==!1&&(e.width=x+(w?0:q+u));var y=b(d.height);return y!==!1&&(e.height=y+(w?0:r+v)),e.innerWidth=e.width-(q+u),e.innerHeight=e.height-(r+v),e.outerWidth=e.width+s,e.outerHeight=e.height+t,e}}function h(a,b){if(e||-1===b.indexOf("%"))return b;var c=a.style,d=c.left,f=a.runtimeStyle,g=f&&f.left;return g&&(f.left=a.currentStyle.left),c.left=b,b=c.pixelLeft,c.left=d,g&&(f.left=g),b}var i,j=a("boxSizing");return function(){if(j){var a=document.createElement("div");a.style.width="200px",a.style.padding="1px 2px 3px 4px",a.style.borderStyle="solid",a.style.borderWidth="1px 2px 3px 4px",a.style[j]="border-box";var c=document.body||document.documentElement;c.appendChild(a);var d=f(a);i=200===b(d.width),c.removeChild(a)}}(),d}var e=a.getComputedStyle,f=e?function(a){return e(a,null)}:function(a){return a.currentStyle},g=["paddingLeft","paddingRight","paddingTop","paddingBottom","marginLeft","marginRight","marginTop","marginBottom","borderLeftWidth","borderRightWidth","borderTopWidth","borderBottomWidth"];"function"==typeof define&&define.amd?define("get-size/get-size",["get-style-property/get-style-property"],d):"object"==typeof exports?module.exports=d(require("get-style-property")):a.getSize=d(a.getStyleProperty)}(window),function(a,b){function c(a,b){return a[h](b)}function d(a){if(!a.parentNode){var b=document.createDocumentFragment();b.appendChild(a)}}function e(a,b){d(a);for(var c=a.parentNode.querySelectorAll(b),e=0,f=c.length;f>e;e++)if(c[e]===a)return!0;return!1}function f(a,b){return d(a),c(a,b)}var g,h=function(){if(b.matchesSelector)return"matchesSelector";for(var a=["webkit","moz","ms","o"],c=0,d=a.length;d>c;c++){var e=a[c],f=e+"MatchesSelector";if(b[f])return f}}();if(h){var i=document.createElement("div"),j=c(i,"div");g=j?c:f}else g=e;"function"==typeof define&&define.amd?define("matches-selector/matches-selector",[],function(){return g}):window.matchesSelector=g}(this,Element.prototype),function(a){function b(a,b){for(var c in b)a[c]=b[c];return a}function c(a){for(var b in a)return!1;return b=null,!0}function d(a){return a.replace(/([A-Z])/g,function(a){return"-"+a.toLowerCase()})}function e(a,e,f){function h(a,b){a&&(this.element=a,this.layout=b,this.position={x:0,y:0},this._create())}var i=f("transition"),j=f("transform"),k=i&&j,l=!!f("perspective"),m={WebkitTransition:"webkitTransitionEnd",MozTransition:"transitionend",OTransition:"otransitionend",transition:"transitionend"}[i],n=["transform","transition","transitionDuration","transitionProperty"],o=function(){for(var a={},b=0,c=n.length;c>b;b++){var d=n[b],e=f(d);e&&e!==d&&(a[d]=e)}return a}();b(h.prototype,a.prototype),h.prototype._create=function(){this._transn={ingProperties:{},clean:{},onEnd:{}},this.css({position:"absolute"})},h.prototype.handleEvent=function(a){var b="on"+a.type;this[b]&&this[b](a)},h.prototype.getSize=function(){this.size=e(this.element)},h.prototype.css=function(a){var b=this.element.style;for(var c in a){var d=o[c]||c;b[d]=a[c]}},h.prototype.getPosition=function(){var a=g(this.element),b=this.layout.options,c=b.isOriginLeft,d=b.isOriginTop,e=parseInt(a[c?"left":"right"],10),f=parseInt(a[d?"top":"bottom"],10);e=isNaN(e)?0:e,f=isNaN(f)?0:f;var h=this.layout.size;e-=c?h.paddingLeft:h.paddingRight,f-=d?h.paddingTop:h.paddingBottom,this.position.x=e,this.position.y=f},h.prototype.layoutPosition=function(){var a=this.layout.size,b=this.layout.options,c={};b.isOriginLeft?(c.left=this.position.x+a.paddingLeft+"px",c.right=""):(c.right=this.position.x+a.paddingRight+"px",c.left=""),b.isOriginTop?(c.top=this.position.y+a.paddingTop+"px",c.bottom=""):(c.bottom=this.position.y+a.paddingBottom+"px",c.top=""),this.css(c),this.emitEvent("layout",[this])};var p=l?function(a,b){return"translate3d("+a+"px, "+b+"px, 0)"}:function(a,b){return"translate("+a+"px, "+b+"px)"};h.prototype._transitionTo=function(a,b){this.getPosition();var c=this.position.x,d=this.position.y,e=parseInt(a,10),f=parseInt(b,10),g=e===this.position.x&&f===this.position.y;if(this.setPosition(a,b),g&&!this.isTransitioning)return void this.layoutPosition();var h=a-c,i=b-d,j={},k=this.layout.options;h=k.isOriginLeft?h:-h,i=k.isOriginTop?i:-i,j.transform=p(h,i),this.transition({to:j,onTransitionEnd:{transform:this.layoutPosition},isCleaning:!0})},h.prototype.goTo=function(a,b){this.setPosition(a,b),this.layoutPosition()},h.prototype.moveTo=k?h.prototype._transitionTo:h.prototype.goTo,h.prototype.setPosition=function(a,b){this.position.x=parseInt(a,10),this.position.y=parseInt(b,10)},h.prototype._nonTransition=function(a){this.css(a.to),a.isCleaning&&this._removeStyles(a.to);for(var b in a.onTransitionEnd)a.onTransitionEnd[b].call(this)},h.prototype._transition=function(a){if(!parseFloat(this.layout.options.transitionDuration))return void this._nonTransition(a);var b=this._transn;for(var c in a.onTransitionEnd)b.onEnd[c]=a.onTransitionEnd[c];for(c in a.to)b.ingProperties[c]=!0,a.isCleaning&&(b.clean[c]=!0);if(a.from){this.css(a.from);var d=this.element.offsetHeight;d=null}this.enableTransition(a.to),this.css(a.to),this.isTransitioning=!0};var q=j&&d(j)+",opacity";h.prototype.enableTransition=function(){this.isTransitioning||(this.css({transitionProperty:q,transitionDuration:this.layout.options.transitionDuration}),this.element.addEventListener(m,this,!1))},h.prototype.transition=h.prototype[i?"_transition":"_nonTransition"],h.prototype.onwebkitTransitionEnd=function(a){this.ontransitionend(a)},h.prototype.onotransitionend=function(a){this.ontransitionend(a)};var r={"-webkit-transform":"transform","-moz-transform":"transform","-o-transform":"transform"};h.prototype.ontransitionend=function(a){if(a.target===this.element){var b=this._transn,d=r[a.propertyName]||a.propertyName;if(delete b.ingProperties[d],c(b.ingProperties)&&this.disableTransition(),d in b.clean&&(this.element.style[a.propertyName]="",delete b.clean[d]),d in b.onEnd){var e=b.onEnd[d];e.call(this),delete b.onEnd[d]}this.emitEvent("transitionEnd",[this])}},h.prototype.disableTransition=function(){this.removeTransitionStyles(),this.element.removeEventListener(m,this,!1),this.isTransitioning=!1},h.prototype._removeStyles=function(a){var b={};for(var c in a)b[c]="";this.css(b)};var s={transitionProperty:"",transitionDuration:""};return h.prototype.removeTransitionStyles=function(){this.css(s)},h.prototype.removeElem=function(){this.element.parentNode.removeChild(this.element),this.emitEvent("remove",[this])},h.prototype.remove=function(){if(!i||!parseFloat(this.layout.options.transitionDuration))return void this.removeElem();var a=this;this.on("transitionEnd",function(){return a.removeElem(),!0}),this.hide()},h.prototype.reveal=function(){delete this.isHidden,this.css({display:""});var a=this.layout.options;this.transition({from:a.hiddenStyle,to:a.visibleStyle,isCleaning:!0})},h.prototype.hide=function(){this.isHidden=!0,this.css({display:""});var a=this.layout.options;this.transition({from:a.visibleStyle,to:a.hiddenStyle,isCleaning:!0,onTransitionEnd:{opacity:function(){this.isHidden&&this.css({display:"none"})}}})},h.prototype.destroy=function(){this.css({position:"",left:"",right:"",top:"",bottom:"",transition:"",transform:""})},h}var f=a.getComputedStyle,g=f?function(a){return f(a,null)}:function(a){return a.currentStyle};"function"==typeof define&&define.amd?define("outlayer/item",["eventEmitter/EventEmitter","get-size/get-size","get-style-property/get-style-property"],e):(a.Outlayer={},a.Outlayer.Item=e(a.EventEmitter,a.getSize,a.getStyleProperty))}(window),function(a){function b(a,b){for(var c in b)a[c]=b[c];return a}function c(a){return"[object Array]"===l.call(a)}function d(a){var b=[];if(c(a))b=a;else if(a&&"number"==typeof a.length)for(var d=0,e=a.length;e>d;d++)b.push(a[d]);else b.push(a);return b}function e(a,b){var c=n(b,a);-1!==c&&b.splice(c,1)}function f(a){return a.replace(/(.)([A-Z])/g,function(a,b,c){return b+"-"+c}).toLowerCase()}function g(c,g,l,n,o,p){function q(a,c){if("string"==typeof a&&(a=h.querySelector(a)),!a||!m(a))return void(i&&i.error("Bad "+this.constructor.namespace+" element: "+a));this.element=a,this.options=b({},this.constructor.defaults),this.option(c);var d=++r;this.element.outlayerGUID=d,s[d]=this,this._create(),this.options.isInitLayout&&this.layout()}var r=0,s={};return q.namespace="outlayer",q.Item=p,q.defaults={containerStyle:{position:"relative"},isInitLayout:!0,isOriginLeft:!0,isOriginTop:!0,isResizeBound:!0,isResizingContainer:!0,transitionDuration:"0.4s",hiddenStyle:{opacity:0,transform:"scale(0.001)"},visibleStyle:{opacity:1,transform:"scale(1)"}},b(q.prototype,l.prototype),q.prototype.option=function(a){b(this.options,a)},q.prototype._create=function(){this.reloadItems(),this.stamps=[],this.stamp(this.options.stamp),b(this.element.style,this.options.containerStyle),this.options.isResizeBound&&this.bindResize()},q.prototype.reloadItems=function(){this.items=this._itemize(this.element.children)},q.prototype._itemize=function(a){for(var b=this._filterFindItemElements(a),c=this.constructor.Item,d=[],e=0,f=b.length;f>e;e++){var g=b[e],h=new c(g,this);d.push(h)}return d},q.prototype._filterFindItemElements=function(a){a=d(a);for(var b=this.options.itemSelector,c=[],e=0,f=a.length;f>e;e++){var g=a[e];if(m(g))if(b){o(g,b)&&c.push(g);for(var h=g.querySelectorAll(b),i=0,j=h.length;j>i;i++)c.push(h[i])}else c.push(g)}return c},q.prototype.getItemElements=function(){for(var a=[],b=0,c=this.items.length;c>b;b++)a.push(this.items[b].element);return a},q.prototype.layout=function(){this._resetLayout(),this._manageStamps();var a=void 0!==this.options.isLayoutInstant?this.options.isLayoutInstant:!this._isLayoutInited;this.layoutItems(this.items,a),this._isLayoutInited=!0},q.prototype._init=q.prototype.layout,q.prototype._resetLayout=function(){this.getSize()},q.prototype.getSize=function(){this.size=n(this.element)},q.prototype._getMeasurement=function(a,b){var c,d=this.options[a];d?("string"==typeof d?c=this.element.querySelector(d):m(d)&&(c=d),this[a]=c?n(c)[b]:d):this[a]=0},q.prototype.layoutItems=function(a,b){a=this._getItemsForLayout(a),this._layoutItems(a,b),this._postLayout()},q.prototype._getItemsForLayout=function(a){for(var b=[],c=0,d=a.length;d>c;c++){var e=a[c];e.isIgnored||b.push(e)}return b},q.prototype._layoutItems=function(a,b){function c(){d.emitEvent("layoutComplete",[d,a])}var d=this;if(!a||!a.length)return void c();this._itemsOn(a,"layout",c);for(var e=[],f=0,g=a.length;g>f;f++){var h=a[f],i=this._getItemLayoutPosition(h);i.item=h,i.isInstant=b||h.isLayoutInstant,e.push(i)}this._processLayoutQueue(e)},q.prototype._getItemLayoutPosition=function(){return{x:0,y:0}},q.prototype._processLayoutQueue=function(a){for(var b=0,c=a.length;c>b;b++){var d=a[b];this._positionItem(d.item,d.x,d.y,d.isInstant)}},q.prototype._positionItem=function(a,b,c,d){d?a.goTo(b,c):a.moveTo(b,c)},q.prototype._postLayout=function(){this.resizeContainer()},q.prototype.resizeContainer=function(){if(this.options.isResizingContainer){var a=this._getContainerSize();a&&(this._setContainerMeasure(a.width,!0),this._setContainerMeasure(a.height,!1))}},q.prototype._getContainerSize=k,q.prototype._setContainerMeasure=function(a,b){if(void 0!==a){var c=this.size;c.isBorderBox&&(a+=b?c.paddingLeft+c.paddingRight+c.borderLeftWidth+c.borderRightWidth:c.paddingBottom+c.paddingTop+c.borderTopWidth+c.borderBottomWidth),a=Math.max(a,0),this.element.style[b?"width":"height"]=a+"px"}},q.prototype._itemsOn=function(a,b,c){function d(){return e++,e===f&&c.call(g),!0}for(var e=0,f=a.length,g=this,h=0,i=a.length;i>h;h++){var j=a[h];j.on(b,d)}},q.prototype.ignore=function(a){var b=this.getItem(a);b&&(b.isIgnored=!0)},q.prototype.unignore=function(a){var b=this.getItem(a);b&&delete b.isIgnored},q.prototype.stamp=function(a){if(a=this._find(a)){this.stamps=this.stamps.concat(a);for(var b=0,c=a.length;c>b;b++){var d=a[b];this.ignore(d)}}},q.prototype.unstamp=function(a){if(a=this._find(a))for(var b=0,c=a.length;c>b;b++){var d=a[b];e(d,this.stamps),this.unignore(d)}},q.prototype._find=function(a){return a?("string"==typeof a&&(a=this.element.querySelectorAll(a)),a=d(a)):void 0},q.prototype._manageStamps=function(){if(this.stamps&&this.stamps.length){this._getBoundingRect();for(var a=0,b=this.stamps.length;b>a;a++){var c=this.stamps[a];this._manageStamp(c)}}},q.prototype._getBoundingRect=function(){var a=this.element.getBoundingClientRect(),b=this.size;this._boundingRect={left:a.left+b.paddingLeft+b.borderLeftWidth,top:a.top+b.paddingTop+b.borderTopWidth,right:a.right-(b.paddingRight+b.borderRightWidth),bottom:a.bottom-(b.paddingBottom+b.borderBottomWidth)}},q.prototype._manageStamp=k,q.prototype._getElementOffset=function(a){var b=a.getBoundingClientRect(),c=this._boundingRect,d=n(a),e={left:b.left-c.left-d.marginLeft,top:b.top-c.top-d.marginTop,right:c.right-b.right-d.marginRight,bottom:c.bottom-b.bottom-d.marginBottom};return e},q.prototype.handleEvent=function(a){var b="on"+a.type;this[b]&&this[b](a)},q.prototype.bindResize=function(){this.isResizeBound||(c.bind(a,"resize",this),this.isResizeBound=!0)},q.prototype.unbindResize=function(){this.isResizeBound&&c.unbind(a,"resize",this),this.isResizeBound=!1},q.prototype.onresize=function(){function a(){b.resize(),delete b.resizeTimeout}this.resizeTimeout&&clearTimeout(this.resizeTimeout);var b=this;this.resizeTimeout=setTimeout(a,100)},q.prototype.resize=function(){this.isResizeBound&&this.needsResizeLayout()&&this.layout()},q.prototype.needsResizeLayout=function(){var a=n(this.element),b=this.size&&a;return b&&a.innerWidth!==this.size.innerWidth},q.prototype.addItems=function(a){var b=this._itemize(a);return b.length&&(this.items=this.items.concat(b)),b},q.prototype.appended=function(a){var b=this.addItems(a);b.length&&(this.layoutItems(b,!0),this.reveal(b))},q.prototype.prepended=function(a){var b=this._itemize(a);if(b.length){var c=this.items.slice(0);this.items=b.concat(c),this._resetLayout(),this._manageStamps(),this.layoutItems(b,!0),this.reveal(b),this.layoutItems(c)}},q.prototype.reveal=function(a){var b=a&&a.length;if(b)for(var c=0;b>c;c++){var d=a[c];d.reveal()}},q.prototype.hide=function(a){var b=a&&a.length;if(b)for(var c=0;b>c;c++){var d=a[c];d.hide()}},q.prototype.getItem=function(a){for(var b=0,c=this.items.length;c>b;b++){var d=this.items[b];if(d.element===a)return d}},q.prototype.getItems=function(a){if(a&&a.length){for(var b=[],c=0,d=a.length;d>c;c++){var e=a[c],f=this.getItem(e);f&&b.push(f)}return b}},q.prototype.remove=function(a){a=d(a);var b=this.getItems(a);if(b&&b.length){this._itemsOn(b,"remove",function(){this.emitEvent("removeComplete",[this,b])});for(var c=0,f=b.length;f>c;c++){var g=b[c];g.remove(),e(g,this.items)}}},q.prototype.destroy=function(){var a=this.element.style;a.height="",a.position="",a.width="";for(var b=0,c=this.items.length;c>b;b++){var d=this.items[b];d.destroy()}this.unbindResize(),delete this.element.outlayerGUID,j&&j.removeData(this.element,this.constructor.namespace)},q.data=function(a){var b=a&&a.outlayerGUID;return b&&s[b]},q.create=function(a,c){function d(){q.apply(this,arguments)}return Object.create?d.prototype=Object.create(q.prototype):b(d.prototype,q.prototype),d.prototype.constructor=d,d.defaults=b({},q.defaults),b(d.defaults,c),d.prototype.settings={},d.namespace=a,d.data=q.data,d.Item=function(){p.apply(this,arguments)},d.Item.prototype=new p,g(function(){for(var b=f(a),c=h.querySelectorAll(".js-"+b),e="data-"+b+"-options",g=0,k=c.length;k>g;g++){var l,m=c[g],n=m.getAttribute(e);try{l=n&&JSON.parse(n)}catch(o){i&&i.error("Error parsing "+e+" on "+m.nodeName.toLowerCase()+(m.id?"#"+m.id:"")+": "+o);continue}var p=new d(m,l);j&&j.data(m,a,p)}}),j&&j.bridget&&j.bridget(a,d),d},q.Item=p,q}var h=a.document,i=a.console,j=a.jQuery,k=function(){},l=Object.prototype.toString,m="object"==typeof HTMLElement?function(a){return a instanceof HTMLElement}:function(a){return a&&"object"==typeof a&&1===a.nodeType&&"string"==typeof a.nodeName},n=Array.prototype.indexOf?function(a,b){return a.indexOf(b)}:function(a,b){for(var c=0,d=a.length;d>c;c++)if(a[c]===b)return c;return-1};"function"==typeof define&&define.amd?define("outlayer/outlayer",["eventie/eventie","doc-ready/doc-ready","eventEmitter/EventEmitter","get-size/get-size","matches-selector/matches-selector","./item"],g):a.Outlayer=g(a.eventie,a.docReady,a.EventEmitter,a.getSize,a.matchesSelector,a.Outlayer.Item)}(window),function(a){function b(a,b){var d=a.create("masonry");return d.prototype._resetLayout=function(){this.getSize(),this._getMeasurement("columnWidth","outerWidth"),this._getMeasurement("gutter","outerWidth"),this.measureColumns();var a=this.cols;for(this.colYs=[];a--;)this.colYs.push(0);this.maxY=0},d.prototype.measureColumns=function(){if(this.getContainerWidth(),!this.columnWidth){var a=this.items[0],c=a&&a.element;this.columnWidth=c&&b(c).outerWidth||this.containerWidth}this.columnWidth+=this.gutter,this.cols=Math.floor((this.containerWidth+this.gutter)/this.columnWidth),this.cols=Math.max(this.cols,1)},d.prototype.getContainerWidth=function(){var a=this.options.isFitWidth?this.element.parentNode:this.element,c=b(a);this.containerWidth=c&&c.innerWidth},d.prototype._getItemLayoutPosition=function(a){a.getSize();var b=a.size.outerWidth%this.columnWidth,d=b&&1>b?"round":"ceil",e=Math[d](a.size.outerWidth/this.columnWidth);e=Math.min(e,this.cols);for(var f=this._getColGroup(e),g=Math.min.apply(Math,f),h=c(f,g),i={x:this.columnWidth*h,y:g},j=g+a.size.outerHeight,k=this.cols+1-f.length,l=0;k>l;l++)this.colYs[h+l]=j;return i},d.prototype._getColGroup=function(a){if(2>a)return this.colYs;for(var b=[],c=this.cols+1-a,d=0;c>d;d++){var e=this.colYs.slice(d,d+a);b[d]=Math.max.apply(Math,e)}return b},d.prototype._manageStamp=function(a){var c=b(a),d=this._getElementOffset(a),e=this.options.isOriginLeft?d.left:d.right,f=e+c.outerWidth,g=Math.floor(e/this.columnWidth);g=Math.max(0,g);var h=Math.floor(f/this.columnWidth);h-=f%this.columnWidth?0:1,h=Math.min(this.cols-1,h);for(var i=(this.options.isOriginTop?d.top:d.bottom)+c.outerHeight,j=g;h>=j;j++)this.colYs[j]=Math.max(i,this.colYs[j])},d.prototype._getContainerSize=function(){this.maxY=Math.max.apply(Math,this.colYs);var a={height:this.maxY};return this.options.isFitWidth&&(a.width=this._getContainerFitWidth()),a},d.prototype._getContainerFitWidth=function(){for(var a=0,b=this.cols;--b&&0===this.colYs[b];)a++;return(this.cols-a)*this.columnWidth-this.gutter},d.prototype.needsResizeLayout=function(){var a=this.containerWidth;return this.getContainerWidth(),a!==this.containerWidth},d}var c=Array.prototype.indexOf?function(a,b){return a.indexOf(b)}:function(a,b){for(var c=0,d=a.length;d>c;c++){var e=a[c];if(e===b)return c}return-1};"function"==typeof define&&define.amd?define(["outlayer/outlayer","get-size/get-size"],b):a.Masonry=b(a.Outlayer,a.getSize)}(window);
\ No newline at end of file
--- /dev/null
+/* qTip2 v2.2.0 tips viewport | qtip2.com | Licensed MIT, GPL | Mon Dec 16 2013 11:39:27 */
+
+!function(a,b,c){!function(a){"use strict";"function"==typeof define&&define.amd?define(["jquery"],a):jQuery&&!jQuery.fn.qtip&&a(jQuery)}(function(d){"use strict";function e(a,b,c,e){this.id=c,this.target=a,this.tooltip=E,this.elements={target:a},this._id=R+"-"+c,this.timers={img:{}},this.options=b,this.plugins={},this.cache={event:{},target:d(),disabled:D,attr:e,onTooltip:D,lastClass:""},this.rendered=this.destroyed=this.disabled=this.waiting=this.hiddenDuringWait=this.positioning=this.triggering=D}function f(a){return a===E||"object"!==d.type(a)}function g(a){return!(d.isFunction(a)||a&&a.attr||a.length||"object"===d.type(a)&&(a.jquery||a.then))}function h(a){var b,c,e,h;return f(a)?D:(f(a.metadata)&&(a.metadata={type:a.metadata}),"content"in a&&(b=a.content,f(b)||b.jquery||b.done?b=a.content={text:c=g(b)?D:b}:c=b.text,"ajax"in b&&(e=b.ajax,h=e&&e.once!==D,delete b.ajax,b.text=function(a,b){var f=c||d(this).attr(b.options.content.attr)||"Loading...",g=d.ajax(d.extend({},e,{context:b})).then(e.success,E,e.error).then(function(a){return a&&h&&b.set("content.text",a),a},function(a,c,d){b.destroyed||0===a.status||b.set("content.text",c+": "+d)});return h?f:(b.set("content.text",f),g)}),"title"in b&&(f(b.title)||(b.button=b.title.button,b.title=b.title.text),g(b.title||D)&&(b.title=D))),"position"in a&&f(a.position)&&(a.position={my:a.position,at:a.position}),"show"in a&&f(a.show)&&(a.show=a.show.jquery?{target:a.show}:a.show===C?{ready:C}:{event:a.show}),"hide"in a&&f(a.hide)&&(a.hide=a.hide.jquery?{target:a.hide}:{event:a.hide}),"style"in a&&f(a.style)&&(a.style={classes:a.style}),d.each(Q,function(){this.sanitize&&this.sanitize(a)}),a)}function i(a,b){for(var c,d=0,e=a,f=b.split(".");e=e[f[d++]];)d<f.length&&(c=e);return[c||a,f.pop()]}function j(a,b){var c,d,e;for(c in this.checks)for(d in this.checks[c])(e=new RegExp(d,"i").exec(a))&&(b.push(e),("builtin"===c||this.plugins[c])&&this.checks[c][d].apply(this.plugins[c]||this,b))}function k(a){return U.concat("").join(a?"-"+a+" ":" ")}function l(c){return c&&{type:c.type,pageX:c.pageX,pageY:c.pageY,target:c.target,relatedTarget:c.relatedTarget,scrollX:c.scrollX||a.pageXOffset||b.body.scrollLeft||b.documentElement.scrollLeft,scrollY:c.scrollY||a.pageYOffset||b.body.scrollTop||b.documentElement.scrollTop}||{}}function m(a,b){return b>0?setTimeout(d.proxy(a,this),b):(a.call(this),void 0)}function n(a){return this.tooltip.hasClass(_)?D:(clearTimeout(this.timers.show),clearTimeout(this.timers.hide),this.timers.show=m.call(this,function(){this.toggle(C,a)},this.options.show.delay),void 0)}function o(a){if(this.tooltip.hasClass(_))return D;var b=d(a.relatedTarget),c=b.closest(V)[0]===this.tooltip[0],e=b[0]===this.options.show.target[0];if(clearTimeout(this.timers.show),clearTimeout(this.timers.hide),this!==b[0]&&"mouse"===this.options.position.target&&c||this.options.hide.fixed&&/mouse(out|leave|move)/.test(a.type)&&(c||e))try{a.preventDefault(),a.stopImmediatePropagation()}catch(f){}else this.timers.hide=m.call(this,function(){this.toggle(D,a)},this.options.hide.delay,this)}function p(a){return this.tooltip.hasClass(_)||!this.options.hide.inactive?D:(clearTimeout(this.timers.inactive),this.timers.inactive=m.call(this,function(){this.hide(a)},this.options.hide.inactive),void 0)}function q(a){this.rendered&&this.tooltip[0].offsetWidth>0&&this.reposition(a)}function r(a,c,e){d(b.body).delegate(a,(c.split?c:c.join(gb+" "))+gb,function(){var a=x.api[d.attr(this,T)];a&&!a.disabled&&e.apply(a,arguments)})}function s(a,c,f){var g,i,j,k,l,m=d(b.body),n=a[0]===b?m:a,o=a.metadata?a.metadata(f.metadata):E,p="html5"===f.metadata.type&&o?o[f.metadata.name]:E,q=a.data(f.metadata.name||"qtipopts");try{q="string"==typeof q?d.parseJSON(q):q}catch(r){}if(k=d.extend(C,{},x.defaults,f,"object"==typeof q?h(q):E,h(p||o)),i=k.position,k.id=c,"boolean"==typeof k.content.text){if(j=a.attr(k.content.attr),k.content.attr===D||!j)return D;k.content.text=j}if(i.container.length||(i.container=m),i.target===D&&(i.target=n),k.show.target===D&&(k.show.target=n),k.show.solo===C&&(k.show.solo=i.container.closest("body")),k.hide.target===D&&(k.hide.target=n),k.position.viewport===C&&(k.position.viewport=i.container),i.container=i.container.eq(0),i.at=new z(i.at,C),i.my=new z(i.my),a.data(R))if(k.overwrite)a.qtip("destroy",!0);else if(k.overwrite===D)return D;return a.attr(S,c),k.suppress&&(l=a.attr("title"))&&a.removeAttr("title").attr(bb,l).attr("title",""),g=new e(a,k,c,!!j),a.data(R,g),a.one("remove.qtip-"+c+" removeqtip.qtip-"+c,function(){var a;(a=d(this).data(R))&&a.destroy(!0)}),g}function t(a){return a.charAt(0).toUpperCase()+a.slice(1)}function u(a,b){var d,e,f=b.charAt(0).toUpperCase()+b.slice(1),g=(b+" "+rb.join(f+" ")+f).split(" "),h=0;if(qb[b])return a.css(qb[b]);for(;d=g[h++];)if((e=a.css(d))!==c)return qb[b]=d,e}function v(a,b){return Math.ceil(parseFloat(u(a,b)))}function w(a,b){this._ns="tip",this.options=b,this.offset=b.offset,this.size=[b.width,b.height],this.init(this.qtip=a)}var x,y,z,A,B,C=!0,D=!1,E=null,F="x",G="y",H="width",I="height",J="top",K="left",L="bottom",M="right",N="center",O="flipinvert",P="shift",Q={},R="qtip",S="data-hasqtip",T="data-qtip-id",U=["ui-widget","ui-tooltip"],V="."+R,W="click dblclick mousedown mouseup mousemove mouseleave mouseenter".split(" "),X=R+"-fixed",Y=R+"-default",Z=R+"-focus",$=R+"-hover",_=R+"-disabled",ab="_replacedByqTip",bb="oldtitle",cb={ie:function(){for(var a=3,c=b.createElement("div");(c.innerHTML="<!--[if gt IE "+ ++a+"]><i></i><![endif]-->")&&c.getElementsByTagName("i")[0];);return a>4?a:0/0}(),iOS:parseFloat((""+(/CPU.*OS ([0-9_]{1,5})|(CPU like).*AppleWebKit.*Mobile/i.exec(navigator.userAgent)||[0,""])[1]).replace("undefined","3_2").replace("_",".").replace("_",""))||D};y=e.prototype,y._when=function(a){return d.when.apply(d,a)},y.render=function(a){if(this.rendered||this.destroyed)return this;var b,c=this,e=this.options,f=this.cache,g=this.elements,h=e.content.text,i=e.content.title,j=e.content.button,k=e.position,l=("."+this._id+" ",[]);return d.attr(this.target[0],"aria-describedby",this._id),this.tooltip=g.tooltip=b=d("<div/>",{id:this._id,"class":[R,Y,e.style.classes,R+"-pos-"+e.position.my.abbrev()].join(" "),width:e.style.width||"",height:e.style.height||"",tracking:"mouse"===k.target&&k.adjust.mouse,role:"alert","aria-live":"polite","aria-atomic":D,"aria-describedby":this._id+"-content","aria-hidden":C}).toggleClass(_,this.disabled).attr(T,this.id).data(R,this).appendTo(k.container).append(g.content=d("<div />",{"class":R+"-content",id:this._id+"-content","aria-atomic":C})),this.rendered=-1,this.positioning=C,i&&(this._createTitle(),d.isFunction(i)||l.push(this._updateTitle(i,D))),j&&this._createButton(),d.isFunction(h)||l.push(this._updateContent(h,D)),this.rendered=C,this._setWidget(),d.each(Q,function(a){var b;"render"===this.initialize&&(b=this(c))&&(c.plugins[a]=b)}),this._unassignEvents(),this._assignEvents(),this._when(l).then(function(){c._trigger("render"),c.positioning=D,c.hiddenDuringWait||!e.show.ready&&!a||c.toggle(C,f.event,D),c.hiddenDuringWait=D}),x.api[this.id]=this,this},y.destroy=function(a){function b(){if(!this.destroyed){this.destroyed=C;var a=this.target,b=a.attr(bb);this.rendered&&this.tooltip.stop(1,0).find("*").remove().end().remove(),d.each(this.plugins,function(){this.destroy&&this.destroy()}),clearTimeout(this.timers.show),clearTimeout(this.timers.hide),this._unassignEvents(),a.removeData(R).removeAttr(T).removeAttr(S).removeAttr("aria-describedby"),this.options.suppress&&b&&a.attr("title",b).removeAttr(bb),this._unbind(a),this.options=this.elements=this.cache=this.timers=this.plugins=this.mouse=E,delete x.api[this.id]}}return this.destroyed?this.target:(a===C&&"hide"!==this.triggering||!this.rendered?b.call(this):(this.tooltip.one("tooltiphidden",d.proxy(b,this)),!this.triggering&&this.hide()),this.target)},A=y.checks={builtin:{"^id$":function(a,b,c,e){var f=c===C?x.nextid:c,g=R+"-"+f;f!==D&&f.length>0&&!d("#"+g).length?(this._id=g,this.rendered&&(this.tooltip[0].id=this._id,this.elements.content[0].id=this._id+"-content",this.elements.title[0].id=this._id+"-title")):a[b]=e},"^prerender":function(a,b,c){c&&!this.rendered&&this.render(this.options.show.ready)},"^content.text$":function(a,b,c){this._updateContent(c)},"^content.attr$":function(a,b,c,d){this.options.content.text===this.target.attr(d)&&this._updateContent(this.target.attr(c))},"^content.title$":function(a,b,c){return c?(c&&!this.elements.title&&this._createTitle(),this._updateTitle(c),void 0):this._removeTitle()},"^content.button$":function(a,b,c){this._updateButton(c)},"^content.title.(text|button)$":function(a,b,c){this.set("content."+b,c)},"^position.(my|at)$":function(a,b,c){"string"==typeof c&&(a[b]=new z(c,"at"===b))},"^position.container$":function(a,b,c){this.rendered&&this.tooltip.appendTo(c)},"^show.ready$":function(a,b,c){c&&(!this.rendered&&this.render(C)||this.toggle(C))},"^style.classes$":function(a,b,c,d){this.rendered&&this.tooltip.removeClass(d).addClass(c)},"^style.(width|height)":function(a,b,c){this.rendered&&this.tooltip.css(b,c)},"^style.widget|content.title":function(){this.rendered&&this._setWidget()},"^style.def":function(a,b,c){this.rendered&&this.tooltip.toggleClass(Y,!!c)},"^events.(render|show|move|hide|focus|blur)$":function(a,b,c){this.rendered&&this.tooltip[(d.isFunction(c)?"":"un")+"bind"]("tooltip"+b,c)},"^(show|hide|position).(event|target|fixed|inactive|leave|distance|viewport|adjust)":function(){if(this.rendered){var a=this.options.position;this.tooltip.attr("tracking","mouse"===a.target&&a.adjust.mouse),this._unassignEvents(),this._assignEvents()}}}},y.get=function(a){if(this.destroyed)return this;var b=i(this.options,a.toLowerCase()),c=b[0][b[1]];return c.precedance?c.string():c};var db=/^position\.(my|at|adjust|target|container|viewport)|style|content|show\.ready/i,eb=/^prerender|show\.ready/i;y.set=function(a,b){if(this.destroyed)return this;{var c,e=this.rendered,f=D,g=this.options;this.checks}return"string"==typeof a?(c=a,a={},a[c]=b):a=d.extend({},a),d.each(a,function(b,c){if(e&&eb.test(b))return delete a[b],void 0;var h,j=i(g,b.toLowerCase());h=j[0][j[1]],j[0][j[1]]=c&&c.nodeType?d(c):c,f=db.test(b)||f,a[b]=[j[0],j[1],c,h]}),h(g),this.positioning=C,d.each(a,d.proxy(j,this)),this.positioning=D,this.rendered&&this.tooltip[0].offsetWidth>0&&f&&this.reposition("mouse"===g.position.target?E:this.cache.event),this},y._update=function(a,b){var c=this,e=this.cache;return this.rendered&&a?(d.isFunction(a)&&(a=a.call(this.elements.target,e.event,this)||""),d.isFunction(a.then)?(e.waiting=C,a.then(function(a){return e.waiting=D,c._update(a,b)},E,function(a){return c._update(a,b)})):a===D||!a&&""!==a?D:(a.jquery&&a.length>0?b.empty().append(a.css({display:"block",visibility:"visible"})):b.html(a),this._waitForContent(b).then(function(a){a.images&&a.images.length&&c.rendered&&c.tooltip[0].offsetWidth>0&&c.reposition(e.event,!a.length)}))):D},y._waitForContent=function(a){var b=this.cache;return b.waiting=C,(d.fn.imagesLoaded?a.imagesLoaded():d.Deferred().resolve([])).done(function(){b.waiting=D}).promise()},y._updateContent=function(a,b){this._update(a,this.elements.content,b)},y._updateTitle=function(a,b){this._update(a,this.elements.title,b)===D&&this._removeTitle(D)},y._createTitle=function(){var a=this.elements,b=this._id+"-title";a.titlebar&&this._removeTitle(),a.titlebar=d("<div />",{"class":R+"-titlebar "+(this.options.style.widget?k("header"):"")}).append(a.title=d("<div />",{id:b,"class":R+"-title","aria-atomic":C})).insertBefore(a.content).delegate(".qtip-close","mousedown keydown mouseup keyup mouseout",function(a){d(this).toggleClass("ui-state-active ui-state-focus","down"===a.type.substr(-4))}).delegate(".qtip-close","mouseover mouseout",function(a){d(this).toggleClass("ui-state-hover","mouseover"===a.type)}),this.options.content.button&&this._createButton()},y._removeTitle=function(a){var b=this.elements;b.title&&(b.titlebar.remove(),b.titlebar=b.title=b.button=E,a!==D&&this.reposition())},y.reposition=function(c,e){if(!this.rendered||this.positioning||this.destroyed)return this;this.positioning=C;var f,g,h=this.cache,i=this.tooltip,j=this.options.position,k=j.target,l=j.my,m=j.at,n=j.viewport,o=j.container,p=j.adjust,q=p.method.split(" "),r=i.outerWidth(D),s=i.outerHeight(D),t=0,u=0,v=i.css("position"),w={left:0,top:0},x=i[0].offsetWidth>0,y=c&&"scroll"===c.type,z=d(a),A=o[0].ownerDocument,B=this.mouse;if(d.isArray(k)&&2===k.length)m={x:K,y:J},w={left:k[0],top:k[1]};else if("mouse"===k)m={x:K,y:J},!B||!B.pageX||!p.mouse&&c&&c.pageX?c&&c.pageX||((!p.mouse||this.options.show.distance)&&h.origin&&h.origin.pageX?c=h.origin:(!c||c&&("resize"===c.type||"scroll"===c.type))&&(c=h.event)):c=B,"static"!==v&&(w=o.offset()),A.body.offsetWidth!==(a.innerWidth||A.documentElement.clientWidth)&&(g=d(b.body).offset()),w={left:c.pageX-w.left+(g&&g.left||0),top:c.pageY-w.top+(g&&g.top||0)},p.mouse&&y&&B&&(w.left-=(B.scrollX||0)-z.scrollLeft(),w.top-=(B.scrollY||0)-z.scrollTop());else{if("event"===k?c&&c.target&&"scroll"!==c.type&&"resize"!==c.type?h.target=d(c.target):c.target||(h.target=this.elements.target):"event"!==k&&(h.target=d(k.jquery?k:this.elements.target)),k=h.target,k=d(k).eq(0),0===k.length)return this;k[0]===b||k[0]===a?(t=cb.iOS?a.innerWidth:k.width(),u=cb.iOS?a.innerHeight:k.height(),k[0]===a&&(w={top:(n||k).scrollTop(),left:(n||k).scrollLeft()})):Q.imagemap&&k.is("area")?f=Q.imagemap(this,k,m,Q.viewport?q:D):Q.svg&&k&&k[0].ownerSVGElement?f=Q.svg(this,k,m,Q.viewport?q:D):(t=k.outerWidth(D),u=k.outerHeight(D),w=k.offset()),f&&(t=f.width,u=f.height,g=f.offset,w=f.position),w=this.reposition.offset(k,w,o),(cb.iOS>3.1&&cb.iOS<4.1||cb.iOS>=4.3&&cb.iOS<4.33||!cb.iOS&&"fixed"===v)&&(w.left-=z.scrollLeft(),w.top-=z.scrollTop()),(!f||f&&f.adjustable!==D)&&(w.left+=m.x===M?t:m.x===N?t/2:0,w.top+=m.y===L?u:m.y===N?u/2:0)}return w.left+=p.x+(l.x===M?-r:l.x===N?-r/2:0),w.top+=p.y+(l.y===L?-s:l.y===N?-s/2:0),Q.viewport?(w.adjusted=Q.viewport(this,w,j,t,u,r,s),g&&w.adjusted.left&&(w.left+=g.left),g&&w.adjusted.top&&(w.top+=g.top)):w.adjusted={left:0,top:0},this._trigger("move",[w,n.elem||n],c)?(delete w.adjusted,e===D||!x||isNaN(w.left)||isNaN(w.top)||"mouse"===k||!d.isFunction(j.effect)?i.css(w):d.isFunction(j.effect)&&(j.effect.call(i,this,d.extend({},w)),i.queue(function(a){d(this).css({opacity:"",height:""}),cb.ie&&this.style.removeAttribute("filter"),a()})),this.positioning=D,this):this},y.reposition.offset=function(a,c,e){function f(a,b){c.left+=b*a.scrollLeft(),c.top+=b*a.scrollTop()}if(!e[0])return c;var g,h,i,j,k=d(a[0].ownerDocument),l=!!cb.ie&&"CSS1Compat"!==b.compatMode,m=e[0];do"static"!==(h=d.css(m,"position"))&&("fixed"===h?(i=m.getBoundingClientRect(),f(k,-1)):(i=d(m).position(),i.left+=parseFloat(d.css(m,"borderLeftWidth"))||0,i.top+=parseFloat(d.css(m,"borderTopWidth"))||0),c.left-=i.left+(parseFloat(d.css(m,"marginLeft"))||0),c.top-=i.top+(parseFloat(d.css(m,"marginTop"))||0),g||"hidden"===(j=d.css(m,"overflow"))||"visible"===j||(g=d(m)));while(m=m.offsetParent);return g&&(g[0]!==k[0]||l)&&f(g,1),c};var fb=(z=y.reposition.Corner=function(a,b){a=(""+a).replace(/([A-Z])/," $1").replace(/middle/gi,N).toLowerCase(),this.x=(a.match(/left|right/i)||a.match(/center/)||["inherit"])[0].toLowerCase(),this.y=(a.match(/top|bottom|center/i)||["inherit"])[0].toLowerCase(),this.forceY=!!b;var c=a.charAt(0);this.precedance="t"===c||"b"===c?G:F}).prototype;fb.invert=function(a,b){this[a]=this[a]===K?M:this[a]===M?K:b||this[a]},fb.string=function(){var a=this.x,b=this.y;return a===b?a:this.precedance===G||this.forceY&&"center"!==b?b+" "+a:a+" "+b},fb.abbrev=function(){var a=this.string().split(" ");return a[0].charAt(0)+(a[1]&&a[1].charAt(0)||"")},fb.clone=function(){return new z(this.string(),this.forceY)},y.toggle=function(a,c){var e=this.cache,f=this.options,g=this.tooltip;if(c){if(/over|enter/.test(c.type)&&/out|leave/.test(e.event.type)&&f.show.target.add(c.target).length===f.show.target.length&&g.has(c.relatedTarget).length)return this;e.event=l(c)}if(this.waiting&&!a&&(this.hiddenDuringWait=C),!this.rendered)return a?this.render(1):this;if(this.destroyed||this.disabled)return this;var h,i,j,k=a?"show":"hide",m=this.options[k],n=(this.options[a?"hide":"show"],this.options.position),o=this.options.content,p=this.tooltip.css("width"),q=this.tooltip.is(":visible"),r=a||1===m.target.length,s=!c||m.target.length<2||e.target[0]===c.target;return(typeof a).search("boolean|number")&&(a=!q),h=!g.is(":animated")&&q===a&&s,i=h?E:!!this._trigger(k,[90]),this.destroyed?this:(i!==D&&a&&this.focus(c),!i||h?this:(d.attr(g[0],"aria-hidden",!a),a?(e.origin=l(this.mouse),d.isFunction(o.text)&&this._updateContent(o.text,D),d.isFunction(o.title)&&this._updateTitle(o.title,D),!B&&"mouse"===n.target&&n.adjust.mouse&&(d(b).bind("mousemove."+R,this._storeMouse),B=C),p||g.css("width",g.outerWidth(D)),this.reposition(c,arguments[2]),p||g.css("width",""),m.solo&&("string"==typeof m.solo?d(m.solo):d(V,m.solo)).not(g).not(m.target).qtip("hide",d.Event("tooltipsolo"))):(clearTimeout(this.timers.show),delete e.origin,B&&!d(V+'[tracking="true"]:visible',m.solo).not(g).length&&(d(b).unbind("mousemove."+R),B=D),this.blur(c)),j=d.proxy(function(){a?(cb.ie&&g[0].style.removeAttribute("filter"),g.css("overflow",""),"string"==typeof m.autofocus&&d(this.options.show.autofocus,g).focus(),this.options.show.target.trigger("qtip-"+this.id+"-inactive")):g.css({display:"",visibility:"",opacity:"",left:"",top:""}),this._trigger(a?"visible":"hidden")},this),m.effect===D||r===D?(g[k](),j()):d.isFunction(m.effect)?(g.stop(1,1),m.effect.call(g,this),g.queue("fx",function(a){j(),a()})):g.fadeTo(90,a?1:0,j),a&&m.target.trigger("qtip-"+this.id+"-inactive"),this))},y.show=function(a){return this.toggle(C,a)},y.hide=function(a){return this.toggle(D,a)},y.focus=function(a){if(!this.rendered||this.destroyed)return this;var b=d(V),c=this.tooltip,e=parseInt(c[0].style.zIndex,10),f=x.zindex+b.length;return c.hasClass(Z)||this._trigger("focus",[f],a)&&(e!==f&&(b.each(function(){this.style.zIndex>e&&(this.style.zIndex=this.style.zIndex-1)}),b.filter("."+Z).qtip("blur",a)),c.addClass(Z)[0].style.zIndex=f),this},y.blur=function(a){return!this.rendered||this.destroyed?this:(this.tooltip.removeClass(Z),this._trigger("blur",[this.tooltip.css("zIndex")],a),this)},y.disable=function(a){return this.destroyed?this:("toggle"===a?a=!(this.rendered?this.tooltip.hasClass(_):this.disabled):"boolean"!=typeof a&&(a=C),this.rendered&&this.tooltip.toggleClass(_,a).attr("aria-disabled",a),this.disabled=!!a,this)},y.enable=function(){return this.disable(D)},y._createButton=function(){var a=this,b=this.elements,c=b.tooltip,e=this.options.content.button,f="string"==typeof e,g=f?e:"Close tooltip";b.button&&b.button.remove(),b.button=e.jquery?e:d("<a />",{"class":"qtip-close "+(this.options.style.widget?"":R+"-icon"),title:g,"aria-label":g}).prepend(d("<span />",{"class":"ui-icon ui-icon-close",html:"×"})),b.button.appendTo(b.titlebar||c).attr("role","button").click(function(b){return c.hasClass(_)||a.hide(b),D})},y._updateButton=function(a){if(!this.rendered)return D;var b=this.elements.button;a?this._createButton():b.remove()},y._setWidget=function(){var a=this.options.style.widget,b=this.elements,c=b.tooltip,d=c.hasClass(_);c.removeClass(_),_=a?"ui-state-disabled":"qtip-disabled",c.toggleClass(_,d),c.toggleClass("ui-helper-reset "+k(),a).toggleClass(Y,this.options.style.def&&!a),b.content&&b.content.toggleClass(k("content"),a),b.titlebar&&b.titlebar.toggleClass(k("header"),a),b.button&&b.button.toggleClass(R+"-icon",!a)},y._storeMouse=function(a){(this.mouse=l(a)).type="mousemove"},y._bind=function(a,b,c,e,f){var g="."+this._id+(e?"-"+e:"");b.length&&d(a).bind((b.split?b:b.join(g+" "))+g,d.proxy(c,f||this))},y._unbind=function(a,b){d(a).unbind("."+this._id+(b?"-"+b:""))};var gb="."+R;d(function(){r(V,["mouseenter","mouseleave"],function(a){var b="mouseenter"===a.type,c=d(a.currentTarget),e=d(a.relatedTarget||a.target),f=this.options;b?(this.focus(a),c.hasClass(X)&&!c.hasClass(_)&&clearTimeout(this.timers.hide)):"mouse"===f.position.target&&f.hide.event&&f.show.target&&!e.closest(f.show.target[0]).length&&this.hide(a),c.toggleClass($,b)}),r("["+T+"]",W,p)}),y._trigger=function(a,b,c){var e=d.Event("tooltip"+a);return e.originalEvent=c&&d.extend({},c)||this.cache.event||E,this.triggering=a,this.tooltip.trigger(e,[this].concat(b||[])),this.triggering=D,!e.isDefaultPrevented()},y._bindEvents=function(a,b,c,e,f,g){if(e.add(c).length===e.length){var h=[];b=d.map(b,function(b){var c=d.inArray(b,a);return c>-1?(h.push(a.splice(c,1)[0]),void 0):b}),h.length&&this._bind(c,h,function(a){var b=this.rendered?this.tooltip[0].offsetWidth>0:!1;(b?g:f).call(this,a)})}this._bind(c,a,f),this._bind(e,b,g)},y._assignInitialEvents=function(a){function b(a){return this.disabled||this.destroyed?D:(this.cache.event=l(a),this.cache.target=a?d(a.target):[c],clearTimeout(this.timers.show),this.timers.show=m.call(this,function(){this.render("object"==typeof a||e.show.ready)},e.show.delay),void 0)}var e=this.options,f=e.show.target,g=e.hide.target,h=e.show.event?d.trim(""+e.show.event).split(" "):[],i=e.hide.event?d.trim(""+e.hide.event).split(" "):[];/mouse(over|enter)/i.test(e.show.event)&&!/mouse(out|leave)/i.test(e.hide.event)&&i.push("mouseleave"),this._bind(f,"mousemove",function(a){this._storeMouse(a),this.cache.onTarget=C}),this._bindEvents(h,i,f,g,b,function(){clearTimeout(this.timers.show)}),(e.show.ready||e.prerender)&&b.call(this,a)},y._assignEvents=function(){var c=this,e=this.options,f=e.position,g=this.tooltip,h=e.show.target,i=e.hide.target,j=f.container,k=f.viewport,l=d(b),m=(d(b.body),d(a)),r=e.show.event?d.trim(""+e.show.event).split(" "):[],s=e.hide.event?d.trim(""+e.hide.event).split(" "):[];d.each(e.events,function(a,b){c._bind(g,"toggle"===a?["tooltipshow","tooltiphide"]:["tooltip"+a],b,null,g)}),/mouse(out|leave)/i.test(e.hide.event)&&"window"===e.hide.leave&&this._bind(l,["mouseout","blur"],function(a){/select|option/.test(a.target.nodeName)||a.relatedTarget||this.hide(a)}),e.hide.fixed?i=i.add(g.addClass(X)):/mouse(over|enter)/i.test(e.show.event)&&this._bind(i,"mouseleave",function(){clearTimeout(this.timers.show)}),(""+e.hide.event).indexOf("unfocus")>-1&&this._bind(j.closest("html"),["mousedown","touchstart"],function(a){var b=d(a.target),c=this.rendered&&!this.tooltip.hasClass(_)&&this.tooltip[0].offsetWidth>0,e=b.parents(V).filter(this.tooltip[0]).length>0;b[0]===this.target[0]||b[0]===this.tooltip[0]||e||this.target.has(b[0]).length||!c||this.hide(a)}),"number"==typeof e.hide.inactive&&(this._bind(h,"qtip-"+this.id+"-inactive",p),this._bind(i.add(g),x.inactiveEvents,p,"-inactive")),this._bindEvents(r,s,h,i,n,o),this._bind(h.add(g),"mousemove",function(a){if("number"==typeof e.hide.distance){var b=this.cache.origin||{},c=this.options.hide.distance,d=Math.abs;(d(a.pageX-b.pageX)>=c||d(a.pageY-b.pageY)>=c)&&this.hide(a)}this._storeMouse(a)}),"mouse"===f.target&&f.adjust.mouse&&(e.hide.event&&this._bind(h,["mouseenter","mouseleave"],function(a){this.cache.onTarget="mouseenter"===a.type}),this._bind(l,"mousemove",function(a){this.rendered&&this.cache.onTarget&&!this.tooltip.hasClass(_)&&this.tooltip[0].offsetWidth>0&&this.reposition(a)})),(f.adjust.resize||k.length)&&this._bind(d.event.special.resize?k:m,"resize",q),f.adjust.scroll&&this._bind(m.add(f.container),"scroll",q)},y._unassignEvents=function(){var c=[this.options.show.target[0],this.options.hide.target[0],this.rendered&&this.tooltip[0],this.options.position.container[0],this.options.position.viewport[0],this.options.position.container.closest("html")[0],a,b];this._unbind(d([]).pushStack(d.grep(c,function(a){return"object"==typeof a})))},x=d.fn.qtip=function(a,b,e){var f=(""+a).toLowerCase(),g=E,i=d.makeArray(arguments).slice(1),j=i[i.length-1],k=this[0]?d.data(this[0],R):E;return!arguments.length&&k||"api"===f?k:"string"==typeof a?(this.each(function(){var a=d.data(this,R);if(!a)return C;if(j&&j.timeStamp&&(a.cache.event=j),!b||"option"!==f&&"options"!==f)a[f]&&a[f].apply(a,i);else{if(e===c&&!d.isPlainObject(b))return g=a.get(b),D;a.set(b,e)}}),g!==E?g:this):"object"!=typeof a&&arguments.length?void 0:(k=h(d.extend(C,{},a)),this.each(function(a){var b,c;return c=d.isArray(k.id)?k.id[a]:k.id,c=!c||c===D||c.length<1||x.api[c]?x.nextid++:c,b=s(d(this),c,k),b===D?C:(x.api[c]=b,d.each(Q,function(){"initialize"===this.initialize&&this(b)}),b._assignInitialEvents(j),void 0)}))},d.qtip=e,x.api={},d.each({attr:function(a,b){if(this.length){var c=this[0],e="title",f=d.data(c,"qtip");if(a===e&&f&&"object"==typeof f&&f.options.suppress)return arguments.length<2?d.attr(c,bb):(f&&f.options.content.attr===e&&f.cache.attr&&f.set("content.text",b),this.attr(bb,b))}return d.fn["attr"+ab].apply(this,arguments)},clone:function(a){var b=(d([]),d.fn["clone"+ab].apply(this,arguments));return a||b.filter("["+bb+"]").attr("title",function(){return d.attr(this,bb)}).removeAttr(bb),b}},function(a,b){if(!b||d.fn[a+ab])return C;var c=d.fn[a+ab]=d.fn[a];d.fn[a]=function(){return b.apply(this,arguments)||c.apply(this,arguments)}}),d.ui||(d["cleanData"+ab]=d.cleanData,d.cleanData=function(a){for(var b,c=0;(b=d(a[c])).length;c++)if(b.attr(S))try{b.triggerHandler("removeqtip")}catch(e){}d["cleanData"+ab].apply(this,arguments)}),x.version="2.2.0",x.nextid=0,x.inactiveEvents=W,x.zindex=15e3,x.defaults={prerender:D,id:D,overwrite:C,suppress:C,content:{text:C,attr:"title",title:D,button:D},position:{my:"top left",at:"bottom right",target:D,container:D,viewport:D,adjust:{x:0,y:0,mouse:C,scroll:C,resize:C,method:"flipinvert flipinvert"},effect:function(a,b){d(this).animate(b,{duration:200,queue:D})}},show:{target:D,event:"mouseenter",effect:C,delay:90,solo:D,ready:D,autofocus:D},hide:{target:D,event:"mouseleave",effect:C,delay:0,fixed:D,inactive:D,leave:"window",distance:D},style:{classes:"",widget:D,width:D,height:D,def:C},events:{render:E,move:E,show:E,hide:E,toggle:E,visible:E,hidden:E,focus:E,blur:E}};var hb,ib="margin",jb="border",kb="color",lb="background-color",mb="transparent",nb=" !important",ob=!!b.createElement("canvas").getContext,pb=/rgba?\(0, 0, 0(, 0)?\)|transparent|#123456/i,qb={},rb=["Webkit","O","Moz","ms"];if(ob)var sb=a.devicePixelRatio||1,tb=function(){var a=b.createElement("canvas").getContext("2d");return a.backingStorePixelRatio||a.webkitBackingStorePixelRatio||a.mozBackingStorePixelRatio||a.msBackingStorePixelRatio||a.oBackingStorePixelRatio||1}(),ub=sb/tb;else var vb=function(a,b,c){return"<qtipvml:"+a+' xmlns="urn:schemas-microsoft.com:vml" class="qtip-vml" '+(b||"")+' style="behavior: url(#default#VML); '+(c||"")+'" />'};d.extend(w.prototype,{init:function(a){var b,c;c=this.element=a.elements.tip=d("<div />",{"class":R+"-tip"}).prependTo(a.tooltip),ob?(b=d("<canvas />").appendTo(this.element)[0].getContext("2d"),b.lineJoin="miter",b.miterLimit=1e5,b.save()):(b=vb("shape",'coordorigin="0,0"',"position:absolute;"),this.element.html(b+b),a._bind(d("*",c).add(c),["click","mousedown"],function(a){a.stopPropagation()},this._ns)),a._bind(a.tooltip,"tooltipmove",this.reposition,this._ns,this),this.create()},_swapDimensions:function(){this.size[0]=this.options.height,this.size[1]=this.options.width},_resetDimensions:function(){this.size[0]=this.options.width,this.size[1]=this.options.height},_useTitle:function(a){var b=this.qtip.elements.titlebar;return b&&(a.y===J||a.y===N&&this.element.position().top+this.size[1]/2+this.options.offset<b.outerHeight(C))},_parseCorner:function(a){var b=this.qtip.options.position.my;return a===D||b===D?a=D:a===C?a=new z(b.string()):a.string||(a=new z(a),a.fixed=C),a},_parseWidth:function(a,b,c){var d=this.qtip.elements,e=jb+t(b)+"Width";return(c?v(c,e):v(d.content,e)||v(this._useTitle(a)&&d.titlebar||d.content,e)||v(d.tooltip,e))||0},_parseRadius:function(a){var b=this.qtip.elements,c=jb+t(a.y)+t(a.x)+"Radius";return cb.ie<9?0:v(this._useTitle(a)&&b.titlebar||b.content,c)||v(b.tooltip,c)||0},_invalidColour:function(a,b,c){var d=a.css(b);return!d||c&&d===a.css(c)||pb.test(d)?D:d},_parseColours:function(a){var b=this.qtip.elements,c=this.element.css("cssText",""),e=jb+t(a[a.precedance])+t(kb),f=this._useTitle(a)&&b.titlebar||b.content,g=this._invalidColour,h=[];return h[0]=g(c,lb)||g(f,lb)||g(b.content,lb)||g(b.tooltip,lb)||c.css(lb),h[1]=g(c,e,kb)||g(f,e,kb)||g(b.content,e,kb)||g(b.tooltip,e,kb)||b.tooltip.css(e),d("*",c).add(c).css("cssText",lb+":"+mb+nb+";"+jb+":0"+nb+";"),h},_calculateSize:function(a){var b,c,d,e=a.precedance===G,f=this.options.width,g=this.options.height,h="c"===a.abbrev(),i=(e?f:g)*(h?.5:1),j=Math.pow,k=Math.round,l=Math.sqrt(j(i,2)+j(g,2)),m=[this.border/i*l,this.border/g*l];return m[2]=Math.sqrt(j(m[0],2)-j(this.border,2)),m[3]=Math.sqrt(j(m[1],2)-j(this.border,2)),b=l+m[2]+m[3]+(h?0:m[0]),c=b/l,d=[k(c*f),k(c*g)],e?d:d.reverse()},_calculateTip:function(a,b,c){c=c||1,b=b||this.size;var d=b[0]*c,e=b[1]*c,f=Math.ceil(d/2),g=Math.ceil(e/2),h={br:[0,0,d,e,d,0],bl:[0,0,d,0,0,e],tr:[0,e,d,0,d,e],tl:[0,0,0,e,d,e],tc:[0,e,f,0,d,e],bc:[0,0,d,0,f,e],rc:[0,0,d,g,0,e],lc:[d,0,d,e,0,g]};return h.lt=h.br,h.rt=h.bl,h.lb=h.tr,h.rb=h.tl,h[a.abbrev()]},_drawCoords:function(a,b){a.beginPath(),a.moveTo(b[0],b[1]),a.lineTo(b[2],b[3]),a.lineTo(b[4],b[5]),a.closePath()},create:function(){var a=this.corner=(ob||cb.ie)&&this._parseCorner(this.options.corner);return(this.enabled=!!this.corner&&"c"!==this.corner.abbrev())&&(this.qtip.cache.corner=a.clone(),this.update()),this.element.toggle(this.enabled),this.corner},update:function(b,c){if(!this.enabled)return this;var e,f,g,h,i,j,k,l,m=this.qtip.elements,n=this.element,o=n.children(),p=this.options,q=this.size,r=p.mimic,s=Math.round;b||(b=this.qtip.cache.corner||this.corner),r===D?r=b:(r=new z(r),r.precedance=b.precedance,"inherit"===r.x?r.x=b.x:"inherit"===r.y?r.y=b.y:r.x===r.y&&(r[b.precedance]=b[b.precedance])),f=r.precedance,b.precedance===F?this._swapDimensions():this._resetDimensions(),e=this.color=this._parseColours(b),e[1]!==mb?(l=this.border=this._parseWidth(b,b[b.precedance]),p.border&&1>l&&!pb.test(e[1])&&(e[0]=e[1]),this.border=l=p.border!==C?p.border:l):this.border=l=0,k=this.size=this._calculateSize(b),n.css({width:k[0],height:k[1],lineHeight:k[1]+"px"}),j=b.precedance===G?[s(r.x===K?l:r.x===M?k[0]-q[0]-l:(k[0]-q[0])/2),s(r.y===J?k[1]-q[1]:0)]:[s(r.x===K?k[0]-q[0]:0),s(r.y===J?l:r.y===L?k[1]-q[1]-l:(k[1]-q[1])/2)],ob?(g=o[0].getContext("2d"),g.restore(),g.save(),g.clearRect(0,0,6e3,6e3),h=this._calculateTip(r,q,ub),i=this._calculateTip(r,this.size,ub),o.attr(H,k[0]*ub).attr(I,k[1]*ub),o.css(H,k[0]).css(I,k[1]),this._drawCoords(g,i),g.fillStyle=e[1],g.fill(),g.translate(j[0]*ub,j[1]*ub),this._drawCoords(g,h),g.fillStyle=e[0],g.fill()):(h=this._calculateTip(r),h="m"+h[0]+","+h[1]+" l"+h[2]+","+h[3]+" "+h[4]+","+h[5]+" xe",j[2]=l&&/^(r|b)/i.test(b.string())?8===cb.ie?2:1:0,o.css({coordsize:k[0]+l+" "+(k[1]+l),antialias:""+(r.string().indexOf(N)>-1),left:j[0]-j[2]*Number(f===F),top:j[1]-j[2]*Number(f===G),width:k[0]+l,height:k[1]+l}).each(function(a){var b=d(this);b[b.prop?"prop":"attr"]({coordsize:k[0]+l+" "+(k[1]+l),path:h,fillcolor:e[0],filled:!!a,stroked:!a}).toggle(!(!l&&!a)),!a&&b.html(vb("stroke",'weight="'+2*l+'px" color="'+e[1]+'" miterlimit="1000" joinstyle="miter"'))})),a.opera&&setTimeout(function(){m.tip.css({display:"inline-block",visibility:"visible"})},1),c!==D&&this.calculate(b,k)},calculate:function(a,b){if(!this.enabled)return D;var c,e,f=this,g=this.qtip.elements,h=this.element,i=this.options.offset,j=(g.tooltip.hasClass("ui-widget"),{});return a=a||this.corner,c=a.precedance,b=b||this._calculateSize(a),e=[a.x,a.y],c===F&&e.reverse(),d.each(e,function(d,e){var h,k,l;e===N?(h=c===G?K:J,j[h]="50%",j[ib+"-"+h]=-Math.round(b[c===G?0:1]/2)+i):(h=f._parseWidth(a,e,g.tooltip),k=f._parseWidth(a,e,g.content),l=f._parseRadius(a),j[e]=Math.max(-f.border,d?k:i+(l>h?l:-h)))}),j[a[c]]-=b[c===F?0:1],h.css({margin:"",top:"",bottom:"",left:"",right:""}).css(j),j
+},reposition:function(a,b,d){function e(a,b,c,d,e){a===P&&j.precedance===b&&k[d]&&j[c]!==N?j.precedance=j.precedance===F?G:F:a!==P&&k[d]&&(j[b]=j[b]===N?k[d]>0?d:e:j[b]===d?e:d)}function f(a,b,e){j[a]===N?p[ib+"-"+b]=o[a]=g[ib+"-"+b]-k[b]:(h=g[e]!==c?[k[b],-g[b]]:[-k[b],g[b]],(o[a]=Math.max(h[0],h[1]))>h[0]&&(d[b]-=k[b],o[b]=D),p[g[e]!==c?e:b]=o[a])}if(this.enabled){var g,h,i=b.cache,j=this.corner.clone(),k=d.adjusted,l=b.options.position.adjust.method.split(" "),m=l[0],n=l[1]||l[0],o={left:D,top:D,x:0,y:0},p={};this.corner.fixed!==C&&(e(m,F,G,K,M),e(n,G,F,J,L),j.string()===i.corner.string()||i.cornerTop===k.top&&i.cornerLeft===k.left||this.update(j,D)),g=this.calculate(j),g.right!==c&&(g.left=-g.right),g.bottom!==c&&(g.top=-g.bottom),g.user=this.offset,(o.left=m===P&&!!k.left)&&f(F,K,M),(o.top=n===P&&!!k.top)&&f(G,J,L),this.element.css(p).toggle(!(o.x&&o.y||j.x===N&&o.y||j.y===N&&o.x)),d.left-=g.left.charAt?g.user:m!==P||o.top||!o.left&&!o.top?g.left+this.border:0,d.top-=g.top.charAt?g.user:n!==P||o.left||!o.left&&!o.top?g.top+this.border:0,i.cornerLeft=k.left,i.cornerTop=k.top,i.corner=j.clone()}},destroy:function(){this.qtip._unbind(this.qtip.tooltip,this._ns),this.qtip.elements.tip&&this.qtip.elements.tip.find("*").remove().end().remove()}}),hb=Q.tip=function(a){return new w(a,a.options.style.tip)},hb.initialize="render",hb.sanitize=function(a){if(a.style&&"tip"in a.style){var b=a.style.tip;"object"!=typeof b&&(b=a.style.tip={corner:b}),/string|boolean/i.test(typeof b.corner)||(b.corner=C)}},A.tip={"^position.my|style.tip.(corner|mimic|border)$":function(){this.create(),this.qtip.reposition()},"^style.tip.(height|width)$":function(a){this.size=[a.width,a.height],this.update(),this.qtip.reposition()},"^content.title|style.(classes|widget)$":function(){this.update()}},d.extend(C,x.defaults,{style:{tip:{corner:C,mimic:D,width:6,height:6,border:C,offset:0}}}),Q.viewport=function(c,d,e,f,g,h,i){function j(a,b,c,e,f,g,h,i,j){var k=d[f],m=v[a],t=w[a],u=c===P,x=m===f?j:m===g?-j:-j/2,y=t===f?i:t===g?-i:-i/2,z=r[f]+s[f]-(o?0:n[f]),A=z-k,B=k+j-(h===H?p:q)-z,C=x-(v.precedance===a||m===v[b]?y:0)-(t===N?i/2:0);return u?(C=(m===f?1:-1)*x,d[f]+=A>0?A:B>0?-B:0,d[f]=Math.max(-n[f]+s[f],k-C,Math.min(Math.max(-n[f]+s[f]+(h===H?p:q),k+C),d[f],"center"===m?k-x:1e9))):(e*=c===O?2:0,A>0&&(m!==f||B>0)?(d[f]-=C+e,l.invert(a,f)):B>0&&(m!==g||A>0)&&(d[f]-=(m===N?-C:C)+e,l.invert(a,g)),d[f]<r&&-d[f]>B&&(d[f]=k,l=v.clone())),d[f]-k}var k,l,m,n,o,p,q,r,s,t=e.target,u=c.elements.tooltip,v=e.my,w=e.at,x=e.adjust,y=x.method.split(" "),z=y[0],A=y[1]||y[0],B=e.viewport,C=e.container,E=c.cache,Q={left:0,top:0};return B.jquery&&t[0]!==a&&t[0]!==b.body&&"none"!==x.method?(n=C.offset()||Q,o="static"===C.css("position"),k="fixed"===u.css("position"),p=B[0]===a?B.width():B.outerWidth(D),q=B[0]===a?B.height():B.outerHeight(D),r={left:k?0:B.scrollLeft(),top:k?0:B.scrollTop()},s=B.offset()||Q,("shift"!==z||"shift"!==A)&&(l=v.clone()),Q={left:"none"!==z?j(F,G,z,x.x,K,M,H,f,h):0,top:"none"!==A?j(G,F,A,x.y,J,L,I,g,i):0},l&&E.lastClass!==(m=R+"-pos-"+l.abbrev())&&u.removeClass(c.cache.lastClass).addClass(c.cache.lastClass=m),Q):Q}})}(window,document);
+//# sourceMappingURL=http://cdnjs.cloudflare.com/ajax/libs/qtip2/2.2.0//var/www/qtip2/build/tmp/tmp-9404f1j0t40/jquery.qtip.min.map
\ No newline at end of file
--- /dev/null
+/**
+ * jQuery.ScrollTo - Easy element scrolling using jQuery.
+ * Copyright (c) 2007-2009 Ariel Flesler - aflesler(at)gmail(dot)com | http://flesler.blogspot.com
+ * Dual licensed under MIT and GPL.
+ * Date: 5/25/2009
+ * @author Ariel Flesler
+ * @version 1.4.2
+ *
+ * http://flesler.blogspot.com/2007/10/jqueryscrollto.html
+ */
+;(function(d){var k=d.scrollTo=function(a,i,e){d(window).scrollTo(a,i,e)};k.defaults={axis:'xy',duration:parseFloat(d.fn.jquery)>=1.3?0:1};k.window=function(a){return d(window)._scrollable()};d.fn._scrollable=function(){return this.map(function(){var a=this,i=!a.nodeName||d.inArray(a.nodeName.toLowerCase(),['iframe','#document','html','body'])!=-1;if(!i)return a;var e=(a.contentWindow||a).document||a.ownerDocument||a;return d.browser.safari||e.compatMode=='BackCompat'?e.body:e.documentElement})};d.fn.scrollTo=function(n,j,b){if(typeof j=='object'){b=j;j=0}if(typeof b=='function')b={onAfter:b};if(n=='max')n=9e9;b=d.extend({},k.defaults,b);j=j||b.speed||b.duration;b.queue=b.queue&&b.axis.length>1;if(b.queue)j/=2;b.offset=p(b.offset);b.over=p(b.over);return this._scrollable().each(function(){var q=this,r=d(q),f=n,s,g={},u=r.is('html,body');switch(typeof f){case'number':case'string':if(/^([+-]=)?\d+(\.\d+)?(px|%)?$/.test(f)){f=p(f);break}f=d(f,this);case'object':if(f.is||f.style)s=(f=d(f)).offset()}d.each(b.axis.split(''),function(a,i){var e=i=='x'?'Left':'Top',h=e.toLowerCase(),c='scroll'+e,l=q[c],m=k.max(q,i);if(s){g[c]=s[h]+(u?0:l-r.offset()[h]);if(b.margin){g[c]-=parseInt(f.css('margin'+e))||0;g[c]-=parseInt(f.css('border'+e+'Width'))||0}g[c]+=b.offset[h]||0;if(b.over[h])g[c]+=f[i=='x'?'width':'height']()*b.over[h]}else{var o=f[h];g[c]=o.slice&&o.slice(-1)=='%'?parseFloat(o)/100*m:o}if(/^\d+$/.test(g[c]))g[c]=g[c]<=0?0:Math.min(g[c],m);if(!a&&b.queue){if(l!=g[c])t(b.onAfterFirst);delete g[c]}});t(b.onAfter);function t(a){r.animate(g,j,b.easing,a&&function(){a.call(this,n,b)})}}).end()};k.max=function(a,i){var e=i=='x'?'Width':'Height',h='scroll'+e;if(!d(a).is('html,body'))return a[h]-d(a)[e.toLowerCase()]();var c='client'+e,l=a.ownerDocument.documentElement,m=a.ownerDocument.body;return Math.max(l[h],m[h])-Math.min(l[c],m[c])};function p(a){return typeof a=='object'?a:{top:a,left:a}}})(jQuery);
\ No newline at end of file
--- /dev/null
+/*
+ * Tabby jQuery plugin version 0.12
+ *
+ * Ted Devito - http://teddevito.com/demos/textarea.html
+ *
+ * Copyright (c) 2009 Ted Devito
+ */
+ (function(d){d.fn.tabby=function(f){var g=d.extend({},d.fn.tabby.defaults,f);var h=d.fn.tabby.pressed;return this.each(function(){$this=d(this);var i=d.meta?d.extend({},g,$this.data()):g;$this.bind("keydown",function(k){var j=d.fn.tabby.catch_kc(k);if(16==j){h.shft=true}if(17==j){h.ctrl=true;setTimeout("$.fn.tabby.pressed.ctrl = false;",1000)}if(18==j){h.alt=true;setTimeout("$.fn.tabby.pressed.alt = false;",1000)}if(9==j&&!h.ctrl&&!h.alt){k.preventDefault;h.last=j;setTimeout("$.fn.tabby.pressed.last = null;",0);e(d(k.target).get(0),h.shft,i);return false}}).bind("keyup",function(j){if(16==d.fn.tabby.catch_kc(j)){h.shft=false}}).bind("blur",function(j){if(9==h.last){d(j.target).one("focus",function(k){h.last=null}).get(0).focus()}})})};d.fn.tabby.catch_kc=function(f){return f.keyCode?f.keyCode:f.charCode?f.charCode:f.which};d.fn.tabby.pressed={shft:false,ctrl:false,alt:false,last:null};function b(f){if(window.console&&window.console.log){window.console.log("textarea count: "+f.size())}}function e(i,h,g){var f=i.scrollTop;if(i.setSelectionRange){a(i,h,g)}else{if(document.selection){c(i,h,g)}}i.scrollTop=f}d.fn.tabby.defaults={tabString:String.fromCharCode(9)};function a(j,f,u){var t=j.selectionStart;var r=j.selectionEnd;if(t==r){if(f){if(t-u.tabString==j.value.substring(t-u.tabString.length,t)){j.value=j.value.substring(0,t-u.tabString.length)+j.value.substring(t);j.focus();j.setSelectionRange(t-u.tabString.length,t-u.tabString.length)}else{if(t-u.tabString==j.value.substring(t,t+u.tabString.length)){j.value=j.value.substring(0,t)+j.value.substring(t+u.tabString.length);j.focus();j.setSelectionRange(t,t)}}}else{j.value=j.value.substring(0,t)+u.tabString+j.value.substring(t);j.focus();j.setSelectionRange(t+u.tabString.length,t+u.tabString.length)}}else{while(t<j.value.length&&j.value.charAt(t).match(/[ \t]/)){t++}var v=j.value.split("\n");var s=new Array();var l=0;var h=0;var g=false;for(var n in v){h=l+v[n].length;s.push({start:l,end:h,selected:(l<=t&&h>t)||(h>=r&&l<r)||(l>t&&h<r)});l=h+1}var k=0;for(var n in s){if(s[n].selected){var q=s[n].start+k;if(f&&u.tabString==j.value.substring(q,q+u.tabString.length)){j.value=j.value.substring(0,q)+j.value.substring(q+u.tabString.length);k-=u.tabString.length}else{if(!f){j.value=j.value.substring(0,q)+u.tabString+j.value.substring(q);k+=u.tabString.length}}}}j.focus();var p=t+((k>0)?u.tabString.length:(k<0)?-u.tabString.length:0);var m=r+k;j.setSelectionRange(p,m)}}function c(q,w,f){var p=document.selection.createRange();if(q==p.parentElement()){if(""==p.text){if(w){var l=p.getBookmark();p.moveStart("character",-f.tabString.length);if(f.tabString==p.text){p.text=""}else{p.moveToBookmark(l);p.moveEnd("character",f.tabString.length);if(f.tabString==p.text){p.text=""}}p.collapse(true);p.select()}else{p.text=f.tabString;p.collapse(false);p.select()}}else{var k=p.text;var n=k.length;var u=k.split("\r\n");var z=document.body.createTextRange();z.moveToElementText(q);z.setEndPoint("EndToStart",p);var m=z.text;var x=m.split("\r\n");var r=m.length;var y=document.body.createTextRange();y.moveToElementText(q);y.setEndPoint("StartToEnd",p);var v=y.text;var g=document.body.createTextRange();g.moveToElementText(q);g.setEndPoint("StartToEnd",z);var s=g.text;var h=d(q).html();d("#r3").text(r+" + "+n+" + "+v.length+" = "+h.length);if((r+s.length)<h.length){x.push("");r+=2;if(w&&f.tabString==u[0].substring(0,f.tabString.length)){u[0]=u[0].substring(f.tabString.length)}else{if(!w){u[0]=f.tabString+u[0]}}}else{if(w&&f.tabString==x[x.length-1].substring(0,f.tabString.length)){x[x.length-1]=x[x.length-1].substring(f.tabString.length)}else{if(!w){x[x.length-1]=f.tabString+x[x.length-1]}}}for(var t=1;t<u.length;t++){if(w&&f.tabString==u[t].substring(0,f.tabString.length)){u[t]=u[t].substring(f.tabString.length)}else{if(!w){u[t]=f.tabString+u[t]}}}if(1==x.length&&0==r){if(w&&f.tabString==u[0].substring(0,f.tabString.length)){u[0]=u[0].substring(f.tabString.length)}else{if(!w){u[0]=f.tabString+u[0]}}}if((r+n+v.length)<h.length){u.push("");n+=2}z.text=x.join("\r\n");p.text=u.join("\r\n");var j=document.body.createTextRange();j.moveToElementText(q);if(0<r){j.setEndPoint("StartToEnd",z)}else{j.setEndPoint("StartToStart",z)}j.setEndPoint("EndToEnd",p);j.select()}}}})(jQuery);
\ No newline at end of file
--- /dev/null
+// Knockout JavaScript library v3.1.0
+// (c) Steven Sanderson - http://knockoutjs.com/
+// License: MIT (http://www.opensource.org/licenses/mit-license.php)
+
+(function(){
+var DEBUG=true;
+(function(undefined){
+ // (0, eval)('this') is a robust way of getting a reference to the global object
+ // For details, see http://stackoverflow.com/questions/14119988/return-this-0-evalthis/14120023#14120023
+ var window = this || (0, eval)('this'),
+ document = window['document'],
+ navigator = window['navigator'],
+ jQuery = window["jQuery"],
+ JSON = window["JSON"];
+(function(factory) {
+ // Support three module loading scenarios
+ if (typeof require === 'function' && typeof exports === 'object' && typeof module === 'object') {
+ // [1] CommonJS/Node.js
+ var target = module['exports'] || exports; // module.exports is for Node.js
+ factory(target);
+ } else if (typeof define === 'function' && define['amd']) {
+ // [2] AMD anonymous module
+ define(['exports'], factory);
+ } else {
+ // [3] No module loader (plain <script> tag) - put directly in global namespace
+ factory(window['ko'] = {});
+ }
+}(function(koExports){
+// Internally, all KO objects are attached to koExports (even the non-exported ones whose names will be minified by the closure compiler).
+// In the future, the following "ko" variable may be made distinct from "koExports" so that private objects are not externally reachable.
+var ko = typeof koExports !== 'undefined' ? koExports : {};
+// Google Closure Compiler helpers (used only to make the minified file smaller)
+ko.exportSymbol = function(koPath, object) {
+ var tokens = koPath.split(".");
+
+ // In the future, "ko" may become distinct from "koExports" (so that non-exported objects are not reachable)
+ // At that point, "target" would be set to: (typeof koExports !== "undefined" ? koExports : ko)
+ var target = ko;
+
+ for (var i = 0; i < tokens.length - 1; i++)
+ target = target[tokens[i]];
+ target[tokens[tokens.length - 1]] = object;
+};
+ko.exportProperty = function(owner, publicName, object) {
+ owner[publicName] = object;
+};
+ko.version = "3.1.0";
+
+ko.exportSymbol('version', ko.version);
+ko.utils = (function () {
+ function objectForEach(obj, action) {
+ for (var prop in obj) {
+ if (obj.hasOwnProperty(prop)) {
+ action(prop, obj[prop]);
+ }
+ }
+ }
+
+ function extend(target, source) {
+ if (source) {
+ for(var prop in source) {
+ if(source.hasOwnProperty(prop)) {
+ target[prop] = source[prop];
+ }
+ }
+ }
+ return target;
+ }
+
+ function setPrototypeOf(obj, proto) {
+ obj.__proto__ = proto;
+ return obj;
+ }
+
+ var canSetPrototype = ({ __proto__: [] } instanceof Array);
+
+ // Represent the known event types in a compact way, then at runtime transform it into a hash with event name as key (for fast lookup)
+ var knownEvents = {}, knownEventTypesByEventName = {};
+ var keyEventTypeName = (navigator && /Firefox\/2/i.test(navigator.userAgent)) ? 'KeyboardEvent' : 'UIEvents';
+ knownEvents[keyEventTypeName] = ['keyup', 'keydown', 'keypress'];
+ knownEvents['MouseEvents'] = ['click', 'dblclick', 'mousedown', 'mouseup', 'mousemove', 'mouseover', 'mouseout', 'mouseenter', 'mouseleave'];
+ objectForEach(knownEvents, function(eventType, knownEventsForType) {
+ if (knownEventsForType.length) {
+ for (var i = 0, j = knownEventsForType.length; i < j; i++)
+ knownEventTypesByEventName[knownEventsForType[i]] = eventType;
+ }
+ });
+ var eventsThatMustBeRegisteredUsingAttachEvent = { 'propertychange': true }; // Workaround for an IE9 issue - https://github.com/SteveSanderson/knockout/issues/406
+
+ // Detect IE versions for bug workarounds (uses IE conditionals, not UA string, for robustness)
+ // Note that, since IE 10 does not support conditional comments, the following logic only detects IE < 10.
+ // Currently this is by design, since IE 10+ behaves correctly when treated as a standard browser.
+ // If there is a future need to detect specific versions of IE10+, we will amend this.
+ var ieVersion = document && (function() {
+ var version = 3, div = document.createElement('div'), iElems = div.getElementsByTagName('i');
+
+ // Keep constructing conditional HTML blocks until we hit one that resolves to an empty fragment
+ while (
+ div.innerHTML = '<!--[if gt IE ' + (++version) + ']><i></i><![endif]-->',
+ iElems[0]
+ ) {}
+ return version > 4 ? version : undefined;
+ }());
+ var isIe6 = ieVersion === 6,
+ isIe7 = ieVersion === 7;
+
+ function isClickOnCheckableElement(element, eventType) {
+ if ((ko.utils.tagNameLower(element) !== "input") || !element.type) return false;
+ if (eventType.toLowerCase() != "click") return false;
+ var inputType = element.type;
+ return (inputType == "checkbox") || (inputType == "radio");
+ }
+
+ return {
+ fieldsIncludedWithJsonPost: ['authenticity_token', /^__RequestVerificationToken(_.*)?$/],
+
+ arrayForEach: function (array, action) {
+ for (var i = 0, j = array.length; i < j; i++)
+ action(array[i], i);
+ },
+
+ arrayIndexOf: function (array, item) {
+ if (typeof Array.prototype.indexOf == "function")
+ return Array.prototype.indexOf.call(array, item);
+ for (var i = 0, j = array.length; i < j; i++)
+ if (array[i] === item)
+ return i;
+ return -1;
+ },
+
+ arrayFirst: function (array, predicate, predicateOwner) {
+ for (var i = 0, j = array.length; i < j; i++)
+ if (predicate.call(predicateOwner, array[i], i))
+ return array[i];
+ return null;
+ },
+
+ arrayRemoveItem: function (array, itemToRemove) {
+ var index = ko.utils.arrayIndexOf(array, itemToRemove);
+ if (index > 0) {
+ array.splice(index, 1);
+ }
+ else if (index === 0) {
+ array.shift();
+ }
+ },
+
+ arrayGetDistinctValues: function (array) {
+ array = array || [];
+ var result = [];
+ for (var i = 0, j = array.length; i < j; i++) {
+ if (ko.utils.arrayIndexOf(result, array[i]) < 0)
+ result.push(array[i]);
+ }
+ return result;
+ },
+
+ arrayMap: function (array, mapping) {
+ array = array || [];
+ var result = [];
+ for (var i = 0, j = array.length; i < j; i++)
+ result.push(mapping(array[i], i));
+ return result;
+ },
+
+ arrayFilter: function (array, predicate) {
+ array = array || [];
+ var result = [];
+ for (var i = 0, j = array.length; i < j; i++)
+ if (predicate(array[i], i))
+ result.push(array[i]);
+ return result;
+ },
+
+ arrayPushAll: function (array, valuesToPush) {
+ if (valuesToPush instanceof Array)
+ array.push.apply(array, valuesToPush);
+ else
+ for (var i = 0, j = valuesToPush.length; i < j; i++)
+ array.push(valuesToPush[i]);
+ return array;
+ },
+
+ addOrRemoveItem: function(array, value, included) {
+ var existingEntryIndex = ko.utils.arrayIndexOf(ko.utils.peekObservable(array), value);
+ if (existingEntryIndex < 0) {
+ if (included)
+ array.push(value);
+ } else {
+ if (!included)
+ array.splice(existingEntryIndex, 1);
+ }
+ },
+
+ canSetPrototype: canSetPrototype,
+
+ extend: extend,
+
+ setPrototypeOf: setPrototypeOf,
+
+ setPrototypeOfOrExtend: canSetPrototype ? setPrototypeOf : extend,
+
+ objectForEach: objectForEach,
+
+ objectMap: function(source, mapping) {
+ if (!source)
+ return source;
+ var target = {};
+ for (var prop in source) {
+ if (source.hasOwnProperty(prop)) {
+ target[prop] = mapping(source[prop], prop, source);
+ }
+ }
+ return target;
+ },
+
+ emptyDomNode: function (domNode) {
+ while (domNode.firstChild) {
+ ko.removeNode(domNode.firstChild);
+ }
+ },
+
+ moveCleanedNodesToContainerElement: function(nodes) {
+ // Ensure it's a real array, as we're about to reparent the nodes and
+ // we don't want the underlying collection to change while we're doing that.
+ var nodesArray = ko.utils.makeArray(nodes);
+
+ var container = document.createElement('div');
+ for (var i = 0, j = nodesArray.length; i < j; i++) {
+ container.appendChild(ko.cleanNode(nodesArray[i]));
+ }
+ return container;
+ },
+
+ cloneNodes: function (nodesArray, shouldCleanNodes) {
+ for (var i = 0, j = nodesArray.length, newNodesArray = []; i < j; i++) {
+ var clonedNode = nodesArray[i].cloneNode(true);
+ newNodesArray.push(shouldCleanNodes ? ko.cleanNode(clonedNode) : clonedNode);
+ }
+ return newNodesArray;
+ },
+
+ setDomNodeChildren: function (domNode, childNodes) {
+ ko.utils.emptyDomNode(domNode);
+ if (childNodes) {
+ for (var i = 0, j = childNodes.length; i < j; i++)
+ domNode.appendChild(childNodes[i]);
+ }
+ },
+
+ replaceDomNodes: function (nodeToReplaceOrNodeArray, newNodesArray) {
+ var nodesToReplaceArray = nodeToReplaceOrNodeArray.nodeType ? [nodeToReplaceOrNodeArray] : nodeToReplaceOrNodeArray;
+ if (nodesToReplaceArray.length > 0) {
+ var insertionPoint = nodesToReplaceArray[0];
+ var parent = insertionPoint.parentNode;
+ for (var i = 0, j = newNodesArray.length; i < j; i++)
+ parent.insertBefore(newNodesArray[i], insertionPoint);
+ for (var i = 0, j = nodesToReplaceArray.length; i < j; i++) {
+ ko.removeNode(nodesToReplaceArray[i]);
+ }
+ }
+ },
+
+ fixUpContinuousNodeArray: function(continuousNodeArray, parentNode) {
+ // Before acting on a set of nodes that were previously outputted by a template function, we have to reconcile
+ // them against what is in the DOM right now. It may be that some of the nodes have already been removed, or that
+ // new nodes might have been inserted in the middle, for example by a binding. Also, there may previously have been
+ // leading comment nodes (created by rewritten string-based templates) that have since been removed during binding.
+ // So, this function translates the old "map" output array into its best guess of the set of current DOM nodes.
+ //
+ // Rules:
+ // [A] Any leading nodes that have been removed should be ignored
+ // These most likely correspond to memoization nodes that were already removed during binding
+ // See https://github.com/SteveSanderson/knockout/pull/440
+ // [B] We want to output a continuous series of nodes. So, ignore any nodes that have already been removed,
+ // and include any nodes that have been inserted among the previous collection
+
+ if (continuousNodeArray.length) {
+ // The parent node can be a virtual element; so get the real parent node
+ parentNode = (parentNode.nodeType === 8 && parentNode.parentNode) || parentNode;
+
+ // Rule [A]
+ while (continuousNodeArray.length && continuousNodeArray[0].parentNode !== parentNode)
+ continuousNodeArray.shift();
+
+ // Rule [B]
+ if (continuousNodeArray.length > 1) {
+ var current = continuousNodeArray[0], last = continuousNodeArray[continuousNodeArray.length - 1];
+ // Replace with the actual new continuous node set
+ continuousNodeArray.length = 0;
+ while (current !== last) {
+ continuousNodeArray.push(current);
+ current = current.nextSibling;
+ if (!current) // Won't happen, except if the developer has manually removed some DOM elements (then we're in an undefined scenario)
+ return;
+ }
+ continuousNodeArray.push(last);
+ }
+ }
+ return continuousNodeArray;
+ },
+
+ setOptionNodeSelectionState: function (optionNode, isSelected) {
+ // IE6 sometimes throws "unknown error" if you try to write to .selected directly, whereas Firefox struggles with setAttribute. Pick one based on browser.
+ if (ieVersion < 7)
+ optionNode.setAttribute("selected", isSelected);
+ else
+ optionNode.selected = isSelected;
+ },
+
+ stringTrim: function (string) {
+ return string === null || string === undefined ? '' :
+ string.trim ?
+ string.trim() :
+ string.toString().replace(/^[\s\xa0]+|[\s\xa0]+$/g, '');
+ },
+
+ stringTokenize: function (string, delimiter) {
+ var result = [];
+ var tokens = (string || "").split(delimiter);
+ for (var i = 0, j = tokens.length; i < j; i++) {
+ var trimmed = ko.utils.stringTrim(tokens[i]);
+ if (trimmed !== "")
+ result.push(trimmed);
+ }
+ return result;
+ },
+
+ stringStartsWith: function (string, startsWith) {
+ string = string || "";
+ if (startsWith.length > string.length)
+ return false;
+ return string.substring(0, startsWith.length) === startsWith;
+ },
+
+ domNodeIsContainedBy: function (node, containedByNode) {
+ if (node === containedByNode)
+ return true;
+ if (node.nodeType === 11)
+ return false; // Fixes issue #1162 - can't use node.contains for document fragments on IE8
+ if (containedByNode.contains)
+ return containedByNode.contains(node.nodeType === 3 ? node.parentNode : node);
+ if (containedByNode.compareDocumentPosition)
+ return (containedByNode.compareDocumentPosition(node) & 16) == 16;
+ while (node && node != containedByNode) {
+ node = node.parentNode;
+ }
+ return !!node;
+ },
+
+ domNodeIsAttachedToDocument: function (node) {
+ return ko.utils.domNodeIsContainedBy(node, node.ownerDocument.documentElement);
+ },
+
+ anyDomNodeIsAttachedToDocument: function(nodes) {
+ return !!ko.utils.arrayFirst(nodes, ko.utils.domNodeIsAttachedToDocument);
+ },
+
+ tagNameLower: function(element) {
+ // For HTML elements, tagName will always be upper case; for XHTML elements, it'll be lower case.
+ // Possible future optimization: If we know it's an element from an XHTML document (not HTML),
+ // we don't need to do the .toLowerCase() as it will always be lower case anyway.
+ return element && element.tagName && element.tagName.toLowerCase();
+ },
+
+ registerEventHandler: function (element, eventType, handler) {
+ var mustUseAttachEvent = ieVersion && eventsThatMustBeRegisteredUsingAttachEvent[eventType];
+ if (!mustUseAttachEvent && jQuery) {
+ jQuery(element)['bind'](eventType, handler);
+ } else if (!mustUseAttachEvent && typeof element.addEventListener == "function")
+ element.addEventListener(eventType, handler, false);
+ else if (typeof element.attachEvent != "undefined") {
+ var attachEventHandler = function (event) { handler.call(element, event); },
+ attachEventName = "on" + eventType;
+ element.attachEvent(attachEventName, attachEventHandler);
+
+ // IE does not dispose attachEvent handlers automatically (unlike with addEventListener)
+ // so to avoid leaks, we have to remove them manually. See bug #856
+ ko.utils.domNodeDisposal.addDisposeCallback(element, function() {
+ element.detachEvent(attachEventName, attachEventHandler);
+ });
+ } else
+ throw new Error("Browser doesn't support addEventListener or attachEvent");
+ },
+
+ triggerEvent: function (element, eventType) {
+ if (!(element && element.nodeType))
+ throw new Error("element must be a DOM node when calling triggerEvent");
+
+ // For click events on checkboxes and radio buttons, jQuery toggles the element checked state *after* the
+ // event handler runs instead of *before*. (This was fixed in 1.9 for checkboxes but not for radio buttons.)
+ // IE doesn't change the checked state when you trigger the click event using "fireEvent".
+ // In both cases, we'll use the click method instead.
+ var useClickWorkaround = isClickOnCheckableElement(element, eventType);
+
+ if (jQuery && !useClickWorkaround) {
+ jQuery(element)['trigger'](eventType);
+ } else if (typeof document.createEvent == "function") {
+ if (typeof element.dispatchEvent == "function") {
+ var eventCategory = knownEventTypesByEventName[eventType] || "HTMLEvents";
+ var event = document.createEvent(eventCategory);
+ event.initEvent(eventType, true, true, window, 0, 0, 0, 0, 0, false, false, false, false, 0, element);
+ element.dispatchEvent(event);
+ }
+ else
+ throw new Error("The supplied element doesn't support dispatchEvent");
+ } else if (useClickWorkaround && element.click) {
+ element.click();
+ } else if (typeof element.fireEvent != "undefined") {
+ element.fireEvent("on" + eventType);
+ } else {
+ throw new Error("Browser doesn't support triggering events");
+ }
+ },
+
+ unwrapObservable: function (value) {
+ return ko.isObservable(value) ? value() : value;
+ },
+
+ peekObservable: function (value) {
+ return ko.isObservable(value) ? value.peek() : value;
+ },
+
+ toggleDomNodeCssClass: function (node, classNames, shouldHaveClass) {
+ if (classNames) {
+ var cssClassNameRegex = /\S+/g,
+ currentClassNames = node.className.match(cssClassNameRegex) || [];
+ ko.utils.arrayForEach(classNames.match(cssClassNameRegex), function(className) {
+ ko.utils.addOrRemoveItem(currentClassNames, className, shouldHaveClass);
+ });
+ node.className = currentClassNames.join(" ");
+ }
+ },
+
+ setTextContent: function(element, textContent) {
+ var value = ko.utils.unwrapObservable(textContent);
+ if ((value === null) || (value === undefined))
+ value = "";
+
+ // We need there to be exactly one child: a text node.
+ // If there are no children, more than one, or if it's not a text node,
+ // we'll clear everything and create a single text node.
+ var innerTextNode = ko.virtualElements.firstChild(element);
+ if (!innerTextNode || innerTextNode.nodeType != 3 || ko.virtualElements.nextSibling(innerTextNode)) {
+ ko.virtualElements.setDomNodeChildren(element, [element.ownerDocument.createTextNode(value)]);
+ } else {
+ innerTextNode.data = value;
+ }
+
+ ko.utils.forceRefresh(element);
+ },
+
+ setElementName: function(element, name) {
+ element.name = name;
+
+ // Workaround IE 6/7 issue
+ // - https://github.com/SteveSanderson/knockout/issues/197
+ // - http://www.matts411.com/post/setting_the_name_attribute_in_ie_dom/
+ if (ieVersion <= 7) {
+ try {
+ element.mergeAttributes(document.createElement("<input name='" + element.name + "'/>"), false);
+ }
+ catch(e) {} // For IE9 with doc mode "IE9 Standards" and browser mode "IE9 Compatibility View"
+ }
+ },
+
+ forceRefresh: function(node) {
+ // Workaround for an IE9 rendering bug - https://github.com/SteveSanderson/knockout/issues/209
+ if (ieVersion >= 9) {
+ // For text nodes and comment nodes (most likely virtual elements), we will have to refresh the container
+ var elem = node.nodeType == 1 ? node : node.parentNode;
+ if (elem.style)
+ elem.style.zoom = elem.style.zoom;
+ }
+ },
+
+ ensureSelectElementIsRenderedCorrectly: function(selectElement) {
+ // Workaround for IE9 rendering bug - it doesn't reliably display all the text in dynamically-added select boxes unless you force it to re-render by updating the width.
+ // (See https://github.com/SteveSanderson/knockout/issues/312, http://stackoverflow.com/questions/5908494/select-only-shows-first-char-of-selected-option)
+ // Also fixes IE7 and IE8 bug that causes selects to be zero width if enclosed by 'if' or 'with'. (See issue #839)
+ if (ieVersion) {
+ var originalWidth = selectElement.style.width;
+ selectElement.style.width = 0;
+ selectElement.style.width = originalWidth;
+ }
+ },
+
+ range: function (min, max) {
+ min = ko.utils.unwrapObservable(min);
+ max = ko.utils.unwrapObservable(max);
+ var result = [];
+ for (var i = min; i <= max; i++)
+ result.push(i);
+ return result;
+ },
+
+ makeArray: function(arrayLikeObject) {
+ var result = [];
+ for (var i = 0, j = arrayLikeObject.length; i < j; i++) {
+ result.push(arrayLikeObject[i]);
+ };
+ return result;
+ },
+
+ isIe6 : isIe6,
+ isIe7 : isIe7,
+ ieVersion : ieVersion,
+
+ getFormFields: function(form, fieldName) {
+ var fields = ko.utils.makeArray(form.getElementsByTagName("input")).concat(ko.utils.makeArray(form.getElementsByTagName("textarea")));
+ var isMatchingField = (typeof fieldName == 'string')
+ ? function(field) { return field.name === fieldName }
+ : function(field) { return fieldName.test(field.name) }; // Treat fieldName as regex or object containing predicate
+ var matches = [];
+ for (var i = fields.length - 1; i >= 0; i--) {
+ if (isMatchingField(fields[i]))
+ matches.push(fields[i]);
+ };
+ return matches;
+ },
+
+ parseJson: function (jsonString) {
+ if (typeof jsonString == "string") {
+ jsonString = ko.utils.stringTrim(jsonString);
+ if (jsonString) {
+ if (JSON && JSON.parse) // Use native parsing where available
+ return JSON.parse(jsonString);
+ return (new Function("return " + jsonString))(); // Fallback on less safe parsing for older browsers
+ }
+ }
+ return null;
+ },
+
+ stringifyJson: function (data, replacer, space) { // replacer and space are optional
+ if (!JSON || !JSON.stringify)
+ throw new Error("Cannot find JSON.stringify(). Some browsers (e.g., IE < 8) don't support it natively, but you can overcome this by adding a script reference to json2.js, downloadable from http://www.json.org/json2.js");
+ return JSON.stringify(ko.utils.unwrapObservable(data), replacer, space);
+ },
+
+ postJson: function (urlOrForm, data, options) {
+ options = options || {};
+ var params = options['params'] || {};
+ var includeFields = options['includeFields'] || this.fieldsIncludedWithJsonPost;
+ var url = urlOrForm;
+
+ // If we were given a form, use its 'action' URL and pick out any requested field values
+ if((typeof urlOrForm == 'object') && (ko.utils.tagNameLower(urlOrForm) === "form")) {
+ var originalForm = urlOrForm;
+ url = originalForm.action;
+ for (var i = includeFields.length - 1; i >= 0; i--) {
+ var fields = ko.utils.getFormFields(originalForm, includeFields[i]);
+ for (var j = fields.length - 1; j >= 0; j--)
+ params[fields[j].name] = fields[j].value;
+ }
+ }
+
+ data = ko.utils.unwrapObservable(data);
+ var form = document.createElement("form");
+ form.style.display = "none";
+ form.action = url;
+ form.method = "post";
+ for (var key in data) {
+ // Since 'data' this is a model object, we include all properties including those inherited from its prototype
+ var input = document.createElement("input");
+ input.name = key;
+ input.value = ko.utils.stringifyJson(ko.utils.unwrapObservable(data[key]));
+ form.appendChild(input);
+ }
+ objectForEach(params, function(key, value) {
+ var input = document.createElement("input");
+ input.name = key;
+ input.value = value;
+ form.appendChild(input);
+ });
+ document.body.appendChild(form);
+ options['submitter'] ? options['submitter'](form) : form.submit();
+ setTimeout(function () { form.parentNode.removeChild(form); }, 0);
+ }
+ }
+}());
+
+ko.exportSymbol('utils', ko.utils);
+ko.exportSymbol('utils.arrayForEach', ko.utils.arrayForEach);
+ko.exportSymbol('utils.arrayFirst', ko.utils.arrayFirst);
+ko.exportSymbol('utils.arrayFilter', ko.utils.arrayFilter);
+ko.exportSymbol('utils.arrayGetDistinctValues', ko.utils.arrayGetDistinctValues);
+ko.exportSymbol('utils.arrayIndexOf', ko.utils.arrayIndexOf);
+ko.exportSymbol('utils.arrayMap', ko.utils.arrayMap);
+ko.exportSymbol('utils.arrayPushAll', ko.utils.arrayPushAll);
+ko.exportSymbol('utils.arrayRemoveItem', ko.utils.arrayRemoveItem);
+ko.exportSymbol('utils.extend', ko.utils.extend);
+ko.exportSymbol('utils.fieldsIncludedWithJsonPost', ko.utils.fieldsIncludedWithJsonPost);
+ko.exportSymbol('utils.getFormFields', ko.utils.getFormFields);
+ko.exportSymbol('utils.peekObservable', ko.utils.peekObservable);
+ko.exportSymbol('utils.postJson', ko.utils.postJson);
+ko.exportSymbol('utils.parseJson', ko.utils.parseJson);
+ko.exportSymbol('utils.registerEventHandler', ko.utils.registerEventHandler);
+ko.exportSymbol('utils.stringifyJson', ko.utils.stringifyJson);
+ko.exportSymbol('utils.range', ko.utils.range);
+ko.exportSymbol('utils.toggleDomNodeCssClass', ko.utils.toggleDomNodeCssClass);
+ko.exportSymbol('utils.triggerEvent', ko.utils.triggerEvent);
+ko.exportSymbol('utils.unwrapObservable', ko.utils.unwrapObservable);
+ko.exportSymbol('utils.objectForEach', ko.utils.objectForEach);
+ko.exportSymbol('utils.addOrRemoveItem', ko.utils.addOrRemoveItem);
+ko.exportSymbol('unwrap', ko.utils.unwrapObservable); // Convenient shorthand, because this is used so commonly
+
+if (!Function.prototype['bind']) {
+ // Function.prototype.bind is a standard part of ECMAScript 5th Edition (December 2009, http://www.ecma-international.org/publications/files/ECMA-ST/ECMA-262.pdf)
+ // In case the browser doesn't implement it natively, provide a JavaScript implementation. This implementation is based on the one in prototype.js
+ Function.prototype['bind'] = function (object) {
+ var originalFunction = this, args = Array.prototype.slice.call(arguments), object = args.shift();
+ return function () {
+ return originalFunction.apply(object, args.concat(Array.prototype.slice.call(arguments)));
+ };
+ };
+}
+
+ko.utils.domData = new (function () {
+ var uniqueId = 0;
+ var dataStoreKeyExpandoPropertyName = "__ko__" + (new Date).getTime();
+ var dataStore = {};
+
+ function getAll(node, createIfNotFound) {
+ var dataStoreKey = node[dataStoreKeyExpandoPropertyName];
+ var hasExistingDataStore = dataStoreKey && (dataStoreKey !== "null") && dataStore[dataStoreKey];
+ if (!hasExistingDataStore) {
+ if (!createIfNotFound)
+ return undefined;
+ dataStoreKey = node[dataStoreKeyExpandoPropertyName] = "ko" + uniqueId++;
+ dataStore[dataStoreKey] = {};
+ }
+ return dataStore[dataStoreKey];
+ }
+
+ return {
+ get: function (node, key) {
+ var allDataForNode = getAll(node, false);
+ return allDataForNode === undefined ? undefined : allDataForNode[key];
+ },
+ set: function (node, key, value) {
+ if (value === undefined) {
+ // Make sure we don't actually create a new domData key if we are actually deleting a value
+ if (getAll(node, false) === undefined)
+ return;
+ }
+ var allDataForNode = getAll(node, true);
+ allDataForNode[key] = value;
+ },
+ clear: function (node) {
+ var dataStoreKey = node[dataStoreKeyExpandoPropertyName];
+ if (dataStoreKey) {
+ delete dataStore[dataStoreKey];
+ node[dataStoreKeyExpandoPropertyName] = null;
+ return true; // Exposing "did clean" flag purely so specs can infer whether things have been cleaned up as intended
+ }
+ return false;
+ },
+
+ nextKey: function () {
+ return (uniqueId++) + dataStoreKeyExpandoPropertyName;
+ }
+ };
+})();
+
+ko.exportSymbol('utils.domData', ko.utils.domData);
+ko.exportSymbol('utils.domData.clear', ko.utils.domData.clear); // Exporting only so specs can clear up after themselves fully
+
+ko.utils.domNodeDisposal = new (function () {
+ var domDataKey = ko.utils.domData.nextKey();
+ var cleanableNodeTypes = { 1: true, 8: true, 9: true }; // Element, Comment, Document
+ var cleanableNodeTypesWithDescendants = { 1: true, 9: true }; // Element, Document
+
+ function getDisposeCallbacksCollection(node, createIfNotFound) {
+ var allDisposeCallbacks = ko.utils.domData.get(node, domDataKey);
+ if ((allDisposeCallbacks === undefined) && createIfNotFound) {
+ allDisposeCallbacks = [];
+ ko.utils.domData.set(node, domDataKey, allDisposeCallbacks);
+ }
+ return allDisposeCallbacks;
+ }
+ function destroyCallbacksCollection(node) {
+ ko.utils.domData.set(node, domDataKey, undefined);
+ }
+
+ function cleanSingleNode(node) {
+ // Run all the dispose callbacks
+ var callbacks = getDisposeCallbacksCollection(node, false);
+ if (callbacks) {
+ callbacks = callbacks.slice(0); // Clone, as the array may be modified during iteration (typically, callbacks will remove themselves)
+ for (var i = 0; i < callbacks.length; i++)
+ callbacks[i](node);
+ }
+
+ // Erase the DOM data
+ ko.utils.domData.clear(node);
+
+ // Perform cleanup needed by external libraries (currently only jQuery, but can be extended)
+ ko.utils.domNodeDisposal["cleanExternalData"](node);
+
+ // Clear any immediate-child comment nodes, as these wouldn't have been found by
+ // node.getElementsByTagName("*") in cleanNode() (comment nodes aren't elements)
+ if (cleanableNodeTypesWithDescendants[node.nodeType])
+ cleanImmediateCommentTypeChildren(node);
+ }
+
+ function cleanImmediateCommentTypeChildren(nodeWithChildren) {
+ var child, nextChild = nodeWithChildren.firstChild;
+ while (child = nextChild) {
+ nextChild = child.nextSibling;
+ if (child.nodeType === 8)
+ cleanSingleNode(child);
+ }
+ }
+
+ return {
+ addDisposeCallback : function(node, callback) {
+ if (typeof callback != "function")
+ throw new Error("Callback must be a function");
+ getDisposeCallbacksCollection(node, true).push(callback);
+ },
+
+ removeDisposeCallback : function(node, callback) {
+ var callbacksCollection = getDisposeCallbacksCollection(node, false);
+ if (callbacksCollection) {
+ ko.utils.arrayRemoveItem(callbacksCollection, callback);
+ if (callbacksCollection.length == 0)
+ destroyCallbacksCollection(node);
+ }
+ },
+
+ cleanNode : function(node) {
+ // First clean this node, where applicable
+ if (cleanableNodeTypes[node.nodeType]) {
+ cleanSingleNode(node);
+
+ // ... then its descendants, where applicable
+ if (cleanableNodeTypesWithDescendants[node.nodeType]) {
+ // Clone the descendants list in case it changes during iteration
+ var descendants = [];
+ ko.utils.arrayPushAll(descendants, node.getElementsByTagName("*"));
+ for (var i = 0, j = descendants.length; i < j; i++)
+ cleanSingleNode(descendants[i]);
+ }
+ }
+ return node;
+ },
+
+ removeNode : function(node) {
+ ko.cleanNode(node);
+ if (node.parentNode)
+ node.parentNode.removeChild(node);
+ },
+
+ "cleanExternalData" : function (node) {
+ // Special support for jQuery here because it's so commonly used.
+ // Many jQuery plugins (including jquery.tmpl) store data using jQuery's equivalent of domData
+ // so notify it to tear down any resources associated with the node & descendants here.
+ if (jQuery && (typeof jQuery['cleanData'] == "function"))
+ jQuery['cleanData']([node]);
+ }
+ }
+})();
+ko.cleanNode = ko.utils.domNodeDisposal.cleanNode; // Shorthand name for convenience
+ko.removeNode = ko.utils.domNodeDisposal.removeNode; // Shorthand name for convenience
+ko.exportSymbol('cleanNode', ko.cleanNode);
+ko.exportSymbol('removeNode', ko.removeNode);
+ko.exportSymbol('utils.domNodeDisposal', ko.utils.domNodeDisposal);
+ko.exportSymbol('utils.domNodeDisposal.addDisposeCallback', ko.utils.domNodeDisposal.addDisposeCallback);
+ko.exportSymbol('utils.domNodeDisposal.removeDisposeCallback', ko.utils.domNodeDisposal.removeDisposeCallback);
+(function () {
+ var leadingCommentRegex = /^(\s*)<!--(.*?)-->/;
+
+ function simpleHtmlParse(html) {
+ // Based on jQuery's "clean" function, but only accounting for table-related elements.
+ // If you have referenced jQuery, this won't be used anyway - KO will use jQuery's "clean" function directly
+
+ // Note that there's still an issue in IE < 9 whereby it will discard comment nodes that are the first child of
+ // a descendant node. For example: "<div><!-- mycomment -->abc</div>" will get parsed as "<div>abc</div>"
+ // This won't affect anyone who has referenced jQuery, and there's always the workaround of inserting a dummy node
+ // (possibly a text node) in front of the comment. So, KO does not attempt to workaround this IE issue automatically at present.
+
+ // Trim whitespace, otherwise indexOf won't work as expected
+ var tags = ko.utils.stringTrim(html).toLowerCase(), div = document.createElement("div");
+
+ // Finds the first match from the left column, and returns the corresponding "wrap" data from the right column
+ var wrap = tags.match(/^<(thead|tbody|tfoot)/) && [1, "<table>", "</table>"] ||
+ !tags.indexOf("<tr") && [2, "<table><tbody>", "</tbody></table>"] ||
+ (!tags.indexOf("<td") || !tags.indexOf("<th")) && [3, "<table><tbody><tr>", "</tr></tbody></table>"] ||
+ /* anything else */ [0, "", ""];
+
+ // Go to html and back, then peel off extra wrappers
+ // Note that we always prefix with some dummy text, because otherwise, IE<9 will strip out leading comment nodes in descendants. Total madness.
+ var markup = "ignored<div>" + wrap[1] + html + wrap[2] + "</div>";
+ if (typeof window['innerShiv'] == "function") {
+ div.appendChild(window['innerShiv'](markup));
+ } else {
+ div.innerHTML = markup;
+ }
+
+ // Move to the right depth
+ while (wrap[0]--)
+ div = div.lastChild;
+
+ return ko.utils.makeArray(div.lastChild.childNodes);
+ }
+
+ function jQueryHtmlParse(html) {
+ // jQuery's "parseHTML" function was introduced in jQuery 1.8.0 and is a documented public API.
+ if (jQuery['parseHTML']) {
+ return jQuery['parseHTML'](html) || []; // Ensure we always return an array and never null
+ } else {
+ // For jQuery < 1.8.0, we fall back on the undocumented internal "clean" function.
+ var elems = jQuery['clean']([html]);
+
+ // As of jQuery 1.7.1, jQuery parses the HTML by appending it to some dummy parent nodes held in an in-memory document fragment.
+ // Unfortunately, it never clears the dummy parent nodes from the document fragment, so it leaks memory over time.
+ // Fix this by finding the top-most dummy parent element, and detaching it from its owner fragment.
+ if (elems && elems[0]) {
+ // Find the top-most parent element that's a direct child of a document fragment
+ var elem = elems[0];
+ while (elem.parentNode && elem.parentNode.nodeType !== 11 /* i.e., DocumentFragment */)
+ elem = elem.parentNode;
+ // ... then detach it
+ if (elem.parentNode)
+ elem.parentNode.removeChild(elem);
+ }
+
+ return elems;
+ }
+ }
+
+ ko.utils.parseHtmlFragment = function(html) {
+ return jQuery ? jQueryHtmlParse(html) // As below, benefit from jQuery's optimisations where possible
+ : simpleHtmlParse(html); // ... otherwise, this simple logic will do in most common cases.
+ };
+
+ ko.utils.setHtml = function(node, html) {
+ ko.utils.emptyDomNode(node);
+
+ // There's no legitimate reason to display a stringified observable without unwrapping it, so we'll unwrap it
+ html = ko.utils.unwrapObservable(html);
+
+ if ((html !== null) && (html !== undefined)) {
+ if (typeof html != 'string')
+ html = html.toString();
+
+ // jQuery contains a lot of sophisticated code to parse arbitrary HTML fragments,
+ // for example <tr> elements which are not normally allowed to exist on their own.
+ // If you've referenced jQuery we'll use that rather than duplicating its code.
+ if (jQuery) {
+ jQuery(node)['html'](html);
+ } else {
+ // ... otherwise, use KO's own parsing logic.
+ var parsedNodes = ko.utils.parseHtmlFragment(html);
+ for (var i = 0; i < parsedNodes.length; i++)
+ node.appendChild(parsedNodes[i]);
+ }
+ }
+ };
+})();
+
+ko.exportSymbol('utils.parseHtmlFragment', ko.utils.parseHtmlFragment);
+ko.exportSymbol('utils.setHtml', ko.utils.setHtml);
+
+ko.memoization = (function () {
+ var memos = {};
+
+ function randomMax8HexChars() {
+ return (((1 + Math.random()) * 0x100000000) | 0).toString(16).substring(1);
+ }
+ function generateRandomId() {
+ return randomMax8HexChars() + randomMax8HexChars();
+ }
+ function findMemoNodes(rootNode, appendToArray) {
+ if (!rootNode)
+ return;
+ if (rootNode.nodeType == 8) {
+ var memoId = ko.memoization.parseMemoText(rootNode.nodeValue);
+ if (memoId != null)
+ appendToArray.push({ domNode: rootNode, memoId: memoId });
+ } else if (rootNode.nodeType == 1) {
+ for (var i = 0, childNodes = rootNode.childNodes, j = childNodes.length; i < j; i++)
+ findMemoNodes(childNodes[i], appendToArray);
+ }
+ }
+
+ return {
+ memoize: function (callback) {
+ if (typeof callback != "function")
+ throw new Error("You can only pass a function to ko.memoization.memoize()");
+ var memoId = generateRandomId();
+ memos[memoId] = callback;
+ return "<!--[ko_memo:" + memoId + "]-->";
+ },
+
+ unmemoize: function (memoId, callbackParams) {
+ var callback = memos[memoId];
+ if (callback === undefined)
+ throw new Error("Couldn't find any memo with ID " + memoId + ". Perhaps it's already been unmemoized.");
+ try {
+ callback.apply(null, callbackParams || []);
+ return true;
+ }
+ finally { delete memos[memoId]; }
+ },
+
+ unmemoizeDomNodeAndDescendants: function (domNode, extraCallbackParamsArray) {
+ var memos = [];
+ findMemoNodes(domNode, memos);
+ for (var i = 0, j = memos.length; i < j; i++) {
+ var node = memos[i].domNode;
+ var combinedParams = [node];
+ if (extraCallbackParamsArray)
+ ko.utils.arrayPushAll(combinedParams, extraCallbackParamsArray);
+ ko.memoization.unmemoize(memos[i].memoId, combinedParams);
+ node.nodeValue = ""; // Neuter this node so we don't try to unmemoize it again
+ if (node.parentNode)
+ node.parentNode.removeChild(node); // If possible, erase it totally (not always possible - someone else might just hold a reference to it then call unmemoizeDomNodeAndDescendants again)
+ }
+ },
+
+ parseMemoText: function (memoText) {
+ var match = memoText.match(/^\[ko_memo\:(.*?)\]$/);
+ return match ? match[1] : null;
+ }
+ };
+})();
+
+ko.exportSymbol('memoization', ko.memoization);
+ko.exportSymbol('memoization.memoize', ko.memoization.memoize);
+ko.exportSymbol('memoization.unmemoize', ko.memoization.unmemoize);
+ko.exportSymbol('memoization.parseMemoText', ko.memoization.parseMemoText);
+ko.exportSymbol('memoization.unmemoizeDomNodeAndDescendants', ko.memoization.unmemoizeDomNodeAndDescendants);
+ko.extenders = {
+ 'throttle': function(target, timeout) {
+ // Throttling means two things:
+
+ // (1) For dependent observables, we throttle *evaluations* so that, no matter how fast its dependencies
+ // notify updates, the target doesn't re-evaluate (and hence doesn't notify) faster than a certain rate
+ target['throttleEvaluation'] = timeout;
+
+ // (2) For writable targets (observables, or writable dependent observables), we throttle *writes*
+ // so the target cannot change value synchronously or faster than a certain rate
+ var writeTimeoutInstance = null;
+ return ko.dependentObservable({
+ 'read': target,
+ 'write': function(value) {
+ clearTimeout(writeTimeoutInstance);
+ writeTimeoutInstance = setTimeout(function() {
+ target(value);
+ }, timeout);
+ }
+ });
+ },
+
+ 'rateLimit': function(target, options) {
+ var timeout, method, limitFunction;
+
+ if (typeof options == 'number') {
+ timeout = options;
+ } else {
+ timeout = options['timeout'];
+ method = options['method'];
+ }
+
+ limitFunction = method == 'notifyWhenChangesStop' ? debounce : throttle;
+ target.limit(function(callback) {
+ return limitFunction(callback, timeout);
+ });
+ },
+
+ 'notify': function(target, notifyWhen) {
+ target["equalityComparer"] = notifyWhen == "always" ?
+ null : // null equalityComparer means to always notify
+ valuesArePrimitiveAndEqual;
+ }
+};
+
+var primitiveTypes = { 'undefined':1, 'boolean':1, 'number':1, 'string':1 };
+function valuesArePrimitiveAndEqual(a, b) {
+ var oldValueIsPrimitive = (a === null) || (typeof(a) in primitiveTypes);
+ return oldValueIsPrimitive ? (a === b) : false;
+}
+
+function throttle(callback, timeout) {
+ var timeoutInstance;
+ return function () {
+ if (!timeoutInstance) {
+ timeoutInstance = setTimeout(function() {
+ timeoutInstance = undefined;
+ callback();
+ }, timeout);
+ }
+ };
+}
+
+function debounce(callback, timeout) {
+ var timeoutInstance;
+ return function () {
+ clearTimeout(timeoutInstance);
+ timeoutInstance = setTimeout(callback, timeout);
+ };
+}
+
+function applyExtenders(requestedExtenders) {
+ var target = this;
+ if (requestedExtenders) {
+ ko.utils.objectForEach(requestedExtenders, function(key, value) {
+ var extenderHandler = ko.extenders[key];
+ if (typeof extenderHandler == 'function') {
+ target = extenderHandler(target, value) || target;
+ }
+ });
+ }
+ return target;
+}
+
+ko.exportSymbol('extenders', ko.extenders);
+
+ko.subscription = function (target, callback, disposeCallback) {
+ this.target = target;
+ this.callback = callback;
+ this.disposeCallback = disposeCallback;
+ this.isDisposed = false;
+ ko.exportProperty(this, 'dispose', this.dispose);
+};
+ko.subscription.prototype.dispose = function () {
+ this.isDisposed = true;
+ this.disposeCallback();
+};
+
+ko.subscribable = function () {
+ ko.utils.setPrototypeOfOrExtend(this, ko.subscribable['fn']);
+ this._subscriptions = {};
+}
+
+var defaultEvent = "change";
+
+var ko_subscribable_fn = {
+ subscribe: function (callback, callbackTarget, event) {
+ var self = this;
+
+ event = event || defaultEvent;
+ var boundCallback = callbackTarget ? callback.bind(callbackTarget) : callback;
+
+ var subscription = new ko.subscription(self, boundCallback, function () {
+ ko.utils.arrayRemoveItem(self._subscriptions[event], subscription);
+ });
+
+ // This will force a computed with deferEvaluation to evaluate before any subscriptions
+ // are registered.
+ if (self.peek) {
+ self.peek();
+ }
+
+ if (!self._subscriptions[event])
+ self._subscriptions[event] = [];
+ self._subscriptions[event].push(subscription);
+ return subscription;
+ },
+
+ "notifySubscribers": function (valueToNotify, event) {
+ event = event || defaultEvent;
+ if (this.hasSubscriptionsForEvent(event)) {
+ try {
+ ko.dependencyDetection.begin(); // Begin suppressing dependency detection (by setting the top frame to undefined)
+ for (var a = this._subscriptions[event].slice(0), i = 0, subscription; subscription = a[i]; ++i) {
+ // In case a subscription was disposed during the arrayForEach cycle, check
+ // for isDisposed on each subscription before invoking its callback
+ if (!subscription.isDisposed)
+ subscription.callback(valueToNotify);
+ }
+ } finally {
+ ko.dependencyDetection.end(); // End suppressing dependency detection
+ }
+ }
+ },
+
+ limit: function(limitFunction) {
+ var self = this, selfIsObservable = ko.isObservable(self),
+ isPending, previousValue, pendingValue, beforeChange = 'beforeChange';
+
+ if (!self._origNotifySubscribers) {
+ self._origNotifySubscribers = self["notifySubscribers"];
+ self["notifySubscribers"] = function(value, event) {
+ if (!event || event === defaultEvent) {
+ self._rateLimitedChange(value);
+ } else if (event === beforeChange) {
+ self._rateLimitedBeforeChange(value);
+ } else {
+ self._origNotifySubscribers(value, event);
+ }
+ };
+ }
+
+ var finish = limitFunction(function() {
+ // If an observable provided a reference to itself, access it to get the latest value.
+ // This allows computed observables to delay calculating their value until needed.
+ if (selfIsObservable && pendingValue === self) {
+ pendingValue = self();
+ }
+ isPending = false;
+ if (self.isDifferent(previousValue, pendingValue)) {
+ self._origNotifySubscribers(previousValue = pendingValue);
+ }
+ });
+
+ self._rateLimitedChange = function(value) {
+ isPending = true;
+ pendingValue = value;
+ finish();
+ };
+ self._rateLimitedBeforeChange = function(value) {
+ if (!isPending) {
+ previousValue = value;
+ self._origNotifySubscribers(value, beforeChange);
+ }
+ };
+ },
+
+ hasSubscriptionsForEvent: function(event) {
+ return this._subscriptions[event] && this._subscriptions[event].length;
+ },
+
+ getSubscriptionsCount: function () {
+ var total = 0;
+ ko.utils.objectForEach(this._subscriptions, function(eventName, subscriptions) {
+ total += subscriptions.length;
+ });
+ return total;
+ },
+
+ isDifferent: function(oldValue, newValue) {
+ return !this['equalityComparer'] || !this['equalityComparer'](oldValue, newValue);
+ },
+
+ extend: applyExtenders
+};
+
+ko.exportProperty(ko_subscribable_fn, 'subscribe', ko_subscribable_fn.subscribe);
+ko.exportProperty(ko_subscribable_fn, 'extend', ko_subscribable_fn.extend);
+ko.exportProperty(ko_subscribable_fn, 'getSubscriptionsCount', ko_subscribable_fn.getSubscriptionsCount);
+
+// For browsers that support proto assignment, we overwrite the prototype of each
+// observable instance. Since observables are functions, we need Function.prototype
+// to still be in the prototype chain.
+if (ko.utils.canSetPrototype) {
+ ko.utils.setPrototypeOf(ko_subscribable_fn, Function.prototype);
+}
+
+ko.subscribable['fn'] = ko_subscribable_fn;
+
+
+ko.isSubscribable = function (instance) {
+ return instance != null && typeof instance.subscribe == "function" && typeof instance["notifySubscribers"] == "function";
+};
+
+ko.exportSymbol('subscribable', ko.subscribable);
+ko.exportSymbol('isSubscribable', ko.isSubscribable);
+
+ko.computedContext = ko.dependencyDetection = (function () {
+ var outerFrames = [],
+ currentFrame,
+ lastId = 0;
+
+ // Return a unique ID that can be assigned to an observable for dependency tracking.
+ // Theoretically, you could eventually overflow the number storage size, resulting
+ // in duplicate IDs. But in JavaScript, the largest exact integral value is 2^53
+ // or 9,007,199,254,740,992. If you created 1,000,000 IDs per second, it would
+ // take over 285 years to reach that number.
+ // Reference http://blog.vjeux.com/2010/javascript/javascript-max_int-number-limits.html
+ function getId() {
+ return ++lastId;
+ }
+
+ function begin(options) {
+ outerFrames.push(currentFrame);
+ currentFrame = options;
+ }
+
+ function end() {
+ currentFrame = outerFrames.pop();
+ }
+
+ return {
+ begin: begin,
+
+ end: end,
+
+ registerDependency: function (subscribable) {
+ if (currentFrame) {
+ if (!ko.isSubscribable(subscribable))
+ throw new Error("Only subscribable things can act as dependencies");
+ currentFrame.callback(subscribable, subscribable._id || (subscribable._id = getId()));
+ }
+ },
+
+ ignore: function (callback, callbackTarget, callbackArgs) {
+ try {
+ begin();
+ return callback.apply(callbackTarget, callbackArgs || []);
+ } finally {
+ end();
+ }
+ },
+
+ getDependenciesCount: function () {
+ if (currentFrame)
+ return currentFrame.computed.getDependenciesCount();
+ },
+
+ isInitial: function() {
+ if (currentFrame)
+ return currentFrame.isInitial;
+ }
+ };
+})();
+
+ko.exportSymbol('computedContext', ko.computedContext);
+ko.exportSymbol('computedContext.getDependenciesCount', ko.computedContext.getDependenciesCount);
+ko.exportSymbol('computedContext.isInitial', ko.computedContext.isInitial);
+ko.observable = function (initialValue) {
+ var _latestValue = initialValue;
+
+ function observable() {
+ if (arguments.length > 0) {
+ // Write
+
+ // Ignore writes if the value hasn't changed
+ if (observable.isDifferent(_latestValue, arguments[0])) {
+ observable.valueWillMutate();
+ _latestValue = arguments[0];
+ if (DEBUG) observable._latestValue = _latestValue;
+ observable.valueHasMutated();
+ }
+ return this; // Permits chained assignments
+ }
+ else {
+ // Read
+ ko.dependencyDetection.registerDependency(observable); // The caller only needs to be notified of changes if they did a "read" operation
+ return _latestValue;
+ }
+ }
+ ko.subscribable.call(observable);
+ ko.utils.setPrototypeOfOrExtend(observable, ko.observable['fn']);
+
+ if (DEBUG) observable._latestValue = _latestValue;
+ observable.peek = function() { return _latestValue };
+ observable.valueHasMutated = function () { observable["notifySubscribers"](_latestValue); }
+ observable.valueWillMutate = function () { observable["notifySubscribers"](_latestValue, "beforeChange"); }
+
+ ko.exportProperty(observable, 'peek', observable.peek);
+ ko.exportProperty(observable, "valueHasMutated", observable.valueHasMutated);
+ ko.exportProperty(observable, "valueWillMutate", observable.valueWillMutate);
+
+ return observable;
+}
+
+ko.observable['fn'] = {
+ "equalityComparer": valuesArePrimitiveAndEqual
+};
+
+var protoProperty = ko.observable.protoProperty = "__ko_proto__";
+ko.observable['fn'][protoProperty] = ko.observable;
+
+// Note that for browsers that don't support proto assignment, the
+// inheritance chain is created manually in the ko.observable constructor
+if (ko.utils.canSetPrototype) {
+ ko.utils.setPrototypeOf(ko.observable['fn'], ko.subscribable['fn']);
+}
+
+ko.hasPrototype = function(instance, prototype) {
+ if ((instance === null) || (instance === undefined) || (instance[protoProperty] === undefined)) return false;
+ if (instance[protoProperty] === prototype) return true;
+ return ko.hasPrototype(instance[protoProperty], prototype); // Walk the prototype chain
+};
+
+ko.isObservable = function (instance) {
+ return ko.hasPrototype(instance, ko.observable);
+}
+ko.isWriteableObservable = function (instance) {
+ // Observable
+ if ((typeof instance == "function") && instance[protoProperty] === ko.observable)
+ return true;
+ // Writeable dependent observable
+ if ((typeof instance == "function") && (instance[protoProperty] === ko.dependentObservable) && (instance.hasWriteFunction))
+ return true;
+ // Anything else
+ return false;
+}
+
+
+ko.exportSymbol('observable', ko.observable);
+ko.exportSymbol('isObservable', ko.isObservable);
+ko.exportSymbol('isWriteableObservable', ko.isWriteableObservable);
+ko.observableArray = function (initialValues) {
+ initialValues = initialValues || [];
+
+ if (typeof initialValues != 'object' || !('length' in initialValues))
+ throw new Error("The argument passed when initializing an observable array must be an array, or null, or undefined.");
+
+ var result = ko.observable(initialValues);
+ ko.utils.setPrototypeOfOrExtend(result, ko.observableArray['fn']);
+ return result.extend({'trackArrayChanges':true});
+};
+
+ko.observableArray['fn'] = {
+ 'remove': function (valueOrPredicate) {
+ var underlyingArray = this.peek();
+ var removedValues = [];
+ var predicate = typeof valueOrPredicate == "function" && !ko.isObservable(valueOrPredicate) ? valueOrPredicate : function (value) { return value === valueOrPredicate; };
+ for (var i = 0; i < underlyingArray.length; i++) {
+ var value = underlyingArray[i];
+ if (predicate(value)) {
+ if (removedValues.length === 0) {
+ this.valueWillMutate();
+ }
+ removedValues.push(value);
+ underlyingArray.splice(i, 1);
+ i--;
+ }
+ }
+ if (removedValues.length) {
+ this.valueHasMutated();
+ }
+ return removedValues;
+ },
+
+ 'removeAll': function (arrayOfValues) {
+ // If you passed zero args, we remove everything
+ if (arrayOfValues === undefined) {
+ var underlyingArray = this.peek();
+ var allValues = underlyingArray.slice(0);
+ this.valueWillMutate();
+ underlyingArray.splice(0, underlyingArray.length);
+ this.valueHasMutated();
+ return allValues;
+ }
+ // If you passed an arg, we interpret it as an array of entries to remove
+ if (!arrayOfValues)
+ return [];
+ return this['remove'](function (value) {
+ return ko.utils.arrayIndexOf(arrayOfValues, value) >= 0;
+ });
+ },
+
+ 'destroy': function (valueOrPredicate) {
+ var underlyingArray = this.peek();
+ var predicate = typeof valueOrPredicate == "function" && !ko.isObservable(valueOrPredicate) ? valueOrPredicate : function (value) { return value === valueOrPredicate; };
+ this.valueWillMutate();
+ for (var i = underlyingArray.length - 1; i >= 0; i--) {
+ var value = underlyingArray[i];
+ if (predicate(value))
+ underlyingArray[i]["_destroy"] = true;
+ }
+ this.valueHasMutated();
+ },
+
+ 'destroyAll': function (arrayOfValues) {
+ // If you passed zero args, we destroy everything
+ if (arrayOfValues === undefined)
+ return this['destroy'](function() { return true });
+
+ // If you passed an arg, we interpret it as an array of entries to destroy
+ if (!arrayOfValues)
+ return [];
+ return this['destroy'](function (value) {
+ return ko.utils.arrayIndexOf(arrayOfValues, value) >= 0;
+ });
+ },
+
+ 'indexOf': function (item) {
+ var underlyingArray = this();
+ return ko.utils.arrayIndexOf(underlyingArray, item);
+ },
+
+ 'replace': function(oldItem, newItem) {
+ var index = this['indexOf'](oldItem);
+ if (index >= 0) {
+ this.valueWillMutate();
+ this.peek()[index] = newItem;
+ this.valueHasMutated();
+ }
+ }
+};
+
+// Populate ko.observableArray.fn with read/write functions from native arrays
+// Important: Do not add any additional functions here that may reasonably be used to *read* data from the array
+// because we'll eval them without causing subscriptions, so ko.computed output could end up getting stale
+ko.utils.arrayForEach(["pop", "push", "reverse", "shift", "sort", "splice", "unshift"], function (methodName) {
+ ko.observableArray['fn'][methodName] = function () {
+ // Use "peek" to avoid creating a subscription in any computed that we're executing in the context of
+ // (for consistency with mutating regular observables)
+ var underlyingArray = this.peek();
+ this.valueWillMutate();
+ this.cacheDiffForKnownOperation(underlyingArray, methodName, arguments);
+ var methodCallResult = underlyingArray[methodName].apply(underlyingArray, arguments);
+ this.valueHasMutated();
+ return methodCallResult;
+ };
+});
+
+// Populate ko.observableArray.fn with read-only functions from native arrays
+ko.utils.arrayForEach(["slice"], function (methodName) {
+ ko.observableArray['fn'][methodName] = function () {
+ var underlyingArray = this();
+ return underlyingArray[methodName].apply(underlyingArray, arguments);
+ };
+});
+
+// Note that for browsers that don't support proto assignment, the
+// inheritance chain is created manually in the ko.observableArray constructor
+if (ko.utils.canSetPrototype) {
+ ko.utils.setPrototypeOf(ko.observableArray['fn'], ko.observable['fn']);
+}
+
+ko.exportSymbol('observableArray', ko.observableArray);
+var arrayChangeEventName = 'arrayChange';
+ko.extenders['trackArrayChanges'] = function(target) {
+ // Only modify the target observable once
+ if (target.cacheDiffForKnownOperation) {
+ return;
+ }
+ var trackingChanges = false,
+ cachedDiff = null,
+ pendingNotifications = 0,
+ underlyingSubscribeFunction = target.subscribe;
+
+ // Intercept "subscribe" calls, and for array change events, ensure change tracking is enabled
+ target.subscribe = target['subscribe'] = function(callback, callbackTarget, event) {
+ if (event === arrayChangeEventName) {
+ trackChanges();
+ }
+ return underlyingSubscribeFunction.apply(this, arguments);
+ };
+
+ function trackChanges() {
+ // Calling 'trackChanges' multiple times is the same as calling it once
+ if (trackingChanges) {
+ return;
+ }
+
+ trackingChanges = true;
+
+ // Intercept "notifySubscribers" to track how many times it was called.
+ var underlyingNotifySubscribersFunction = target['notifySubscribers'];
+ target['notifySubscribers'] = function(valueToNotify, event) {
+ if (!event || event === defaultEvent) {
+ ++pendingNotifications;
+ }
+ return underlyingNotifySubscribersFunction.apply(this, arguments);
+ };
+
+ // Each time the array changes value, capture a clone so that on the next
+ // change it's possible to produce a diff
+ var previousContents = [].concat(target.peek() || []);
+ cachedDiff = null;
+ target.subscribe(function(currentContents) {
+ // Make a copy of the current contents and ensure it's an array
+ currentContents = [].concat(currentContents || []);
+
+ // Compute the diff and issue notifications, but only if someone is listening
+ if (target.hasSubscriptionsForEvent(arrayChangeEventName)) {
+ var changes = getChanges(previousContents, currentContents);
+ if (changes.length) {
+ target['notifySubscribers'](changes, arrayChangeEventName);
+ }
+ }
+
+ // Eliminate references to the old, removed items, so they can be GCed
+ previousContents = currentContents;
+ cachedDiff = null;
+ pendingNotifications = 0;
+ });
+ }
+
+ function getChanges(previousContents, currentContents) {
+ // We try to re-use cached diffs.
+ // The scenarios where pendingNotifications > 1 are when using rate-limiting or the Deferred Updates
+ // plugin, which without this check would not be compatible with arrayChange notifications. Normally,
+ // notifications are issued immediately so we wouldn't be queueing up more than one.
+ if (!cachedDiff || pendingNotifications > 1) {
+ cachedDiff = ko.utils.compareArrays(previousContents, currentContents, { 'sparse': true });
+ }
+
+ return cachedDiff;
+ }
+
+ target.cacheDiffForKnownOperation = function(rawArray, operationName, args) {
+ // Only run if we're currently tracking changes for this observable array
+ // and there aren't any pending deferred notifications.
+ if (!trackingChanges || pendingNotifications) {
+ return;
+ }
+ var diff = [],
+ arrayLength = rawArray.length,
+ argsLength = args.length,
+ offset = 0;
+
+ function pushDiff(status, value, index) {
+ return diff[diff.length] = { 'status': status, 'value': value, 'index': index };
+ }
+ switch (operationName) {
+ case 'push':
+ offset = arrayLength;
+ case 'unshift':
+ for (var index = 0; index < argsLength; index++) {
+ pushDiff('added', args[index], offset + index);
+ }
+ break;
+
+ case 'pop':
+ offset = arrayLength - 1;
+ case 'shift':
+ if (arrayLength) {
+ pushDiff('deleted', rawArray[offset], offset);
+ }
+ break;
+
+ case 'splice':
+ // Negative start index means 'from end of array'. After that we clamp to [0...arrayLength].
+ // See https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/splice
+ var startIndex = Math.min(Math.max(0, args[0] < 0 ? arrayLength + args[0] : args[0]), arrayLength),
+ endDeleteIndex = argsLength === 1 ? arrayLength : Math.min(startIndex + (args[1] || 0), arrayLength),
+ endAddIndex = startIndex + argsLength - 2,
+ endIndex = Math.max(endDeleteIndex, endAddIndex),
+ additions = [], deletions = [];
+ for (var index = startIndex, argsIndex = 2; index < endIndex; ++index, ++argsIndex) {
+ if (index < endDeleteIndex)
+ deletions.push(pushDiff('deleted', rawArray[index], index));
+ if (index < endAddIndex)
+ additions.push(pushDiff('added', args[argsIndex], index));
+ }
+ ko.utils.findMovesInArrayComparison(deletions, additions);
+ break;
+
+ default:
+ return;
+ }
+ cachedDiff = diff;
+ };
+};
+ko.computed = ko.dependentObservable = function (evaluatorFunctionOrOptions, evaluatorFunctionTarget, options) {
+ var _latestValue,
+ _needsEvaluation = true,
+ _isBeingEvaluated = false,
+ _suppressDisposalUntilDisposeWhenReturnsFalse = false,
+ _isDisposed = false,
+ readFunction = evaluatorFunctionOrOptions;
+
+ if (readFunction && typeof readFunction == "object") {
+ // Single-parameter syntax - everything is on this "options" param
+ options = readFunction;
+ readFunction = options["read"];
+ } else {
+ // Multi-parameter syntax - construct the options according to the params passed
+ options = options || {};
+ if (!readFunction)
+ readFunction = options["read"];
+ }
+ if (typeof readFunction != "function")
+ throw new Error("Pass a function that returns the value of the ko.computed");
+
+ function addSubscriptionToDependency(subscribable, id) {
+ if (!_subscriptionsToDependencies[id]) {
+ _subscriptionsToDependencies[id] = subscribable.subscribe(evaluatePossiblyAsync);
+ ++_dependenciesCount;
+ }
+ }
+
+ function disposeAllSubscriptionsToDependencies() {
+ _isDisposed = true;
+ ko.utils.objectForEach(_subscriptionsToDependencies, function (id, subscription) {
+ subscription.dispose();
+ });
+ _subscriptionsToDependencies = {};
+ _dependenciesCount = 0;
+ _needsEvaluation = false;
+ }
+
+ function evaluatePossiblyAsync() {
+ var throttleEvaluationTimeout = dependentObservable['throttleEvaluation'];
+ if (throttleEvaluationTimeout && throttleEvaluationTimeout >= 0) {
+ clearTimeout(evaluationTimeoutInstance);
+ evaluationTimeoutInstance = setTimeout(evaluateImmediate, throttleEvaluationTimeout);
+ } else if (dependentObservable._evalRateLimited) {
+ dependentObservable._evalRateLimited();
+ } else {
+ evaluateImmediate();
+ }
+ }
+
+ function evaluateImmediate() {
+ if (_isBeingEvaluated) {
+ // If the evaluation of a ko.computed causes side effects, it's possible that it will trigger its own re-evaluation.
+ // This is not desirable (it's hard for a developer to realise a chain of dependencies might cause this, and they almost
+ // certainly didn't intend infinite re-evaluations). So, for predictability, we simply prevent ko.computeds from causing
+ // their own re-evaluation. Further discussion at https://github.com/SteveSanderson/knockout/pull/387
+ return;
+ }
+
+ // Do not evaluate (and possibly capture new dependencies) if disposed
+ if (_isDisposed) {
+ return;
+ }
+
+ if (disposeWhen && disposeWhen()) {
+ // See comment below about _suppressDisposalUntilDisposeWhenReturnsFalse
+ if (!_suppressDisposalUntilDisposeWhenReturnsFalse) {
+ dispose();
+ return;
+ }
+ } else {
+ // It just did return false, so we can stop suppressing now
+ _suppressDisposalUntilDisposeWhenReturnsFalse = false;
+ }
+
+ _isBeingEvaluated = true;
+ try {
+ // Initially, we assume that none of the subscriptions are still being used (i.e., all are candidates for disposal).
+ // Then, during evaluation, we cross off any that are in fact still being used.
+ var disposalCandidates = _subscriptionsToDependencies, disposalCount = _dependenciesCount;
+ ko.dependencyDetection.begin({
+ callback: function(subscribable, id) {
+ if (!_isDisposed) {
+ if (disposalCount && disposalCandidates[id]) {
+ // Don't want to dispose this subscription, as it's still being used
+ _subscriptionsToDependencies[id] = disposalCandidates[id];
+ ++_dependenciesCount;
+ delete disposalCandidates[id];
+ --disposalCount;
+ } else {
+ // Brand new subscription - add it
+ addSubscriptionToDependency(subscribable, id);
+ }
+ }
+ },
+ computed: dependentObservable,
+ isInitial: !_dependenciesCount // If we're evaluating when there are no previous dependencies, it must be the first time
+ });
+
+ _subscriptionsToDependencies = {};
+ _dependenciesCount = 0;
+
+ try {
+ var newValue = evaluatorFunctionTarget ? readFunction.call(evaluatorFunctionTarget) : readFunction();
+
+ } finally {
+ ko.dependencyDetection.end();
+
+ // For each subscription no longer being used, remove it from the active subscriptions list and dispose it
+ if (disposalCount) {
+ ko.utils.objectForEach(disposalCandidates, function(id, toDispose) {
+ toDispose.dispose();
+ });
+ }
+
+ _needsEvaluation = false;
+ }
+
+ if (dependentObservable.isDifferent(_latestValue, newValue)) {
+ dependentObservable["notifySubscribers"](_latestValue, "beforeChange");
+
+ _latestValue = newValue;
+ if (DEBUG) dependentObservable._latestValue = _latestValue;
+
+ // If rate-limited, the notification will happen within the limit function. Otherwise,
+ // notify as soon as the value changes. Check specifically for the throttle setting since
+ // it overrides rateLimit.
+ if (!dependentObservable._evalRateLimited || dependentObservable['throttleEvaluation']) {
+ dependentObservable["notifySubscribers"](_latestValue);
+ }
+ }
+ } finally {
+ _isBeingEvaluated = false;
+ }
+
+ if (!_dependenciesCount)
+ dispose();
+ }
+
+ function dependentObservable() {
+ if (arguments.length > 0) {
+ if (typeof writeFunction === "function") {
+ // Writing a value
+ writeFunction.apply(evaluatorFunctionTarget, arguments);
+ } else {
+ throw new Error("Cannot write a value to a ko.computed unless you specify a 'write' option. If you wish to read the current value, don't pass any parameters.");
+ }
+ return this; // Permits chained assignments
+ } else {
+ // Reading the value
+ if (_needsEvaluation)
+ evaluateImmediate();
+ ko.dependencyDetection.registerDependency(dependentObservable);
+ return _latestValue;
+ }
+ }
+
+ function peek() {
+ // Peek won't re-evaluate, except to get the initial value when "deferEvaluation" is set.
+ // That's the only time that both of these conditions will be satisfied.
+ if (_needsEvaluation && !_dependenciesCount)
+ evaluateImmediate();
+ return _latestValue;
+ }
+
+ function isActive() {
+ return _needsEvaluation || _dependenciesCount > 0;
+ }
+
+ // By here, "options" is always non-null
+ var writeFunction = options["write"],
+ disposeWhenNodeIsRemoved = options["disposeWhenNodeIsRemoved"] || options.disposeWhenNodeIsRemoved || null,
+ disposeWhenOption = options["disposeWhen"] || options.disposeWhen,
+ disposeWhen = disposeWhenOption,
+ dispose = disposeAllSubscriptionsToDependencies,
+ _subscriptionsToDependencies = {},
+ _dependenciesCount = 0,
+ evaluationTimeoutInstance = null;
+
+ if (!evaluatorFunctionTarget)
+ evaluatorFunctionTarget = options["owner"];
+
+ ko.subscribable.call(dependentObservable);
+ ko.utils.setPrototypeOfOrExtend(dependentObservable, ko.dependentObservable['fn']);
+
+ dependentObservable.peek = peek;
+ dependentObservable.getDependenciesCount = function () { return _dependenciesCount; };
+ dependentObservable.hasWriteFunction = typeof options["write"] === "function";
+ dependentObservable.dispose = function () { dispose(); };
+ dependentObservable.isActive = isActive;
+
+ // Replace the limit function with one that delays evaluation as well.
+ var originalLimit = dependentObservable.limit;
+ dependentObservable.limit = function(limitFunction) {
+ originalLimit.call(dependentObservable, limitFunction);
+ dependentObservable._evalRateLimited = function() {
+ dependentObservable._rateLimitedBeforeChange(_latestValue);
+
+ _needsEvaluation = true; // Mark as dirty
+
+ // Pass the observable to the rate-limit code, which will access it when
+ // it's time to do the notification.
+ dependentObservable._rateLimitedChange(dependentObservable);
+ }
+ };
+
+ ko.exportProperty(dependentObservable, 'peek', dependentObservable.peek);
+ ko.exportProperty(dependentObservable, 'dispose', dependentObservable.dispose);
+ ko.exportProperty(dependentObservable, 'isActive', dependentObservable.isActive);
+ ko.exportProperty(dependentObservable, 'getDependenciesCount', dependentObservable.getDependenciesCount);
+
+ // Add a "disposeWhen" callback that, on each evaluation, disposes if the node was removed without using ko.removeNode.
+ if (disposeWhenNodeIsRemoved) {
+ // Since this computed is associated with a DOM node, and we don't want to dispose the computed
+ // until the DOM node is *removed* from the document (as opposed to never having been in the document),
+ // we'll prevent disposal until "disposeWhen" first returns false.
+ _suppressDisposalUntilDisposeWhenReturnsFalse = true;
+
+ // Only watch for the node's disposal if the value really is a node. It might not be,
+ // e.g., { disposeWhenNodeIsRemoved: true } can be used to opt into the "only dispose
+ // after first false result" behaviour even if there's no specific node to watch. This
+ // technique is intended for KO's internal use only and shouldn't be documented or used
+ // by application code, as it's likely to change in a future version of KO.
+ if (disposeWhenNodeIsRemoved.nodeType) {
+ disposeWhen = function () {
+ return !ko.utils.domNodeIsAttachedToDocument(disposeWhenNodeIsRemoved) || (disposeWhenOption && disposeWhenOption());
+ };
+ }
+ }
+
+ // Evaluate, unless deferEvaluation is true
+ if (options['deferEvaluation'] !== true)
+ evaluateImmediate();
+
+ // Attach a DOM node disposal callback so that the computed will be proactively disposed as soon as the node is
+ // removed using ko.removeNode. But skip if isActive is false (there will never be any dependencies to dispose).
+ if (disposeWhenNodeIsRemoved && isActive() && disposeWhenNodeIsRemoved.nodeType) {
+ dispose = function() {
+ ko.utils.domNodeDisposal.removeDisposeCallback(disposeWhenNodeIsRemoved, dispose);
+ disposeAllSubscriptionsToDependencies();
+ };
+ ko.utils.domNodeDisposal.addDisposeCallback(disposeWhenNodeIsRemoved, dispose);
+ }
+
+ return dependentObservable;
+};
+
+ko.isComputed = function(instance) {
+ return ko.hasPrototype(instance, ko.dependentObservable);
+};
+
+var protoProp = ko.observable.protoProperty; // == "__ko_proto__"
+ko.dependentObservable[protoProp] = ko.observable;
+
+ko.dependentObservable['fn'] = {
+ "equalityComparer": valuesArePrimitiveAndEqual
+};
+ko.dependentObservable['fn'][protoProp] = ko.dependentObservable;
+
+// Note that for browsers that don't support proto assignment, the
+// inheritance chain is created manually in the ko.dependentObservable constructor
+if (ko.utils.canSetPrototype) {
+ ko.utils.setPrototypeOf(ko.dependentObservable['fn'], ko.subscribable['fn']);
+}
+
+ko.exportSymbol('dependentObservable', ko.dependentObservable);
+ko.exportSymbol('computed', ko.dependentObservable); // Make "ko.computed" an alias for "ko.dependentObservable"
+ko.exportSymbol('isComputed', ko.isComputed);
+
+(function() {
+ var maxNestedObservableDepth = 10; // Escape the (unlikely) pathalogical case where an observable's current value is itself (or similar reference cycle)
+
+ ko.toJS = function(rootObject) {
+ if (arguments.length == 0)
+ throw new Error("When calling ko.toJS, pass the object you want to convert.");
+
+ // We just unwrap everything at every level in the object graph
+ return mapJsObjectGraph(rootObject, function(valueToMap) {
+ // Loop because an observable's value might in turn be another observable wrapper
+ for (var i = 0; ko.isObservable(valueToMap) && (i < maxNestedObservableDepth); i++)
+ valueToMap = valueToMap();
+ return valueToMap;
+ });
+ };
+
+ ko.toJSON = function(rootObject, replacer, space) { // replacer and space are optional
+ var plainJavaScriptObject = ko.toJS(rootObject);
+ return ko.utils.stringifyJson(plainJavaScriptObject, replacer, space);
+ };
+
+ function mapJsObjectGraph(rootObject, mapInputCallback, visitedObjects) {
+ visitedObjects = visitedObjects || new objectLookup();
+
+ rootObject = mapInputCallback(rootObject);
+ var canHaveProperties = (typeof rootObject == "object") && (rootObject !== null) && (rootObject !== undefined) && (!(rootObject instanceof Date)) && (!(rootObject instanceof String)) && (!(rootObject instanceof Number)) && (!(rootObject instanceof Boolean));
+ if (!canHaveProperties)
+ return rootObject;
+
+ var outputProperties = rootObject instanceof Array ? [] : {};
+ visitedObjects.save(rootObject, outputProperties);
+
+ visitPropertiesOrArrayEntries(rootObject, function(indexer) {
+ var propertyValue = mapInputCallback(rootObject[indexer]);
+
+ switch (typeof propertyValue) {
+ case "boolean":
+ case "number":
+ case "string":
+ case "function":
+ outputProperties[indexer] = propertyValue;
+ break;
+ case "object":
+ case "undefined":
+ var previouslyMappedValue = visitedObjects.get(propertyValue);
+ outputProperties[indexer] = (previouslyMappedValue !== undefined)
+ ? previouslyMappedValue
+ : mapJsObjectGraph(propertyValue, mapInputCallback, visitedObjects);
+ break;
+ }
+ });
+
+ return outputProperties;
+ }
+
+ function visitPropertiesOrArrayEntries(rootObject, visitorCallback) {
+ if (rootObject instanceof Array) {
+ for (var i = 0; i < rootObject.length; i++)
+ visitorCallback(i);
+
+ // For arrays, also respect toJSON property for custom mappings (fixes #278)
+ if (typeof rootObject['toJSON'] == 'function')
+ visitorCallback('toJSON');
+ } else {
+ for (var propertyName in rootObject) {
+ visitorCallback(propertyName);
+ }
+ }
+ };
+
+ function objectLookup() {
+ this.keys = [];
+ this.values = [];
+ };
+
+ objectLookup.prototype = {
+ constructor: objectLookup,
+ save: function(key, value) {
+ var existingIndex = ko.utils.arrayIndexOf(this.keys, key);
+ if (existingIndex >= 0)
+ this.values[existingIndex] = value;
+ else {
+ this.keys.push(key);
+ this.values.push(value);
+ }
+ },
+ get: function(key) {
+ var existingIndex = ko.utils.arrayIndexOf(this.keys, key);
+ return (existingIndex >= 0) ? this.values[existingIndex] : undefined;
+ }
+ };
+})();
+
+ko.exportSymbol('toJS', ko.toJS);
+ko.exportSymbol('toJSON', ko.toJSON);
+(function () {
+ var hasDomDataExpandoProperty = '__ko__hasDomDataOptionValue__';
+
+ // Normally, SELECT elements and their OPTIONs can only take value of type 'string' (because the values
+ // are stored on DOM attributes). ko.selectExtensions provides a way for SELECTs/OPTIONs to have values
+ // that are arbitrary objects. This is very convenient when implementing things like cascading dropdowns.
+ ko.selectExtensions = {
+ readValue : function(element) {
+ switch (ko.utils.tagNameLower(element)) {
+ case 'option':
+ if (element[hasDomDataExpandoProperty] === true)
+ return ko.utils.domData.get(element, ko.bindingHandlers.options.optionValueDomDataKey);
+ return ko.utils.ieVersion <= 7
+ ? (element.getAttributeNode('value') && element.getAttributeNode('value').specified ? element.value : element.text)
+ : element.value;
+ case 'select':
+ return element.selectedIndex >= 0 ? ko.selectExtensions.readValue(element.options[element.selectedIndex]) : undefined;
+ default:
+ return element.value;
+ }
+ },
+
+ writeValue: function(element, value, allowUnset) {
+ switch (ko.utils.tagNameLower(element)) {
+ case 'option':
+ switch(typeof value) {
+ case "string":
+ ko.utils.domData.set(element, ko.bindingHandlers.options.optionValueDomDataKey, undefined);
+ if (hasDomDataExpandoProperty in element) { // IE <= 8 throws errors if you delete non-existent properties from a DOM node
+ delete element[hasDomDataExpandoProperty];
+ }
+ element.value = value;
+ break;
+ default:
+ // Store arbitrary object using DomData
+ ko.utils.domData.set(element, ko.bindingHandlers.options.optionValueDomDataKey, value);
+ element[hasDomDataExpandoProperty] = true;
+
+ // Special treatment of numbers is just for backward compatibility. KO 1.2.1 wrote numerical values to element.value.
+ element.value = typeof value === "number" ? value : "";
+ break;
+ }
+ break;
+ case 'select':
+ if (value === "" || value === null) // A blank string or null value will select the caption
+ value = undefined;
+ var selection = -1;
+ for (var i = 0, n = element.options.length, optionValue; i < n; ++i) {
+ optionValue = ko.selectExtensions.readValue(element.options[i]);
+ // Include special check to handle selecting a caption with a blank string value
+ if (optionValue == value || (optionValue == "" && value === undefined)) {
+ selection = i;
+ break;
+ }
+ }
+ if (allowUnset || selection >= 0 || (value === undefined && element.size > 1)) {
+ element.selectedIndex = selection;
+ }
+ break;
+ default:
+ if ((value === null) || (value === undefined))
+ value = "";
+ element.value = value;
+ break;
+ }
+ }
+ };
+})();
+
+ko.exportSymbol('selectExtensions', ko.selectExtensions);
+ko.exportSymbol('selectExtensions.readValue', ko.selectExtensions.readValue);
+ko.exportSymbol('selectExtensions.writeValue', ko.selectExtensions.writeValue);
+ko.expressionRewriting = (function () {
+ var javaScriptReservedWords = ["true", "false", "null", "undefined"];
+
+ // Matches something that can be assigned to--either an isolated identifier or something ending with a property accessor
+ // This is designed to be simple and avoid false negatives, but could produce false positives (e.g., a+b.c).
+ // This also will not properly handle nested brackets (e.g., obj1[obj2['prop']]; see #911).
+ var javaScriptAssignmentTarget = /^(?:[$_a-z][$\w]*|(.+)(\.\s*[$_a-z][$\w]*|\[.+\]))$/i;
+
+ function getWriteableValue(expression) {
+ if (ko.utils.arrayIndexOf(javaScriptReservedWords, expression) >= 0)
+ return false;
+ var match = expression.match(javaScriptAssignmentTarget);
+ return match === null ? false : match[1] ? ('Object(' + match[1] + ')' + match[2]) : expression;
+ }
+
+ // The following regular expressions will be used to split an object-literal string into tokens
+
+ // These two match strings, either with double quotes or single quotes
+ var stringDouble = '"(?:[^"\\\\]|\\\\.)*"',
+ stringSingle = "'(?:[^'\\\\]|\\\\.)*'",
+ // Matches a regular expression (text enclosed by slashes), but will also match sets of divisions
+ // as a regular expression (this is handled by the parsing loop below).
+ stringRegexp = '/(?:[^/\\\\]|\\\\.)*/\w*',
+ // These characters have special meaning to the parser and must not appear in the middle of a
+ // token, except as part of a string.
+ specials = ',"\'{}()/:[\\]',
+ // Match text (at least two characters) that does not contain any of the above special characters,
+ // although some of the special characters are allowed to start it (all but the colon and comma).
+ // The text can contain spaces, but leading or trailing spaces are skipped.
+ everyThingElse = '[^\\s:,/][^' + specials + ']*[^\\s' + specials + ']',
+ // Match any non-space character not matched already. This will match colons and commas, since they're
+ // not matched by "everyThingElse", but will also match any other single character that wasn't already
+ // matched (for example: in "a: 1, b: 2", each of the non-space characters will be matched by oneNotSpace).
+ oneNotSpace = '[^\\s]',
+
+ // Create the actual regular expression by or-ing the above strings. The order is important.
+ bindingToken = RegExp(stringDouble + '|' + stringSingle + '|' + stringRegexp + '|' + everyThingElse + '|' + oneNotSpace, 'g'),
+
+ // Match end of previous token to determine whether a slash is a division or regex.
+ divisionLookBehind = /[\])"'A-Za-z0-9_$]+$/,
+ keywordRegexLookBehind = {'in':1,'return':1,'typeof':1};
+
+ function parseObjectLiteral(objectLiteralString) {
+ // Trim leading and trailing spaces from the string
+ var str = ko.utils.stringTrim(objectLiteralString);
+
+ // Trim braces '{' surrounding the whole object literal
+ if (str.charCodeAt(0) === 123) str = str.slice(1, -1);
+
+ // Split into tokens
+ var result = [], toks = str.match(bindingToken), key, values, depth = 0;
+
+ if (toks) {
+ // Append a comma so that we don't need a separate code block to deal with the last item
+ toks.push(',');
+
+ for (var i = 0, tok; tok = toks[i]; ++i) {
+ var c = tok.charCodeAt(0);
+ // A comma signals the end of a key/value pair if depth is zero
+ if (c === 44) { // ","
+ if (depth <= 0) {
+ if (key)
+ result.push(values ? {key: key, value: values.join('')} : {'unknown': key});
+ key = values = depth = 0;
+ continue;
+ }
+ // Simply skip the colon that separates the name and value
+ } else if (c === 58) { // ":"
+ if (!values)
+ continue;
+ // A set of slashes is initially matched as a regular expression, but could be division
+ } else if (c === 47 && i && tok.length > 1) { // "/"
+ // Look at the end of the previous token to determine if the slash is actually division
+ var match = toks[i-1].match(divisionLookBehind);
+ if (match && !keywordRegexLookBehind[match[0]]) {
+ // The slash is actually a division punctuator; re-parse the remainder of the string (not including the slash)
+ str = str.substr(str.indexOf(tok) + 1);
+ toks = str.match(bindingToken);
+ toks.push(',');
+ i = -1;
+ // Continue with just the slash
+ tok = '/';
+ }
+ // Increment depth for parentheses, braces, and brackets so that interior commas are ignored
+ } else if (c === 40 || c === 123 || c === 91) { // '(', '{', '['
+ ++depth;
+ } else if (c === 41 || c === 125 || c === 93) { // ')', '}', ']'
+ --depth;
+ // The key must be a single token; if it's a string, trim the quotes
+ } else if (!key && !values) {
+ key = (c === 34 || c === 39) /* '"', "'" */ ? tok.slice(1, -1) : tok;
+ continue;
+ }
+ if (values)
+ values.push(tok);
+ else
+ values = [tok];
+ }
+ }
+ return result;
+ }
+
+ // Two-way bindings include a write function that allow the handler to update the value even if it's not an observable.
+ var twoWayBindings = {};
+
+ function preProcessBindings(bindingsStringOrKeyValueArray, bindingOptions) {
+ bindingOptions = bindingOptions || {};
+
+ function processKeyValue(key, val) {
+ var writableVal;
+ function callPreprocessHook(obj) {
+ return (obj && obj['preprocess']) ? (val = obj['preprocess'](val, key, processKeyValue)) : true;
+ }
+ if (!callPreprocessHook(ko['getBindingHandler'](key)))
+ return;
+
+ if (twoWayBindings[key] && (writableVal = getWriteableValue(val))) {
+ // For two-way bindings, provide a write method in case the value
+ // isn't a writable observable.
+ propertyAccessorResultStrings.push("'" + key + "':function(_z){" + writableVal + "=_z}");
+ }
+
+ // Values are wrapped in a function so that each value can be accessed independently
+ if (makeValueAccessors) {
+ val = 'function(){return ' + val + ' }';
+ }
+ resultStrings.push("'" + key + "':" + val);
+ }
+
+ var resultStrings = [],
+ propertyAccessorResultStrings = [],
+ makeValueAccessors = bindingOptions['valueAccessors'],
+ keyValueArray = typeof bindingsStringOrKeyValueArray === "string" ?
+ parseObjectLiteral(bindingsStringOrKeyValueArray) : bindingsStringOrKeyValueArray;
+
+ ko.utils.arrayForEach(keyValueArray, function(keyValue) {
+ processKeyValue(keyValue.key || keyValue['unknown'], keyValue.value);
+ });
+
+ if (propertyAccessorResultStrings.length)
+ processKeyValue('_ko_property_writers', "{" + propertyAccessorResultStrings.join(",") + " }");
+
+ return resultStrings.join(",");
+ }
+
+ return {
+ bindingRewriteValidators: [],
+
+ twoWayBindings: twoWayBindings,
+
+ parseObjectLiteral: parseObjectLiteral,
+
+ preProcessBindings: preProcessBindings,
+
+ keyValueArrayContainsKey: function(keyValueArray, key) {
+ for (var i = 0; i < keyValueArray.length; i++)
+ if (keyValueArray[i]['key'] == key)
+ return true;
+ return false;
+ },
+
+ // Internal, private KO utility for updating model properties from within bindings
+ // property: If the property being updated is (or might be) an observable, pass it here
+ // If it turns out to be a writable observable, it will be written to directly
+ // allBindings: An object with a get method to retrieve bindings in the current execution context.
+ // This will be searched for a '_ko_property_writers' property in case you're writing to a non-observable
+ // key: The key identifying the property to be written. Example: for { hasFocus: myValue }, write to 'myValue' by specifying the key 'hasFocus'
+ // value: The value to be written
+ // checkIfDifferent: If true, and if the property being written is a writable observable, the value will only be written if
+ // it is !== existing value on that writable observable
+ writeValueToProperty: function(property, allBindings, key, value, checkIfDifferent) {
+ if (!property || !ko.isObservable(property)) {
+ var propWriters = allBindings.get('_ko_property_writers');
+ if (propWriters && propWriters[key])
+ propWriters[key](value);
+ } else if (ko.isWriteableObservable(property) && (!checkIfDifferent || property.peek() !== value)) {
+ property(value);
+ }
+ }
+ };
+})();
+
+ko.exportSymbol('expressionRewriting', ko.expressionRewriting);
+ko.exportSymbol('expressionRewriting.bindingRewriteValidators', ko.expressionRewriting.bindingRewriteValidators);
+ko.exportSymbol('expressionRewriting.parseObjectLiteral', ko.expressionRewriting.parseObjectLiteral);
+ko.exportSymbol('expressionRewriting.preProcessBindings', ko.expressionRewriting.preProcessBindings);
+
+// Making bindings explicitly declare themselves as "two way" isn't ideal in the long term (it would be better if
+// all bindings could use an official 'property writer' API without needing to declare that they might). However,
+// since this is not, and has never been, a public API (_ko_property_writers was never documented), it's acceptable
+// as an internal implementation detail in the short term.
+// For those developers who rely on _ko_property_writers in their custom bindings, we expose _twoWayBindings as an
+// undocumented feature that makes it relatively easy to upgrade to KO 3.0. However, this is still not an official
+// public API, and we reserve the right to remove it at any time if we create a real public property writers API.
+ko.exportSymbol('expressionRewriting._twoWayBindings', ko.expressionRewriting.twoWayBindings);
+
+// For backward compatibility, define the following aliases. (Previously, these function names were misleading because
+// they referred to JSON specifically, even though they actually work with arbitrary JavaScript object literal expressions.)
+ko.exportSymbol('jsonExpressionRewriting', ko.expressionRewriting);
+ko.exportSymbol('jsonExpressionRewriting.insertPropertyAccessorsIntoJson', ko.expressionRewriting.preProcessBindings);
+(function() {
+ // "Virtual elements" is an abstraction on top of the usual DOM API which understands the notion that comment nodes
+ // may be used to represent hierarchy (in addition to the DOM's natural hierarchy).
+ // If you call the DOM-manipulating functions on ko.virtualElements, you will be able to read and write the state
+ // of that virtual hierarchy
+ //
+ // The point of all this is to support containerless templates (e.g., <!-- ko foreach:someCollection -->blah<!-- /ko -->)
+ // without having to scatter special cases all over the binding and templating code.
+
+ // IE 9 cannot reliably read the "nodeValue" property of a comment node (see https://github.com/SteveSanderson/knockout/issues/186)
+ // but it does give them a nonstandard alternative property called "text" that it can read reliably. Other browsers don't have that property.
+ // So, use node.text where available, and node.nodeValue elsewhere
+ var commentNodesHaveTextProperty = document && document.createComment("test").text === "<!--test-->";
+
+ var startCommentRegex = commentNodesHaveTextProperty ? /^<!--\s*ko(?:\s+([\s\S]+))?\s*-->$/ : /^\s*ko(?:\s+([\s\S]+))?\s*$/;
+ var endCommentRegex = commentNodesHaveTextProperty ? /^<!--\s*\/ko\s*-->$/ : /^\s*\/ko\s*$/;
+ var htmlTagsWithOptionallyClosingChildren = { 'ul': true, 'ol': true };
+
+ function isStartComment(node) {
+ return (node.nodeType == 8) && startCommentRegex.test(commentNodesHaveTextProperty ? node.text : node.nodeValue);
+ }
+
+ function isEndComment(node) {
+ return (node.nodeType == 8) && endCommentRegex.test(commentNodesHaveTextProperty ? node.text : node.nodeValue);
+ }
+
+ function getVirtualChildren(startComment, allowUnbalanced) {
+ var currentNode = startComment;
+ var depth = 1;
+ var children = [];
+ while (currentNode = currentNode.nextSibling) {
+ if (isEndComment(currentNode)) {
+ depth--;
+ if (depth === 0)
+ return children;
+ }
+
+ children.push(currentNode);
+
+ if (isStartComment(currentNode))
+ depth++;
+ }
+ if (!allowUnbalanced)
+ throw new Error("Cannot find closing comment tag to match: " + startComment.nodeValue);
+ return null;
+ }
+
+ function getMatchingEndComment(startComment, allowUnbalanced) {
+ var allVirtualChildren = getVirtualChildren(startComment, allowUnbalanced);
+ if (allVirtualChildren) {
+ if (allVirtualChildren.length > 0)
+ return allVirtualChildren[allVirtualChildren.length - 1].nextSibling;
+ return startComment.nextSibling;
+ } else
+ return null; // Must have no matching end comment, and allowUnbalanced is true
+ }
+
+ function getUnbalancedChildTags(node) {
+ // e.g., from <div>OK</div><!-- ko blah --><span>Another</span>, returns: <!-- ko blah --><span>Another</span>
+ // from <div>OK</div><!-- /ko --><!-- /ko -->, returns: <!-- /ko --><!-- /ko -->
+ var childNode = node.firstChild, captureRemaining = null;
+ if (childNode) {
+ do {
+ if (captureRemaining) // We already hit an unbalanced node and are now just scooping up all subsequent nodes
+ captureRemaining.push(childNode);
+ else if (isStartComment(childNode)) {
+ var matchingEndComment = getMatchingEndComment(childNode, /* allowUnbalanced: */ true);
+ if (matchingEndComment) // It's a balanced tag, so skip immediately to the end of this virtual set
+ childNode = matchingEndComment;
+ else
+ captureRemaining = [childNode]; // It's unbalanced, so start capturing from this point
+ } else if (isEndComment(childNode)) {
+ captureRemaining = [childNode]; // It's unbalanced (if it wasn't, we'd have skipped over it already), so start capturing
+ }
+ } while (childNode = childNode.nextSibling);
+ }
+ return captureRemaining;
+ }
+
+ ko.virtualElements = {
+ allowedBindings: {},
+
+ childNodes: function(node) {
+ return isStartComment(node) ? getVirtualChildren(node) : node.childNodes;
+ },
+
+ emptyNode: function(node) {
+ if (!isStartComment(node))
+ ko.utils.emptyDomNode(node);
+ else {
+ var virtualChildren = ko.virtualElements.childNodes(node);
+ for (var i = 0, j = virtualChildren.length; i < j; i++)
+ ko.removeNode(virtualChildren[i]);
+ }
+ },
+
+ setDomNodeChildren: function(node, childNodes) {
+ if (!isStartComment(node))
+ ko.utils.setDomNodeChildren(node, childNodes);
+ else {
+ ko.virtualElements.emptyNode(node);
+ var endCommentNode = node.nextSibling; // Must be the next sibling, as we just emptied the children
+ for (var i = 0, j = childNodes.length; i < j; i++)
+ endCommentNode.parentNode.insertBefore(childNodes[i], endCommentNode);
+ }
+ },
+
+ prepend: function(containerNode, nodeToPrepend) {
+ if (!isStartComment(containerNode)) {
+ if (containerNode.firstChild)
+ containerNode.insertBefore(nodeToPrepend, containerNode.firstChild);
+ else
+ containerNode.appendChild(nodeToPrepend);
+ } else {
+ // Start comments must always have a parent and at least one following sibling (the end comment)
+ containerNode.parentNode.insertBefore(nodeToPrepend, containerNode.nextSibling);
+ }
+ },
+
+ insertAfter: function(containerNode, nodeToInsert, insertAfterNode) {
+ if (!insertAfterNode) {
+ ko.virtualElements.prepend(containerNode, nodeToInsert);
+ } else if (!isStartComment(containerNode)) {
+ // Insert after insertion point
+ if (insertAfterNode.nextSibling)
+ containerNode.insertBefore(nodeToInsert, insertAfterNode.nextSibling);
+ else
+ containerNode.appendChild(nodeToInsert);
+ } else {
+ // Children of start comments must always have a parent and at least one following sibling (the end comment)
+ containerNode.parentNode.insertBefore(nodeToInsert, insertAfterNode.nextSibling);
+ }
+ },
+
+ firstChild: function(node) {
+ if (!isStartComment(node))
+ return node.firstChild;
+ if (!node.nextSibling || isEndComment(node.nextSibling))
+ return null;
+ return node.nextSibling;
+ },
+
+ nextSibling: function(node) {
+ if (isStartComment(node))
+ node = getMatchingEndComment(node);
+ if (node.nextSibling && isEndComment(node.nextSibling))
+ return null;
+ return node.nextSibling;
+ },
+
+ hasBindingValue: isStartComment,
+
+ virtualNodeBindingValue: function(node) {
+ var regexMatch = (commentNodesHaveTextProperty ? node.text : node.nodeValue).match(startCommentRegex);
+ return regexMatch ? regexMatch[1] : null;
+ },
+
+ normaliseVirtualElementDomStructure: function(elementVerified) {
+ // Workaround for https://github.com/SteveSanderson/knockout/issues/155
+ // (IE <= 8 or IE 9 quirks mode parses your HTML weirdly, treating closing </li> tags as if they don't exist, thereby moving comment nodes
+ // that are direct descendants of <ul> into the preceding <li>)
+ if (!htmlTagsWithOptionallyClosingChildren[ko.utils.tagNameLower(elementVerified)])
+ return;
+
+ // Scan immediate children to see if they contain unbalanced comment tags. If they do, those comment tags
+ // must be intended to appear *after* that child, so move them there.
+ var childNode = elementVerified.firstChild;
+ if (childNode) {
+ do {
+ if (childNode.nodeType === 1) {
+ var unbalancedTags = getUnbalancedChildTags(childNode);
+ if (unbalancedTags) {
+ // Fix up the DOM by moving the unbalanced tags to where they most likely were intended to be placed - *after* the child
+ var nodeToInsertBefore = childNode.nextSibling;
+ for (var i = 0; i < unbalancedTags.length; i++) {
+ if (nodeToInsertBefore)
+ elementVerified.insertBefore(unbalancedTags[i], nodeToInsertBefore);
+ else
+ elementVerified.appendChild(unbalancedTags[i]);
+ }
+ }
+ }
+ } while (childNode = childNode.nextSibling);
+ }
+ }
+ };
+})();
+ko.exportSymbol('virtualElements', ko.virtualElements);
+ko.exportSymbol('virtualElements.allowedBindings', ko.virtualElements.allowedBindings);
+ko.exportSymbol('virtualElements.emptyNode', ko.virtualElements.emptyNode);
+//ko.exportSymbol('virtualElements.firstChild', ko.virtualElements.firstChild); // firstChild is not minified
+ko.exportSymbol('virtualElements.insertAfter', ko.virtualElements.insertAfter);
+//ko.exportSymbol('virtualElements.nextSibling', ko.virtualElements.nextSibling); // nextSibling is not minified
+ko.exportSymbol('virtualElements.prepend', ko.virtualElements.prepend);
+ko.exportSymbol('virtualElements.setDomNodeChildren', ko.virtualElements.setDomNodeChildren);
+(function() {
+ var defaultBindingAttributeName = "data-bind";
+
+ ko.bindingProvider = function() {
+ this.bindingCache = {};
+ };
+
+ ko.utils.extend(ko.bindingProvider.prototype, {
+ 'nodeHasBindings': function(node) {
+ switch (node.nodeType) {
+ case 1: return node.getAttribute(defaultBindingAttributeName) != null; // Element
+ case 8: return ko.virtualElements.hasBindingValue(node); // Comment node
+ default: return false;
+ }
+ },
+
+ 'getBindings': function(node, bindingContext) {
+ var bindingsString = this['getBindingsString'](node, bindingContext);
+ return bindingsString ? this['parseBindingsString'](bindingsString, bindingContext, node) : null;
+ },
+
+ 'getBindingAccessors': function(node, bindingContext) {
+ var bindingsString = this['getBindingsString'](node, bindingContext);
+ return bindingsString ? this['parseBindingsString'](bindingsString, bindingContext, node, {'valueAccessors':true}) : null;
+ },
+
+ // The following function is only used internally by this default provider.
+ // It's not part of the interface definition for a general binding provider.
+ 'getBindingsString': function(node, bindingContext) {
+ switch (node.nodeType) {
+ case 1: return node.getAttribute(defaultBindingAttributeName); // Element
+ case 8: return ko.virtualElements.virtualNodeBindingValue(node); // Comment node
+ default: return null;
+ }
+ },
+
+ // The following function is only used internally by this default provider.
+ // It's not part of the interface definition for a general binding provider.
+ 'parseBindingsString': function(bindingsString, bindingContext, node, options) {
+ try {
+ var bindingFunction = createBindingsStringEvaluatorViaCache(bindingsString, this.bindingCache, options);
+ return bindingFunction(bindingContext, node);
+ } catch (ex) {
+ ex.message = "Unable to parse bindings.\nBindings value: " + bindingsString + "\nMessage: " + ex.message;
+ throw ex;
+ }
+ }
+ });
+
+ ko.bindingProvider['instance'] = new ko.bindingProvider();
+
+ function createBindingsStringEvaluatorViaCache(bindingsString, cache, options) {
+ var cacheKey = bindingsString + (options && options['valueAccessors'] || '');
+ return cache[cacheKey]
+ || (cache[cacheKey] = createBindingsStringEvaluator(bindingsString, options));
+ }
+
+ function createBindingsStringEvaluator(bindingsString, options) {
+ // Build the source for a function that evaluates "expression"
+ // For each scope variable, add an extra level of "with" nesting
+ // Example result: with(sc1) { with(sc0) { return (expression) } }
+ var rewrittenBindings = ko.expressionRewriting.preProcessBindings(bindingsString, options),
+ functionBody = "with($context){with($data||{}){return{" + rewrittenBindings + "}}}";
+ return new Function("$context", "$element", functionBody);
+ }
+})();
+
+ko.exportSymbol('bindingProvider', ko.bindingProvider);
+(function () {
+ ko.bindingHandlers = {};
+
+ // The following element types will not be recursed into during binding. In the future, we
+ // may consider adding <template> to this list, because such elements' contents are always
+ // intended to be bound in a different context from where they appear in the document.
+ var bindingDoesNotRecurseIntoElementTypes = {
+ // Don't want bindings that operate on text nodes to mutate <script> contents,
+ // because it's unexpected and a potential XSS issue
+ 'script': true
+ };
+
+ // Use an overridable method for retrieving binding handlers so that a plugins may support dynamically created handlers
+ ko['getBindingHandler'] = function(bindingKey) {
+ return ko.bindingHandlers[bindingKey];
+ };
+
+ // The ko.bindingContext constructor is only called directly to create the root context. For child
+ // contexts, use bindingContext.createChildContext or bindingContext.extend.
+ ko.bindingContext = function(dataItemOrAccessor, parentContext, dataItemAlias, extendCallback) {
+
+ // The binding context object includes static properties for the current, parent, and root view models.
+ // If a view model is actually stored in an observable, the corresponding binding context object, and
+ // any child contexts, must be updated when the view model is changed.
+ function updateContext() {
+ // Most of the time, the context will directly get a view model object, but if a function is given,
+ // we call the function to retrieve the view model. If the function accesses any obsevables or returns
+ // an observable, the dependency is tracked, and those observables can later cause the binding
+ // context to be updated.
+ var dataItemOrObservable = isFunc ? dataItemOrAccessor() : dataItemOrAccessor,
+ dataItem = ko.utils.unwrapObservable(dataItemOrObservable);
+
+ if (parentContext) {
+ // When a "parent" context is given, register a dependency on the parent context. Thus whenever the
+ // parent context is updated, this context will also be updated.
+ if (parentContext._subscribable)
+ parentContext._subscribable();
+
+ // Copy $root and any custom properties from the parent context
+ ko.utils.extend(self, parentContext);
+
+ // Because the above copy overwrites our own properties, we need to reset them.
+ // During the first execution, "subscribable" isn't set, so don't bother doing the update then.
+ if (subscribable) {
+ self._subscribable = subscribable;
+ }
+ } else {
+ self['$parents'] = [];
+ self['$root'] = dataItem;
+
+ // Export 'ko' in the binding context so it will be available in bindings and templates
+ // even if 'ko' isn't exported as a global, such as when using an AMD loader.
+ // See https://github.com/SteveSanderson/knockout/issues/490
+ self['ko'] = ko;
+ }
+ self['$rawData'] = dataItemOrObservable;
+ self['$data'] = dataItem;
+ if (dataItemAlias)
+ self[dataItemAlias] = dataItem;
+
+ // The extendCallback function is provided when creating a child context or extending a context.
+ // It handles the specific actions needed to finish setting up the binding context. Actions in this
+ // function could also add dependencies to this binding context.
+ if (extendCallback)
+ extendCallback(self, parentContext, dataItem);
+
+ return self['$data'];
+ }
+ function disposeWhen() {
+ return nodes && !ko.utils.anyDomNodeIsAttachedToDocument(nodes);
+ }
+
+ var self = this,
+ isFunc = typeof(dataItemOrAccessor) == "function" && !ko.isObservable(dataItemOrAccessor),
+ nodes,
+ subscribable = ko.dependentObservable(updateContext, null, { disposeWhen: disposeWhen, disposeWhenNodeIsRemoved: true });
+
+ // At this point, the binding context has been initialized, and the "subscribable" computed observable is
+ // subscribed to any observables that were accessed in the process. If there is nothing to track, the
+ // computed will be inactive, and we can safely throw it away. If it's active, the computed is stored in
+ // the context object.
+ if (subscribable.isActive()) {
+ self._subscribable = subscribable;
+
+ // Always notify because even if the model ($data) hasn't changed, other context properties might have changed
+ subscribable['equalityComparer'] = null;
+
+ // We need to be able to dispose of this computed observable when it's no longer needed. This would be
+ // easy if we had a single node to watch, but binding contexts can be used by many different nodes, and
+ // we cannot assume that those nodes have any relation to each other. So instead we track any node that
+ // the context is attached to, and dispose the computed when all of those nodes have been cleaned.
+
+ // Add properties to *subscribable* instead of *self* because any properties added to *self* may be overwritten on updates
+ nodes = [];
+ subscribable._addNode = function(node) {
+ nodes.push(node);
+ ko.utils.domNodeDisposal.addDisposeCallback(node, function(node) {
+ ko.utils.arrayRemoveItem(nodes, node);
+ if (!nodes.length) {
+ subscribable.dispose();
+ self._subscribable = subscribable = undefined;
+ }
+ });
+ };
+ }
+ }
+
+ // Extend the binding context hierarchy with a new view model object. If the parent context is watching
+ // any obsevables, the new child context will automatically get a dependency on the parent context.
+ // But this does not mean that the $data value of the child context will also get updated. If the child
+ // view model also depends on the parent view model, you must provide a function that returns the correct
+ // view model on each update.
+ ko.bindingContext.prototype['createChildContext'] = function (dataItemOrAccessor, dataItemAlias, extendCallback) {
+ return new ko.bindingContext(dataItemOrAccessor, this, dataItemAlias, function(self, parentContext) {
+ // Extend the context hierarchy by setting the appropriate pointers
+ self['$parentContext'] = parentContext;
+ self['$parent'] = parentContext['$data'];
+ self['$parents'] = (parentContext['$parents'] || []).slice(0);
+ self['$parents'].unshift(self['$parent']);
+ if (extendCallback)
+ extendCallback(self);
+ });
+ };
+
+ // Extend the binding context with new custom properties. This doesn't change the context hierarchy.
+ // Similarly to "child" contexts, provide a function here to make sure that the correct values are set
+ // when an observable view model is updated.
+ ko.bindingContext.prototype['extend'] = function(properties) {
+ // If the parent context references an observable view model, "_subscribable" will always be the
+ // latest view model object. If not, "_subscribable" isn't set, and we can use the static "$data" value.
+ return new ko.bindingContext(this._subscribable || this['$data'], this, null, function(self, parentContext) {
+ // This "child" context doesn't directly track a parent observable view model,
+ // so we need to manually set the $rawData value to match the parent.
+ self['$rawData'] = parentContext['$rawData'];
+ ko.utils.extend(self, typeof(properties) == "function" ? properties() : properties);
+ });
+ };
+
+ // Returns the valueAccesor function for a binding value
+ function makeValueAccessor(value) {
+ return function() {
+ return value;
+ };
+ }
+
+ // Returns the value of a valueAccessor function
+ function evaluateValueAccessor(valueAccessor) {
+ return valueAccessor();
+ }
+
+ // Given a function that returns bindings, create and return a new object that contains
+ // binding value-accessors functions. Each accessor function calls the original function
+ // so that it always gets the latest value and all dependencies are captured. This is used
+ // by ko.applyBindingsToNode and getBindingsAndMakeAccessors.
+ function makeAccessorsFromFunction(callback) {
+ return ko.utils.objectMap(ko.dependencyDetection.ignore(callback), function(value, key) {
+ return function() {
+ return callback()[key];
+ };
+ });
+ }
+
+ // Given a bindings function or object, create and return a new object that contains
+ // binding value-accessors functions. This is used by ko.applyBindingsToNode.
+ function makeBindingAccessors(bindings, context, node) {
+ if (typeof bindings === 'function') {
+ return makeAccessorsFromFunction(bindings.bind(null, context, node));
+ } else {
+ return ko.utils.objectMap(bindings, makeValueAccessor);
+ }
+ }
+
+ // This function is used if the binding provider doesn't include a getBindingAccessors function.
+ // It must be called with 'this' set to the provider instance.
+ function getBindingsAndMakeAccessors(node, context) {
+ return makeAccessorsFromFunction(this['getBindings'].bind(this, node, context));
+ }
+
+ function validateThatBindingIsAllowedForVirtualElements(bindingName) {
+ var validator = ko.virtualElements.allowedBindings[bindingName];
+ if (!validator)
+ throw new Error("The binding '" + bindingName + "' cannot be used with virtual elements")
+ }
+
+ function applyBindingsToDescendantsInternal (bindingContext, elementOrVirtualElement, bindingContextsMayDifferFromDomParentElement) {
+ var currentChild,
+ nextInQueue = ko.virtualElements.firstChild(elementOrVirtualElement),
+ provider = ko.bindingProvider['instance'],
+ preprocessNode = provider['preprocessNode'];
+
+ // Preprocessing allows a binding provider to mutate a node before bindings are applied to it. For example it's
+ // possible to insert new siblings after it, and/or replace the node with a different one. This can be used to
+ // implement custom binding syntaxes, such as {{ value }} for string interpolation, or custom element types that
+ // trigger insertion of <template> contents at that point in the document.
+ if (preprocessNode) {
+ while (currentChild = nextInQueue) {
+ nextInQueue = ko.virtualElements.nextSibling(currentChild);
+ preprocessNode.call(provider, currentChild);
+ }
+ // Reset nextInQueue for the next loop
+ nextInQueue = ko.virtualElements.firstChild(elementOrVirtualElement);
+ }
+
+ while (currentChild = nextInQueue) {
+ // Keep a record of the next child *before* applying bindings, in case the binding removes the current child from its position
+ nextInQueue = ko.virtualElements.nextSibling(currentChild);
+ applyBindingsToNodeAndDescendantsInternal(bindingContext, currentChild, bindingContextsMayDifferFromDomParentElement);
+ }
+ }
+
+ function applyBindingsToNodeAndDescendantsInternal (bindingContext, nodeVerified, bindingContextMayDifferFromDomParentElement) {
+ var shouldBindDescendants = true;
+
+ // Perf optimisation: Apply bindings only if...
+ // (1) We need to store the binding context on this node (because it may differ from the DOM parent node's binding context)
+ // Note that we can't store binding contexts on non-elements (e.g., text nodes), as IE doesn't allow expando properties for those
+ // (2) It might have bindings (e.g., it has a data-bind attribute, or it's a marker for a containerless template)
+ var isElement = (nodeVerified.nodeType === 1);
+ if (isElement) // Workaround IE <= 8 HTML parsing weirdness
+ ko.virtualElements.normaliseVirtualElementDomStructure(nodeVerified);
+
+ var shouldApplyBindings = (isElement && bindingContextMayDifferFromDomParentElement) // Case (1)
+ || ko.bindingProvider['instance']['nodeHasBindings'](nodeVerified); // Case (2)
+ if (shouldApplyBindings)
+ shouldBindDescendants = applyBindingsToNodeInternal(nodeVerified, null, bindingContext, bindingContextMayDifferFromDomParentElement)['shouldBindDescendants'];
+
+ if (shouldBindDescendants && !bindingDoesNotRecurseIntoElementTypes[ko.utils.tagNameLower(nodeVerified)]) {
+ // We're recursing automatically into (real or virtual) child nodes without changing binding contexts. So,
+ // * For children of a *real* element, the binding context is certainly the same as on their DOM .parentNode,
+ // hence bindingContextsMayDifferFromDomParentElement is false
+ // * For children of a *virtual* element, we can't be sure. Evaluating .parentNode on those children may
+ // skip over any number of intermediate virtual elements, any of which might define a custom binding context,
+ // hence bindingContextsMayDifferFromDomParentElement is true
+ applyBindingsToDescendantsInternal(bindingContext, nodeVerified, /* bindingContextsMayDifferFromDomParentElement: */ !isElement);
+ }
+ }
+
+ var boundElementDomDataKey = ko.utils.domData.nextKey();
+
+
+ function topologicalSortBindings(bindings) {
+ // Depth-first sort
+ var result = [], // The list of key/handler pairs that we will return
+ bindingsConsidered = {}, // A temporary record of which bindings are already in 'result'
+ cyclicDependencyStack = []; // Keeps track of a depth-search so that, if there's a cycle, we know which bindings caused it
+ ko.utils.objectForEach(bindings, function pushBinding(bindingKey) {
+ if (!bindingsConsidered[bindingKey]) {
+ var binding = ko['getBindingHandler'](bindingKey);
+ if (binding) {
+ // First add dependencies (if any) of the current binding
+ if (binding['after']) {
+ cyclicDependencyStack.push(bindingKey);
+ ko.utils.arrayForEach(binding['after'], function(bindingDependencyKey) {
+ if (bindings[bindingDependencyKey]) {
+ if (ko.utils.arrayIndexOf(cyclicDependencyStack, bindingDependencyKey) !== -1) {
+ throw Error("Cannot combine the following bindings, because they have a cyclic dependency: " + cyclicDependencyStack.join(", "));
+ } else {
+ pushBinding(bindingDependencyKey);
+ }
+ }
+ });
+ cyclicDependencyStack.length--;
+ }
+ // Next add the current binding
+ result.push({ key: bindingKey, handler: binding });
+ }
+ bindingsConsidered[bindingKey] = true;
+ }
+ });
+
+ return result;
+ }
+
+ function applyBindingsToNodeInternal(node, sourceBindings, bindingContext, bindingContextMayDifferFromDomParentElement) {
+ // Prevent multiple applyBindings calls for the same node, except when a binding value is specified
+ var alreadyBound = ko.utils.domData.get(node, boundElementDomDataKey);
+ if (!sourceBindings) {
+ if (alreadyBound) {
+ throw Error("You cannot apply bindings multiple times to the same element.");
+ }
+ ko.utils.domData.set(node, boundElementDomDataKey, true);
+ }
+
+ // Optimization: Don't store the binding context on this node if it's definitely the same as on node.parentNode, because
+ // we can easily recover it just by scanning up the node's ancestors in the DOM
+ // (note: here, parent node means "real DOM parent" not "virtual parent", as there's no O(1) way to find the virtual parent)
+ if (!alreadyBound && bindingContextMayDifferFromDomParentElement)
+ ko.storedBindingContextForNode(node, bindingContext);
+
+ // Use bindings if given, otherwise fall back on asking the bindings provider to give us some bindings
+ var bindings;
+ if (sourceBindings && typeof sourceBindings !== 'function') {
+ bindings = sourceBindings;
+ } else {
+ var provider = ko.bindingProvider['instance'],
+ getBindings = provider['getBindingAccessors'] || getBindingsAndMakeAccessors;
+
+ // Get the binding from the provider within a computed observable so that we can update the bindings whenever
+ // the binding context is updated or if the binding provider accesses observables.
+ var bindingsUpdater = ko.dependentObservable(
+ function() {
+ bindings = sourceBindings ? sourceBindings(bindingContext, node) : getBindings.call(provider, node, bindingContext);
+ // Register a dependency on the binding context to support obsevable view models.
+ if (bindings && bindingContext._subscribable)
+ bindingContext._subscribable();
+ return bindings;
+ },
+ null, { disposeWhenNodeIsRemoved: node }
+ );
+
+ if (!bindings || !bindingsUpdater.isActive())
+ bindingsUpdater = null;
+ }
+
+ var bindingHandlerThatControlsDescendantBindings;
+ if (bindings) {
+ // Return the value accessor for a given binding. When bindings are static (won't be updated because of a binding
+ // context update), just return the value accessor from the binding. Otherwise, return a function that always gets
+ // the latest binding value and registers a dependency on the binding updater.
+ var getValueAccessor = bindingsUpdater
+ ? function(bindingKey) {
+ return function() {
+ return evaluateValueAccessor(bindingsUpdater()[bindingKey]);
+ };
+ } : function(bindingKey) {
+ return bindings[bindingKey];
+ };
+
+ // Use of allBindings as a function is maintained for backwards compatibility, but its use is deprecated
+ function allBindings() {
+ return ko.utils.objectMap(bindingsUpdater ? bindingsUpdater() : bindings, evaluateValueAccessor);
+ }
+ // The following is the 3.x allBindings API
+ allBindings['get'] = function(key) {
+ return bindings[key] && evaluateValueAccessor(getValueAccessor(key));
+ };
+ allBindings['has'] = function(key) {
+ return key in bindings;
+ };
+
+ // First put the bindings into the right order
+ var orderedBindings = topologicalSortBindings(bindings);
+
+ // Go through the sorted bindings, calling init and update for each
+ ko.utils.arrayForEach(orderedBindings, function(bindingKeyAndHandler) {
+ // Note that topologicalSortBindings has already filtered out any nonexistent binding handlers,
+ // so bindingKeyAndHandler.handler will always be nonnull.
+ var handlerInitFn = bindingKeyAndHandler.handler["init"],
+ handlerUpdateFn = bindingKeyAndHandler.handler["update"],
+ bindingKey = bindingKeyAndHandler.key;
+
+ if (node.nodeType === 8) {
+ validateThatBindingIsAllowedForVirtualElements(bindingKey);
+ }
+
+ try {
+ // Run init, ignoring any dependencies
+ if (typeof handlerInitFn == "function") {
+ ko.dependencyDetection.ignore(function() {
+ var initResult = handlerInitFn(node, getValueAccessor(bindingKey), allBindings, bindingContext['$data'], bindingContext);
+
+ // If this binding handler claims to control descendant bindings, make a note of this
+ if (initResult && initResult['controlsDescendantBindings']) {
+ if (bindingHandlerThatControlsDescendantBindings !== undefined)
+ throw new Error("Multiple bindings (" + bindingHandlerThatControlsDescendantBindings + " and " + bindingKey + ") are trying to control descendant bindings of the same element. You cannot use these bindings together on the same element.");
+ bindingHandlerThatControlsDescendantBindings = bindingKey;
+ }
+ });
+ }
+
+ // Run update in its own computed wrapper
+ if (typeof handlerUpdateFn == "function") {
+ ko.dependentObservable(
+ function() {
+ handlerUpdateFn(node, getValueAccessor(bindingKey), allBindings, bindingContext['$data'], bindingContext);
+ },
+ null,
+ { disposeWhenNodeIsRemoved: node }
+ );
+ }
+ } catch (ex) {
+ ex.message = "Unable to process binding \"" + bindingKey + ": " + bindings[bindingKey] + "\"\nMessage: " + ex.message;
+ throw ex;
+ }
+ });
+ }
+
+ return {
+ 'shouldBindDescendants': bindingHandlerThatControlsDescendantBindings === undefined
+ };
+ };
+
+ var storedBindingContextDomDataKey = ko.utils.domData.nextKey();
+ ko.storedBindingContextForNode = function (node, bindingContext) {
+ if (arguments.length == 2) {
+ ko.utils.domData.set(node, storedBindingContextDomDataKey, bindingContext);
+ if (bindingContext._subscribable)
+ bindingContext._subscribable._addNode(node);
+ } else {
+ return ko.utils.domData.get(node, storedBindingContextDomDataKey);
+ }
+ }
+
+ function getBindingContext(viewModelOrBindingContext) {
+ return viewModelOrBindingContext && (viewModelOrBindingContext instanceof ko.bindingContext)
+ ? viewModelOrBindingContext
+ : new ko.bindingContext(viewModelOrBindingContext);
+ }
+
+ ko.applyBindingAccessorsToNode = function (node, bindings, viewModelOrBindingContext) {
+ if (node.nodeType === 1) // If it's an element, workaround IE <= 8 HTML parsing weirdness
+ ko.virtualElements.normaliseVirtualElementDomStructure(node);
+ return applyBindingsToNodeInternal(node, bindings, getBindingContext(viewModelOrBindingContext), true);
+ };
+
+ ko.applyBindingsToNode = function (node, bindings, viewModelOrBindingContext) {
+ var context = getBindingContext(viewModelOrBindingContext);
+ return ko.applyBindingAccessorsToNode(node, makeBindingAccessors(bindings, context, node), context);
+ };
+
+ ko.applyBindingsToDescendants = function(viewModelOrBindingContext, rootNode) {
+ if (rootNode.nodeType === 1 || rootNode.nodeType === 8)
+ applyBindingsToDescendantsInternal(getBindingContext(viewModelOrBindingContext), rootNode, true);
+ };
+
+ ko.applyBindings = function (viewModelOrBindingContext, rootNode) {
+ // If jQuery is loaded after Knockout, we won't initially have access to it. So save it here.
+ if (!jQuery && window['jQuery']) {
+ jQuery = window['jQuery'];
+ }
+
+ if (rootNode && (rootNode.nodeType !== 1) && (rootNode.nodeType !== 8))
+ throw new Error("ko.applyBindings: first parameter should be your view model; second parameter should be a DOM node");
+ rootNode = rootNode || window.document.body; // Make "rootNode" parameter optional
+
+ applyBindingsToNodeAndDescendantsInternal(getBindingContext(viewModelOrBindingContext), rootNode, true);
+ };
+
+ // Retrieving binding context from arbitrary nodes
+ ko.contextFor = function(node) {
+ // We can only do something meaningful for elements and comment nodes (in particular, not text nodes, as IE can't store domdata for them)
+ switch (node.nodeType) {
+ case 1:
+ case 8:
+ var context = ko.storedBindingContextForNode(node);
+ if (context) return context;
+ if (node.parentNode) return ko.contextFor(node.parentNode);
+ break;
+ }
+ return undefined;
+ };
+ ko.dataFor = function(node) {
+ var context = ko.contextFor(node);
+ return context ? context['$data'] : undefined;
+ };
+
+ ko.exportSymbol('bindingHandlers', ko.bindingHandlers);
+ ko.exportSymbol('applyBindings', ko.applyBindings);
+ ko.exportSymbol('applyBindingsToDescendants', ko.applyBindingsToDescendants);
+ ko.exportSymbol('applyBindingAccessorsToNode', ko.applyBindingAccessorsToNode);
+ ko.exportSymbol('applyBindingsToNode', ko.applyBindingsToNode);
+ ko.exportSymbol('contextFor', ko.contextFor);
+ ko.exportSymbol('dataFor', ko.dataFor);
+})();
+var attrHtmlToJavascriptMap = { 'class': 'className', 'for': 'htmlFor' };
+ko.bindingHandlers['attr'] = {
+ 'update': function(element, valueAccessor, allBindings) {
+ var value = ko.utils.unwrapObservable(valueAccessor()) || {};
+ ko.utils.objectForEach(value, function(attrName, attrValue) {
+ attrValue = ko.utils.unwrapObservable(attrValue);
+
+ // To cover cases like "attr: { checked:someProp }", we want to remove the attribute entirely
+ // when someProp is a "no value"-like value (strictly null, false, or undefined)
+ // (because the absence of the "checked" attr is how to mark an element as not checked, etc.)
+ var toRemove = (attrValue === false) || (attrValue === null) || (attrValue === undefined);
+ if (toRemove)
+ element.removeAttribute(attrName);
+
+ // In IE <= 7 and IE8 Quirks Mode, you have to use the Javascript property name instead of the
+ // HTML attribute name for certain attributes. IE8 Standards Mode supports the correct behavior,
+ // but instead of figuring out the mode, we'll just set the attribute through the Javascript
+ // property for IE <= 8.
+ if (ko.utils.ieVersion <= 8 && attrName in attrHtmlToJavascriptMap) {
+ attrName = attrHtmlToJavascriptMap[attrName];
+ if (toRemove)
+ element.removeAttribute(attrName);
+ else
+ element[attrName] = attrValue;
+ } else if (!toRemove) {
+ element.setAttribute(attrName, attrValue.toString());
+ }
+
+ // Treat "name" specially - although you can think of it as an attribute, it also needs
+ // special handling on older versions of IE (https://github.com/SteveSanderson/knockout/pull/333)
+ // Deliberately being case-sensitive here because XHTML would regard "Name" as a different thing
+ // entirely, and there's no strong reason to allow for such casing in HTML.
+ if (attrName === "name") {
+ ko.utils.setElementName(element, toRemove ? "" : attrValue.toString());
+ }
+ });
+ }
+};
+(function() {
+
+ko.bindingHandlers['checked'] = {
+ 'after': ['value', 'attr'],
+ 'init': function (element, valueAccessor, allBindings) {
+ function checkedValue() {
+ return allBindings['has']('checkedValue')
+ ? ko.utils.unwrapObservable(allBindings.get('checkedValue'))
+ : element.value;
+ }
+
+ function updateModel() {
+ // This updates the model value from the view value.
+ // It runs in response to DOM events (click) and changes in checkedValue.
+ var isChecked = element.checked,
+ elemValue = useCheckedValue ? checkedValue() : isChecked;
+
+ // When we're first setting up this computed, don't change any model state.
+ if (ko.computedContext.isInitial()) {
+ return;
+ }
+
+ // We can ignore unchecked radio buttons, because some other radio
+ // button will be getting checked, and that one can take care of updating state.
+ if (isRadio && !isChecked) {
+ return;
+ }
+
+ var modelValue = ko.dependencyDetection.ignore(valueAccessor);
+ if (isValueArray) {
+ if (oldElemValue !== elemValue) {
+ // When we're responding to the checkedValue changing, and the element is
+ // currently checked, replace the old elem value with the new elem value
+ // in the model array.
+ if (isChecked) {
+ ko.utils.addOrRemoveItem(modelValue, elemValue, true);
+ ko.utils.addOrRemoveItem(modelValue, oldElemValue, false);
+ }
+
+ oldElemValue = elemValue;
+ } else {
+ // When we're responding to the user having checked/unchecked a checkbox,
+ // add/remove the element value to the model array.
+ ko.utils.addOrRemoveItem(modelValue, elemValue, isChecked);
+ }
+ } else {
+ ko.expressionRewriting.writeValueToProperty(modelValue, allBindings, 'checked', elemValue, true);
+ }
+ };
+
+ function updateView() {
+ // This updates the view value from the model value.
+ // It runs in response to changes in the bound (checked) value.
+ var modelValue = ko.utils.unwrapObservable(valueAccessor());
+
+ if (isValueArray) {
+ // When a checkbox is bound to an array, being checked represents its value being present in that array
+ element.checked = ko.utils.arrayIndexOf(modelValue, checkedValue()) >= 0;
+ } else if (isCheckbox) {
+ // When a checkbox is bound to any other value (not an array), being checked represents the value being trueish
+ element.checked = modelValue;
+ } else {
+ // For radio buttons, being checked means that the radio button's value corresponds to the model value
+ element.checked = (checkedValue() === modelValue);
+ }
+ };
+
+ var isCheckbox = element.type == "checkbox",
+ isRadio = element.type == "radio";
+
+ // Only bind to check boxes and radio buttons
+ if (!isCheckbox && !isRadio) {
+ return;
+ }
+
+ var isValueArray = isCheckbox && (ko.utils.unwrapObservable(valueAccessor()) instanceof Array),
+ oldElemValue = isValueArray ? checkedValue() : undefined,
+ useCheckedValue = isRadio || isValueArray;
+
+ // IE 6 won't allow radio buttons to be selected unless they have a name
+ if (isRadio && !element.name)
+ ko.bindingHandlers['uniqueName']['init'](element, function() { return true });
+
+ // Set up two computeds to update the binding:
+
+ // The first responds to changes in the checkedValue value and to element clicks
+ ko.computed(updateModel, null, { disposeWhenNodeIsRemoved: element });
+ ko.utils.registerEventHandler(element, "click", updateModel);
+
+ // The second responds to changes in the model value (the one associated with the checked binding)
+ ko.computed(updateView, null, { disposeWhenNodeIsRemoved: element });
+ }
+};
+ko.expressionRewriting.twoWayBindings['checked'] = true;
+
+ko.bindingHandlers['checkedValue'] = {
+ 'update': function (element, valueAccessor) {
+ element.value = ko.utils.unwrapObservable(valueAccessor());
+ }
+};
+
+})();var classesWrittenByBindingKey = '__ko__cssValue';
+ko.bindingHandlers['css'] = {
+ 'update': function (element, valueAccessor) {
+ var value = ko.utils.unwrapObservable(valueAccessor());
+ if (typeof value == "object") {
+ ko.utils.objectForEach(value, function(className, shouldHaveClass) {
+ shouldHaveClass = ko.utils.unwrapObservable(shouldHaveClass);
+ ko.utils.toggleDomNodeCssClass(element, className, shouldHaveClass);
+ });
+ } else {
+ value = String(value || ''); // Make sure we don't try to store or set a non-string value
+ ko.utils.toggleDomNodeCssClass(element, element[classesWrittenByBindingKey], false);
+ element[classesWrittenByBindingKey] = value;
+ ko.utils.toggleDomNodeCssClass(element, value, true);
+ }
+ }
+};
+ko.bindingHandlers['enable'] = {
+ 'update': function (element, valueAccessor) {
+ var value = ko.utils.unwrapObservable(valueAccessor());
+ if (value && element.disabled)
+ element.removeAttribute("disabled");
+ else if ((!value) && (!element.disabled))
+ element.disabled = true;
+ }
+};
+
+ko.bindingHandlers['disable'] = {
+ 'update': function (element, valueAccessor) {
+ ko.bindingHandlers['enable']['update'](element, function() { return !ko.utils.unwrapObservable(valueAccessor()) });
+ }
+};
+// For certain common events (currently just 'click'), allow a simplified data-binding syntax
+// e.g. click:handler instead of the usual full-length event:{click:handler}
+function makeEventHandlerShortcut(eventName) {
+ ko.bindingHandlers[eventName] = {
+ 'init': function(element, valueAccessor, allBindings, viewModel, bindingContext) {
+ var newValueAccessor = function () {
+ var result = {};
+ result[eventName] = valueAccessor();
+ return result;
+ };
+ return ko.bindingHandlers['event']['init'].call(this, element, newValueAccessor, allBindings, viewModel, bindingContext);
+ }
+ }
+}
+
+ko.bindingHandlers['event'] = {
+ 'init' : function (element, valueAccessor, allBindings, viewModel, bindingContext) {
+ var eventsToHandle = valueAccessor() || {};
+ ko.utils.objectForEach(eventsToHandle, function(eventName) {
+ if (typeof eventName == "string") {
+ ko.utils.registerEventHandler(element, eventName, function (event) {
+ var handlerReturnValue;
+ var handlerFunction = valueAccessor()[eventName];
+ if (!handlerFunction)
+ return;
+
+ try {
+ // Take all the event args, and prefix with the viewmodel
+ var argsForHandler = ko.utils.makeArray(arguments);
+ viewModel = bindingContext['$data'];
+ argsForHandler.unshift(viewModel);
+ handlerReturnValue = handlerFunction.apply(viewModel, argsForHandler);
+ } finally {
+ if (handlerReturnValue !== true) { // Normally we want to prevent default action. Developer can override this be explicitly returning true.
+ if (event.preventDefault)
+ event.preventDefault();
+ else
+ event.returnValue = false;
+ }
+ }
+
+ var bubble = allBindings.get(eventName + 'Bubble') !== false;
+ if (!bubble) {
+ event.cancelBubble = true;
+ if (event.stopPropagation)
+ event.stopPropagation();
+ }
+ });
+ }
+ });
+ }
+};
+// "foreach: someExpression" is equivalent to "template: { foreach: someExpression }"
+// "foreach: { data: someExpression, afterAdd: myfn }" is equivalent to "template: { foreach: someExpression, afterAdd: myfn }"
+ko.bindingHandlers['foreach'] = {
+ makeTemplateValueAccessor: function(valueAccessor) {
+ return function() {
+ var modelValue = valueAccessor(),
+ unwrappedValue = ko.utils.peekObservable(modelValue); // Unwrap without setting a dependency here
+
+ // If unwrappedValue is the array, pass in the wrapped value on its own
+ // The value will be unwrapped and tracked within the template binding
+ // (See https://github.com/SteveSanderson/knockout/issues/523)
+ if ((!unwrappedValue) || typeof unwrappedValue.length == "number")
+ return { 'foreach': modelValue, 'templateEngine': ko.nativeTemplateEngine.instance };
+
+ // If unwrappedValue.data is the array, preserve all relevant options and unwrap again value so we get updates
+ ko.utils.unwrapObservable(modelValue);
+ return {
+ 'foreach': unwrappedValue['data'],
+ 'as': unwrappedValue['as'],
+ 'includeDestroyed': unwrappedValue['includeDestroyed'],
+ 'afterAdd': unwrappedValue['afterAdd'],
+ 'beforeRemove': unwrappedValue['beforeRemove'],
+ 'afterRender': unwrappedValue['afterRender'],
+ 'beforeMove': unwrappedValue['beforeMove'],
+ 'afterMove': unwrappedValue['afterMove'],
+ 'templateEngine': ko.nativeTemplateEngine.instance
+ };
+ };
+ },
+ 'init': function(element, valueAccessor, allBindings, viewModel, bindingContext) {
+ return ko.bindingHandlers['template']['init'](element, ko.bindingHandlers['foreach'].makeTemplateValueAccessor(valueAccessor));
+ },
+ 'update': function(element, valueAccessor, allBindings, viewModel, bindingContext) {
+ return ko.bindingHandlers['template']['update'](element, ko.bindingHandlers['foreach'].makeTemplateValueAccessor(valueAccessor), allBindings, viewModel, bindingContext);
+ }
+};
+ko.expressionRewriting.bindingRewriteValidators['foreach'] = false; // Can't rewrite control flow bindings
+ko.virtualElements.allowedBindings['foreach'] = true;
+var hasfocusUpdatingProperty = '__ko_hasfocusUpdating';
+var hasfocusLastValue = '__ko_hasfocusLastValue';
+ko.bindingHandlers['hasfocus'] = {
+ 'init': function(element, valueAccessor, allBindings) {
+ var handleElementFocusChange = function(isFocused) {
+ // Where possible, ignore which event was raised and determine focus state using activeElement,
+ // as this avoids phantom focus/blur events raised when changing tabs in modern browsers.
+ // However, not all KO-targeted browsers (Firefox 2) support activeElement. For those browsers,
+ // prevent a loss of focus when changing tabs/windows by setting a flag that prevents hasfocus
+ // from calling 'blur()' on the element when it loses focus.
+ // Discussion at https://github.com/SteveSanderson/knockout/pull/352
+ element[hasfocusUpdatingProperty] = true;
+ var ownerDoc = element.ownerDocument;
+ if ("activeElement" in ownerDoc) {
+ var active;
+ try {
+ active = ownerDoc.activeElement;
+ } catch(e) {
+ // IE9 throws if you access activeElement during page load (see issue #703)
+ active = ownerDoc.body;
+ }
+ isFocused = (active === element);
+ }
+ var modelValue = valueAccessor();
+ ko.expressionRewriting.writeValueToProperty(modelValue, allBindings, 'hasfocus', isFocused, true);
+
+ //cache the latest value, so we can avoid unnecessarily calling focus/blur in the update function
+ element[hasfocusLastValue] = isFocused;
+ element[hasfocusUpdatingProperty] = false;
+ };
+ var handleElementFocusIn = handleElementFocusChange.bind(null, true);
+ var handleElementFocusOut = handleElementFocusChange.bind(null, false);
+
+ ko.utils.registerEventHandler(element, "focus", handleElementFocusIn);
+ ko.utils.registerEventHandler(element, "focusin", handleElementFocusIn); // For IE
+ ko.utils.registerEventHandler(element, "blur", handleElementFocusOut);
+ ko.utils.registerEventHandler(element, "focusout", handleElementFocusOut); // For IE
+ },
+ 'update': function(element, valueAccessor) {
+ var value = !!ko.utils.unwrapObservable(valueAccessor()); //force boolean to compare with last value
+ if (!element[hasfocusUpdatingProperty] && element[hasfocusLastValue] !== value) {
+ value ? element.focus() : element.blur();
+ ko.dependencyDetection.ignore(ko.utils.triggerEvent, null, [element, value ? "focusin" : "focusout"]); // For IE, which doesn't reliably fire "focus" or "blur" events synchronously
+ }
+ }
+};
+ko.expressionRewriting.twoWayBindings['hasfocus'] = true;
+
+ko.bindingHandlers['hasFocus'] = ko.bindingHandlers['hasfocus']; // Make "hasFocus" an alias
+ko.expressionRewriting.twoWayBindings['hasFocus'] = true;
+ko.bindingHandlers['html'] = {
+ 'init': function() {
+ // Prevent binding on the dynamically-injected HTML (as developers are unlikely to expect that, and it has security implications)
+ return { 'controlsDescendantBindings': true };
+ },
+ 'update': function (element, valueAccessor) {
+ // setHtml will unwrap the value if needed
+ ko.utils.setHtml(element, valueAccessor());
+ }
+};
+// Makes a binding like with or if
+function makeWithIfBinding(bindingKey, isWith, isNot, makeContextCallback) {
+ ko.bindingHandlers[bindingKey] = {
+ 'init': function(element, valueAccessor, allBindings, viewModel, bindingContext) {
+ var didDisplayOnLastUpdate,
+ savedNodes;
+ ko.computed(function() {
+ var dataValue = ko.utils.unwrapObservable(valueAccessor()),
+ shouldDisplay = !isNot !== !dataValue, // equivalent to isNot ? !dataValue : !!dataValue
+ isFirstRender = !savedNodes,
+ needsRefresh = isFirstRender || isWith || (shouldDisplay !== didDisplayOnLastUpdate);
+
+ if (needsRefresh) {
+ // Save a copy of the inner nodes on the initial update, but only if we have dependencies.
+ if (isFirstRender && ko.computedContext.getDependenciesCount()) {
+ savedNodes = ko.utils.cloneNodes(ko.virtualElements.childNodes(element), true /* shouldCleanNodes */);
+ }
+
+ if (shouldDisplay) {
+ if (!isFirstRender) {
+ ko.virtualElements.setDomNodeChildren(element, ko.utils.cloneNodes(savedNodes));
+ }
+ ko.applyBindingsToDescendants(makeContextCallback ? makeContextCallback(bindingContext, dataValue) : bindingContext, element);
+ } else {
+ ko.virtualElements.emptyNode(element);
+ }
+
+ didDisplayOnLastUpdate = shouldDisplay;
+ }
+ }, null, { disposeWhenNodeIsRemoved: element });
+ return { 'controlsDescendantBindings': true };
+ }
+ };
+ ko.expressionRewriting.bindingRewriteValidators[bindingKey] = false; // Can't rewrite control flow bindings
+ ko.virtualElements.allowedBindings[bindingKey] = true;
+}
+
+// Construct the actual binding handlers
+makeWithIfBinding('if');
+makeWithIfBinding('ifnot', false /* isWith */, true /* isNot */);
+makeWithIfBinding('with', true /* isWith */, false /* isNot */,
+ function(bindingContext, dataValue) {
+ return bindingContext['createChildContext'](dataValue);
+ }
+);
+var captionPlaceholder = {};
+ko.bindingHandlers['options'] = {
+ 'init': function(element) {
+ if (ko.utils.tagNameLower(element) !== "select")
+ throw new Error("options binding applies only to SELECT elements");
+
+ // Remove all existing <option>s.
+ while (element.length > 0) {
+ element.remove(0);
+ }
+
+ // Ensures that the binding processor doesn't try to bind the options
+ return { 'controlsDescendantBindings': true };
+ },
+ 'update': function (element, valueAccessor, allBindings) {
+ function selectedOptions() {
+ return ko.utils.arrayFilter(element.options, function (node) { return node.selected; });
+ }
+
+ var selectWasPreviouslyEmpty = element.length == 0;
+ var previousScrollTop = (!selectWasPreviouslyEmpty && element.multiple) ? element.scrollTop : null;
+ var unwrappedArray = ko.utils.unwrapObservable(valueAccessor());
+ var includeDestroyed = allBindings.get('optionsIncludeDestroyed');
+ var arrayToDomNodeChildrenOptions = {};
+ var captionValue;
+ var filteredArray;
+ var previousSelectedValues;
+
+ if (element.multiple) {
+ previousSelectedValues = ko.utils.arrayMap(selectedOptions(), ko.selectExtensions.readValue);
+ } else {
+ previousSelectedValues = element.selectedIndex >= 0 ? [ ko.selectExtensions.readValue(element.options[element.selectedIndex]) ] : [];
+ }
+
+ if (unwrappedArray) {
+ if (typeof unwrappedArray.length == "undefined") // Coerce single value into array
+ unwrappedArray = [unwrappedArray];
+
+ // Filter out any entries marked as destroyed
+ filteredArray = ko.utils.arrayFilter(unwrappedArray, function(item) {
+ return includeDestroyed || item === undefined || item === null || !ko.utils.unwrapObservable(item['_destroy']);
+ });
+
+ // If caption is included, add it to the array
+ if (allBindings['has']('optionsCaption')) {
+ captionValue = ko.utils.unwrapObservable(allBindings.get('optionsCaption'));
+ // If caption value is null or undefined, don't show a caption
+ if (captionValue !== null && captionValue !== undefined) {
+ filteredArray.unshift(captionPlaceholder);
+ }
+ }
+ } else {
+ // If a falsy value is provided (e.g. null), we'll simply empty the select element
+ }
+
+ function applyToObject(object, predicate, defaultValue) {
+ var predicateType = typeof predicate;
+ if (predicateType == "function") // Given a function; run it against the data value
+ return predicate(object);
+ else if (predicateType == "string") // Given a string; treat it as a property name on the data value
+ return object[predicate];
+ else // Given no optionsText arg; use the data value itself
+ return defaultValue;
+ }
+
+ // The following functions can run at two different times:
+ // The first is when the whole array is being updated directly from this binding handler.
+ // The second is when an observable value for a specific array entry is updated.
+ // oldOptions will be empty in the first case, but will be filled with the previously generated option in the second.
+ var itemUpdate = false;
+ function optionForArrayItem(arrayEntry, index, oldOptions) {
+ if (oldOptions.length) {
+ previousSelectedValues = oldOptions[0].selected ? [ ko.selectExtensions.readValue(oldOptions[0]) ] : [];
+ itemUpdate = true;
+ }
+ var option = element.ownerDocument.createElement("option");
+ if (arrayEntry === captionPlaceholder) {
+ ko.utils.setTextContent(option, allBindings.get('optionsCaption'));
+ ko.selectExtensions.writeValue(option, undefined);
+ } else {
+ // Apply a value to the option element
+ var optionValue = applyToObject(arrayEntry, allBindings.get('optionsValue'), arrayEntry);
+ ko.selectExtensions.writeValue(option, ko.utils.unwrapObservable(optionValue));
+
+ // Apply some text to the option element
+ var optionText = applyToObject(arrayEntry, allBindings.get('optionsText'), optionValue);
+ ko.utils.setTextContent(option, optionText);
+ }
+ return [option];
+ }
+
+ // By using a beforeRemove callback, we delay the removal until after new items are added. This fixes a selection
+ // problem in IE<=8 and Firefox. See https://github.com/knockout/knockout/issues/1208
+ arrayToDomNodeChildrenOptions['beforeRemove'] =
+ function (option) {
+ element.removeChild(option);
+ };
+
+ function setSelectionCallback(arrayEntry, newOptions) {
+ // IE6 doesn't like us to assign selection to OPTION nodes before they're added to the document.
+ // That's why we first added them without selection. Now it's time to set the selection.
+ if (previousSelectedValues.length) {
+ var isSelected = ko.utils.arrayIndexOf(previousSelectedValues, ko.selectExtensions.readValue(newOptions[0])) >= 0;
+ ko.utils.setOptionNodeSelectionState(newOptions[0], isSelected);
+
+ // If this option was changed from being selected during a single-item update, notify the change
+ if (itemUpdate && !isSelected)
+ ko.dependencyDetection.ignore(ko.utils.triggerEvent, null, [element, "change"]);
+ }
+ }
+
+ var callback = setSelectionCallback;
+ if (allBindings['has']('optionsAfterRender')) {
+ callback = function(arrayEntry, newOptions) {
+ setSelectionCallback(arrayEntry, newOptions);
+ ko.dependencyDetection.ignore(allBindings.get('optionsAfterRender'), null, [newOptions[0], arrayEntry !== captionPlaceholder ? arrayEntry : undefined]);
+ }
+ }
+
+ ko.utils.setDomNodeChildrenFromArrayMapping(element, filteredArray, optionForArrayItem, arrayToDomNodeChildrenOptions, callback);
+
+ ko.dependencyDetection.ignore(function () {
+ if (allBindings.get('valueAllowUnset') && allBindings['has']('value')) {
+ // The model value is authoritative, so make sure its value is the one selected
+ ko.selectExtensions.writeValue(element, ko.utils.unwrapObservable(allBindings.get('value')), true /* allowUnset */);
+ } else {
+ // Determine if the selection has changed as a result of updating the options list
+ var selectionChanged;
+ if (element.multiple) {
+ // For a multiple-select box, compare the new selection count to the previous one
+ // But if nothing was selected before, the selection can't have changed
+ selectionChanged = previousSelectedValues.length && selectedOptions().length < previousSelectedValues.length;
+ } else {
+ // For a single-select box, compare the current value to the previous value
+ // But if nothing was selected before or nothing is selected now, just look for a change in selection
+ selectionChanged = (previousSelectedValues.length && element.selectedIndex >= 0)
+ ? (ko.selectExtensions.readValue(element.options[element.selectedIndex]) !== previousSelectedValues[0])
+ : (previousSelectedValues.length || element.selectedIndex >= 0);
+ }
+
+ // Ensure consistency between model value and selected option.
+ // If the dropdown was changed so that selection is no longer the same,
+ // notify the value or selectedOptions binding.
+ if (selectionChanged) {
+ ko.utils.triggerEvent(element, "change");
+ }
+ }
+ });
+
+ // Workaround for IE bug
+ ko.utils.ensureSelectElementIsRenderedCorrectly(element);
+
+ if (previousScrollTop && Math.abs(previousScrollTop - element.scrollTop) > 20)
+ element.scrollTop = previousScrollTop;
+ }
+};
+ko.bindingHandlers['options'].optionValueDomDataKey = ko.utils.domData.nextKey();
+ko.bindingHandlers['selectedOptions'] = {
+ 'after': ['options', 'foreach'],
+ 'init': function (element, valueAccessor, allBindings) {
+ ko.utils.registerEventHandler(element, "change", function () {
+ var value = valueAccessor(), valueToWrite = [];
+ ko.utils.arrayForEach(element.getElementsByTagName("option"), function(node) {
+ if (node.selected)
+ valueToWrite.push(ko.selectExtensions.readValue(node));
+ });
+ ko.expressionRewriting.writeValueToProperty(value, allBindings, 'selectedOptions', valueToWrite);
+ });
+ },
+ 'update': function (element, valueAccessor) {
+ if (ko.utils.tagNameLower(element) != "select")
+ throw new Error("values binding applies only to SELECT elements");
+
+ var newValue = ko.utils.unwrapObservable(valueAccessor());
+ if (newValue && typeof newValue.length == "number") {
+ ko.utils.arrayForEach(element.getElementsByTagName("option"), function(node) {
+ var isSelected = ko.utils.arrayIndexOf(newValue, ko.selectExtensions.readValue(node)) >= 0;
+ ko.utils.setOptionNodeSelectionState(node, isSelected);
+ });
+ }
+ }
+};
+ko.expressionRewriting.twoWayBindings['selectedOptions'] = true;
+ko.bindingHandlers['style'] = {
+ 'update': function (element, valueAccessor) {
+ var value = ko.utils.unwrapObservable(valueAccessor() || {});
+ ko.utils.objectForEach(value, function(styleName, styleValue) {
+ styleValue = ko.utils.unwrapObservable(styleValue);
+ element.style[styleName] = styleValue || ""; // Empty string removes the value, whereas null/undefined have no effect
+ });
+ }
+};
+ko.bindingHandlers['submit'] = {
+ 'init': function (element, valueAccessor, allBindings, viewModel, bindingContext) {
+ if (typeof valueAccessor() != "function")
+ throw new Error("The value for a submit binding must be a function");
+ ko.utils.registerEventHandler(element, "submit", function (event) {
+ var handlerReturnValue;
+ var value = valueAccessor();
+ try { handlerReturnValue = value.call(bindingContext['$data'], element); }
+ finally {
+ if (handlerReturnValue !== true) { // Normally we want to prevent default action. Developer can override this be explicitly returning true.
+ if (event.preventDefault)
+ event.preventDefault();
+ else
+ event.returnValue = false;
+ }
+ }
+ });
+ }
+};
+ko.bindingHandlers['text'] = {
+ 'init': function() {
+ // Prevent binding on the dynamically-injected text node (as developers are unlikely to expect that, and it has security implications).
+ // It should also make things faster, as we no longer have to consider whether the text node might be bindable.
+ return { 'controlsDescendantBindings': true };
+ },
+ 'update': function (element, valueAccessor) {
+ ko.utils.setTextContent(element, valueAccessor());
+ }
+};
+ko.virtualElements.allowedBindings['text'] = true;
+ko.bindingHandlers['uniqueName'] = {
+ 'init': function (element, valueAccessor) {
+ if (valueAccessor()) {
+ var name = "ko_unique_" + (++ko.bindingHandlers['uniqueName'].currentIndex);
+ ko.utils.setElementName(element, name);
+ }
+ }
+};
+ko.bindingHandlers['uniqueName'].currentIndex = 0;
+ko.bindingHandlers['value'] = {
+ 'after': ['options', 'foreach'],
+ 'init': function (element, valueAccessor, allBindings) {
+ // Always catch "change" event; possibly other events too if asked
+ var eventsToCatch = ["change"];
+ var requestedEventsToCatch = allBindings.get("valueUpdate");
+ var propertyChangedFired = false;
+ if (requestedEventsToCatch) {
+ if (typeof requestedEventsToCatch == "string") // Allow both individual event names, and arrays of event names
+ requestedEventsToCatch = [requestedEventsToCatch];
+ ko.utils.arrayPushAll(eventsToCatch, requestedEventsToCatch);
+ eventsToCatch = ko.utils.arrayGetDistinctValues(eventsToCatch);
+ }
+
+ var valueUpdateHandler = function() {
+ propertyChangedFired = false;
+ var modelValue = valueAccessor();
+ var elementValue = ko.selectExtensions.readValue(element);
+ ko.expressionRewriting.writeValueToProperty(modelValue, allBindings, 'value', elementValue);
+ }
+
+ // Workaround for https://github.com/SteveSanderson/knockout/issues/122
+ // IE doesn't fire "change" events on textboxes if the user selects a value from its autocomplete list
+ var ieAutoCompleteHackNeeded = ko.utils.ieVersion && element.tagName.toLowerCase() == "input" && element.type == "text"
+ && element.autocomplete != "off" && (!element.form || element.form.autocomplete != "off");
+ if (ieAutoCompleteHackNeeded && ko.utils.arrayIndexOf(eventsToCatch, "propertychange") == -1) {
+ ko.utils.registerEventHandler(element, "propertychange", function () { propertyChangedFired = true });
+ ko.utils.registerEventHandler(element, "focus", function () { propertyChangedFired = false });
+ ko.utils.registerEventHandler(element, "blur", function() {
+ if (propertyChangedFired) {
+ valueUpdateHandler();
+ }
+ });
+ }
+
+ ko.utils.arrayForEach(eventsToCatch, function(eventName) {
+ // The syntax "after<eventname>" means "run the handler asynchronously after the event"
+ // This is useful, for example, to catch "keydown" events after the browser has updated the control
+ // (otherwise, ko.selectExtensions.readValue(this) will receive the control's value *before* the key event)
+ var handler = valueUpdateHandler;
+ if (ko.utils.stringStartsWith(eventName, "after")) {
+ handler = function() { setTimeout(valueUpdateHandler, 0) };
+ eventName = eventName.substring("after".length);
+ }
+ ko.utils.registerEventHandler(element, eventName, handler);
+ });
+ },
+ 'update': function (element, valueAccessor, allBindings) {
+ var newValue = ko.utils.unwrapObservable(valueAccessor());
+ var elementValue = ko.selectExtensions.readValue(element);
+ var valueHasChanged = (newValue !== elementValue);
+
+ if (valueHasChanged) {
+ if (ko.utils.tagNameLower(element) === "select") {
+ var allowUnset = allBindings.get('valueAllowUnset');
+ var applyValueAction = function () {
+ ko.selectExtensions.writeValue(element, newValue, allowUnset);
+ };
+ applyValueAction();
+
+ if (!allowUnset && newValue !== ko.selectExtensions.readValue(element)) {
+ // If you try to set a model value that can't be represented in an already-populated dropdown, reject that change,
+ // because you're not allowed to have a model value that disagrees with a visible UI selection.
+ ko.dependencyDetection.ignore(ko.utils.triggerEvent, null, [element, "change"]);
+ } else {
+ // Workaround for IE6 bug: It won't reliably apply values to SELECT nodes during the same execution thread
+ // right after you've changed the set of OPTION nodes on it. So for that node type, we'll schedule a second thread
+ // to apply the value as well.
+ setTimeout(applyValueAction, 0);
+ }
+ } else {
+ ko.selectExtensions.writeValue(element, newValue);
+ }
+ }
+ }
+};
+ko.expressionRewriting.twoWayBindings['value'] = true;
+ko.bindingHandlers['visible'] = {
+ 'update': function (element, valueAccessor) {
+ var value = ko.utils.unwrapObservable(valueAccessor());
+ var isCurrentlyVisible = !(element.style.display == "none");
+ if (value && !isCurrentlyVisible)
+ element.style.display = "";
+ else if ((!value) && isCurrentlyVisible)
+ element.style.display = "none";
+ }
+};
+// 'click' is just a shorthand for the usual full-length event:{click:handler}
+makeEventHandlerShortcut('click');
+// If you want to make a custom template engine,
+//
+// [1] Inherit from this class (like ko.nativeTemplateEngine does)
+// [2] Override 'renderTemplateSource', supplying a function with this signature:
+//
+// function (templateSource, bindingContext, options) {
+// // - templateSource.text() is the text of the template you should render
+// // - bindingContext.$data is the data you should pass into the template
+// // - you might also want to make bindingContext.$parent, bindingContext.$parents,
+// // and bindingContext.$root available in the template too
+// // - options gives you access to any other properties set on "data-bind: { template: options }"
+// //
+// // Return value: an array of DOM nodes
+// }
+//
+// [3] Override 'createJavaScriptEvaluatorBlock', supplying a function with this signature:
+//
+// function (script) {
+// // Return value: Whatever syntax means "Evaluate the JavaScript statement 'script' and output the result"
+// // For example, the jquery.tmpl template engine converts 'someScript' to '${ someScript }'
+// }
+//
+// This is only necessary if you want to allow data-bind attributes to reference arbitrary template variables.
+// If you don't want to allow that, you can set the property 'allowTemplateRewriting' to false (like ko.nativeTemplateEngine does)
+// and then you don't need to override 'createJavaScriptEvaluatorBlock'.
+
+ko.templateEngine = function () { };
+
+ko.templateEngine.prototype['renderTemplateSource'] = function (templateSource, bindingContext, options) {
+ throw new Error("Override renderTemplateSource");
+};
+
+ko.templateEngine.prototype['createJavaScriptEvaluatorBlock'] = function (script) {
+ throw new Error("Override createJavaScriptEvaluatorBlock");
+};
+
+ko.templateEngine.prototype['makeTemplateSource'] = function(template, templateDocument) {
+ // Named template
+ if (typeof template == "string") {
+ templateDocument = templateDocument || document;
+ var elem = templateDocument.getElementById(template);
+ if (!elem)
+ throw new Error("Cannot find template with ID " + template);
+ return new ko.templateSources.domElement(elem);
+ } else if ((template.nodeType == 1) || (template.nodeType == 8)) {
+ // Anonymous template
+ return new ko.templateSources.anonymousTemplate(template);
+ } else
+ throw new Error("Unknown template type: " + template);
+};
+
+ko.templateEngine.prototype['renderTemplate'] = function (template, bindingContext, options, templateDocument) {
+ var templateSource = this['makeTemplateSource'](template, templateDocument);
+ return this['renderTemplateSource'](templateSource, bindingContext, options);
+};
+
+ko.templateEngine.prototype['isTemplateRewritten'] = function (template, templateDocument) {
+ // Skip rewriting if requested
+ if (this['allowTemplateRewriting'] === false)
+ return true;
+ return this['makeTemplateSource'](template, templateDocument)['data']("isRewritten");
+};
+
+ko.templateEngine.prototype['rewriteTemplate'] = function (template, rewriterCallback, templateDocument) {
+ var templateSource = this['makeTemplateSource'](template, templateDocument);
+ var rewritten = rewriterCallback(templateSource['text']());
+ templateSource['text'](rewritten);
+ templateSource['data']("isRewritten", true);
+};
+
+ko.exportSymbol('templateEngine', ko.templateEngine);
+
+ko.templateRewriting = (function () {
+ var memoizeDataBindingAttributeSyntaxRegex = /(<([a-z]+\d*)(?:\s+(?!data-bind\s*=\s*)[a-z0-9\-]+(?:=(?:\"[^\"]*\"|\'[^\']*\'))?)*\s+)data-bind\s*=\s*(["'])([\s\S]*?)\3/gi;
+ var memoizeVirtualContainerBindingSyntaxRegex = /<!--\s*ko\b\s*([\s\S]*?)\s*-->/g;
+
+ function validateDataBindValuesForRewriting(keyValueArray) {
+ var allValidators = ko.expressionRewriting.bindingRewriteValidators;
+ for (var i = 0; i < keyValueArray.length; i++) {
+ var key = keyValueArray[i]['key'];
+ if (allValidators.hasOwnProperty(key)) {
+ var validator = allValidators[key];
+
+ if (typeof validator === "function") {
+ var possibleErrorMessage = validator(keyValueArray[i]['value']);
+ if (possibleErrorMessage)
+ throw new Error(possibleErrorMessage);
+ } else if (!validator) {
+ throw new Error("This template engine does not support the '" + key + "' binding within its templates");
+ }
+ }
+ }
+ }
+
+ function constructMemoizedTagReplacement(dataBindAttributeValue, tagToRetain, nodeName, templateEngine) {
+ var dataBindKeyValueArray = ko.expressionRewriting.parseObjectLiteral(dataBindAttributeValue);
+ validateDataBindValuesForRewriting(dataBindKeyValueArray);
+ var rewrittenDataBindAttributeValue = ko.expressionRewriting.preProcessBindings(dataBindKeyValueArray, {'valueAccessors':true});
+
+ // For no obvious reason, Opera fails to evaluate rewrittenDataBindAttributeValue unless it's wrapped in an additional
+ // anonymous function, even though Opera's built-in debugger can evaluate it anyway. No other browser requires this
+ // extra indirection.
+ var applyBindingsToNextSiblingScript =
+ "ko.__tr_ambtns(function($context,$element){return(function(){return{ " + rewrittenDataBindAttributeValue + " } })()},'" + nodeName.toLowerCase() + "')";
+ return templateEngine['createJavaScriptEvaluatorBlock'](applyBindingsToNextSiblingScript) + tagToRetain;
+ }
+
+ return {
+ ensureTemplateIsRewritten: function (template, templateEngine, templateDocument) {
+ if (!templateEngine['isTemplateRewritten'](template, templateDocument))
+ templateEngine['rewriteTemplate'](template, function (htmlString) {
+ return ko.templateRewriting.memoizeBindingAttributeSyntax(htmlString, templateEngine);
+ }, templateDocument);
+ },
+
+ memoizeBindingAttributeSyntax: function (htmlString, templateEngine) {
+ return htmlString.replace(memoizeDataBindingAttributeSyntaxRegex, function () {
+ return constructMemoizedTagReplacement(/* dataBindAttributeValue: */ arguments[4], /* tagToRetain: */ arguments[1], /* nodeName: */ arguments[2], templateEngine);
+ }).replace(memoizeVirtualContainerBindingSyntaxRegex, function() {
+ return constructMemoizedTagReplacement(/* dataBindAttributeValue: */ arguments[1], /* tagToRetain: */ "<!-- ko -->", /* nodeName: */ "#comment", templateEngine);
+ });
+ },
+
+ applyMemoizedBindingsToNextSibling: function (bindings, nodeName) {
+ return ko.memoization.memoize(function (domNode, bindingContext) {
+ var nodeToBind = domNode.nextSibling;
+ if (nodeToBind && nodeToBind.nodeName.toLowerCase() === nodeName) {
+ ko.applyBindingAccessorsToNode(nodeToBind, bindings, bindingContext);
+ }
+ });
+ }
+ }
+})();
+
+
+// Exported only because it has to be referenced by string lookup from within rewritten template
+ko.exportSymbol('__tr_ambtns', ko.templateRewriting.applyMemoizedBindingsToNextSibling);
+(function() {
+ // A template source represents a read/write way of accessing a template. This is to eliminate the need for template loading/saving
+ // logic to be duplicated in every template engine (and means they can all work with anonymous templates, etc.)
+ //
+ // Two are provided by default:
+ // 1. ko.templateSources.domElement - reads/writes the text content of an arbitrary DOM element
+ // 2. ko.templateSources.anonymousElement - uses ko.utils.domData to read/write text *associated* with the DOM element, but
+ // without reading/writing the actual element text content, since it will be overwritten
+ // with the rendered template output.
+ // You can implement your own template source if you want to fetch/store templates somewhere other than in DOM elements.
+ // Template sources need to have the following functions:
+ // text() - returns the template text from your storage location
+ // text(value) - writes the supplied template text to your storage location
+ // data(key) - reads values stored using data(key, value) - see below
+ // data(key, value) - associates "value" with this template and the key "key". Is used to store information like "isRewritten".
+ //
+ // Optionally, template sources can also have the following functions:
+ // nodes() - returns a DOM element containing the nodes of this template, where available
+ // nodes(value) - writes the given DOM element to your storage location
+ // If a DOM element is available for a given template source, template engines are encouraged to use it in preference over text()
+ // for improved speed. However, all templateSources must supply text() even if they don't supply nodes().
+ //
+ // Once you've implemented a templateSource, make your template engine use it by subclassing whatever template engine you were
+ // using and overriding "makeTemplateSource" to return an instance of your custom template source.
+
+ ko.templateSources = {};
+
+ // ---- ko.templateSources.domElement -----
+
+ ko.templateSources.domElement = function(element) {
+ this.domElement = element;
+ }
+
+ ko.templateSources.domElement.prototype['text'] = function(/* valueToWrite */) {
+ var tagNameLower = ko.utils.tagNameLower(this.domElement),
+ elemContentsProperty = tagNameLower === "script" ? "text"
+ : tagNameLower === "textarea" ? "value"
+ : "innerHTML";
+
+ if (arguments.length == 0) {
+ return this.domElement[elemContentsProperty];
+ } else {
+ var valueToWrite = arguments[0];
+ if (elemContentsProperty === "innerHTML")
+ ko.utils.setHtml(this.domElement, valueToWrite);
+ else
+ this.domElement[elemContentsProperty] = valueToWrite;
+ }
+ };
+
+ var dataDomDataPrefix = ko.utils.domData.nextKey() + "_";
+ ko.templateSources.domElement.prototype['data'] = function(key /*, valueToWrite */) {
+ if (arguments.length === 1) {
+ return ko.utils.domData.get(this.domElement, dataDomDataPrefix + key);
+ } else {
+ ko.utils.domData.set(this.domElement, dataDomDataPrefix + key, arguments[1]);
+ }
+ };
+
+ // ---- ko.templateSources.anonymousTemplate -----
+ // Anonymous templates are normally saved/retrieved as DOM nodes through "nodes".
+ // For compatibility, you can also read "text"; it will be serialized from the nodes on demand.
+ // Writing to "text" is still supported, but then the template data will not be available as DOM nodes.
+
+ var anonymousTemplatesDomDataKey = ko.utils.domData.nextKey();
+ ko.templateSources.anonymousTemplate = function(element) {
+ this.domElement = element;
+ }
+ ko.templateSources.anonymousTemplate.prototype = new ko.templateSources.domElement();
+ ko.templateSources.anonymousTemplate.prototype.constructor = ko.templateSources.anonymousTemplate;
+ ko.templateSources.anonymousTemplate.prototype['text'] = function(/* valueToWrite */) {
+ if (arguments.length == 0) {
+ var templateData = ko.utils.domData.get(this.domElement, anonymousTemplatesDomDataKey) || {};
+ if (templateData.textData === undefined && templateData.containerData)
+ templateData.textData = templateData.containerData.innerHTML;
+ return templateData.textData;
+ } else {
+ var valueToWrite = arguments[0];
+ ko.utils.domData.set(this.domElement, anonymousTemplatesDomDataKey, {textData: valueToWrite});
+ }
+ };
+ ko.templateSources.domElement.prototype['nodes'] = function(/* valueToWrite */) {
+ if (arguments.length == 0) {
+ var templateData = ko.utils.domData.get(this.domElement, anonymousTemplatesDomDataKey) || {};
+ return templateData.containerData;
+ } else {
+ var valueToWrite = arguments[0];
+ ko.utils.domData.set(this.domElement, anonymousTemplatesDomDataKey, {containerData: valueToWrite});
+ }
+ };
+
+ ko.exportSymbol('templateSources', ko.templateSources);
+ ko.exportSymbol('templateSources.domElement', ko.templateSources.domElement);
+ ko.exportSymbol('templateSources.anonymousTemplate', ko.templateSources.anonymousTemplate);
+})();
+(function () {
+ var _templateEngine;
+ ko.setTemplateEngine = function (templateEngine) {
+ if ((templateEngine != undefined) && !(templateEngine instanceof ko.templateEngine))
+ throw new Error("templateEngine must inherit from ko.templateEngine");
+ _templateEngine = templateEngine;
+ }
+
+ function invokeForEachNodeInContinuousRange(firstNode, lastNode, action) {
+ var node, nextInQueue = firstNode, firstOutOfRangeNode = ko.virtualElements.nextSibling(lastNode);
+ while (nextInQueue && ((node = nextInQueue) !== firstOutOfRangeNode)) {
+ nextInQueue = ko.virtualElements.nextSibling(node);
+ action(node, nextInQueue);
+ }
+ }
+
+ function activateBindingsOnContinuousNodeArray(continuousNodeArray, bindingContext) {
+ // To be used on any nodes that have been rendered by a template and have been inserted into some parent element
+ // Walks through continuousNodeArray (which *must* be continuous, i.e., an uninterrupted sequence of sibling nodes, because
+ // the algorithm for walking them relies on this), and for each top-level item in the virtual-element sense,
+ // (1) Does a regular "applyBindings" to associate bindingContext with this node and to activate any non-memoized bindings
+ // (2) Unmemoizes any memos in the DOM subtree (e.g., to activate bindings that had been memoized during template rewriting)
+
+ if (continuousNodeArray.length) {
+ var firstNode = continuousNodeArray[0],
+ lastNode = continuousNodeArray[continuousNodeArray.length - 1],
+ parentNode = firstNode.parentNode,
+ provider = ko.bindingProvider['instance'],
+ preprocessNode = provider['preprocessNode'];
+
+ if (preprocessNode) {
+ invokeForEachNodeInContinuousRange(firstNode, lastNode, function(node, nextNodeInRange) {
+ var nodePreviousSibling = node.previousSibling;
+ var newNodes = preprocessNode.call(provider, node);
+ if (newNodes) {
+ if (node === firstNode)
+ firstNode = newNodes[0] || nextNodeInRange;
+ if (node === lastNode)
+ lastNode = newNodes[newNodes.length - 1] || nodePreviousSibling;
+ }
+ });
+
+ // Because preprocessNode can change the nodes, including the first and last nodes, update continuousNodeArray to match.
+ // We need the full set, including inner nodes, because the unmemoize step might remove the first node (and so the real
+ // first node needs to be in the array).
+ continuousNodeArray.length = 0;
+ if (!firstNode) { // preprocessNode might have removed all the nodes, in which case there's nothing left to do
+ return;
+ }
+ if (firstNode === lastNode) {
+ continuousNodeArray.push(firstNode);
+ } else {
+ continuousNodeArray.push(firstNode, lastNode);
+ ko.utils.fixUpContinuousNodeArray(continuousNodeArray, parentNode);
+ }
+ }
+
+ // Need to applyBindings *before* unmemoziation, because unmemoization might introduce extra nodes (that we don't want to re-bind)
+ // whereas a regular applyBindings won't introduce new memoized nodes
+ invokeForEachNodeInContinuousRange(firstNode, lastNode, function(node) {
+ if (node.nodeType === 1 || node.nodeType === 8)
+ ko.applyBindings(bindingContext, node);
+ });
+ invokeForEachNodeInContinuousRange(firstNode, lastNode, function(node) {
+ if (node.nodeType === 1 || node.nodeType === 8)
+ ko.memoization.unmemoizeDomNodeAndDescendants(node, [bindingContext]);
+ });
+
+ // Make sure any changes done by applyBindings or unmemoize are reflected in the array
+ ko.utils.fixUpContinuousNodeArray(continuousNodeArray, parentNode);
+ }
+ }
+
+ function getFirstNodeFromPossibleArray(nodeOrNodeArray) {
+ return nodeOrNodeArray.nodeType ? nodeOrNodeArray
+ : nodeOrNodeArray.length > 0 ? nodeOrNodeArray[0]
+ : null;
+ }
+
+ function executeTemplate(targetNodeOrNodeArray, renderMode, template, bindingContext, options) {
+ options = options || {};
+ var firstTargetNode = targetNodeOrNodeArray && getFirstNodeFromPossibleArray(targetNodeOrNodeArray);
+ var templateDocument = firstTargetNode && firstTargetNode.ownerDocument;
+ var templateEngineToUse = (options['templateEngine'] || _templateEngine);
+ ko.templateRewriting.ensureTemplateIsRewritten(template, templateEngineToUse, templateDocument);
+ var renderedNodesArray = templateEngineToUse['renderTemplate'](template, bindingContext, options, templateDocument);
+
+ // Loosely check result is an array of DOM nodes
+ if ((typeof renderedNodesArray.length != "number") || (renderedNodesArray.length > 0 && typeof renderedNodesArray[0].nodeType != "number"))
+ throw new Error("Template engine must return an array of DOM nodes");
+
+ var haveAddedNodesToParent = false;
+ switch (renderMode) {
+ case "replaceChildren":
+ ko.virtualElements.setDomNodeChildren(targetNodeOrNodeArray, renderedNodesArray);
+ haveAddedNodesToParent = true;
+ break;
+ case "replaceNode":
+ ko.utils.replaceDomNodes(targetNodeOrNodeArray, renderedNodesArray);
+ haveAddedNodesToParent = true;
+ break;
+ case "ignoreTargetNode": break;
+ default:
+ throw new Error("Unknown renderMode: " + renderMode);
+ }
+
+ if (haveAddedNodesToParent) {
+ activateBindingsOnContinuousNodeArray(renderedNodesArray, bindingContext);
+ if (options['afterRender'])
+ ko.dependencyDetection.ignore(options['afterRender'], null, [renderedNodesArray, bindingContext['$data']]);
+ }
+
+ return renderedNodesArray;
+ }
+
+ ko.renderTemplate = function (template, dataOrBindingContext, options, targetNodeOrNodeArray, renderMode) {
+ options = options || {};
+ if ((options['templateEngine'] || _templateEngine) == undefined)
+ throw new Error("Set a template engine before calling renderTemplate");
+ renderMode = renderMode || "replaceChildren";
+
+ if (targetNodeOrNodeArray) {
+ var firstTargetNode = getFirstNodeFromPossibleArray(targetNodeOrNodeArray);
+
+ var whenToDispose = function () { return (!firstTargetNode) || !ko.utils.domNodeIsAttachedToDocument(firstTargetNode); }; // Passive disposal (on next evaluation)
+ var activelyDisposeWhenNodeIsRemoved = (firstTargetNode && renderMode == "replaceNode") ? firstTargetNode.parentNode : firstTargetNode;
+
+ return ko.dependentObservable( // So the DOM is automatically updated when any dependency changes
+ function () {
+ // Ensure we've got a proper binding context to work with
+ var bindingContext = (dataOrBindingContext && (dataOrBindingContext instanceof ko.bindingContext))
+ ? dataOrBindingContext
+ : new ko.bindingContext(ko.utils.unwrapObservable(dataOrBindingContext));
+
+ // Support selecting template as a function of the data being rendered
+ var templateName = ko.isObservable(template) ? template()
+ : typeof(template) == 'function' ? template(bindingContext['$data'], bindingContext) : template;
+
+ var renderedNodesArray = executeTemplate(targetNodeOrNodeArray, renderMode, templateName, bindingContext, options);
+ if (renderMode == "replaceNode") {
+ targetNodeOrNodeArray = renderedNodesArray;
+ firstTargetNode = getFirstNodeFromPossibleArray(targetNodeOrNodeArray);
+ }
+ },
+ null,
+ { disposeWhen: whenToDispose, disposeWhenNodeIsRemoved: activelyDisposeWhenNodeIsRemoved }
+ );
+ } else {
+ // We don't yet have a DOM node to evaluate, so use a memo and render the template later when there is a DOM node
+ return ko.memoization.memoize(function (domNode) {
+ ko.renderTemplate(template, dataOrBindingContext, options, domNode, "replaceNode");
+ });
+ }
+ };
+
+ ko.renderTemplateForEach = function (template, arrayOrObservableArray, options, targetNode, parentBindingContext) {
+ // Since setDomNodeChildrenFromArrayMapping always calls executeTemplateForArrayItem and then
+ // activateBindingsCallback for added items, we can store the binding context in the former to use in the latter.
+ var arrayItemContext;
+
+ // This will be called by setDomNodeChildrenFromArrayMapping to get the nodes to add to targetNode
+ var executeTemplateForArrayItem = function (arrayValue, index) {
+ // Support selecting template as a function of the data being rendered
+ arrayItemContext = parentBindingContext['createChildContext'](arrayValue, options['as'], function(context) {
+ context['$index'] = index;
+ });
+ var templateName = typeof(template) == 'function' ? template(arrayValue, arrayItemContext) : template;
+ return executeTemplate(null, "ignoreTargetNode", templateName, arrayItemContext, options);
+ }
+
+ // This will be called whenever setDomNodeChildrenFromArrayMapping has added nodes to targetNode
+ var activateBindingsCallback = function(arrayValue, addedNodesArray, index) {
+ activateBindingsOnContinuousNodeArray(addedNodesArray, arrayItemContext);
+ if (options['afterRender'])
+ options['afterRender'](addedNodesArray, arrayValue);
+ };
+
+ return ko.dependentObservable(function () {
+ var unwrappedArray = ko.utils.unwrapObservable(arrayOrObservableArray) || [];
+ if (typeof unwrappedArray.length == "undefined") // Coerce single value into array
+ unwrappedArray = [unwrappedArray];
+
+ // Filter out any entries marked as destroyed
+ var filteredArray = ko.utils.arrayFilter(unwrappedArray, function(item) {
+ return options['includeDestroyed'] || item === undefined || item === null || !ko.utils.unwrapObservable(item['_destroy']);
+ });
+
+ // Call setDomNodeChildrenFromArrayMapping, ignoring any observables unwrapped within (most likely from a callback function).
+ // If the array items are observables, though, they will be unwrapped in executeTemplateForArrayItem and managed within setDomNodeChildrenFromArrayMapping.
+ ko.dependencyDetection.ignore(ko.utils.setDomNodeChildrenFromArrayMapping, null, [targetNode, filteredArray, executeTemplateForArrayItem, options, activateBindingsCallback]);
+
+ }, null, { disposeWhenNodeIsRemoved: targetNode });
+ };
+
+ var templateComputedDomDataKey = ko.utils.domData.nextKey();
+ function disposeOldComputedAndStoreNewOne(element, newComputed) {
+ var oldComputed = ko.utils.domData.get(element, templateComputedDomDataKey);
+ if (oldComputed && (typeof(oldComputed.dispose) == 'function'))
+ oldComputed.dispose();
+ ko.utils.domData.set(element, templateComputedDomDataKey, (newComputed && newComputed.isActive()) ? newComputed : undefined);
+ }
+
+ ko.bindingHandlers['template'] = {
+ 'init': function(element, valueAccessor) {
+ // Support anonymous templates
+ var bindingValue = ko.utils.unwrapObservable(valueAccessor());
+ if (typeof bindingValue == "string" || bindingValue['name']) {
+ // It's a named template - clear the element
+ ko.virtualElements.emptyNode(element);
+ } else {
+ // It's an anonymous template - store the element contents, then clear the element
+ var templateNodes = ko.virtualElements.childNodes(element),
+ container = ko.utils.moveCleanedNodesToContainerElement(templateNodes); // This also removes the nodes from their current parent
+ new ko.templateSources.anonymousTemplate(element)['nodes'](container);
+ }
+ return { 'controlsDescendantBindings': true };
+ },
+ 'update': function (element, valueAccessor, allBindings, viewModel, bindingContext) {
+ var value = valueAccessor(),
+ dataValue,
+ options = ko.utils.unwrapObservable(value),
+ shouldDisplay = true,
+ templateComputed = null,
+ templateName;
+
+ if (typeof options == "string") {
+ templateName = value;
+ options = {};
+ } else {
+ templateName = options['name'];
+
+ // Support "if"/"ifnot" conditions
+ if ('if' in options)
+ shouldDisplay = ko.utils.unwrapObservable(options['if']);
+ if (shouldDisplay && 'ifnot' in options)
+ shouldDisplay = !ko.utils.unwrapObservable(options['ifnot']);
+
+ dataValue = ko.utils.unwrapObservable(options['data']);
+ }
+
+ if ('foreach' in options) {
+ // Render once for each data point (treating data set as empty if shouldDisplay==false)
+ var dataArray = (shouldDisplay && options['foreach']) || [];
+ templateComputed = ko.renderTemplateForEach(templateName || element, dataArray, options, element, bindingContext);
+ } else if (!shouldDisplay) {
+ ko.virtualElements.emptyNode(element);
+ } else {
+ // Render once for this single data point (or use the viewModel if no data was provided)
+ var innerBindingContext = ('data' in options) ?
+ bindingContext['createChildContext'](dataValue, options['as']) : // Given an explitit 'data' value, we create a child binding context for it
+ bindingContext; // Given no explicit 'data' value, we retain the same binding context
+ templateComputed = ko.renderTemplate(templateName || element, innerBindingContext, options, element);
+ }
+
+ // It only makes sense to have a single template computed per element (otherwise which one should have its output displayed?)
+ disposeOldComputedAndStoreNewOne(element, templateComputed);
+ }
+ };
+
+ // Anonymous templates can't be rewritten. Give a nice error message if you try to do it.
+ ko.expressionRewriting.bindingRewriteValidators['template'] = function(bindingValue) {
+ var parsedBindingValue = ko.expressionRewriting.parseObjectLiteral(bindingValue);
+
+ if ((parsedBindingValue.length == 1) && parsedBindingValue[0]['unknown'])
+ return null; // It looks like a string literal, not an object literal, so treat it as a named template (which is allowed for rewriting)
+
+ if (ko.expressionRewriting.keyValueArrayContainsKey(parsedBindingValue, "name"))
+ return null; // Named templates can be rewritten, so return "no error"
+ return "This template engine does not support anonymous templates nested within its templates";
+ };
+
+ ko.virtualElements.allowedBindings['template'] = true;
+})();
+
+ko.exportSymbol('setTemplateEngine', ko.setTemplateEngine);
+ko.exportSymbol('renderTemplate', ko.renderTemplate);
+// Go through the items that have been added and deleted and try to find matches between them.
+ko.utils.findMovesInArrayComparison = function (left, right, limitFailedCompares) {
+ if (left.length && right.length) {
+ var failedCompares, l, r, leftItem, rightItem;
+ for (failedCompares = l = 0; (!limitFailedCompares || failedCompares < limitFailedCompares) && (leftItem = left[l]); ++l) {
+ for (r = 0; rightItem = right[r]; ++r) {
+ if (leftItem['value'] === rightItem['value']) {
+ leftItem['moved'] = rightItem['index'];
+ rightItem['moved'] = leftItem['index'];
+ right.splice(r, 1); // This item is marked as moved; so remove it from right list
+ failedCompares = r = 0; // Reset failed compares count because we're checking for consecutive failures
+ break;
+ }
+ }
+ failedCompares += r;
+ }
+ }
+};
+
+ko.utils.compareArrays = (function () {
+ var statusNotInOld = 'added', statusNotInNew = 'deleted';
+
+ // Simple calculation based on Levenshtein distance.
+ function compareArrays(oldArray, newArray, options) {
+ // For backward compatibility, if the third arg is actually a bool, interpret
+ // it as the old parameter 'dontLimitMoves'. Newer code should use { dontLimitMoves: true }.
+ options = (typeof options === 'boolean') ? { 'dontLimitMoves': options } : (options || {});
+ oldArray = oldArray || [];
+ newArray = newArray || [];
+
+ if (oldArray.length <= newArray.length)
+ return compareSmallArrayToBigArray(oldArray, newArray, statusNotInOld, statusNotInNew, options);
+ else
+ return compareSmallArrayToBigArray(newArray, oldArray, statusNotInNew, statusNotInOld, options);
+ }
+
+ function compareSmallArrayToBigArray(smlArray, bigArray, statusNotInSml, statusNotInBig, options) {
+ var myMin = Math.min,
+ myMax = Math.max,
+ editDistanceMatrix = [],
+ smlIndex, smlIndexMax = smlArray.length,
+ bigIndex, bigIndexMax = bigArray.length,
+ compareRange = (bigIndexMax - smlIndexMax) || 1,
+ maxDistance = smlIndexMax + bigIndexMax + 1,
+ thisRow, lastRow,
+ bigIndexMaxForRow, bigIndexMinForRow;
+
+ for (smlIndex = 0; smlIndex <= smlIndexMax; smlIndex++) {
+ lastRow = thisRow;
+ editDistanceMatrix.push(thisRow = []);
+ bigIndexMaxForRow = myMin(bigIndexMax, smlIndex + compareRange);
+ bigIndexMinForRow = myMax(0, smlIndex - 1);
+ for (bigIndex = bigIndexMinForRow; bigIndex <= bigIndexMaxForRow; bigIndex++) {
+ if (!bigIndex)
+ thisRow[bigIndex] = smlIndex + 1;
+ else if (!smlIndex) // Top row - transform empty array into new array via additions
+ thisRow[bigIndex] = bigIndex + 1;
+ else if (smlArray[smlIndex - 1] === bigArray[bigIndex - 1])
+ thisRow[bigIndex] = lastRow[bigIndex - 1]; // copy value (no edit)
+ else {
+ var northDistance = lastRow[bigIndex] || maxDistance; // not in big (deletion)
+ var westDistance = thisRow[bigIndex - 1] || maxDistance; // not in small (addition)
+ thisRow[bigIndex] = myMin(northDistance, westDistance) + 1;
+ }
+ }
+ }
+
+ var editScript = [], meMinusOne, notInSml = [], notInBig = [];
+ for (smlIndex = smlIndexMax, bigIndex = bigIndexMax; smlIndex || bigIndex;) {
+ meMinusOne = editDistanceMatrix[smlIndex][bigIndex] - 1;
+ if (bigIndex && meMinusOne === editDistanceMatrix[smlIndex][bigIndex-1]) {
+ notInSml.push(editScript[editScript.length] = { // added
+ 'status': statusNotInSml,
+ 'value': bigArray[--bigIndex],
+ 'index': bigIndex });
+ } else if (smlIndex && meMinusOne === editDistanceMatrix[smlIndex - 1][bigIndex]) {
+ notInBig.push(editScript[editScript.length] = { // deleted
+ 'status': statusNotInBig,
+ 'value': smlArray[--smlIndex],
+ 'index': smlIndex });
+ } else {
+ --bigIndex;
+ --smlIndex;
+ if (!options['sparse']) {
+ editScript.push({
+ 'status': "retained",
+ 'value': bigArray[bigIndex] });
+ }
+ }
+ }
+
+ // Set a limit on the number of consecutive non-matching comparisons; having it a multiple of
+ // smlIndexMax keeps the time complexity of this algorithm linear.
+ ko.utils.findMovesInArrayComparison(notInSml, notInBig, smlIndexMax * 10);
+
+ return editScript.reverse();
+ }
+
+ return compareArrays;
+})();
+
+ko.exportSymbol('utils.compareArrays', ko.utils.compareArrays);
+(function () {
+ // Objective:
+ // * Given an input array, a container DOM node, and a function from array elements to arrays of DOM nodes,
+ // map the array elements to arrays of DOM nodes, concatenate together all these arrays, and use them to populate the container DOM node
+ // * Next time we're given the same combination of things (with the array possibly having mutated), update the container DOM node
+ // so that its children is again the concatenation of the mappings of the array elements, but don't re-map any array elements that we
+ // previously mapped - retain those nodes, and just insert/delete other ones
+
+ // "callbackAfterAddingNodes" will be invoked after any "mapping"-generated nodes are inserted into the container node
+ // You can use this, for example, to activate bindings on those nodes.
+
+ function mapNodeAndRefreshWhenChanged(containerNode, mapping, valueToMap, callbackAfterAddingNodes, index) {
+ // Map this array value inside a dependentObservable so we re-map when any dependency changes
+ var mappedNodes = [];
+ var dependentObservable = ko.dependentObservable(function() {
+ var newMappedNodes = mapping(valueToMap, index, ko.utils.fixUpContinuousNodeArray(mappedNodes, containerNode)) || [];
+
+ // On subsequent evaluations, just replace the previously-inserted DOM nodes
+ if (mappedNodes.length > 0) {
+ ko.utils.replaceDomNodes(mappedNodes, newMappedNodes);
+ if (callbackAfterAddingNodes)
+ ko.dependencyDetection.ignore(callbackAfterAddingNodes, null, [valueToMap, newMappedNodes, index]);
+ }
+
+ // Replace the contents of the mappedNodes array, thereby updating the record
+ // of which nodes would be deleted if valueToMap was itself later removed
+ mappedNodes.length = 0;
+ ko.utils.arrayPushAll(mappedNodes, newMappedNodes);
+ }, null, { disposeWhenNodeIsRemoved: containerNode, disposeWhen: function() { return !ko.utils.anyDomNodeIsAttachedToDocument(mappedNodes); } });
+ return { mappedNodes : mappedNodes, dependentObservable : (dependentObservable.isActive() ? dependentObservable : undefined) };
+ }
+
+ var lastMappingResultDomDataKey = ko.utils.domData.nextKey();
+
+ ko.utils.setDomNodeChildrenFromArrayMapping = function (domNode, array, mapping, options, callbackAfterAddingNodes) {
+ // Compare the provided array against the previous one
+ array = array || [];
+ options = options || {};
+ var isFirstExecution = ko.utils.domData.get(domNode, lastMappingResultDomDataKey) === undefined;
+ var lastMappingResult = ko.utils.domData.get(domNode, lastMappingResultDomDataKey) || [];
+ var lastArray = ko.utils.arrayMap(lastMappingResult, function (x) { return x.arrayEntry; });
+ var editScript = ko.utils.compareArrays(lastArray, array, options['dontLimitMoves']);
+
+ // Build the new mapping result
+ var newMappingResult = [];
+ var lastMappingResultIndex = 0;
+ var newMappingResultIndex = 0;
+
+ var nodesToDelete = [];
+ var itemsToProcess = [];
+ var itemsForBeforeRemoveCallbacks = [];
+ var itemsForMoveCallbacks = [];
+ var itemsForAfterAddCallbacks = [];
+ var mapData;
+
+ function itemMovedOrRetained(editScriptIndex, oldPosition) {
+ mapData = lastMappingResult[oldPosition];
+ if (newMappingResultIndex !== oldPosition)
+ itemsForMoveCallbacks[editScriptIndex] = mapData;
+ // Since updating the index might change the nodes, do so before calling fixUpContinuousNodeArray
+ mapData.indexObservable(newMappingResultIndex++);
+ ko.utils.fixUpContinuousNodeArray(mapData.mappedNodes, domNode);
+ newMappingResult.push(mapData);
+ itemsToProcess.push(mapData);
+ }
+
+ function callCallback(callback, items) {
+ if (callback) {
+ for (var i = 0, n = items.length; i < n; i++) {
+ if (items[i]) {
+ ko.utils.arrayForEach(items[i].mappedNodes, function(node) {
+ callback(node, i, items[i].arrayEntry);
+ });
+ }
+ }
+ }
+ }
+
+ for (var i = 0, editScriptItem, movedIndex; editScriptItem = editScript[i]; i++) {
+ movedIndex = editScriptItem['moved'];
+ switch (editScriptItem['status']) {
+ case "deleted":
+ if (movedIndex === undefined) {
+ mapData = lastMappingResult[lastMappingResultIndex];
+
+ // Stop tracking changes to the mapping for these nodes
+ if (mapData.dependentObservable)
+ mapData.dependentObservable.dispose();
+
+ // Queue these nodes for later removal
+ nodesToDelete.push.apply(nodesToDelete, ko.utils.fixUpContinuousNodeArray(mapData.mappedNodes, domNode));
+ if (options['beforeRemove']) {
+ itemsForBeforeRemoveCallbacks[i] = mapData;
+ itemsToProcess.push(mapData);
+ }
+ }
+ lastMappingResultIndex++;
+ break;
+
+ case "retained":
+ itemMovedOrRetained(i, lastMappingResultIndex++);
+ break;
+
+ case "added":
+ if (movedIndex !== undefined) {
+ itemMovedOrRetained(i, movedIndex);
+ } else {
+ mapData = { arrayEntry: editScriptItem['value'], indexObservable: ko.observable(newMappingResultIndex++) };
+ newMappingResult.push(mapData);
+ itemsToProcess.push(mapData);
+ if (!isFirstExecution)
+ itemsForAfterAddCallbacks[i] = mapData;
+ }
+ break;
+ }
+ }
+
+ // Call beforeMove first before any changes have been made to the DOM
+ callCallback(options['beforeMove'], itemsForMoveCallbacks);
+
+ // Next remove nodes for deleted items (or just clean if there's a beforeRemove callback)
+ ko.utils.arrayForEach(nodesToDelete, options['beforeRemove'] ? ko.cleanNode : ko.removeNode);
+
+ // Next add/reorder the remaining items (will include deleted items if there's a beforeRemove callback)
+ for (var i = 0, nextNode = ko.virtualElements.firstChild(domNode), lastNode, node; mapData = itemsToProcess[i]; i++) {
+ // Get nodes for newly added items
+ if (!mapData.mappedNodes)
+ ko.utils.extend(mapData, mapNodeAndRefreshWhenChanged(domNode, mapping, mapData.arrayEntry, callbackAfterAddingNodes, mapData.indexObservable));
+
+ // Put nodes in the right place if they aren't there already
+ for (var j = 0; node = mapData.mappedNodes[j]; nextNode = node.nextSibling, lastNode = node, j++) {
+ if (node !== nextNode)
+ ko.virtualElements.insertAfter(domNode, node, lastNode);
+ }
+
+ // Run the callbacks for newly added nodes (for example, to apply bindings, etc.)
+ if (!mapData.initialized && callbackAfterAddingNodes) {
+ callbackAfterAddingNodes(mapData.arrayEntry, mapData.mappedNodes, mapData.indexObservable);
+ mapData.initialized = true;
+ }
+ }
+
+ // If there's a beforeRemove callback, call it after reordering.
+ // Note that we assume that the beforeRemove callback will usually be used to remove the nodes using
+ // some sort of animation, which is why we first reorder the nodes that will be removed. If the
+ // callback instead removes the nodes right away, it would be more efficient to skip reordering them.
+ // Perhaps we'll make that change in the future if this scenario becomes more common.
+ callCallback(options['beforeRemove'], itemsForBeforeRemoveCallbacks);
+
+ // Finally call afterMove and afterAdd callbacks
+ callCallback(options['afterMove'], itemsForMoveCallbacks);
+ callCallback(options['afterAdd'], itemsForAfterAddCallbacks);
+
+ // Store a copy of the array items we just considered so we can difference it next time
+ ko.utils.domData.set(domNode, lastMappingResultDomDataKey, newMappingResult);
+ }
+})();
+
+ko.exportSymbol('utils.setDomNodeChildrenFromArrayMapping', ko.utils.setDomNodeChildrenFromArrayMapping);
+ko.nativeTemplateEngine = function () {
+ this['allowTemplateRewriting'] = false;
+}
+
+ko.nativeTemplateEngine.prototype = new ko.templateEngine();
+ko.nativeTemplateEngine.prototype.constructor = ko.nativeTemplateEngine;
+ko.nativeTemplateEngine.prototype['renderTemplateSource'] = function (templateSource, bindingContext, options) {
+ var useNodesIfAvailable = !(ko.utils.ieVersion < 9), // IE<9 cloneNode doesn't work properly
+ templateNodesFunc = useNodesIfAvailable ? templateSource['nodes'] : null,
+ templateNodes = templateNodesFunc ? templateSource['nodes']() : null;
+
+ if (templateNodes) {
+ return ko.utils.makeArray(templateNodes.cloneNode(true).childNodes);
+ } else {
+ var templateText = templateSource['text']();
+ return ko.utils.parseHtmlFragment(templateText);
+ }
+};
+
+ko.nativeTemplateEngine.instance = new ko.nativeTemplateEngine();
+ko.setTemplateEngine(ko.nativeTemplateEngine.instance);
+
+ko.exportSymbol('nativeTemplateEngine', ko.nativeTemplateEngine);
+(function() {
+ ko.jqueryTmplTemplateEngine = function () {
+ // Detect which version of jquery-tmpl you're using. Unfortunately jquery-tmpl
+ // doesn't expose a version number, so we have to infer it.
+ // Note that as of Knockout 1.3, we only support jQuery.tmpl 1.0.0pre and later,
+ // which KO internally refers to as version "2", so older versions are no longer detected.
+ var jQueryTmplVersion = this.jQueryTmplVersion = (function() {
+ if (!jQuery || !(jQuery['tmpl']))
+ return 0;
+ // Since it exposes no official version number, we use our own numbering system. To be updated as jquery-tmpl evolves.
+ try {
+ if (jQuery['tmpl']['tag']['tmpl']['open'].toString().indexOf('__') >= 0) {
+ // Since 1.0.0pre, custom tags should append markup to an array called "__"
+ return 2; // Final version of jquery.tmpl
+ }
+ } catch(ex) { /* Apparently not the version we were looking for */ }
+
+ return 1; // Any older version that we don't support
+ })();
+
+ function ensureHasReferencedJQueryTemplates() {
+ if (jQueryTmplVersion < 2)
+ throw new Error("Your version of jQuery.tmpl is too old. Please upgrade to jQuery.tmpl 1.0.0pre or later.");
+ }
+
+ function executeTemplate(compiledTemplate, data, jQueryTemplateOptions) {
+ return jQuery['tmpl'](compiledTemplate, data, jQueryTemplateOptions);
+ }
+
+ this['renderTemplateSource'] = function(templateSource, bindingContext, options) {
+ options = options || {};
+ ensureHasReferencedJQueryTemplates();
+
+ // Ensure we have stored a precompiled version of this template (don't want to reparse on every render)
+ var precompiled = templateSource['data']('precompiled');
+ if (!precompiled) {
+ var templateText = templateSource['text']() || "";
+ // Wrap in "with($whatever.koBindingContext) { ... }"
+ templateText = "{{ko_with $item.koBindingContext}}" + templateText + "{{/ko_with}}";
+
+ precompiled = jQuery['template'](null, templateText);
+ templateSource['data']('precompiled', precompiled);
+ }
+
+ var data = [bindingContext['$data']]; // Prewrap the data in an array to stop jquery.tmpl from trying to unwrap any arrays
+ var jQueryTemplateOptions = jQuery['extend']({ 'koBindingContext': bindingContext }, options['templateOptions']);
+
+ var resultNodes = executeTemplate(precompiled, data, jQueryTemplateOptions);
+ resultNodes['appendTo'](document.createElement("div")); // Using "appendTo" forces jQuery/jQuery.tmpl to perform necessary cleanup work
+
+ jQuery['fragments'] = {}; // Clear jQuery's fragment cache to avoid a memory leak after a large number of template renders
+ return resultNodes;
+ };
+
+ this['createJavaScriptEvaluatorBlock'] = function(script) {
+ return "{{ko_code ((function() { return " + script + " })()) }}";
+ };
+
+ this['addTemplate'] = function(templateName, templateMarkup) {
+ document.write("<script type='text/html' id='" + templateName + "'>" + templateMarkup + "<" + "/script>");
+ };
+
+ if (jQueryTmplVersion > 0) {
+ jQuery['tmpl']['tag']['ko_code'] = {
+ open: "__.push($1 || '');"
+ };
+ jQuery['tmpl']['tag']['ko_with'] = {
+ open: "with($1) {",
+ close: "} "
+ };
+ }
+ };
+
+ ko.jqueryTmplTemplateEngine.prototype = new ko.templateEngine();
+ ko.jqueryTmplTemplateEngine.prototype.constructor = ko.jqueryTmplTemplateEngine;
+
+ // Use this one by default *only if jquery.tmpl is referenced*
+ var jqueryTmplTemplateEngineInstance = new ko.jqueryTmplTemplateEngine();
+ if (jqueryTmplTemplateEngineInstance.jQueryTmplVersion > 0)
+ ko.setTemplateEngine(jqueryTmplTemplateEngineInstance);
+
+ ko.exportSymbol('jqueryTmplTemplateEngine', ko.jqueryTmplTemplateEngine);
+})();
+}));
+}());
+})();
\ No newline at end of file
--- /dev/null
+<div class="headway-small-wrap headway-getting-started-wrap">
+
+
+ <div class="clearfix"></div>
+ <?php if ( is_main_site() ): ?>
+ <div class="headway-sub-title"><img src="<?php echo headway_url() . '/library/admin/images/headway-32.png'; ?>" alt="">Congratulations! You installed Headway. Now you're ready to start making Headway!</div>
+
+ <?php if ( ! headway_get_license_key( 'headway' ) ): ?>
+ <div id="message" class="updated below-h2 headway-getting-started-license-notice" style="border-left-color: #ffba00;">
+ <p>Please be sure to enter your license key(s) in <a href="<?php echo admin_url('admin.php?page=headway-options'); ?>">Headway Options</a> to receive updates.</p>
+ </div>
+ <?php endif; ?>
+ <?php endif; ?>
+
+ <div id="headway-getting-started-ve-link-container">
+ <input type="submit" value="Ready to jump in? Enter the Visual Editor!"
+ class="headway-big-button button-primary action" id="headway-getting-started-ve-link" name=""
+ onclick="window.location.href = '<?php echo home_url() . '/?visual-editor=true'; ?>'"/>
+
+ <p>
+ You can hide this page by changing the <em>Default Admin Page</em> in <a href="<?php echo admin_url( 'admin.php?page=headway-options' ); ?>" target="_blank">Headway » Options</a>.
+ </p>
+ </div>
+
+ <h2>New to Headway? Keep reading!</h2>
+
+ <p>You navigate to all of Headway's core features in the WordPress admin menu. Here's a brief overview of each.</p>
+
+ <div class="headway-infobox-row">
+ <div class="headway-infobox big inrow">
+ <h3>Getting Started</h3>
+
+ <p>You are here! If you ever get stuck or need to extend your Headway installation, this is the place to
+ start.</p>
+
+ <p>If you're totally new to Headway, it's highly recommended you read our <a
+ href="http://docs.headwaythemes.com/article/95-beginners-guide-building-your-website-start-to-finish"
+ target=_"blank">Headway Beginner's Guide</a>.</p>
+ </div>
+ <div class="headway-infobox big">
+ <h3><a href="<?php echo admin_url( 'admin.php?page=headway-visual-editor' ); ?>">Visual Editor</a></h3>
+
+ <p>The Visual Editor is the magic. It is where you design and style your amazing website.</p>
+
+ <p>Check out this document for a quick overview of the <a
+ href="http://docs.headwaythemes.com/article/26-the-basics-of-customizing-a-layout" target="_blank">basics
+ of the Visual Editor</a></p>
+ </div>
+ </div>
+
+ <div class="headway-infobox-row">
+ <div class="headway-infobox big inrow">
+ <h3><a href="<?php echo admin_url( 'admin.php?page=headway-options' ); ?>">Options</a></h3>
+ <p>This is the place to go to tweak your Headway site, with things like Google Analytics, SEO, favicons and other more advanced settings.</p>
+ </div>
+ <div class="headway-infobox big">
+ <h3><a href="<?php echo admin_url( 'admin.php?page=headway-tools' ); ?>">Tools</a></h3>
+ <p>If you log a request on the forums, it is very useful to provide system info and Tools is the place to find it.</p>
+ <p>And if you really just want to wipe the slate, and start afresh, there's a big red button for that.</p>
+ </div>
+ </div>
+
+ <h2>Need help?</h2>
+ <p>If you ever run into any problems, you can visit our forums or check out the documentation</p>
+
+ <div class="headway-infobox-row headway-infobox-icon-row">
+ <div class="headway-infobox headway-infobox-icon inrow">
+ <span class="dashicons dashicons-groups"></span>
+ <a class="big" href="http://support.headwaythemes.com/" target="_blank">Support</a>
+ </div>
+
+ <div class="headway-infobox headway-infobox-icon">
+ <span class="dashicons dashicons-book-alt bigfix"></span>
+ <a class="big" href="http://docs.headwaythemes.com/" target="_blank">Documentation</a>
+ </div>
+ </div>
+
+ <h2>Extending Headway</h2>
+ <p>We have a wonderful community of third party developers who are creating beautiful Templates that contain all the design and styling already done for you, and fantastically useful Blocks, which provide even more layout possibilites, saving you heaps of time in setting up your designs, such as galleries, sliders, advanced content display and utility blocks.</p>
+
+
+ <div class="headway-infobox-row headway-infobox-icon-row">
+ <div class="headway-infobox inrow headway-infobox-icon">
+ <span class="dashicons dashicons-welcome-widgets-menus"></span>
+ <a class="big" href="http://headwaythemes.com/extend/templates" target="_blank">Templates</a>
+ </div>
+
+ <div class="headway-infobox headway-infobox-icon">
+ <span class="dashicons dashicons-screenoptions"></span>
+ <a class="big" href="http://headwaythemes.com/extend/blocks" target="_blank">Blocks</a>
+ </div>
+ </div>
+
+</div>
--- /dev/null
+<h2 class="nav-tab-wrapper big-tabs-tabs">
+ <a class="nav-tab" href="#tab-general">General</a>
+ <a class="nav-tab" href="#tab-seo">Search Engine Optimization</a>
+ <a class="nav-tab" href="#tab-scripts">Scripts/Analytics</a>
+ <a class="nav-tab" href="#tab-visual-editor">Visual Editor</a>
+ <a class="nav-tab" href="#tab-advanced">Advanced</a>
+</h2>
+
+<?php do_action('headway_admin_save_message'); ?>
+<?php do_action('headway_admin_save_error_message'); ?>
+
+<form method="post">
+ <input type="hidden" value="<?php echo wp_create_nonce('headway-admin-nonce'); ?>" name="headway-admin-nonce" id="headway-admin-nonce" />
+
+ <div class="big-tabs-container">
+
+ <div class="big-tab" id="tab-general-content">
+
+ <?php
+ if ( is_main_site() ) {
+ ?>
+
+ <div class="license-key-input-table">
+
+ <h3 class="title">License Keys</h3>
+
+ <p>
+ Please enter your license key(s) here. This will be used to authenticate your site so you can take advantage of the automatic updates.
+ <br /><br />You may find your license key(s) in the <a href="http://headwaythemes.com/dashboard" target="_blank">Headway Members Dashboard</a>.
+ </p>
+
+ <table class="form-table">
+
+ <?php foreach ( apply_filters('headway_updater_products', array()) as $item_slug => $item_name ): ?>
+
+ <tr valign="top">
+ <th scope="row">
+ <label for="<?php echo 'license-key-' . $item_slug ?>"><?php echo $item_name; ?></label>
+ </th>
+ <td>
+ <input type="password" class="large-text" value="<?php echo headway_get_license_key($item_slug); ?>" placeholder="Enter License Key" id="<?php echo 'license-key-' . $item_slug ?>" name="headway-admin-input[<?php echo 'license-key-' . $item_slug ?>]" />
+ <?php
+ if ( headway_get_license_key($item_slug) ) {
+
+ $status = headway_get_license_status($item_slug);
+
+ if ( $status == 'valid' ) {
+ ?>
+ <input type="submit" class="button-secondary" name="headway-licenses[deactivate][<?php echo $item_slug; ?>]" value="<?php _e('Deactivate License'); ?>" />
+ <span style="color:green;"><?php _e('Active'); ?></span>
+ <?php } else { ?>
+ <input type="submit" class="button-secondary" name="headway-licenses[save-and-activate][<?php echo $item_slug; ?>]" value="<?php _e('Save & Activate License'); ?>" />
+ <?php } ?>
+ <?php } else { ?>
+ <input type="submit" class="button-secondary" name="headway-licenses[save-and-activate][<?php echo $item_slug; ?>]" value="<?php _e('Save & Activate License'); ?>" />
+ <?php } ?>
+ </td>
+ </tr>
+
+ <?php endforeach; ?>
+
+ </table>
+
+ </div><!-- .license-key-input-table -->
+
+ <h3 class="title title-hr">General</h3>
+
+ <?php
+ } else {
+
+ echo '<h3 class="title">General</h3>';
+
+ }
+
+ $form = array(
+ array(
+ 'id' => 'favicon',
+ 'size' => 'large',
+ 'type' => 'text',
+ 'label' => 'Favicon URL',
+ 'value' => HeadwayOption::get('favicon'),
+ 'description' => 'A favicon is the little image that sits next to your address in the favorites menu and on tabs. If you do not know how to save an image as an icon you can go to <a href="http://www.favicon.cc/" target="_blank">favicon.cc</a> and draw or import an image.'
+ ),
+
+ array(
+ 'id' => 'feed-url',
+ 'size' => 'large',
+ 'type' => 'text',
+ 'label' => 'Feed URL',
+ 'description' => 'If you use any service like <a href="http://feedburner.google.com/" target="_blank">FeedBurner</a>, type the feed URL here.',
+ 'value' => HeadwayOption::get('feed-url')
+ )
+ );
+
+ HeadwayAdminInputs::generate($form);
+ ?>
+
+ <h3 class="title title-hr">Admin Preferences</h3>
+
+ <?php
+ $form = array(
+ array(
+ 'id' => 'menu-setup',
+ 'type' => 'radio',
+ 'label' => 'Default Admin Page',
+ 'value' => HeadwayOption::get('menu-setup', false, 'getting-started'),
+ 'radios' => array(
+ array(
+ 'value' => 'getting-started',
+ 'label' => 'Getting Started'
+ ),
+
+ array(
+ 'value' => 'visual-editor',
+ 'label' => 'Visual Editor'
+ ),
+
+ array(
+ 'value' => 'options',
+ 'label' => 'Options'
+ )
+ ),
+ 'description' => 'Select which admin page you would like to be directed to when you click on "Headway" in the WordPress Admin.'
+ )
+ );
+
+ HeadwayAdminInputs::generate($form);
+ ?>
+
+ <h3 class="title title-hr">Affiliate Promotion</h3>
+
+ <?php
+ $form = array(
+ array(
+ 'id' => 'affiliate-link',
+ 'size' => 'large',
+ 'value' => HeadwayOption::get('affiliate-link'),
+ 'type' => 'text',
+ 'label' => 'Affiliate Link',
+ 'description' => '
+ If you are a member of the Headway Affiliate program, you can paste your affiliate link and earn money when someone purchases Headway through your affiliate link. <strong>Do NOT put HTML in this field.</strong>
+ <br /><br /><strong>Not an affiliate?</strong> If you\'re interested in the Headway Affiliate program, you may <a href="http://headwaythemes.com/affiliates" target="_blank">apply here</a>. Once your application is approved you can log in and grab your affiliate link.'
+ )
+ );
+
+ HeadwayAdminInputs::generate($form);
+ ?>
+
+ </div><!-- #tab-general-content -->
+
+
+ <div class="big-tab" id="tab-seo-content">
+
+ <?php
+ if ( HeadwaySEO::plugin_active() ) {
+
+ switch ( HeadwaySEO::plugin_active() ) {
+
+ case 'aioseop':
+ echo '<div class="alert alert-yellow"><p>Headway has detected that you are using the All In One SEO pack plugin. In order to reduce conflicts and save resources, Headway\'s SEO functionality has been disabled.</p></div>';
+ break;
+
+ case 'wpseo':
+ echo '<div class="alert alert-yellow"><p>Headway has detected that you are using Yoast\'s WordPress SEO plugin. In order to reduce conflicts and save resources, Headway\'s SEO functionality has been disabled.</p></div>';
+ break;
+
+ }
+
+ } else {
+ ?>
+
+ <h3 class="title" id="seo-templates-title">SEO Templates</h3>
+
+ <div id="seo-templates">
+ <div id="seo-templates-hidden-inputs">
+ <?php
+ /* SETUP THE TYPES OF SEO TEMPLATE INPUTS */
+ $seo_template_inputs = array(
+ 'title',
+ 'description',
+ 'noindex',
+ 'nofollow',
+ 'noarchive',
+ 'nosnippet',
+ 'noodp',
+ 'noydir'
+ );
+
+ /* GENERATE HIDDEN INPUTS */
+ $seo_options = HeadwayOption::get('seo-templates', 'general', array());
+
+ foreach (HeadwaySEO::output_layouts_and_defaults() as $page => $defaults) {
+
+ foreach ($seo_template_inputs as $input) {
+
+ $name_attr = 'name="headway-admin-input[seo-templates][' . $page . '][' . $input . ']"';
+
+ $default = isset($defaults[$input]) ? $defaults[$input] : null;
+
+ $page_options = headway_get($page, $seo_options, array());
+ $value = headway_get($input, $page_options, $default);
+
+ echo '<input type="hidden" id="seo-' . $page . '-' . $input . '"' . $name_attr . ' value="' . stripslashes(esc_attr($value)) . '" />';
+
+ }
+
+ }
+ ?>
+ </div>
+
+ <div id="seo-templates-header">
+ <span>Select a Template:</span>
+ <select>
+ <option value="index">Blog Index</option>
+
+ <?php
+ if ( get_option('show_on_front') == 'page' )
+ echo '<option value="front_page">Front Page</option>';
+ ?>
+
+ <optgroup label="Single">
+ <?php
+ $post_types = get_post_types(array('public' => true), 'objects');
+
+ foreach($post_types as $post_type)
+ echo '<option value="single-' . $post_type->name . '">' . $post_type->label . '</option>';
+ ?>
+ </optgroup>
+
+ <optgroup label="Archive">
+ <option value="archive-category">Category</option>
+ <option value="archive-search">Search</option>
+ <option value="archive-date">Date</option>
+ <option value="archive-author">Author</option>
+ <option value="archive-post_tag">Post Tag</option>
+ <option value="archive-post_type">Post Type</option>
+ <option value="archive-taxonomy">Taxonomy</option>
+ </optgroup>
+
+ <option value="four04">404</option>
+
+ </select>
+ </div><!-- #seo-templates-header -->
+
+ <div id="seo-templates-inputs">
+
+ <?php
+ $form = array(
+ array(
+ 'id' => 'title',
+ 'type' => 'text',
+ 'size' => 'large',
+ 'label' => 'Title',
+ 'description' => 'The title is the main text that describes the page. It is the single most important on-page SEO element (behind overall content). The title appears at the top of the web browser when viewing the page, in browser tabs, search engine results, and external websites. <strong>Tip:</strong> it is best that the title stays below 70 characters.<br /><br /><a href="http://www.seomoz.org/learn-seo/title-tag" target="_blank">Learn more about Titles »</a>',
+ 'no-submit' => true
+ ),
+
+ array(
+ 'id' => 'description',
+ 'type' => 'paragraph',
+ 'cols' => 60,
+ 'rows' => 3,
+ 'label' => '<code><meta></code> Description',
+ 'description' => 'Meta description tags, while not important to search engine rankings, are extremely important in gaining user click-through from search engine result pages (SERPs). These short paragraphs are your opportunity to advertise content to searchers and let them know exactly what the given page has with regard to what they’re looking for. <strong>Tip:</strong> a good description is around 150 characters.<br /><br /><a href="http://www.seomoz.org/learn-seo/meta-description" target="_blank">Learn more about <meta> Descriptions »</a>',
+ 'no-submit' => true
+ )
+ );
+
+ HeadwayAdminInputs::generate($form);
+ ?>
+
+ <div class="hr"></div>
+
+ <p><strong>You may use the following variables in the Title and Description inputs above:</strong></p>
+
+ <ul>
+ <li><code>%title%</code> — Will retrieve the title of whatever post, archive, or page is being displayed.</li>
+ <li><code>%sitename%</code> — Will retrieve the name of the site. This can be set in <a href="<?php echo admin_url('options-general.php'); ?>" target="_blank">Settings » General</a>.</li>
+ <li><code>%tagline%</code> — Will retrieve the tagline/description of the site. This can be set in <a href="<?php echo admin_url('options-general.php'); ?>" target="_blank">Settings » General</a>.</li>
+ <li><code>%meta%</code> — Used only on taxonomy archives to display the term name.</li>
+ </ul>
+
+ <h3 id="seo-templates-advanced-options-title" class="title title-hr">Advanced Options <span>Show ↓</span></h3>
+
+ <div id="seo-templates-advanced-options">
+ <?php
+ $form = array(
+ array(
+ 'type' => 'checkbox',
+ 'label' => 'Page Indexing',
+ 'checkboxes' => array(
+ array(
+ 'id' => 'noindex',
+ 'label' => 'Enable <code>noindex</code>',
+ 'no-submit' => true
+ )
+ ),
+ 'description' => 'Index/NoIndex tells the engines whether the page should be crawled and kept in the engines\' index for retrieval. If you check this box to opt for <code>noindex</code>, the page will be excluded from the engines. <strong>Note:</strong> if you\'re not sure what this does, do not check this box.'
+ ),
+
+ array(
+ 'type' => 'checkbox',
+ 'label' => 'Link Following',
+ 'checkboxes' => array(
+ array(
+ 'id' => 'nofollow',
+ 'label' => 'Enable <code>nofollow</code>',
+ 'no-submit' => true
+ )
+ ),
+ 'description' => 'Follow/NoFollow tells the engines whether links on the page should be crawled. If you check this box to employ "nofollow," the engines will disregard the links on the page both for discovery and ranking purposes. <strong>Note:</strong> if you\'re not sure what this does, do not check this box.'
+ ),
+
+ array(
+ 'type' => 'checkbox',
+ 'label' => 'Page Archiving',
+ 'checkboxes' => array(
+ array(
+ 'id' => 'noarchive',
+ 'label' => 'Enable <code>noarchive</code>',
+ 'no-submit' => true
+ )
+ ),
+ 'description' => 'Noarchive is used to restrict search engines from saving a cached copy of the page. By default, the engines will maintain visible copies of all pages they indexed, accessible to searchers through the "cached" link in the search results. Check this box to restrict search engines from storing cached copies of this page.'
+ ),
+
+ array(
+ 'type' => 'checkbox',
+ 'label' => 'Snippets',
+ 'checkboxes' => array(
+ array(
+ 'id' => 'nosnippet',
+ 'label' => 'Enable <code>nosnippet</code>',
+ 'no-submit' => true
+ )
+ ),
+ 'description' => 'Nosnippet informs the engines that they should refrain from displaying a descriptive block of text next to the page\'s title and URL in the search results.'
+ ),
+
+ array(
+ 'type' => 'checkbox',
+ 'label' => 'Open Directory Project',
+ 'checkboxes' => array(
+ array(
+ 'id' => 'noodp',
+ 'label' => 'Enable <code>NoODP</code>',
+ 'no-submit' => true
+ )
+ ),
+ 'description' => 'NoODP is a specialized tag telling the engines not to grab a descriptive snippet about a page from the Open Directory Project (DMOZ) for display in the search results.'
+ ),
+
+ array(
+ 'type' => 'checkbox',
+ 'label' => 'Yahoo! Directory',
+ 'checkboxes' => array(
+ array(
+ 'id' => 'noydir',
+ 'label' => 'Enable <code>NoYDir</code>',
+ 'no-submit' => true
+ )
+ ),
+ 'description' => 'NoYDir, like NoODP, is specific to Yahoo!, informing that engine not to use the Yahoo! Directory description of a page/site in the search results.'
+ )
+ );
+
+ HeadwayAdminInputs::generate($form);
+ ?>
+ </div><!-- #seo-templates-advanced-options -->
+
+ </div><!-- #seo-templates-inputs -->
+ </div><!-- #seo-templates-content -->
+
+ <div id="seo-description" class="alert alert-yellow"><p>Unfamiliar with <em>Search Engine Optimization</em>? <a href="http://www.seomoz.org/beginners-guide-to-seo/" target="_blank">Learn More »</a></p></div>
+
+ <h3 class="title title-hr">Content <code>nofollow</code> Links</h3>
+
+ <?php
+ $form = array(
+ array(
+ 'type' => 'checkbox',
+ 'label' => 'Comment Authors\' URL',
+ 'checkboxes' => array(
+ array(
+ 'id' => 'nofollow-comment-author-url',
+ 'label' => 'Add nofollow To Comment Authors\' URL',
+ 'checked' => HeadwayOption::get('nofollow-comment-author-url', 'general', false)
+ )
+ ),
+ 'description' => 'Adding nofollow to the comment authors\' URLs will tell search engines to not visit their website and to stay on yours. Many bloggers frown upon this, which can sometimes discourage comments. Only enable this if you are 100% sure you know you want to.'
+ )
+ );
+
+ HeadwayAdminInputs::generate($form);
+ ?>
+
+ <?php
+ }
+ ?>
+
+ </div><!-- #tab-seo -->
+
+
+ <div class="big-tab" id="tab-scripts-content">
+
+ <?php
+ $form = array(
+ array(
+ 'id' => 'header-scripts',
+ 'type' => 'paragraph',
+ 'cols' => 90,
+ 'rows' => 8,
+ 'label' => 'Header Scripts',
+ 'description' => 'Anything here will go in the <code><head></code> of the website. If you are using <a href="http://google.com/analytics" target="_blank">Google Analytics</a>, paste the code provided here. <strong>Do not place plain text in this!</strong>',
+ 'allow-tabbing' => true,
+ 'value' => HeadwayOption::get('header-scripts')
+ ),
+
+ array(
+ 'id' => 'footer-scripts',
+ 'type' => 'paragraph',
+ 'cols' => 90,
+ 'rows' => 8,
+ 'label' => 'Footer Scripts',
+ 'description' => 'Anything here will be inserted before the <code></body></code> tag of the website. <strong>Do not place plain text in this!</strong>',
+ 'allow-tabbing' => true,
+ 'value' => HeadwayOption::get('footer-scripts')
+ )
+ );
+
+ HeadwayAdminInputs::generate($form);
+ ?>
+
+ </div><!-- #tab-scripts-content -->
+
+
+ <div class="big-tab" id="tab-visual-editor-content">
+
+ <?php
+ $form = array(
+ array(
+ 'type' => 'checkbox',
+ 'label' => 'Tooltips',
+ 'checkboxes' => array(
+ array(
+ 'id' => 'disable-visual-editor-tooltips',
+ 'label' => 'Disable Tooltips in the Visual Editor',
+ 'checked' => HeadwayOption::get('disable-visual-editor-tooltips', false, false)
+ )
+ ),
+ 'description' => 'If you ever feel that the tooltips are too invasive in the visual editor, you can disable them here. Tooltips are the black speech bubbles that appear to assist you when you are not sure what an option is or how it works.'
+ ),
+
+ array(
+ 'type' => 'checkbox',
+ 'label' => 'Live CSS Editor Syntax Highlighting',
+ 'checkboxes' => array(
+ array(
+ 'id' => 'disable-codemirror',
+ 'label' => 'Disable Syntax Highlighing for the Live CSS Editor',
+ 'checked' => HeadwayOption::get('disable-codemirror', false, false)
+ )
+ ),
+ 'description' => 'Headway uses the CodeMirror syntax highlighting library to power the Live CSS editor. If you find the Live CSS editor causing your browser to crash or if you simply prefer to go without the syntax highlighter, you can disable it here.'
+ ),
+
+ array(
+ 'type' => 'checkbox',
+ 'label' => 'Grid Safe Mode',
+ 'checkboxes' => array(
+ array(
+ 'id' => 'grid-safe-mode',
+ 'label' => 'Enable Grid Safe Mode',
+ 'checked' => HeadwayOption::get('grid-safe-mode', false, false)
+ )
+ ),
+ 'description' => 'Under certain circumstances the Visual Editor may not load due to problematic HTML, JavaScript, or CSS in a block or multiple blocks. Enable Grid Safe Mode if you are unable to access the Visual Editor.'
+ ),
+
+ array(
+ 'type' => 'checkbox',
+ 'label' => 'Layout Selector Safe Mode',
+ 'checkboxes' => array(
+ array(
+ 'id' => 'layout-selector-safe-mode',
+ 'label' => 'Enable Layout Selector Safe Mode',
+ 'checked' => HeadwayOption::get('layout-selector-safe-mode', false, false)
+ )
+ ),
+ 'description' => 'On sites that have a very high number of posts (1,000+), sometimes the Visual Editor will have difficultly loading due to the Layout Selector trying to populate itself with the posts and other pages. Enable Layout Selector Safe Mode to exclude everything except for pages from the Layout Selector.<br /><br/><strong>Refrain from using this option unless you are certain it addresses the issue.</strong>'
+ )
+ );
+
+ HeadwayAdminInputs::generate($form);
+ ?>
+
+ </div>
+
+
+ <div class="big-tab" id="tab-advanced-content">
+
+ <h3 class="title">Caching & Compression</h3>
+
+ <?php
+ $form = array(
+ array(
+ 'type' => 'checkbox',
+ 'label' => 'Asset Caching',
+ 'checkboxes' => array(
+ array(
+ 'id' => 'disable-caching',
+ 'label' => 'Disable Headway Caching',
+ 'checked' => HeadwayOption::get('disable-caching', false, false)
+ )
+ ),
+ 'description' => 'By default, Headway will attempt to cache all CSS and JavaScript that it generates. However, there may be rare circumstances where disabling the cache will help with certain issues.<br /><br /><em><strong>Important:</strong> Disabling the Headway cache will cause an <strong>increase in page load times</strong> and <strong>increase the strain your web server</strong> will undergo on every page load.'
+ ),
+
+ array(
+ 'type' => 'checkbox',
+ 'label' => 'Dependency Query Variables',
+ 'checkboxes' => array(
+ array(
+ 'id' => 'remove-dependency-query-vars',
+ 'label' => 'Remove Query Variables from Dependency URLs',
+ 'checked' => HeadwayOption::get('remove-dependency-query-vars', false, false)
+ )
+ ),
+ 'description' => 'To leverage browser caching, Headway can tell WordPress to not put query variables on static assets such as CSS and JavaScript files.'
+ ),
+
+ array(
+ 'type' => 'checkbox',
+ 'label' => '<code>gzip</code> Compression',
+ 'checkboxes' => array(
+ array(
+ 'id' => 'enable-gzip',
+ 'label' => 'Enable <code>gzip</code> Compression',
+ 'checked' => HeadwayOption::get('enable-gzip', false, true)
+ )
+ ),
+ 'description' => 'By default, gzip compression is on. <code>gzip</code> compression will greatly reduce the amount of time it takes to load your website. However, there may be special circumstances where it is necessary to disable it.'
+ )
+ );
+
+ HeadwayAdminInputs::generate($form);
+ ?>
+
+ <h3 class="title title-hr">Admin</h3>
+
+ <?php
+ $form = array(
+ array(
+ 'type' => 'checkbox',
+ 'label' => 'Version Number',
+ 'checkboxes' => array(
+ array(
+ 'id' => 'hide-menu-version-number',
+ 'label' => 'Hide Headway Version Number From Menu',
+ 'checked' => HeadwayOption::get('hide-menu-version-number', false, true)
+ )
+ ),
+ 'description' => 'Check this if you wish to have the Menu say "Headway" instead of "Headway ' .HEADWAY_VERSION . '"'
+ ),
+
+ array(
+ 'type' => 'checkbox',
+ 'label' => 'Update Notices',
+ 'checkboxes' => array(
+ array(
+ 'id' => 'disable-update-notices',
+ 'label' => 'Disable Headway Update Notices',
+ 'checked' => HeadwayOption::get('disable-update-notices', false, false)
+ )
+ ),
+ 'description' => 'If you wish to hide the notices that appear when an update is available for Headway, check this.'
+ ),
+
+ array(
+ 'type' => 'checkbox',
+ 'label' => 'Editor Style',
+ 'checkboxes' => array(
+ array(
+ 'id' => 'disable-editor-style',
+ 'label' => 'Disable Editor Style',
+ 'checked' => HeadwayOption::get('disable-editor-style', false, false)
+ )
+ ),
+ 'description' => 'By default, Headway will take any settings in the Design Editor and add them to <a href="http://codex.wordpress.org/TinyMCE" target="_blank">WordPress\' TinyMCE editor</a> style. Use this option to prevent that.'
+ )
+ );
+
+ HeadwayAdminInputs::generate($form);
+ ?>
+
+ <h3 class="title title-hr">Debugging</h3>
+
+ <div class="alert alert-red"><p>The following option should only be checked if a member of the Headway Themes team asks you to do so.</p></div>
+
+ <?php
+ $form = array(
+ array(
+ 'type' => 'checkbox',
+ 'label' => 'Debug Mode',
+ 'checkboxes' => array(
+ array(
+ 'id' => 'debug-mode',
+ 'label' => 'Enable Debug Mode',
+ 'checked' => HeadwayOption::get('debug-mode', false, false)
+ )
+ ),
+ 'description' => 'Having Debug Mode enabled will allow the Headway Themes team to access the Visual Editor for support purposes, but <strong>will not allow changes to be saved<strong>.'
+ )
+ );
+
+ HeadwayAdminInputs::generate($form);
+ ?>
+
+ </div>
+
+
+ </div>
+
+ <div class="hr hr-submit" style="display: none;"></div>
+
+ <p class="submit" style="display: none;">
+ <input type="submit" name="headway-submit" value="Save Changes" class="button-primary headway-save" />
+ </p>
+
+</form>
\ No newline at end of file
--- /dev/null
+<div id="export-template" style="display: none;">
+ <h3>Export Template</h3>
+ <p>Fill out the information below to export all design settings, layouts, and blocks as a Headway Template</p>
+
+ <form id="export-template-form">
+ <table class="form-table">
+ <tbody>
+ <tr valign="top">
+ <th scope="row"><label for="template-export-name">Template Name</label></th>
+ <td><input id="template-export-name" type="text" name="skin-export-info[name]" class="regular-text" /></td>
+ </tr>
+
+ <?php
+ $current_user = wp_get_current_user();
+ ?>
+
+ <tr valign="top">
+ <th scope="row"><label for="template-export-author">Template Author</label></th>
+ <td><input id="template-export-author" type="text" name="skin-export-info[author]" class="regular-text" value="<?php echo $current_user->display_name; ?>" /></td>
+ </tr>
+
+ <tr valign="top">
+ <th scope="row"><label for="template-export-version">Template Version</label></th>
+ <td><input id="template-export-version" type="text" name="skin-export-info[version]" placeholder="e.g. 1.0" class="medium-text" /></td>
+ </tr>
+
+ <tr valign="top">
+ <th scope="row"><label for="template-export-image">Template Image</label></th>
+ <td>
+ <button id="template-export-image-button" class="button-secondary">
+ <span class="wp-media-buttons-icon"></span>
+ Select Image
+ </button>
+ <input id="template-export-image" type="hidden" name="skin-export-info[image-url]" class="medium-text" />
+ <img src="" id="template-export-image-preview" style="display: none;" />
+ </td>
+ </tr>
+ </tbody>
+ </table>
+
+ <p class="submit"><input type="submit" name="submit" id="export-template-submit" class="button button-primary" value="Export Template"></p>
+ </form>
+</div>
+
+<h2>Headway Templates <a href="#" class="add-new-h2" id="install-template">Install Template</a> <a href="#TB_inline?width=500&height=600&inlineId=export-template" class="add-new-h2 thickbox" id="export-template">Export Current Template</a></h2>
+
+<div id="headway-admin-notifications"></div>
+
+<div class="theme-browser" id="headway-templates-browser">
+ <div class="themes headway-templates">
+ <!-- ko foreach: templates -->
+ <div class="theme headway-template" tabindex="0" aria-describedby="headway-action headway-name" data-bind="attr: { 'data-template-id': id }, css: { 'active': $parent.active().id == id, 'missing-image': !$data['image-url'], 'template-installing': (typeof $data['installing'] != 'undefined' && $data['installing']) }">
+
+ <div class="theme-screenshot">
+ <span class="template-loading-indicator" data-bind="visible: (typeof $data['installing'] != 'undefined' && $data['installing'])"></span>
+ <img src="" alt="" data-bind="visible: $data['image-url'], attr: { 'src': $data['image-url'] }" />
+ </div>
+
+ <div class="theme-author" data-bind="text: 'By ' + author, visible: author"></div>
+
+ <h3 class="theme-name" id="headway-name"><span data-bind="visible: $parent.active().id == id">Active: </span><!-- ko text: name --><!-- /ko --> <!-- ko text:version --><!-- /ko --></h3>
+
+ <div class="theme-actions" data-bind="visible: (typeof $data['installing'] == 'undefined' || !$data['installing'])">
+ <a href="#" class="button button-secondary delete-template" data-bind="click: $parent.deleteSkin, visible: (id != $parent.active().id && id != 'base')">Delete</a>
+ <a class="button button-primary" href="#" data-bind="click: $parent.activateSkin, visible: id != $parent.active().id">Activate</a>
+ </div>
+
+ </div>
+ <!-- /ko -->
+
+ <div class="theme add-new-theme" id="add-blank-template">
+ <a href="#">
+ <div class="theme-screenshot"><span></span></div>
+ <h3 class="theme-name">Add Blank Template</h3>
+ </a>
+ </div>
+ </div>
+ <br class="clear">
+</div>
+
+<form id="upload-skin">
+ <input type="file" />
+</form>
\ No newline at end of file
--- /dev/null
+<h2 class="nav-tab-wrapper big-tabs-tabs">
+ <a class="nav-tab" href="#tab-system-info">System Info</a>
+ <a class="nav-tab" href="#tab-reset">Reset</a>
+</h2>
+
+<?php do_action('headway_admin_save_message'); ?>
+
+
+<div class="big-tabs-container">
+
+ <div class="big-tab" id="tab-system-info-content">
+
+ <div id="system-info">
+
+ <h3 class="title" style="margin-bottom: 10px;"><strong>System Info</strong></h3>
+
+ <p class="description">
+ Copy and paste this information into support/forums if requested.
+ <br /><br />
+ <strong>Please copy all of the content in the text area below and paste it as-is in the requested forum discussion.</strong>
+ </p>
+
+ <?php
+ $browser = headway_get_browser();
+
+ if ( !headway_get('exclude-counts') ) {
+ $post_count = wp_count_posts('post');
+ $page_count = wp_count_posts('page');
+ }
+ ?>
+
+<textarea readonly="readonly" id="system-info-textarea" title="To copy the system info, click below then press Ctrl + C (PC) or Cmd + C (Mac).">
+
+ ### Begin System Info ###
+
+ Child Theme: <?php echo HEADWAY_CHILD_THEME_ACTIVE ? (function_exists('wp_get_theme') ? wp_get_theme() : get_current_theme()) . "\n" : "N/A\n" ?>
+
+ Multi-site: <?php echo is_multisite() ? 'Yes' . "\n" : 'No' . "\n" ?>
+
+ SITE_URL: <?php echo site_url() . "\n"; ?>
+ HOME_URL: <?php echo home_url() . "\n"; ?>
+
+ Headway Version: <?php echo HEADWAY_VERSION . "\n"; ?>
+ WordPress Version: <?php echo get_bloginfo('version') . "\n"; ?>
+
+ PHP Version: <?php echo PHP_VERSION . "\n"; ?>
+ MySQL Version: <?php echo mysql_get_server_info() . "\n"; ?>
+ Web Server Info: <?php echo $_SERVER['SERVER_SOFTWARE'] . "\n"; ?>
+ GD Support: <?php echo function_exists('gd_info') ? "Yes\n" : "***WARNING*** No\n"; ?>
+
+ PHP Memory Limit: <?php echo ini_get('memory_limit') . "\n"; ?>
+ PHP Post Max Size: <?php echo ini_get('post_max_size') . "\n"; ?>
+
+ WP_DEBUG: <?php echo defined('WP_DEBUG') ? WP_DEBUG ? 'Enabled' . "\n" : 'Disabled' . "\n" : 'Not set' . "\n" ?>
+ SCRIPT_DEBUG: <?php echo defined('SCRIPT_DEBUG') ? SCRIPT_DEBUG ? 'Enabled' . "\n" : 'Disabled' . "\n" : 'Not set' . "\n" ?>
+ Debug Mode: <?php echo HeadwayOption::get('debug-mode', false, false) ? 'Enabled' . "\n" : 'Disabled' . "\n" ?>
+
+ Show On Front: <?php echo get_option('show_on_front') . "\n" ?>
+ Page On Front: <?php echo get_option('page_on_front') . "\n" ?>
+ Page For Posts: <?php echo get_option('page_for_posts') . "\n" ?>
+
+ <?php
+ if ( !headway_get('exclude-counts') ):
+ ?>
+ Amount of Posts: ~<?php echo $post_count->publish . "\n" ?>
+ Amount of Pages: ~<?php echo $page_count->publish . "\n" ?>
+ Amount of Blocks: ~<?php echo count(HeadwayBlocksData::get_all_blocks()) . "\n" ?>
+ <?php
+ endif;
+ ?>
+
+ Responsive Grid: <?php echo HeadwayResponsiveGrid::is_enabled() ? 'Enabled' . "\n" : 'Disabled' . "\n" ?>
+
+ Caching Allowed: <?php echo HeadwayCompiler::can_cache() ? 'Yes' . "\n" : 'No' . "\n"; ?>
+ Caching Enabled: <?php echo HeadwayCompiler::caching_enabled() ? 'Yes' . "\n" : 'No' . "\n"; ?>
+ Caching Plugin: <?php echo HeadwayCompiler::is_plugin_caching() ? HeadwayCompiler::is_plugin_caching() . "\n" : 'No caching plugin active' . "\n" ?>
+
+ SEO Plugin: <?php echo HeadwaySEO::plugin_active() ? HeadwaySEO::plugin_active() . "\n" : 'No SEO plugin active' . "\n" ?>
+
+ Operating System: <?php echo ucwords($browser['platform']) . "\n"; ?>
+ Browser: <?php echo $browser['name'] . "\n"; ?>
+ Browser Version: <?php echo $browser['version'] . "\n"; ?>
+
+ Full User Agent:
+ <?php echo $browser['userAgent'] . "\n"; ?>
+
+
+ WEB FONTS IN USE:
+<?php
+$webfonts_in_use = HeadwayWebFontsLoader::get_fonts_in_use();
+
+if ( is_array($webfonts_in_use) && count($webfonts_in_use) ) {
+
+ foreach ( $webfonts_in_use as $provider => $fonts )
+ foreach ( $fonts as $font )
+ echo ' ' . $provider . ': ' . $font . "\n";
+
+} else {
+
+ echo ' None' . "\n";
+
+}
+?>
+
+
+ ACTIVE PLUGINS:
+<?php
+$plugins = get_plugins();
+$active_plugins = get_option('active_plugins', array());
+
+if ( is_array($active_plugins) && count($active_plugins) ) {
+
+ foreach ( $plugins as $plugin_path => $plugin ) {
+
+ //If the plugin isn't active, don't show it.
+ if ( !in_array($plugin_path, $active_plugins) )
+ continue;
+
+ echo ' ' . $plugin['Name'] . ' ' . $plugin['Version'] . "\n";
+
+ if ( isset($plugin['PluginURI']) )
+ echo ' ' . $plugin['PluginURI'] . "\n";
+
+ echo "\n";
+
+ }
+
+} else {
+
+ echo ' None' . "\n\n";
+
+}
+?>
+ ### End System Info ###
+
+</textarea>
+
+ </div><!-- #system-info -->
+
+ </div><!-- #tab-system-info-content -->
+
+ <div class="big-tab" id="tab-reset-content">
+
+ <?php if ( defined('HEADWAY_ALLOW_RESET') && HEADWAY_ALLOW_RESET === true ): ?>
+ <?php if ( !isset($GLOBALS['headway_reset_success']) || $GLOBALS['headway_reset_success'] == false ): ?>
+ <div class="alert-red reset-alert alert">
+ <h3>Warning</h3>
+
+ <p>Clicking the <em>Reset</em> button below will delete <strong>ALL</strong> existing Headway data including, but not limited to: Blocks, Design Settings, and Headway Search Engine Optimization settings.</p>
+
+ <form method="post" id="reset-headway">
+ <input type="hidden" value="<?php echo wp_create_nonce('headway-reset-nonce'); ?>" name="headway-reset-nonce" id="headway-reset-nonce" />
+
+ <input type="submit" value="Reset Headway" class="button alert-big-button" name="reset-headway" id="reset-headway-submit" />
+ </form><!-- #reset -->
+ </div>
+ <?php endif; ?>
+ <?php else: ?>
+ <div class="alert-yellow reset-info alert">
+ <h3>Headway Reset Disabled</h3>
+
+ <p>For your security, resetting Headway is disabled.</p>
+
+ <p>If you wish to reset your Headway installation, please <span style="font-weight: 600;color: #fff;background: #2f2f2f; padding: 2px 4px;">add the code below to your wp-config.php file</span>.<br />Not sure how to edit your wp-config.php file? Please see <a href="http://codex.wordpress.org/Editing_wp-config.php" target="_blank">Editing wp-config.php</a> in the official WordPress documentation.</p>
+
+ <textarea class="code" style="width: 400px;height:45px;resize:none;margin: 10px 0 10px;" readonly="readonly">define('HEADWAY_ALLOW_RESET', true);</textarea>
+ </div>
+ <?php endif; ?>
+
+ </div><!-- #tab-reset-content -->
+
+</div>
\ No newline at end of file
--- /dev/null
+<div class="wrap about-wrap">
+ <h1><?php printf( __( 'Welcome to Headway %s', 'headway' ), '3.7' ); ?></h1>
+
+ <div class="about-text"><?php printf( __( 'Thank you for updating! Headway 3.7 has many improvements we think you\'ll enjoy.', 'headway' ) ); ?></div>
+
+ <hr />
+
+ <div class="changelog customize">
+ <div class="feature-section col two-col">
+ <div>
+ <img src="//gallery.mailchimp.com/b46cd46ad87f36a99ca3c657f/images/Screen_Shot_2014_04_29_at_1.17.51_PM.png">
+
+ <h4>Fresh User Interface</h4>
+
+ <p>We fell in love with the WordPress 3.8 user interface as soon as we saw it. Headway's dark interface was
+ quickly aging and fell short in terms of readability and contrast. It also didn't feel like part of the
+ WordPress experience.</p>
+
+ <p>Not only did the Visual Editor get a new paint job, but we have also made dragging, animations, and
+ general usage feel much more snappy and responsive.</p>
+ </div>
+ <div class="last-feature">
+ <img src="//gallery.mailchimp.com/b46cd46ad87f36a99ca3c657f/images/Screen_Shot_2014_04_30_at_9.29.59_AM.png">
+
+ <h4>Headway Templates Moved to WordPress Admin</h4>
+
+ <p>To reduce confusion between Headway Templates and Layout Templates we have moved the Templates panel
+ from the Visual Editor to the WordPress Admin.</p>
+ </div>
+ </div>
+ </div>
+
+ <div class="changelog customize">
+ <div class="feature-section col two-col">
+ <div>
+ <!-- <img src="//s.w.org/images/core/3.9/theme.jpg?0">-->
+
+ <h4>Improved Data Handling</h4>
+
+ <p>Headway 3.7's blocks, wrappers, design settings, and layout meta are now stored in custom MySQL tables.
+ We have carefully planned out the data structure to ensure that your work will be more reliably stored.</p>
+
+ <p>We've also taken steps to cache all Headway data from the MySQL tables with the WordPress Transient and
+ Caching APIs to your Headway site stays speedy.</p>
+ </div>
+ <div class="last-feature">
+ <!-- <img src="//s.w.org/images/core/3.9/theme.jpg?0">-->
+
+ <h4>Snapshots</h4>
+
+ <p>Let's face it—losing work is a major waste of time and money! Fortunately, we have added Snapshots in
+ Headway 3.7.</p>
+
+ <p>Snapshots are a simple backup system for Headway that allows you to rollback to any snapshot and
+ restore all blocks, wrappers, layout settings, as well as design settings at any time.</p>
+
+ <p>Headway will also automatically store snapshots when you save in the Visual Editor.</p>
+ </div>
+ </div>
+ </div>
+
+ <hr />
+
+ <div class="changelog under-the-hood">
+ <h3>Additional Changes and Improvements</h3>
+
+ <div class="feature-section col three-col">
+ <div>
+ <h4>Improved Live CSS Editor</h4>
+
+ <p>Live CSS Editor Headway's Live CSS Editor is now powered by Ace. Ace has fantastic code-collapsing
+ capabilities, syntax highlighting, as well as suggestions for your CSS.</p>
+
+ <p>We've also changed the Live CSS editor to open in a new browser window rather than a box in the
+ Visual Editor. This means that you can easily tab between two windows or put the Live CSS editor on
+ another monitor if you use multiple displays.</p>
+ </div>
+ <div>
+ <h4>New Block: Search</h4>
+
+ <p>Display a simple search form with a block</p>
+
+ <h4>New Block: Pin Board</h4>
+
+ <p>Pin Board has been moved into the core of Headway and includes many new improvements regarding
+ category queries, taxonomies, and more!</p>
+ </div>
+ <div class="last-feature">
+ <h4>Visual Editor Speed Improvements</h4>
+
+ <p>The Visual Editor now uses Require.js to load scripts. This improves speed and makes debugging easier.</p>
+
+ <h4>Basic Undo/Redo (Experimental)</h4>
+
+ <p>Implemented basic Undo/Redo functionality. Delete a block on accident? Simply push Cmd + Z or Ctrl +
+ Z and the change will be reverted instantly.</p>
+ </div>
+ </div>
+
+ <hr>
+
+ <div class="return-to-dashboard">
+ <a href="<?php echo admin_url('admin.php?page=headway-visual-editor'); ?>">Go to Headway Visual Editor</a>
+ </div>
+
+ </div>
+</div>
\ No newline at end of file
--- /dev/null
+<?php
+/**
+ * See https://core.trac.wordpress.org/ticket/26809
+ */
+add_action('edit_form_after_editor', 'headway_meta_box_save_post_template_bypass');
+function headway_meta_box_save_post_template_bypass() {
+
+ global $post;
+
+ if ( 'page' == $post->post_type && !count(wp_get_theme()->get_page_templates()) ) {
+
+ echo '
+ <!--
+ Added by Headway
+ See: https://core.trac.wordpress.org/ticket/26809
+ -->
+
+ <input type="hidden" name="page_template" value="default" />
+
+ ';
+
+ }
+
+}
+
+
+function headway_register_admin_meta_box($class) {
+
+ add_action('init', create_function('', 'return headway_register_admin_meta_box_callback(\'' . $class . '\');'), 15);
+
+}
+
+
+function headway_register_admin_meta_box_callback($class) {
+
+ if ( !class_exists($class) )
+ return new WP_Error('meta_box_class_does_not_exist', __('Error: The meta box class being registered does not exist.', 'headway'), $class);
+
+ $meta_box = new $class();
+ $meta_box->register();
+
+ return true;
+
+}
+
+
+abstract class HeadwayAdminMetaBoxAPI {
+
+ /**
+ * Simple ID for the meta box. Must not contain spaces.
+ **/
+ protected $id;
+
+ /**
+ * Name of the meta box. This will show at the top of the box.
+ **/
+ protected $name;
+
+ /**
+ * Array containing all of the inputs
+ **/
+ protected $inputs;
+
+ /**
+ * Array (multiple post types) or string (one post type) defining which post types this meta box will be used with.
+ **/
+ protected $post_types;
+
+ /**
+ * Location of the meta box. Generally 'advanced' or 'side'.
+ **/
+ protected $context;
+
+ /**
+ * Integer of where the meta box will be located vertically.
+ **/
+ protected $priority;
+
+ /**
+ * Can be used to show a simple notice box above the inputs.
+ **/
+ protected $info;
+
+ /**
+ * Argument to be used in the post_type_supports() function to check against this meta box.
+ **/
+ protected $post_type_supports_id;
+
+
+ public function register() {
+
+ //Check for at least a name and ID
+ if ( !isset($this->id) )
+ return false;
+
+ if ( !isset($this->name) )
+ return false;
+
+ //Set up default variables
+ $this->post_types = isset($this->post_types) ? $this->post_types : array('post', 'page');
+ $this->context = isset($this->context) ? $this->context : 'advanced';
+ $this->priority = isset($this->priority) ? $this->priority : 'low';
+ $this->post_type_supports_id = isset($this->post_type_supports_id) ? $this->post_type_supports_id : 'headway-admin-meta-box-' . $this->id;
+
+ //Add the prefix to the ID
+ $this->id = 'headway-admin-meta-box-' . $this->id;
+
+ //Change post types to array if it is a string
+ if ( is_string($this->post_types) )
+ $this->post_types = array($this->post_types);
+
+ //Set up hooks
+ add_action('admin_init', array($this, 'init'));
+ add_action('save_post', array($this, 'save'), 10, 2);
+
+ }
+
+
+ public function init() {
+
+ //Register the meta box on the specified post types
+ foreach ($this->post_types as $post_type) {
+ add_meta_box($this->id, $this->name, array($this, 'box'), $post_type, $this->context, $this->priority);
+ }
+
+ //Register the meta box on the post types that "support" the meta box
+ foreach ((array)get_post_types(array('public' => true)) as $post_type) {
+
+ if ( post_type_supports($post_type, $this->post_type_supports_id) )
+ add_meta_box($this->id, $this->name, array($this, 'box'), $post_type, $this->context, $this->priority);
+
+ }
+
+ }
+
+
+ public function box() {
+
+ global $post;
+
+ //Create the nonce
+ echo '<input type="hidden" name="' . $this->id . '_nonce" id="' . $this->id . '_nonce" value="' . wp_create_nonce(md5($this->id)) . '" />';
+
+ if ( method_exists($this, 'modify_arguments') )
+ $this->modify_arguments($post);
+
+ if ( isset($this->info) )
+ echo '<div class="alert alert-yellow"><p>' . $this->info . '</p></div>';
+
+ echo '<table cellspacing="2" cellpadding="5" style="width: 100%;" class="form-table headway-admin-meta-box">';
+
+ foreach($this->inputs as $name => $input) {
+
+ //Change hyphens to underscores with the input types since methods/functions can't have hyphens
+ $input['type'] = str_replace('-', '_', $input['type']);
+
+ //The input type doesn't exist--go ahead and skip it
+ if ( !method_exists($this, 'input_' . $input['type']) )
+ continue;
+
+ if ( !isset($input['group']) )
+ $input['group'] = 'general';
+
+ if ( !isset($input['default']) )
+ $input['default'] = null;
+
+ $input['attr-id'] = $this->id . '-' . $input['id'];
+ $input['attr-name'] = $this->id . '[' . $input['group'] . '][' . $input['id'] . ']';
+
+ $global = $input['id'] == 'template' ? false : true;
+
+ $input['value'] = HeadwayLayoutOption::get($post->ID, $input['id'], $input['default'], $global, $input['group']);
+
+ if ( headway_get('name', $input) ) {
+
+ echo '
+ <tr class="label">
+ <th valign="top" scope="row">
+ <label for="' . $input['attr-id'] . '">' . $input['name'] . '</label>
+ </th>
+ </tr>
+ ';
+
+ }
+
+ call_user_func(array($this, 'input_' . $input['type']), $input);
+
+ if ( isset($input['description']) )
+ echo '<tr class="description"><td><p>' . $input['description'] . '</p></td></tr>';
+
+ }
+
+ echo '</table>';
+
+ }
+
+
+ public function save($post_ID) {
+
+ /* Don't try saving meta if it's an autosave */
+ if ( defined('DOING_AUTOSAVE') && DOING_AUTOSAVE )
+ return $post_ID;
+
+ //Ruh-roh, bad nonce
+ if ( !wp_verify_nonce(headway_post($this->id . '_nonce'), md5($this->id)) )
+ return false;
+
+ // If this is a revision, get real post ID
+ if ( $parent_id = wp_is_post_revision( $post_ID ) )
+ $post_ID = $parent_id;
+
+ //If there are no options, then there's nothing to save
+ if( !isset($_POST[$this->id]) || !is_array($_POST[$this->id]) )
+ return false;
+
+ //Loop through and set the options
+ foreach($_POST[$this->id] as $group => $inputs){
+
+ foreach ( $inputs as $input => $value ) {
+
+ $global = $input == 'template' ? false : true;
+
+ HeadwayLayoutOption::set($post_ID, $input, $value, $global, $group);
+
+ }
+
+ }
+
+ }
+
+
+ protected function modify_arguments($post = false) {
+
+
+
+ }
+
+
+ protected function input_text($input) {
+
+ echo '
+ <tr>
+ <td>
+ <input type="text" value="' . esc_attr($input['value']) . '" id="' . $input['attr-id'] . '" name="' . $input['attr-name'] . '" />
+ </td>
+ </tr>
+ ';
+
+ }
+
+
+ protected function input_textarea($input) {
+
+ echo '
+ <tr>
+ <td>
+ <textarea rows="6" id="' . $input['attr-id'] . '" name="' . $input['attr-name'] . '">'. esc_textarea($input['value']) . '</textarea>
+ </td>
+ </tr>
+ ';
+
+ }
+
+
+ protected function input_checkbox($input) {
+
+ $checked = ( $input['value'] == true && $input['value'] !== '0' ) ? ' checked' : null;
+
+ echo '
+ <tr>
+ <td colspan="2">
+ <label class="selectit" for="' . $input['attr-id'] . '">
+ <input type="hidden" id="' . $input['attr-id'] . '-hidden" value="false" name="' . $input['attr-name']. '" />
+ <input type="checkbox" id="' . $input['attr-id'] . '" value="true" name="' . $input['attr-name']. '" class="check"' . $checked . ' /> ' . $input['name'] . '
+ </label>
+ </td>
+ </tr>';
+
+ }
+
+
+ protected function input_select($input) {
+
+ echo '
+ <tr>
+ <td>
+ <select id="' . $input['attr-id'] . '" name="' . $input['attr-name'] . '">';
+
+ if ( headway_get('blank-option', $input) )
+ echo '<option value="">' . headway_get('blank-option', $input) . '</option>';
+
+ foreach( $input['options'] as $value => $text ) {
+
+ $selected = $input['value'] === $value ? ' selected' : null;
+
+ echo '<option value="' . $value . '"' . $selected . '>' . $text . '</option>';
+
+ }
+
+ echo ' </select>
+ </td>
+ </tr>';
+
+ }
+
+
+ protected function input_radio($input) {
+
+ echo '
+ <tr>
+ <td colspan="2">';
+
+ $count = 0;
+
+ $options = array_keys($input['options']);
+
+ foreach($input['options'] as $value => $label) {
+
+ $count++;
+
+ $checked = ($input['value'] == $value ) ? ' checked="checked"' : null;
+
+ echo '
+ <input type="radio" id="' . $input['attr-id'] . '-' . $value . '" value="' . $value . '" name="' . $input['attr-name'] . '" class="check"' . $checked . ' />
+
+ <label class="selectit" for="' . $input['attr-id'] . '-' . $value . '">
+ ' . $label . '
+ </label>
+ ';
+
+ if ( $count !== count($input['options']) )
+ echo '<br />';
+
+ }
+
+ echo '
+ </td>
+ </tr>
+ ';
+
+ }
+
+
+ protected function input_pages($input) {
+
+ echo '
+ <tr>
+ <td>' .
+ wp_dropdown_pages(array(
+ 'selected' => $input['value'],
+ 'name' => $input['attr-name'],
+ 'id' => $input['attr-id'],
+ 'show_option_none' => ' ',
+ 'sort_column'=> 'menu_order, post_title',
+ 'echo' => false
+ )) . '
+ </td>
+ </tr>
+ ';
+
+ }
+
+
+}
\ No newline at end of file
--- /dev/null
+<?php
+/**
+ * Headway blocks API.
+ *
+ * @package Headway
+ * @subpackage API
+ **/
+function headway_register_block($class, $block_type_url = false) {
+
+ global $headway_unregistered_block_types;
+
+ if ( !is_array($headway_unregistered_block_types) )
+ $headway_unregistered_block_types = array();
+
+ $headway_unregistered_block_types[$class] = $block_type_url;
+
+ return true;
+
+}
+
+
+abstract class HeadwayBlockAPI {
+
+
+ public $id;
+
+ public $name;
+
+ public $block_type_url;
+
+ public $options_class = 'HeadwayBlockOptionsAPI';
+
+ public $fixed_height = false;
+
+ public $html_tag = 'div';
+
+ public $attributes = array();
+
+ public $description = false;
+
+ public $allow_titles = true;
+
+
+ /* System Properties (DO NOT USE OR TOUCH) */
+ protected $options;
+
+ protected $show_content_in_grid = false;
+
+
+ /* System Methods (DO NOT EXTEND OR MODIFY) */
+ public function register() {
+
+ global $headway_block_types;
+
+ //If the Headway blocks array doesn't exist, create it.
+ if ( !is_array($headway_block_types) )
+ $headway_block_types = array();
+
+ //Add block to array. This array will be used for checking if certain blocks exist, the block type selector and so on.
+ $headway_block_types[$this->id] = array(
+ 'name' => $this->name,
+ 'url' => $this->block_type_url,
+ 'class' => get_class($this),
+ 'fixed-height' => $this->fixed_height,
+ 'html-tag' => $this->html_tag,
+ 'attributes' => $this->attributes,
+ 'show-content-in-grid' => $this->show_content_in_grid,
+ 'allow-titles' => $this->allow_titles,
+ 'description' => $this->description
+ );
+
+ //Add the element for the block itself
+ add_action('headway_register_elements', array($this, 'setup_main_block_element'));
+
+ //Run init method if it exists
+ if ( method_exists($this, 'init') )
+ $this->init();
+
+ //Run setup_elements if it exists
+ if ( method_exists($this, 'setup_elements') )
+ add_action('headway_register_elements', array($this, 'setup_elements'));
+
+ //Setup hooks
+ if ( $this->allow_titles )
+ add_action('headway_block_content_' . $this->id, array($this, 'title_and_subtitle'));
+
+ add_action('headway_block_content_' . $this->id, array($this, 'content'));
+
+ add_action('headway_block_options_' . $this->id, array($this, 'options_panel'), 10, 2);
+
+ }
+
+
+ public function setup_main_block_element() {
+
+ HeadwayElementAPI::register_element(array(
+ 'group' => 'blocks',
+ 'id' => 'block-' . $this->id,
+ 'name' => $this->name,
+ 'selector' => '.block-type-' . $this->id,
+ 'properties' => array('background', 'borders', 'fonts', 'padding', 'corners', 'box-shadow', 'overflow'),
+ ));
+
+ if ( $this->allow_titles ) {
+
+ $this->register_block_element(array(
+ 'id' => 'block-title',
+ 'name' => 'Block Title',
+ 'selector' => '.block-title'
+ ));
+
+ $this->register_block_element(array(
+ 'id' => 'block-title-span',
+ 'name' => 'Block Title Inner',
+ 'parent' => 'block-title',
+ 'selector' => '.block-title span',
+ 'inspectable' => false
+ ));
+
+ $this->register_block_element(array(
+ 'id' => 'block-subtitle',
+ 'name' => 'Block Subtitle',
+ 'selector' => '.block-subtitle'
+ ));
+
+ }
+
+ }
+
+
+ public function options_panel($block, $layout) {
+
+ if ( !class_exists($this->options_class) )
+ return new WP_Error('block_options_class_does_not_exist', __('Error: The block options class being registered does not exist.', 'headway'), $this->options_class);
+
+ //Initiate options class
+ $options = new $this->options_class($this);
+ $options->display($block, $layout);
+
+ }
+
+
+ /* Methods to extend (you can modify these!) */
+ public function content($block) {
+
+ }
+
+
+ public function title_and_subtitle($block) {
+
+ if ( !$this->allow_titles )
+ return;
+
+ /* Output Block Titles */
+ if ( headway_get('original', $block) )
+ $block = headway_get('original', $block);
+
+ $block_title = headway_get('block-title', headway_get('settings', $block, array()));
+ $block_subtitle = headway_get('block-subtitle', headway_get('settings', $block, array()));
+
+ if ( $block_title || $block_subtitle ) {
+
+ /* Open hgroup if necessary */
+ if ( $block_title && $block_subtitle )
+ echo '<hgroup>';
+
+ /* Title */
+ if ( $block_title )
+ echo '<h1 class="block-title"><span>' . headway_fix_data_type($block_title) . '</span></h1>';
+
+ /* Subtitle */
+ if ( $block_subtitle )
+ echo '<h2 class="block-subtitle">' . headway_fix_data_type($block_subtitle) . '</h2>';
+
+ /* Close hgroup */
+ if ( $block_title && $block_subtitle )
+ echo '</hgroup>';
+
+ }
+
+ }
+
+
+ /**
+ * The following are commented out so they are not detected
+ *
+ * public static function init_action($block_id, $block) {
+ *
+ * }
+ *
+ *
+ * public static function enqueue_action($block_id, $block, $original_block = null) {
+ *
+ * }
+ *
+ *
+ * public static function dynamic_css($block_id, $block, $original_block = null) {
+ *
+ * }
+ *
+ *
+ * public static function dynamic_js($block_id, $block, $original_block = null) {
+ *
+ * }
+ *
+ **/
+
+
+ /* Methods to use, but not modify! */
+ public function register_block_element($args) {
+
+ /* Add the selector prefix to the selector and even handle commas */
+ $selector_prefix = '.block-type-' . $this->id . ' ';
+
+ $selector_array = explode(',', $args['selector']);
+
+ foreach ( $selector_array as $selector_index => $selector ) {
+
+ if ( strpos(trim($selector_array[$selector_index]), '.block-type-') === 0 )
+ continue;
+
+ $selector_array[$selector_index] = $selector_prefix . trim($selector);
+
+ }
+
+ $modified_selector = implode(',', $selector_array);
+ /* End Selector Modification */
+
+ $defaults = array(
+ 'group' => 'blocks',
+ 'parent' => 'block-' . $this->id,
+ 'id' => 'block-' . $this->id . '-' . $args['id'],
+ 'name' => $args['name'],
+ 'selector' => $modified_selector
+ );
+
+ //Unset the following so they don't overwrite the defaults
+ unset($args['id']);
+ unset($args['name']);
+ unset($args['selector']);
+
+ //If the parent isn't the default then put on block type prefix
+ if ( !empty($args['parent']) && $args['parent'] != 'block-' . $this->id )
+ $args['parent'] = 'block-' . $this->id . '-' . $args['parent'];
+
+ $element = array_merge($defaults, $args);
+
+ //Go through states and add the selector prefix to each state
+ if ( isset($element['states']) && is_array($element['states']) ) {
+
+ foreach ( $element['states'] as $state_name => $state_selector ) {
+
+ $state_selector_array = explode(',', $state_selector);
+
+ foreach ( $state_selector_array as $selector_index => $selector ) {
+
+ if ( strpos(trim($state_selector_array[$selector_index]), '.block-type-') === 0 )
+ continue;
+
+ $state_selector_array[$selector_index] = $selector_prefix . trim($selector);
+
+ }
+
+ $element['states'][$state_name] = trim(implode(',', $state_selector_array));
+
+ }
+
+ }
+
+ return HeadwayElementAPI::register_element($element);
+
+ }
+
+
+ public static function get_setting($block, $setting, $default = null) {
+
+ return HeadwayBlocksData::get_block_setting($block, $setting, $default);
+
+ }
+
+
+}
+
+
+class HeadwayBlockOptionsAPI extends HeadwayVisualEditorPanelAPI {
+
+
+ public $block_type_object;
+
+ public $block = false;
+
+ public $block_id = false;
+
+
+ public function __construct($block_type_object) {
+
+ /* Accept the block type as an argument that way its properties are available for use in this class */
+ $this->block_type_object = $block_type_object;
+
+ }
+
+
+ public function register() {
+
+ return true;
+
+ }
+
+
+ public function display($block, $layout) {
+
+ //Set block properties
+ $this->block = $block;
+
+ //Args for modify_arguments and block_content
+ $args = array(
+ 'block' => $this->block,
+ 'blockID' => $this->block['id'],
+ 'layoutID' => $this->block['layout'],
+
+ /* Backwards Compatibility */
+ 'block_id' => $this->block['id']
+ );
+
+ //Allow developers to modify the properties of the class and use functions since doing a property
+ //outside of a function will not allow you to.
+ $this->modify_arguments($args);
+
+ //Add the standard block tabs
+ $this->add_standard_block_config();
+ $this->add_standard_block_import_export();
+
+ if ( HeadwayResponsiveGrid::is_enabled() )
+ $this->add_standard_block_responsive();
+
+ //Display it
+ $this->panel_content($args);
+
+ }
+
+
+ public function add_standard_block_config() {
+
+ if ( !isset($this->tabs) )
+ $this->tabs = array();
+
+ if ( !isset($this->inputs) )
+ $this->inputs = array();
+
+ //Add the tab
+ $this->tabs['config'] = 'Config';
+
+ /* Add the inputs */
+
+ $this->inputs['config']['mirror-block'] = array(
+ 'type' => 'select',
+ 'name' => 'mirror-block',
+ 'label' => 'Mirror Block',
+ 'default' => '',
+ 'tooltip' => 'By using this option, you can tell a block to "mirror" another block and its content. This option is useful if you are wanting to share a block—such as a header—across layouts on your site. Select the block you wish to mirror the content from in the select box to the right.',
+ 'options' => 'get_blocks_select_options_for_mirroring()',
+ 'callback' => 'updateBlockMirrorStatus(input, block.id, value);',
+ 'value' => HeadwayBlocksData::is_block_mirrored($this->block)
+ );
+
+ $this->inputs['config']['alias'] = array(
+ 'type' => 'text',
+ 'name' => 'alias',
+ 'label' => 'Block Alias',
+ 'default' => '',
+ 'callback' => 'var $block = $i("#block-" + block.id); $block.data("alias", value); updateBlockContentCover($block);',
+ 'tooltip' => 'Enter an easily recognizable name for the block alias and it will be used throughout your site admin. For instance, if you add an alias to a widget area block, that alias will be used in the Widgets panel.',
+ );
+
+ if ( HeadwayResponsiveGrid::is_enabled() ) {
+
+ $this->inputs['config']['responsive-block-hiding'] = array(
+ 'type' => 'multi-select',
+ 'name' => 'responsive-block-hiding',
+ 'label' => 'Responsive Grid Block Hiding',
+ 'default' => '',
+ 'tooltip' => 'If you have the responsive grid enabled and the user views your website on an iPhone (or equivalent device), the grid may be cluttered do to so many blocks being in a small area. If you wish to limit the blocks that are shown on mobile devices, you can use this setting to hide certain blocks for the devices you choose. <strong>If no options are selected, then responsive block hiding will not be active for this block.</strong>',
+ 'options' => array(
+ 'smartphones' => 'iPhone/Smartphones',
+ 'tablets-landscape' => 'iPad/Tablets (Landscape)',
+ 'tablets-portrait' => 'iPad/Tablets (Portrait)',
+ 'computers' => 'Laptops & Desktops (Not Recommended)'
+ )
+ );
+
+ }
+
+ $this->inputs['config']['css-classes'] = array(
+ 'type' => 'text',
+ 'name' => 'css-classes',
+ 'label' => 'Custom CSS Class(es)',
+ 'default' => '',
+ 'tooltip' => 'Need more finite control? Enter the custom CSS class selectors here and they will be added to the block\'s class attribute. <strong>DO NOT</strong> put regular CSS in here. Use the Live CSS editor for that.',
+ );
+
+ $this->inputs['config']['css-classes-bubble'] = array(
+ 'type' => 'checkbox',
+ 'name' => 'css-classes-bubble',
+ 'label' => '<em style="color: #666; font-style: italic;">Advanced:</em> Add Custom CSS Class(es) to Row/Column',
+ 'default' => '',
+ 'tooltip' => 'Copy any custom CSS classes added to this block and add them to the parent row and column <section>\'s',
+ );
+
+ /* Titles */
+ if ( isset($this->block_type_object->allow_titles) && $this->block_type_object->allow_titles ) {
+
+ $this->inputs['config']['titles-heading'] = array(
+ 'name' => 'titles-heading',
+ 'type' => 'heading',
+ 'label' => 'Block Title'
+ );
+
+ $this->inputs['config']['block-title'] = array(
+ 'name' => 'block-title',
+ 'type' => 'text',
+ 'label' => 'Block Title',
+ 'tooltip' => 'Add a custom title above the block content.'
+ );
+
+ $this->inputs['config']['block-subtitle'] = array(
+ 'name' => 'block-subtitle',
+ 'type' => 'text',
+ 'label' => 'Block Subtitle',
+ 'tooltip' => 'Add a custom sub title above the block content and below the block title.'
+ );
+
+ }
+ /* End Titles */
+
+ }
+
+ public function add_standard_block_responsive() {
+
+ if ( !isset($this->tabs) )
+ $this->tabs = array();
+
+ if ( !isset($this->inputs) )
+ $this->inputs = array();
+
+ //Add the tab
+ $this->tabs['responsive'] = 'Responsive Control';
+
+ /* Add the inputs */
+ $this->inputs['responsive']['responsive-options'] = array(
+ 'type' => 'repeater',
+ 'name' => 'responsive-options',
+ 'label' => 'Configure Breakpoints.',
+ 'inputs' => array(
+
+ array(
+ 'type' => 'select',
+ 'name' => 'blocks-breakpoint',
+ 'label' => 'Set Breakpoint',
+ 'options' => array(
+ 'off' => 'Off - No Breakpoint',
+ 'custom' => 'Custom Width',
+ '1824px' => '1824px - Very Large Screens',
+ '1224px' => '1224px - Desktop and Laptop',
+ '1024px' => '1024px - Popular Tablet Landscape',
+ '768px' => '768px - Popular Tablet Portrait',
+ '600px' => '600px - Popular Breakpoint in Headway',
+ '568px' => '568px - iPhone 5 Landscape',
+ '480px' => '480px - iPhone 3 & 4 Landscape',
+ '320px' => '320px - iPhone 3 & 4 & 5 & Android Portrait'
+ ),
+ 'toggle' => array(
+ '' => array(
+ 'hide' => array(
+ '.input:not(#input-blocks-breakpoint)'
+ )
+ ),
+ 'off' => array(
+ 'hide' => array(
+ '.input:not(#input-blocks-breakpoint)'
+ )
+ ),
+ 'custom' => array(
+ 'show' => array(
+ '.input'
+ )
+ ),
+ '1824px' => array(
+ 'show' => array(
+ '.input:not(#input-max-width)'
+ ),
+ 'hide' => array(
+ '#input-max-width'
+ ),
+ ),
+ '1224px' => array(
+ 'show' => array(
+ '.input:not(#input-max-width)'
+ ),
+ 'hide' => array(
+ '#input-max-width'
+ ),
+ ),
+ '1024px' => array(
+ 'show' => array(
+ '.input:not(#input-max-width)'
+ ),
+ 'hide' => array(
+ '#input-max-width'
+ ),
+ ),
+ '768px' => array(
+ 'show' => array(
+ '.input:not(#input-max-width)'
+ ),
+ 'hide' => array(
+ '#input-max-width'
+ ),
+ ),
+ '600px' => array(
+ 'show' => array(
+ '.input:not(#input-max-width)'
+ ),
+ 'hide' => array(
+ '#input-max-width'
+ ),
+ ),
+ '568px' => array(
+ 'show' => array(
+ '.input:not(#input-max-width)'
+ ),
+ 'hide' => array(
+ '#input-max-width'
+ ),
+ ),
+ '480px' => array(
+ 'show' => array(
+ '.input:not(#input-max-width)'
+ ),
+ 'hide' => array(
+ '#input-max-width'
+ ),
+ ),
+ '320px' => array(
+ 'show' => array(
+ '.input:not(#input-max-width)'
+ ),
+ 'hide' => array(
+ '#input-max-width'
+ ),
+ )
+ ),
+ 'tooltip' => 'Select a screen width for these change to take effect.',
+ 'default' => ''
+ ),
+
+ array(
+ 'type' => 'text',
+ 'name' => 'max-width',
+ 'label' => 'Custom Width',
+ 'default' => ''
+ ),
+
+ array(
+ 'type' => 'select',
+ 'name' => 'breakpoint-min-or-max',
+ 'label' => 'Min or Max width',
+ 'options' => array(
+ 'min' => 'Min Width (applies to screens that are wider than breakpoint)',
+ 'max' => 'Max Width (applies to screens that are narrower than breakpoint)'
+ ),
+ 'default' => 'max'
+ ),
+
+ array(
+ 'name' => 'adaptive-heading',
+ 'type' => 'heading',
+ 'label' => 'Adaptive Options'
+ ),
+
+ array(
+ 'type' => 'checkbox',
+ 'name' => 'disable-block-height',
+ 'label' => 'Disable blocks height',
+ 'tooltip'=> 'Disable the height for smaller screens if the block displays too high for smaller screens',
+ 'default' => false
+ ),
+
+ array(
+ 'type' => 'checkbox',
+ 'name' => 'mobile-center-elements',
+ 'label' => 'Attempt to center block elements',
+ 'default' => false
+ ),
+
+ array(
+ 'type' => 'checkbox',
+ 'name' => 'griddify-lists',
+ 'label' => 'Griddify Lists',
+ 'default' => false,
+ 'tooltip' => 'Any kind of list, such as categories, latest posts, even menus etc work fine on large screens in the sidebar. But on smaller screens where the sidebar drops below the content. The lists can look empty due to mass of whitespace. This will put the list items into 2 columns side by side.'
+ ),
+
+ array(
+ 'type' => 'checkbox',
+ 'name' => 'hide-block',
+ 'label' => 'Hide this block',
+ 'default' => false,
+ 'tooltip' => 'This will hide this block for the set breakpoint.'
+ )
+
+ ),
+ 'sortable' => true,
+ 'limit' => false,
+ 'callback' => ''
+ );
+
+ $this->inputs['responsive']['responsive-block-hiding'] = array(
+ 'type' => 'multi-select',
+ 'name' => 'responsive-block-hiding',
+ 'label' => 'Legacy Responsive Grid Block Hiding',
+ 'default' => '',
+ 'tooltip' => 'If you have the responsive grid enabled and the user views your website on an iPhone (or equivalent device), the grid may be cluttered do to so many blocks being in a small area. If you wish to limit the blocks that are shown on mobile devices, you can use this setting to hide certain blocks for the devices you choose. <strong>If no options are selected, then responsive block hiding will not be active for this block.</strong>',
+ 'options' => array(
+ 'smartphones' => 'iPhone/Smartphones',
+ 'tablets-landscape' => 'iPad/Tablets (Landscape)',
+ 'tablets-portrait' => 'iPad/Tablets (Portrait)',
+ 'computers' => 'Laptops & Desktops (Not Recommended)'
+ )
+ );
+
+ }
+
+
+ public function add_standard_block_import_export() {
+
+ if ( !isset($this->tabs) )
+ $this->tabs = array();
+
+ if ( !isset($this->inputs) )
+ $this->inputs = array();
+
+ //Add the tab
+ $this->tabs['import-export'] = 'Import/Export';
+
+ /* Add the inputs */
+
+ $this->inputs['import-export']['import-heading'] = array(
+ 'name' => 'import-heading',
+ 'type' => 'heading',
+ 'label' => 'Import Block Settings'
+ );
+
+ $this->inputs['import-export']['block-import-settings-file'] = array(
+ 'type' => 'import-file',
+ 'name' => 'block-import-settings-file',
+ 'button-label' => 'Select File to Import',
+ 'no-save' => true
+ );
+
+ $this->inputs['import-export']['block-import-include-options'] = array(
+ 'type' => 'checkbox',
+ 'name' => 'block-import-settings-include-options',
+ 'label' => 'Include Block Options',
+ 'default' => true,
+ 'no-save' => true
+ );
+
+ $this->inputs['import-export']['block-import-include-design'] = array(
+ 'type' => 'checkbox',
+ 'name' => 'block-import-settings-include-design',
+ 'label' => 'Include Block Design',
+ 'default' => true,
+ 'no-save' => true
+ );
+
+ $this->inputs['import-export']['block-import-settings'] = array(
+ 'type' => 'button',
+ 'name' => 'block-import-settings',
+ 'button-label' => 'Import Block Settings',
+ 'no-save' => true,
+ 'callback' => 'initiateBlockSettingsImport(args);'
+ );
+
+ $this->inputs['import-export']['export-heading'] = array(
+ 'name' => 'export-heading',
+ 'type' => 'heading',
+ 'label' => 'Export Block Settings'
+ );
+
+ $this->inputs['import-export']['block-export-settings'] = array(
+ 'type' => 'button',
+ 'name' => 'block-export-settings',
+ 'button-label' => 'Download Export File',
+ 'no-save' => true,
+ 'callback' => 'exportBlockSettingsButtonCallback(args);'
+ );
+
+ }
+
+
+ public function get_blocks_select_options_for_mirroring() {
+
+ $block_type = $this->block['type'];
+
+ $blocks = HeadwayBlocksData::get_blocks_by_type($block_type);
+
+ $options = array('' => '– Do Not Mirror –');
+
+ //If there are no blocks, then just return the Do Not Mirror option.
+ if ( !isset($blocks) || !is_array($blocks) )
+ return $options;
+
+ foreach ( $blocks as $block_id => $block ) {
+
+ //If the block is mirrored, skip it
+ if ( HeadwayBlocksData::is_block_mirrored($block) )
+ continue;
+
+ /* Do not show block that's in a mirrored wrapper */
+ if ( HeadwayWrappersData::is_wrapper_mirrored(HeadwayWrappersData::get_wrapper(headway_get('wrapper_id', $block))) )
+ continue;
+
+ //Create the default name by using the block type and ID
+ $default_name = HeadwayBlocks::block_type_nice($block['type']);
+
+ //If we can't get a name for the layout, then things probably aren't looking good. Just skip this block.
+ if ( !($layout_name = HeadwayLayout::get_name($block['layout'])) )
+ continue;
+
+ //Make sure the block exists
+ if ( !HeadwayBlocksData::block_exists($block['id']) )
+ continue;
+
+ $current_layout_suffix = ( $this->block['layout'] == $block['layout'] ) ? ' (Warning: Same Layout)' : null;
+
+ //Get alias if it exists, otherwise use the default name
+ $options[$block['id']] = headway_get('alias', $block['settings'], $default_name) . ' – ' . $layout_name . $current_layout_suffix;
+
+ }
+
+ //Remove the current block from the list
+ unset($options[$this->block['id']]);
+
+ return $options;
+
+ }
+
+
+}
\ No newline at end of file
--- /dev/null
+<?php
+function headway_register_visual_editor_box($class) {
+
+ add_action('headway_visual_editor_display_init', create_function('', 'return headway_register_visual_editor_box_callback(\'' . $class . '\');'));
+
+}
+
+
+function headway_register_visual_editor_box_callback($class) {
+
+ if ( !class_exists($class) )
+ return new WP_Error('box_class_does_not_exist', __('Error: The box class being registered does not exist.', 'headway'), $class);
+
+ $box = new $class();
+ $box->register();
+
+ return true;
+
+}
+
+
+abstract class HeadwayVisualEditorBoxAPI {
+
+
+ /**
+ * Slug/ID of panel. Will be used for HTML IDs and whatnot.
+ **/
+ protected $id;
+
+
+ /**
+ * Name of panel. This will be shown in the title.
+ **/
+ protected $title;
+
+ protected $description = false;
+
+
+ /**
+ * Which mode to put the panel on.
+ **/
+ protected $mode = 'all';
+
+ protected $width = 500;
+
+ protected $height = 300;
+
+ protected $center = true;
+
+ protected $closable = true;
+
+ protected $draggable = true;
+
+ protected $resizable = false;
+
+ protected $min_width = 500;
+
+ protected $min_height = 300;
+
+ protected $black_overlay = false;
+
+ protected $black_overlay_opacity = 0.6;
+
+ protected $black_overlay_iframe = false;
+
+ protected $load_with_ajax = false;
+
+ protected $load_with_ajax_callback = false;
+
+
+ /**
+ * Register the panel.
+ *
+ * @param string Name of panel to be displayed
+ * @param string ID of panel for HTML and options
+ **/
+ public function register() {
+
+ global $headway_registered_ve_boxes;
+
+ if ( !isset($headway_registered_ve_boxes) )
+ $headway_registered_ve_boxes = array();
+
+ if ( in_array($this->id, $headway_registered_ve_boxes) )
+ return false;
+
+ $mode = HeadwayVisualEditor::get_current_mode();
+
+ if ( $this->mode === 'all' || strtolower($this->mode) === strtolower($mode) )
+ add_action('headway_visual_editor_boxes', array($this, 'build_box'));
+
+ if ( $this->load_with_ajax )
+ add_action('headway_visual_editor_ajax_box_content_' . $this->id, array($this, 'content'));
+
+ $headway_registered_ve_boxes[] = $this->id;
+
+ }
+
+
+ public function build_box() {
+
+ $attributes = array(
+ 'class' => 'box',
+ 'id' => 'box-' . $this->id,
+ 'width' => $this->width,
+ 'height' => $this->height,
+ 'center' => $this->center,
+ 'closable' => $this->closable,
+ 'draggable' => $this->draggable,
+ 'resizable' => $this->resizable,
+ 'min_width' => $this->min_width,
+ 'min_height' => $this->min_height,
+ 'black_overlay' => $this->black_overlay,
+ 'black_overlay_opacity' => $this->black_overlay_opacity,
+ 'black_overlay_iframe' => $this->black_overlay_iframe,
+ 'load_with_ajax' => $this->load_with_ajax,
+ 'load_with_ajax_callback' => esc_attr('(function(args){' . $this->load_with_ajax_callback . '})')
+ );
+
+ $attributes_string = '';
+
+ foreach ( $attributes as $attribute => $value )
+ $attributes_string .= $attribute . '="' . $value . '" ';
+
+ echo '<div ' . trim($attributes_string) . '>';
+
+ echo '<div class="box-top">';
+
+ echo '<strong>' . $this->title . '</strong>';
+
+ if ( $this->description ) {
+
+ echo '<span>' . $this->description . '</span>';
+
+ }
+
+ echo '</div>';
+
+ echo '<div class="box-content">';
+
+ if ( !$this->load_with_ajax )
+ $this->content();
+
+ echo '</div>';
+
+ echo '</div><!-- div#box-' . $this->id . ' -->';
+
+ }
+
+
+ public function content() {
+
+ }
+
+
+}
\ No newline at end of file
--- /dev/null
+<?php
+class HeadwayChildThemeAPI {
+
+
+ public static function init() {
+
+ /* Set the HEADWAY_CHILD_THEME_ID constant to the stylesheet option if it hasn't been set. */
+ if ( !defined('HEADWAY_CHILD_THEME_ID') )
+ define('HEADWAY_CHILD_THEME_ID', get_option('stylesheet'));
+
+ }
+
+
+ public static function register_block_style(array $args) {
+
+ return _deprecated_function(__FUNCTION__, '3.7');
+
+ }
+
+
+ public static function get_block_style_classes() {
+
+ return _deprecated_function(__FUNCTION__, '3.7');
+
+ }
+
+
+}
\ No newline at end of file
--- /dev/null
+<?php
+class HeadwayElementAPI {
+
+
+ protected static $elements = array();
+
+ protected static $groups = array();
+
+
+ public static function init() {
+
+ add_action('headway_visual_editor_ajax_pre_get_design_editor_elements', array(__CLASS__, 'register_elements_hook'));
+ add_action('headway_visual_editor_ajax_pre_get_design_editor_elements', array(__CLASS__, 'register_elements_instances_hook'));
+
+ add_action('headway_before_get_block_styling', array(__CLASS__, 'register_elements_hook'));
+ add_action('headway_before_get_block_styling', array(__CLASS__, 'register_elements_instances_hook'));
+
+ add_action('headway_dynamic_style_design_editor_init', array(__CLASS__, 'register_elements_hook'));
+ add_action('headway_dynamic_style_design_editor_init', array(__CLASS__, 'register_elements_instances_hook'));
+
+ }
+
+
+ public static function register_elements_hook() {
+
+ if ( did_action('headway_register_elements') )
+ return;
+
+ //Add a central action where we can register all elements to. This will be performance increase in the long run
+ //since elements will only be registered when they need to be.
+ do_action('headway_register_elements');
+
+ }
+
+
+ public static function register_elements_instances_hook() {
+
+ if ( did_action('headway_register_elements_instances') )
+ return;
+
+ //Add a central action where we can register all elements to. This will be performance increase in the long run
+ //since elements will only be registered when they need to be.
+ do_action('headway_register_elements_instances');
+
+ }
+
+
+ public static function get_all_elements() {
+
+ return self::$elements;
+
+ }
+
+
+ public static function get_groups() {
+
+ return self::$groups;
+
+ }
+
+
+ public static function get_element($element) {
+
+ return headway_get($element, self::$elements);
+
+ }
+
+
+ public static function get_block_elements($block_type) {
+
+ $children = array();
+
+ foreach ( self::get_all_elements() as $element_id => $element_info ) {
+
+ if ( empty($element_info['parent']) || strpos($element_info['parent'], 'block-' . $block_type) !== 0 )
+ continue;
+
+ $children[$element_id] = $element_info;
+
+ }
+
+ return $children;
+
+ }
+
+
+ public static function get_instances($element) {
+
+ if ( !is_array($element) )
+ $element = self::get_element($element);
+
+ return isset($element['instances']) ? $element['instances'] : false;
+
+ }
+
+
+ public static function get_states($element) {
+
+ if ( !is_array($element) )
+ $element = self::get_element($element);
+
+ return isset($element['states']) ? $element['states'] : false;
+
+ }
+
+
+ public static function register_element($args) {
+
+ if ( !is_array($args) )
+ return new WP_Error('hw_elements_register_element_args_not_array', __('Error: Arguments must be an array for this element.', 'headway'), $args);
+
+ $defaults = array(
+ 'group' => null,
+ 'parent' => null,
+ 'id' => null,
+ 'name' => null,
+ 'selector' => null,
+ 'properties' => array('fonts', 'background', 'borders', 'padding', 'corners', 'box-shadow'),
+ 'states' => array(),
+ 'instances' => array(),
+ 'default-element' => false,
+ 'supports-instances' => true,
+ 'inspectable' => true
+ );
+
+ $item = array_merge($defaults, $args);
+
+ //If the element is set to default, change the group to default
+ if ( $item['default-element'] === true )
+ $item['group'] = 'default-elements';
+
+ //If requirements are not met, throw errors
+ if ( !$item['id'] )
+ return new WP_Error('hw_elements_register_element_no_id', __('Error: An ID is required for this element.', 'headway'), $item);
+
+ if ( !$item['name'] )
+ return new WP_Error('hw_elements_register_element_no_name', __('Error: A name is required for this element.', 'headway'), $item);
+
+ if ( $item['group'] === null && $item['default-element'] === false )
+ return new WP_Error('hw_elements_register_element_no_group', __('Error: A group is required for this element.', 'headway'), $item);
+
+ if ( $item['selector'] === null && $item['default-element'] === false )
+ return new WP_Error('hw_elements_register_element_no_selector', __('Error: A CSS selector is required for this element.', 'headway'), $item);
+
+ if ( $item['properties'] === array() )
+ return new WP_Error('hw_elements_register_element_no_properties', __('Error: Properties are required for this element.', 'headway'), $item);
+
+ //Add the guts
+ $destination =& self::$elements[$item['id']];
+ $destination = $item;
+
+ //Remove the empty options
+ if ( $destination['parent'] === null )
+ unset($destination['parent']);
+
+ if ( $destination['states'] === array() ) {
+ unset($destination['states']);
+
+ /* Format states array */
+ } else {
+
+ $unformated_states_array = $destination['states'];
+ $destination['states'] = array();
+
+ foreach ( $unformated_states_array as $state_name => $state_selector ) {
+
+ $destination['states'][strtolower($state_name)] = array(
+ 'name' => $state_name,
+ 'id' => strtolower($state_name),
+ 'selector' => $state_selector
+ );
+
+ }
+
+ }
+
+ if ( $destination['instances'] === array() )
+ unset($destination['instances']);
+
+ //The element is now registered!
+ return $destination;
+
+ }
+
+
+ public static function register_element_instance($args) {
+
+ if ( !is_array($args) )
+ return new WP_Error('hw_elements_register_element_instance_args_not_array', __('Error: Arguments must be an array for this element instance.', 'headway'), $args);
+
+ $defaults = array(
+ 'group' => null,
+ 'element' => null,
+ 'id' => null,
+ 'name' => null,
+ 'selector' => null,
+ 'layout' => null,
+ 'state-of' => null
+ );
+
+ $item = array_merge($defaults, $args);
+
+ //If requirements are not met, throw errors
+ if ( !$item['id'] )
+ return new WP_Error('hw_elements_register_element_instance_no_id', __('Error: An ID is required for this element instance.', 'headway'), $item);
+
+ if ( !$item['name'] )
+ return new WP_Error('hw_elements_register_element_instance_no_name', __('Error: A name is required for this element instance.', 'headway'), $item);
+
+ if ( $item['group'] === null )
+ return new WP_Error('hw_elements_register_element_instance_no_group', __('Error: A group is required for this element instance.', 'headway'), $item);
+
+ if ( $item['element'] === null )
+ return new WP_Error('hw_elements_register_element_instance_no_parent', __('Error: A parent element is required for this element instance.', 'headway'), $item);
+
+ if ( $item['selector'] === null )
+ return new WP_Error('hw_elements_register_element_instance_no_selector', __('Error: A CSS selector is required for this element instance.', 'headway'), $item);
+
+ //If layout is set, then set layout-name as well
+ if ( $item['layout'] )
+ $item['layout-name'] = HeadwayLayout::get_name($item['layout']);
+
+ //Figure out where the element will go in the elements array
+ if ( isset(self::$elements[$item['element']]) )
+ $destination =& self::$elements[$item['element']];
+ else
+ return false;
+
+ //Make sure that the element supports instances
+ if ( !headway_get('supports-instances', $destination) )
+ return false;
+
+ $destination =& $destination['instances'][$item['id']];
+
+ //Add the guts
+ $destination = $item;
+
+ //Remove the extra options
+ unset($destination['element']);
+ unset($destination['group']);
+
+ //The element instance is now registered!
+ return $destination;
+
+ }
+
+
+ public static function register_group($id, $info) {
+
+ //Group already exists
+ if ( isset(self::$groups[$id]) )
+ return new WP_Error('hw_elements_register_group_already_exists', __('Error: The group being registered already exists.', 'headway'), $id);
+
+ /* Groups now accept both name and description in form of array @since 3.7 so we need backwards compatibility */
+ if ( is_string($info) ) {
+
+ $info = array(
+ 'name' => $info
+ );
+
+ }
+
+ //Place group in groups array so we can track name and description
+ self::$groups[$id] = $info;
+
+ return true;
+
+ }
+
+
+}
\ No newline at end of file
--- /dev/null
+<?php
+function headway_register_visual_editor_panel($class) {
+
+ add_action('headway_visual_editor_display_init', create_function('', 'return headway_register_visual_editor_panel_callback(\'' . $class . '\');'), 999);
+
+}
+
+
+function headway_register_visual_editor_panel_callback($class) {
+
+ if ( !class_exists($class) )
+ return new WP_Error('panel_class_does_not_exist', __('Error: The panel class being registered does not exist.', 'headway'), $class);
+
+ $panel = new $class();
+ $panel->register();
+
+ return true;
+
+}
+
+
+abstract class HeadwayVisualEditorPanelAPI {
+
+
+ /**
+ * Slug/ID of panel. Will be used for HTML IDs and whatnot.
+ **/
+ public $id;
+
+
+ /**
+ * Name of panel. This will be shown in the tabs.
+ **/
+ public $name;
+
+
+ /**
+ * Sub tabs. This is not always used.
+ **/
+ public $tabs;
+
+
+ /**
+ * Inputs. This is not always used.
+ **/
+ public $inputs;
+
+
+ /**
+ * Which mode to display the panel on.
+ **/
+ public $mode;
+
+
+ /**
+ * Which options group to save in by default
+ **/
+ public $options_group = 'general';
+
+
+ /**
+ * Will fire when the panel is opened via AJAX
+ **/
+ public $open_js_callback = null;
+
+
+
+ /**
+ * Register the panel.
+ *
+ * @param string Name of panel to be displayed
+ * @param string ID of panel for HTML and options
+ **/
+ public function register() {
+
+ $mode = HeadwayVisualEditor::get_current_mode();
+
+ /* Forward old Manage panels to Design */
+ if ( $this->mode == 'manage' )
+ $this->mode = 'design';
+
+ if ( strtolower($this->mode) !== strtolower($mode) )
+ return false;
+
+ /* Since there is a message that's displayed if there is no panel content, we have to tell it not to display the message now that
+ * we're registering a panel */
+ remove_action('headway_visual_editor_panel_top_tabs', array('HeadwayVisualEditorDisplay', 'add_default_panel_link'));
+ remove_action('headway_visual_editor_content', array('HeadwayVisualEditorDisplay', 'add_default_panel'));
+
+ add_action('headway_visual_editor_panel_top_tabs', array($this, 'panel_link'));
+ add_action('headway_visual_editor_content', array($this, 'build_panel'));
+
+ if ( method_exists($this, 'init') )
+ $this->init();
+
+ }
+
+
+ public function modify_arguments($args) {
+
+ //Allow developers to modify the properties of the class and use functions since doing a property
+ //outside of a function will not allow you to.
+
+ }
+
+
+ public function parse_function_args($array) {
+
+ if ( !is_array($array) || count($array) === 0 )
+ return $array;
+
+ foreach ( $array as $key => $value ) {
+
+ if ( !is_string($value) )
+ continue;
+
+ //Check if it's a function
+ if ( preg_match("/^[a-z0-9_]*(\(\))$/", $value) ) {
+ $array[$key] = call_user_func(array($this, str_replace('()', '', $value)));
+ } else {
+ continue;
+ }
+
+ }
+
+ return $array;
+
+ }
+
+
+ public function panel_link() {
+
+ echo '<li><a href="#' . $this->id . '-tab">' . $this->name . '</a></li>';
+
+ }
+
+
+ public function build_panel($id) {
+
+ $class = ($this->tabs) ? ' sub-tab' : null;
+
+ echo '<div id="' . $this->id . '-tab" class="panel' . $class . '">';
+
+ //Allow developers to modify the properties of the class and use functions since doing a property
+ //outside of a function will not allow you to.
+ $this->modify_arguments(array());
+
+ $this->panel_content();
+
+ echo '</div>';
+
+
+ }
+
+
+ public function panel_content($args = false) {
+
+ if ( $this->tabs && $this->inputs ) {
+
+ echo '<ul class="sub-tabs" data-open-js-callback="' . esc_attr('(function(args){' . $this->open_js_callback . '})') . '">';
+
+ foreach ($this->tabs as $id => $name) {
+
+ echo '<li id="sub-tab-' . $id . '"><a href="#sub-tab-' . $id . '-content">' . $name . '</a></li>';
+
+ }
+
+ echo '</ul>';
+
+ echo '<div class="sub-tabs-content-container" data-panel-args="' . esc_attr(json_encode($args)) . '">';
+
+ foreach ($this->tabs as $id => $name) {
+
+ echo '<div class="sub-tabs-content" id="sub-tab-' . $id . '-content">';
+
+ //Display notice for tab if one exists.
+ if ( isset($this->tab_notices[$id]) )
+ echo '<div class="sub-tab-notice">' . $this->tab_notices[$id] . '</div>';
+
+ $this->sub_tab_content($id, $name);
+
+ echo '</div><!-- div#sub-tab-' . $id . '-content -->';
+
+ }
+
+ echo '</div><!-- .sub-tabs-content-container -->';
+
+ }
+
+ }
+
+
+ public function sub_tab_content($id, $name = false) {
+
+ $this->create_inputs($id);
+
+ }
+
+
+ public function create_inputs($tab) {
+
+ if ( isset($this->inputs[$tab]) && is_array($this->inputs[$tab]) ) {
+
+ foreach ( $this->inputs[$tab] as $name => $input )
+ $this->render_input($input);
+
+ }
+
+ }
+
+
+ public function render_input($input) {
+
+ //Fill defaults
+ $defaults = array(
+ 'tooltip' => false,
+ 'default' => false,
+ 'callback' => null
+ );
+
+ //Merge defaults
+ $input = array_merge($defaults, $input);
+
+ //Fix up inputs
+ $input = $this->parse_function_args($input);
+
+ if ( !isset($input['name']) || !isset($input['type']) )
+ return;
+
+ /* Set up main input variables */
+ $input['name'] = strtolower($input['name']);
+ $input['group'] = ( isset($input['group']) ) ? $input['group'] : $this->options_group;
+ $input['tooltip'] = (isset($input['tooltip']) && $input['tooltip'] != false) ? $input['tooltip'] : false;
+
+ /* Populate the value */
+ $input['default'] = ( isset($input['default']) ) ? $input['default'] : null;
+
+ if ( isset($this->wrapper) && $this->wrapper && !isset($input['value']) )
+ $input['value'] = HeadwayWrappersData::get_wrapper_setting($this->wrapper, $input['name'], $input['default']);
+ else if ( isset($this->block) && $this->block && !isset($input['value']) )
+ $input['value'] = HeadwayBlocksData::get_block_setting($this->block, $input['name'], $input['default']);
+ else if ( !isset($input['value']) && headway_get('template-option', $input, true) )
+ $input['value'] = HeadwaySkinOption::get($input['name'], $input['group'], $input['default']);
+ else if ( !isset($input['value']) )
+ $input['value'] = HeadwayOption::get($input['name'], $input['group'], $input['default']);
+
+ /* Setup Attributes */
+ $attributes_array = array(
+ 'id' => (isset($this->block) && $this->block) ? 'input-' . $this->block['id'] . '-' . $input['name'] : 'input-' . $input['group'] . '-' . $input['name'],
+ 'name' => $input['name'],
+ 'data-group' => $input['group']
+ );
+
+ /* Set up the callback attribute */
+ $attributes_array['data-callback'] = esc_attr('(function(args){var input=args.input;var value=args.value;var block=args.block || null;' . $input['callback'] . '})');
+
+ /* Set up data handler override if it's used */
+ if ( headway_get('data-handler-callback', $input) )
+ $attributes_array['data-data-handler-callback'] = esc_attr('(function(args){' . $input['data-handler-callback'] . '})');
+
+ /* Set up toggle attribute */
+ if ( headway_get('toggle', $input) )
+ $attributes_array['data-toggle'] = esc_attr(json_encode($input['toggle']));
+
+ /* No save attribute */
+ if ( headway_get('no-save', $input, false) )
+ $attributes_array['data-no-save'] = 'true';
+
+ /* Turn attributes array into a string for HTML */
+ $input['attributes'] = '';
+
+ foreach ( $attributes_array as $attribute => $attribute_value )
+ $input['attributes'] .= $attribute . '="' . $attribute_value . '" ';
+
+ $input['attributes'] = trim($input['attributes']);
+
+ /* If it's a repeater then handle it before it's handled as an input */
+ if ( $input['type'] == 'repeater' )
+ return $this->repeater($input);
+
+ /* Handle regular input */
+ if ( method_exists($this, 'input_' . str_replace('-', '_', $input['type'])) ) {
+
+ /* Handle all types except for raw HTML input */
+ if ( $input['type'] != 'raw-html' ) {
+
+ echo '<div class="input input-' . $input['type'] . '" id="input-' . $input['name'] . '">';
+
+ if ( $input['tooltip'] )
+ echo '<div class="tooltip-button" title="' . esc_attr($input['tooltip']) . '"></div>';
+
+ call_user_func(array($this, 'input_' . str_replace('-', '_', $input['type'])), $input);
+
+ echo '</div><!-- #input-' . $input['name'] . ' -->';
+
+ } else {
+
+ call_user_func(array($this, 'input_' . str_replace('-', '_', $input['type'])), $input);
+
+ }
+
+ }
+ /* End regular input handling */
+
+ }
+
+
+ public function repeater($input) {
+
+ $repeater_sortable_class = headway_get('sortable', $input) ? ' repeater-sortable' : null;
+
+ echo '<div class="repeater' . $repeater_sortable_class . '" data-repeater-limit="' . headway_get('limit', $input, '0') . '">';
+
+ if ( $repeater_label = headway_get('label', $input) ) {
+
+ $this->render_input(array(
+ 'name' => 'repeater-' . $input['name'] . '-heading',
+ 'type' => 'heading',
+ 'label' => $repeater_label,
+ 'tooltip' => headway_get('tooltip', $input)
+ ));
+
+ }
+
+ /* If the value is non-existent then show an empty group. */
+ if ( !isset($input['value']) || !is_array($input['value']) || empty($input['value']) ) {
+
+ $this->repeater_group(array_merge($input, array(
+ 'single' => true
+ )));
+
+ /* Values are valid, loop them. */
+ } else {
+
+ foreach ( $input['value'] as $group_index => $value_group ) {
+
+ if ( count($input['value']) === 1 ) {
+ $input['single'] = true;
+ }
+
+ $this->repeater_group( $input, $group_index );
+
+ }
+
+ }
+
+ /* Add the template repeater group that's cloned when a new group is added */
+ $this->repeater_group(array_merge($input, array(
+ 'template' => true,
+ 'value' => null
+ )));
+
+ /* Hidden Input */
+ echo '<input ' . $input['attributes'] . ' type="hidden" value="" class="repeater-group-input" />';
+
+ echo '</div><!-- .repeater -->';
+
+ }
+
+
+ public function repeater_group($input, $group_index = null) {
+
+ $classes = array('repeater-group');
+
+ if ( headway_get('template', $input) )
+ $classes[] = 'repeater-group-template';
+
+ if ( headway_get('single', $input) )
+ $classes[] = 'repeater-group-single';
+
+ echo '<div class="' . implode(' ', $classes) . '">';
+
+ if ( headway_get('sortable', $input) )
+ echo '<span class="sortable-handle"><span></span><span></span><span></span></span>';
+
+ foreach ( $input['inputs'] as $index => $input_options ) {
+
+ $input_value = headway_get($input_options['name'], $input['value'][$group_index], headway_get('default', $input_options));
+
+ $this->render_input(array_merge($input_options, array(
+ 'value' => $input_value
+ )));
+
+ }
+
+ echo '<div class="repeater-group-buttons">';
+ echo '<span class="remove-group"></span>';
+ echo '<span class="add-group"></span>';
+ echo '</div><!-- .repeater-group-buttons -->';
+
+ echo '</div><!-- .repeater-group -->';
+
+ }
+
+
+ public function input_checkbox($input) {
+
+ $checked_attribute = ( (bool)headway_fix_data_type($input['value']) === true ) ? ' checked="checked"' : null;
+
+ echo '
+ <div class="input-left">
+ <label>
+ <input ' . $input['attributes'] . ' type="checkbox" value="true"' . $checked_attribute . ' />
+ ' . $input['label'] . '
+ </label>
+ </div>
+ ';
+
+ }
+
+
+ public function input_text($input) {
+
+ $readonly = ( isset($input['readonly']) && $input['readonly'] === true ) ? ' disabled' : null;
+
+ echo '
+ <div class="input-left">
+ <label>' . $input['label'] . '</label>
+ </div>
+
+ <div class="input-right">
+ <input type="text" ' . $input['attributes'] . ' placeholder="' . stripslashes(esc_attr(headway_get('placeholder', $input))) . '" value="' . stripslashes(esc_attr($input['value'])) . '" class="text"' . $readonly . ' />';
+
+ if ( isset($input['suffix']) ) echo '<span class="suffix">' . $input['suffix'] . '</span>';
+
+ echo '
+ </div>
+ ';
+
+ }
+
+
+ public function input_textarea($input) {
+
+ echo '
+ <div class="input-left">
+ <label>' . $input['label'] . '</label>
+ </div>
+
+ <div class="input-right">
+ <span class="textarea-open pencil-icon tooltip" title="View Textarea"></span>
+ <div class="textarea-container">
+ <textarea ' . $input['attributes'] . '>' . stripslashes(esc_textarea($input['value'])) . '</textarea>
+ </div>
+ </div>
+ ';
+
+ }
+
+
+ public function input_wysiwyg($input) {
+
+ echo '
+ <div class="input-left">
+ <label>' . $input['label'] . '</label>
+ </div>
+
+ <div class="input-right">
+ <span class="wysiwyg-open pencil-icon tooltip" title="View Editor"></span>
+ <div class="wysiwyg-container">
+ <textarea ' . $input['attributes'] . '>' . stripslashes(esc_textarea($input['value'])) . '</textarea>
+ </div>
+ </div>
+ ';
+
+ }
+
+
+ public function input_integer($input) {
+
+ $readonly = ( isset($input['readonly']) && $input['readonly'] === true ) ? ' disabled' : null;
+
+ echo '<div class="input-left">
+ <label>' . $input['label'] . '</label>
+ </div>
+
+ <div class="input-right">
+ <input type="text" ' . $input['attributes'] . ' value="' . (int)$input['value'] . '" class="text"'. $readonly .' />';
+
+ if ( isset($input['unit']) ) echo '<span class="suffix">' . $input['unit'] . '</span>';
+
+ echo '
+ </div>
+ ';
+
+ }
+
+
+ public function input_select($input) {
+
+ echo '
+ <div class="input-left">
+ <label>' . $input['label'] . '</label>
+ </div>
+ ';
+
+
+ echo '<div class="input-right">';
+
+ echo '<div class="select-container"><select ' . $input['attributes'] . '>';
+
+ foreach($input['options'] as $value => $text) {
+
+ $selected = ( $input['value'] == $value ) ? ' selected' : null;
+
+ echo '<option value="' . $value . '"' . $selected . '>' . $text . '</option>';
+
+ }
+
+ echo '</select></div><!-- .select-container -->';
+
+ echo '</div>';
+
+ }
+
+
+ public function input_multi_select($input) {
+
+ echo '
+ <div class="input-left">
+ <label>' . $input['label'] . '</label>
+ </div>
+ ';
+
+ echo '<div class="input-right">';
+
+ echo '<span class="multi-select-open pencil-icon tooltip" title="View Options"></span>';
+ echo '<div class="multi-select-container">';
+
+ echo '<select ' . $input['attributes'] . ' multiple="multiple" class="tooltip" title="Hold Ctrl (Windows) or Command (Mac) to select multiple options.">';
+
+ foreach ( $input['options'] as $value => $text ) {
+
+ $selected = ( is_array($input['value']) && in_array($value, $input['value']) ) ? ' selected' : null;
+
+ echo '<option title="' . $text . '" value="' . $value . '"' . $selected . '>' . $text . '</option>';
+
+ }
+
+ echo '</select>';
+
+ echo '</div><!-- .multi-select-container -->';
+
+ echo '</div>';
+
+ }
+
+
+ public function input_colorpicker($input) {
+
+ $input['value'] = headway_format_color($input['value']);
+
+ echo '
+ <div class="input-left">
+ <label>' . $input['label'] . '</label>
+ </div>
+
+ <div class="input-right">
+ <div class="colorpicker-box-container">
+ <div class="colorpicker-box-transparency"></div>
+ <div class="colorpicker-box" style="background-color:' . $input['value'] . ';"></div>
+ </div><!-- .colorpicker-box-container -->
+
+ <input ' . $input['attributes'] . ' type="hidden" value="' . $input['value'] . '" />
+ </div>
+ ';
+
+ }
+
+
+ public function input_image($input) {
+
+ $src_visibility = ( $input['value'] !== null && is_string($input['value']) ) ? '' : ' style="display:none;"';
+
+ echo '<div class="input-left"><label>' . $input['label'] . '</label></div><!-- .input-left -->';
+
+ $filepath = explode('/', $input['value']);
+ $filename = end($filepath);
+
+ echo '<div class="input-right"><span class="src"' . $src_visibility . '>' . $filename . '</span>
+ <span class="delete-image"' . $src_visibility . '>Delete</span>';
+
+ echo '<span class="button">Choose Image</span>
+ <input ' . $input['attributes'] . ' type="hidden" value="' . $input['value'] . '" /></div><!-- .input-right -->';
+
+ }
+
+
+ public function input_slider($input) {
+
+ $input['slider-interval'] = (isset($input['slider-interval'])) ? $input['slider-interval'] : 1;
+
+ echo '<div class="input-left">
+ <label>' . $input['label'] . '</label>
+ </div><!-- .input-left -->
+
+ <div class="input-right">
+ <div class="input-slider-bar" slider_min="' . $input['slider-min'] . '" slider_max="' . $input['slider-max'] . '" slider_interval="' . $input['slider-interval'] . '"></div><!-- .input-slider-bar -->
+
+ <div class="input-slider-bar-text">
+
+ <input type="number" value="' . $input['value'] . '" ' . $input['attributes'] . ' class="input-slider-bar-input" min="' . $input['slider-min'] . '" max="' . $input['slider-max'] . '" step="' . $input['slider-interval'] . '" pattern="\d*" />';
+
+ if ( isset($input['unit']) && $input['unit'] !== false ) echo '<span class="slider-unit">' . $input['unit'] . '</span>';
+
+ echo '</div><!-- .input-slider-bar-text -->';
+ echo '</div><!-- .input-right -->';
+
+ echo '<input type="hidden" value="' . $input['value'] . '" ' . $input['attributes'] . ' class="input-slider-bar-hidden" />';
+
+ }
+
+
+ public function input_heading($input) {
+
+ echo '
+ <h3 class="options-heading">' . $input['label'] . '</h3>
+ ';
+
+ }
+
+
+ public function input_notice($input) {
+
+ echo '<div class="sub-tab-notice">' . $input['notice'] . '</div>';
+
+ }
+
+
+ public function input_raw_html($input) {
+
+ echo $input['html'];
+
+ }
+
+
+ public function input_button($input) {
+
+ if ( isset($input['label']) && !empty($input['label']) ) {
+
+ echo '<div class="input-left">
+ <label>' . $input['label'] . '</label>
+ </div><!-- .input-left -->';
+
+ }
+
+ echo '<div class="input-right">
+ <span class="button" ' . $input['attributes'] . '>' . $input['button-label'] . '</span>
+ </div><!-- .input-right -->';
+
+ }
+
+
+ public function input_import_file($input) {
+
+ if ( isset($input['label']) && !empty($input['label']) ) {
+
+ echo '<div class="input-left">
+ <label>' . $input['label'] . '</label>
+ </div><!-- .input-left -->';
+
+ }
+
+ echo '<div class="input-right">';
+
+ echo '<span class="button">' . $input['button-label'] . '</span>';
+ echo '<input type="file" ' . $input['attributes'] . ' />';
+
+ $src_visibility = ( $input['value'] !== null && is_string($input['value']) ) ? '' : ' style="display:none;"';
+
+ $file_fragments = explode( '/', $input['value'] );
+ $filename = end($file_fragments);
+
+ echo '<span class="src"' . $src_visibility . '>' . $filename . '</span>
+ <span class="delete-file"' . $src_visibility . '>Delete</span>';
+
+ echo '</div><!-- .input-right -->';
+
+ }
+
+
+}
--- /dev/null
+<?php
+class HeadwayBlocks {
+
+
+ public static $block_actions = array(
+ 'init' => array(),
+ 'enqueue' => array(),
+ 'dynamic-js' => array(),
+ 'dynamic-css' => array(),
+ 'block-objects' => array()
+ );
+
+ public static $core_blocks = array(
+ 'header',
+ 'navigation',
+ 'breadcrumbs',
+ 'content',
+ 'widget-area',
+ 'footer',
+ 'slider',
+ 'embed',
+ 'pin-board',
+ 'custom-code',
+ 'text',
+ 'image',
+ 'search',
+ 'listings',
+ 'social',
+ 'gravity-forms',
+ 'slidedeck'
+ );
+
+
+ public static function init() {
+
+ Headway::load(array(
+ 'api/api-block'
+ ));
+
+ self::load_core_blocks();
+
+ add_action('init', array(__CLASS__, 'register_block_types'), 8);
+
+ add_action('init', array(__CLASS__, 'process_registered_blocks'), 9);
+
+ /* Handle block-specific actions */
+ add_action('init', array(__CLASS__, 'setup_block_actions'), 10);
+
+ add_action('init', array(__CLASS__, 'run_block_init_actions'), 11);
+ add_action('wp', array(__CLASS__, 'run_block_enqueue_actions'));
+ add_action('wp', array(__CLASS__, 'enqueue_block_dynamic_js_file'));
+ /* End block-specific actions */
+
+ add_action('headway_register_elements_instances', array(__CLASS__, 'register_block_element_instances'), 11);
+
+ add_action('headway_block_content_unknown', array(__CLASS__, 'unknown_block_content'));
+
+ /* Clear the block actions cache upon Visual Editor save and others */
+ add_action('headway_visual_editor_save', array(__CLASS__, 'clear_block_actions_cache'));
+ add_action('headway_visual_editor_reset_layout', array(__CLASS__, 'clear_block_actions_cache'));
+ add_action('headway_visual_editor_delete_template', array(__CLASS__, 'clear_block_actions_cache'));
+ add_action('headway_visual_editor_assign_template', array(__CLASS__, 'clear_block_actions_cache'));
+ add_action('headway_visual_editor_unassign_template', array(__CLASS__, 'clear_block_actions_cache'));
+
+ add_action('headway_db_upgrade', array(__CLASS__, 'clear_block_actions_cache'));
+ add_action('headway_activation', array(__CLASS__, 'clear_block_actions_cache'));
+ add_action('headway_global_reset', array(__CLASS__, 'clear_block_actions_cache'));
+
+ add_action('publish_post', array(__CLASS__, 'clear_block_actions_cache'));
+ add_action('delete_post', array(__CLASS__, 'clear_block_actions_cache'));
+ add_action('activate_plugin', array(__CLASS__, 'clear_block_actions_cache'));
+ add_action('deactivate_plugin', array(__CLASS__, 'clear_block_actions_cache'));
+ add_action('switch_theme', array(__CLASS__, 'clear_block_actions_cache'));
+
+ add_action('headway_switch_skin', array(__CLASS__, 'clear_block_actions_cache'));
+
+ }
+
+
+ public static function register_block_types() {
+
+ global $headway_unregistered_block_types;
+
+ foreach ( $headway_unregistered_block_types as $class => $block_type_url ) {
+
+ if ( !class_exists($class) )
+ return new WP_Error('block_class_does_not_exist', __('The block class being registered does not exist.', 'headway'), $class);
+
+ $block = new $class();
+
+ if ( $block_type_url )
+ $block->block_type_url = untrailingslashit($block_type_url);
+
+ $block->register();
+
+ unset($block);
+
+ }
+
+ unset($headway_unregistered_block_types);
+
+ return true;
+
+ }
+
+
+ public static function process_registered_blocks() {
+
+ do_action('headway_register_blocks');
+
+ }
+
+
+ public static function load_core_blocks() {
+
+ foreach ( apply_filters('headway_core_block_types', self::$core_blocks) as $block ) {
+
+ $block_path = '/blocks/' . $block . '/' . $block . '.php';
+
+ /* Allow blocks to be overriden by child themes */
+ if ( HEADWAY_CHILD_THEME_ACTIVE && file_exists( untrailingslashit(get_stylesheet_directory()) . $block_path ) ) {
+ require_once untrailingslashit( get_stylesheet_directory() ) . $block_path;
+ } else {
+ require_once HEADWAY_LIBRARY_DIR . $block_path;
+ }
+
+ }
+
+ }
+
+
+ public static function setup_block_actions() {
+
+ /* If cache exists then use it */
+ if ( ($block_actions_transient = get_transient('hw_block_actions_template_' . HeadwayOption::$current_skin)) && !(headway_get('ve-iframe') && HeadwayCapabilities::can_user_visually_edit()) ) {
+
+ self::$block_actions = $block_actions_transient;
+
+ return self::$block_actions;
+
+ }
+
+ /* Build the cache */
+ $block_types = self::get_block_types();
+
+ foreach ( $block_types as $block_type => $block_type_options ) {
+
+ //Make sure that the block type has at least one of the following: init_action, enqueue_action, or dynamic_js
+ if (
+ !method_exists($block_type_options['class'], 'init_action')
+ && !method_exists($block_type_options['class'], 'enqueue_action')
+ && !(method_exists($block_type_options['class'], 'dynamic_js') || method_exists($block_type_options['class'], 'js_content'))
+ && !method_exists($block_type_options['class'], 'dynamic_css')
+ )
+ continue;
+
+ $blocks = HeadwayBlocksData::get_blocks_by_type($block_type);
+
+ /* If there are no blocks for this type, skip it */
+ if ( !is_array($blocks) || count($blocks) === 0 )
+ continue;
+
+ /* Go through each type and add a flag if the method exists */
+ foreach ( $blocks as $block_id => $block ) {
+
+ $layout_id = $block['layout'];
+
+ /* Make sure that the layout is set to customized and not using a template */
+ if ( !HeadwayLayout::is_customized($layout_id) && strpos($layout_id, 'template-') === false )
+ continue;
+
+ /* Check that the block's wrapper isn't mirrored */
+ if ( HeadwayWrappersData::is_wrapper_mirrored(HeadwayWrappersData::get_wrapper(headway_get('wrapper_id', $block))) )
+ continue;
+
+ /* If layout ID is numeric (a post), change it to the single-POSTTYPE-ID format */
+ if ( is_numeric($layout_id) )
+ $layout_id = 'single-' . get_post_type($layout_id) . '-' . $layout_id;
+
+ /* Init */
+ if ( method_exists($block_type_options['class'], 'init_action') ) {
+
+ if ( !isset(self::$block_actions['init'][$layout_id]) )
+ self::$block_actions['init'][$layout_id] = array();
+
+ if ( !HeadwayBlocksData::is_block_mirrored($block) )
+ self::$block_actions['init'][$layout_id][] = $block_id;
+
+ }
+ /* End Init */
+
+ /* Enqueue */
+ if ( method_exists($block_type_options['class'], 'enqueue_action') ) {
+
+ if ( !isset(self::$block_actions['enqueue'][$layout_id]) )
+ self::$block_actions['enqueue'][$layout_id] = array();
+
+ self::$block_actions['enqueue'][$layout_id][] = $block_id;
+
+ }
+ /* End Enqueue */
+
+ /* Dynamic JS */
+ if ( method_exists($block_type_options['class'], 'dynamic_js') || method_exists($block_type_options['class'], 'js_content') ) {
+
+ if ( !isset(self::$block_actions['dynamic-js'][$layout_id]) )
+ self::$block_actions['dynamic-js'][$layout_id] = array();
+
+ self::$block_actions['dynamic-js'][$layout_id][] = $block_id;
+
+ }
+ /* End JS Content */
+
+ /* Dynamic CSS */
+ if ( method_exists($block_type_options['class'], 'dynamic_css') ) {
+
+ if ( !isset(self::$block_actions['dynamic-css'][$layout_id]) )
+ self::$block_actions['dynamic-css'][$layout_id] = array();
+
+ self::$block_actions['dynamic-css'][$layout_id][] = $block_id;
+
+ }
+ /* End Dynamic CSS */
+
+ /* Add block to Block Objects Array */
+ if ( !isset(self::$block_actions['block-objects']) || !is_array(self::$block_actions['block-objects']) )
+ self::$block_actions['block-objects'] = array();
+
+ if ( !headway_get($block_id, self::$block_actions['block-objects']) ) {
+
+ self::$block_actions['block-objects'][$block_id] = $block;
+ self::$block_actions['block-objects'][$block_id]['class'] = $block_type_options['class'];
+ self::$block_actions['block-objects'][$block_id]['layout'] = $layout_id;
+
+ }
+ /* End block objects array */
+
+ }
+
+ }
+
+ /* Pull block actions from blocks in mirrored wrappers */
+ $mirrored_wrappers = HeadwayWrappersData::get_all_wrappers(false, true);
+
+ self::$block_actions['enqueue'] = array_merge_recursive( self::$block_actions['enqueue'], self::get_block_actions_from_mirrored_wrappers( $mirrored_wrappers, 'enqueue' ) );
+ self::$block_actions['dynamic-js'] = array_merge_recursive( self::$block_actions['dynamic-js'], self::get_block_actions_from_mirrored_wrappers( $mirrored_wrappers, 'dynamic-js' ) );
+ self::$block_actions['dynamic-css'] = array_merge_recursive( self::$block_actions['dynamic-css'], self::get_block_actions_from_mirrored_wrappers( $mirrored_wrappers, 'dynamic-css' ) );
+
+ /* Set the cache */
+ set_transient('hw_block_actions_template_' . HeadwayOption::$current_skin, self::$block_actions);
+
+ return self::$block_actions;
+
+
+ }
+
+
+ public static function clear_block_actions_cache() {
+
+ return delete_transient('hw_block_actions_template_' . HeadwayOption::$current_skin);
+
+ }
+
+
+ public static function get_block_actions_from_mirrored_wrappers($wrappers, $block_action) {
+
+ $blocks = array();
+
+ foreach ( $wrappers as $wrapper_id => $wrapper ) {
+
+ if ( !$wrapper_being_mirrored = HeadwayWrappersData::get_wrapper_mirror($wrapper) )
+ continue;
+
+ foreach ( headway_get($wrapper_being_mirrored['layout'], self::$block_actions[$block_action], array()) as $block_id_on_layout_of_mirrored_wrapper ) {
+
+ /* Make sure the block on the layout from the mirrored wrapper is in the actual wrapper that's mirrored otherwise potentially a ton of extra CSS/JS will be loaded from blocks not in use */
+ if ( headway_get('wrapper_id', headway_get($block_id_on_layout_of_mirrored_wrapper, self::$block_actions['block-objects'])) == $wrapper_being_mirrored['id'] ) {
+
+ if ( !isset($blocks[$wrapper['layout']]) )
+ $blocks[$wrapper['layout']] = array();
+
+ $blocks[$wrapper['layout']][] = $block_id_on_layout_of_mirrored_wrapper;
+
+ }
+
+ }
+
+ }
+
+ return $blocks;
+
+ }
+
+
+ public static function run_block_init_actions() {
+
+ foreach ( self::$block_actions['init'] as $layout_id => $blocks ) {
+
+ foreach ( $blocks as $block_id ) {
+
+ $block_options = headway_get($block_id, self::$block_actions['block-objects']);
+
+ /* Use legacy ID if present */
+ $block_id = HeadwayBlocksData::get_legacy_id($block_options);
+ $block_options['id'] = $block_id;
+
+ if ( $block_options && is_callable(array($block_options['class'], 'init_action')) )
+ call_user_func(array($block_options['class'], 'init_action'), $block_id, $block_options);
+
+ }
+
+ }
+
+ }
+
+
+ public static function run_block_enqueue_actions() {
+
+ //Do not run these if it's the admin page or the visual editor is open
+ if ( is_admin() || HeadwayRoute::is_visual_editor() )
+ return false;
+
+ $layout_id = HeadwayLayout::get_current_in_use();
+
+ $enqueue_action_blocks = headway_get($layout_id, self::$block_actions['enqueue'], array());
+
+ if ( !isset($enqueue_action_blocks) || empty($enqueue_action_blocks) )
+ return;
+
+ foreach ( $enqueue_action_blocks as $block_id ) {
+
+ $block_options = headway_get($block_id, self::$block_actions['block-objects']);
+ $original_block = null;
+
+ if ( !$block_options )
+ continue;
+
+ /* If the block is mirrored, then use that ID instead */
+ if ( $possible_mirror_id = HeadwayBlocksData::is_block_mirrored($block_options) ) {
+
+ $original_block = $block_options;
+
+ $block_id = $possible_mirror_id;
+ $block_options = headway_get($block_id, self::$block_actions['block-objects']);
+
+ }
+
+ /* Use legacy ID if present */
+ $block_id = HeadwayBlocksData::get_legacy_id( $block_options );
+ $block_options['id'] = $block_id;
+
+ if ( is_callable(array($block_options['class'], 'enqueue_action')) )
+ call_user_func(array($block_options['class'], 'enqueue_action'), $block_id, $block_options, $original_block);
+
+ }
+
+ }
+
+
+ /* Functions used for Dynamic JS and Dynamic CSS */
+ /* Get blocks for the specific layout as well as the blocks in mirrored wrappers */
+ public static function get_blocks_for_dynamic_asset($css_or_js, $layout_id) {
+
+ return headway_get($layout_id, self::$block_actions['dynamic-' . $css_or_js], array());
+
+ }
+
+
+ /* Used to loop through block IDs that need JS or CSS to be outputted and does mirror checks */
+ public static function get_dynamic_asset_data($blocks, $css_or_js) {
+
+ if ( empty($blocks) )
+ return;
+
+ $data = '';
+
+ /* Loop through the blocks */
+ foreach ( $blocks as $block_id ) {
+
+ $block_options = headway_get($block_id, self::$block_actions['block-objects']);
+ $original_block = null;
+
+ if ( !$block_options )
+ continue;
+
+ /* If the block is mirrored, then use that ID instead */
+ if ( $possible_mirror_id = HeadwayBlocksData::is_block_mirrored($block_options) ) {
+
+ $original_block = $block_options;
+
+ /* Use legacy ID if present */
+ $original_block['id'] = HeadwayBlocksData::get_legacy_id( $original_block );
+
+ $block_id = $possible_mirror_id;
+ $block_options = headway_get($block_id, self::$block_actions['block-objects']);
+
+ }
+
+ /* Use legacy ID if present */
+ $block_id = HeadwayBlocksData::get_legacy_id( $block_options );
+ $block_options['id'] = $block_id;
+
+ /* Output the CSS or JS */
+ switch ( $css_or_js ) {
+
+ case 'js':
+ if ( is_callable(array($block_options['class'], 'dynamic_js')) )
+ $data .= call_user_func(array($block_options['class'], 'dynamic_js'), $block_id, $block_options, $original_block);
+ elseif ( is_callable(array($block_options['class'], 'js_content')) )
+ $data .= call_user_func(array($block_options['class'], 'js_content'), $block_id, $block_options, $original_block);
+ break;
+
+ case 'css':
+ if ( is_callable(array($block_options['class'], 'dynamic_css')) )
+ $data .= call_user_func(array($block_options['class'], 'dynamic_css'), $block_id, $block_options, $original_block);
+ break;
+
+ }
+
+ }
+
+ return $data;
+
+ }
+
+
+ /* Dynamic JS */
+ public static function output_block_dynamic_js($layout_id = false) {
+
+ $layout_id = !$layout_id ? headway_get('layout-in-use') : $layout_id;
+ $blocks = self::get_blocks_for_dynamic_asset('js', $layout_id);
+
+ if ( empty($blocks) )
+ return;
+
+ return self::get_dynamic_asset_data($blocks, 'js');
+
+ }
+
+ public static function enqueue_block_dynamic_js_file() {
+
+ //Do not run these if it's the admin page or the visual editor is open
+ if ( is_admin() || HeadwayRoute::is_visual_editor() )
+ return false;
+
+ $current_layout_in_use = HeadwayLayout::get_current_in_use();
+ $script_name = str_replace(HeadwayLayout::$sep, '-', 'block-dynamic-js-layout-' . HeadwayLayout::get_current_in_use());
+
+ $block_actions = self::get_blocks_for_dynamic_asset('js', $current_layout_in_use);
+
+ if ( empty($block_actions) )
+ return;
+
+ HeadwayCompiler::register_file(array(
+ 'name' => $script_name,
+ 'format' => 'js',
+ 'fragments' => array(
+ array('HeadwayBlocks', 'output_block_dynamic_js')
+ ),
+ 'enqueue' => false
+ ));
+
+ if ( strlen((string)self::output_block_dynamic_js($current_layout_in_use)) > 0 )
+ wp_enqueue_script($script_name, HeadwayCompiler::get_url($script_name), array('jquery'));
+
+ }
+ /* End Dynamic JS */
+
+
+ /* Dynamic CSS */
+ public static function output_block_dynamic_css($layout_id = false) {
+
+ $layout_id = !$layout_id ? headway_get('layout-in-use') : $layout_id;
+ $blocks = self::get_blocks_for_dynamic_asset('css', $layout_id);
+
+ if ( empty($blocks) )
+ return;
+
+ return self::get_dynamic_asset_data($blocks, 'css');
+
+ }
+ /* End Dynamic CSS */
+
+
+ public static function register_block_element_instances() {
+
+ if ( !($blocks = HeadwayBlocksData::get_all_blocks()) )
+ return false;
+
+ foreach ( $blocks as $block ) {
+
+ /* Do not register instance for block that's in a mirrored wrapper */
+ if ( HeadwayWrappersData::is_wrapper_mirrored(HeadwayWrappersData::get_wrapper(headway_get('wrapper_id', $block))) )
+ continue;
+
+ /* Do not register instance for mirrored block */
+ if ( $block_mirror = HeadwayBlocksData::is_block_mirrored($block) )
+ continue;
+
+ $default_name = self::block_type_nice($block['type']) . ' (Unnamed)';
+ $name = headway_get('alias', $block['settings']) ? headway_get('alias', $block['settings']) : $default_name;
+
+ $block_id_for_selector = HeadwayBlocksData::get_legacy_id( $block );
+
+ HeadwayElementAPI::register_element_instance(array(
+ 'group' => 'blocks',
+ 'element' => 'block-' . $block['type'],
+ 'id' => $block['type'] . '-block-' . $block['id'],
+ 'name' => $name,
+ 'selector' => '#block-' . $block_id_for_selector,
+ 'layout' => $block['layout']
+ ));
+
+ /* Register sub elements */
+ foreach ( HeadwayElementAPI::get_block_elements($block['type']) as $block_element_sub_element ) {
+
+ /* Make sure that the element supports instances */
+ if ( !headway_get('supports-instances', $block_element_sub_element) )
+ continue;
+
+ /* Register instance */
+ $instance_selector = str_replace('.block-type-' . $block['type'], '#block-' . $block_id_for_selector, $block_element_sub_element['selector']);
+
+ HeadwayElementAPI::register_element_instance(array(
+ 'group' => 'blocks',
+ 'element' => $block_element_sub_element['id'],
+ 'id' => $block_element_sub_element['id'] . '-block-' . $block['id'],
+ 'name' => $name . ' – ' . $block_element_sub_element['name'],
+ 'selector' => $instance_selector,
+ 'layout' => $block['layout']
+ ));
+
+ /* Register instance states as instances */
+ if ( !empty($block_element_sub_element['states']) && is_array($block_element_sub_element['states']) ) {
+
+ foreach ( $block_element_sub_element['states'] as $instance_state_id => $instance_state_info ) {
+
+ HeadwayElementAPI::register_element_instance(array(
+ 'group' => 'blocks',
+ 'element' => $block_element_sub_element['id'],
+ 'id' => $block_element_sub_element['id'] . '-block-' . $block['id'] . '-state-' . $instance_state_id,
+ 'name' => $name . ' - ' . $block_element_sub_element['name'] . ' (State: ' . $instance_state_info['name'] . ')',
+ 'selector' => str_replace('.block-type-' . $block['type'], '#block-' . $block_id_for_selector, $instance_state_info['selector']),
+ 'layout' => $block['layout'],
+ 'state-of' => $block_element_sub_element['id'] . '-block-' . $block['id'],
+ 'state-name' => $instance_state_info['name']
+ ));
+
+ }
+
+ }
+
+ } /* /foreach */
+
+ }
+
+ }
+
+
+ public static function display_block($block, $where = null) {
+
+ //We'll allow this function to take either an integer argument to look up the block or to use the existing
+ if ( !is_array($block) )
+ $block = HeadwayBlocksData::get_block($block);
+
+ //Check that the block exists
+ if ( !is_array($block) || !$block )
+ return false;
+
+ $block_types = HeadwayBlocks::get_block_types();
+
+ //Set the original block for future use
+ $original_block = $block;
+ $original_block_id = $where != 'grid' ? HeadwayBlocksData::get_legacy_id( $block ) : $block['id'];
+
+ //Set the block style to null so we don't get an ugly notice down the road if it's not used.
+ $block_style_attr = null;
+
+ //Check if the block type exists
+ if ( !$block_type_settings = headway_get($block['type'], $block_types, array()) ) {
+
+ $block['requested-type'] = $block['type'];
+ $block['type'] = 'unknown';
+
+ }
+
+ //Get the custom CSS classes and change commas to spaces and remove double spaces and remove HTML
+ $custom_css_classes = str_replace(' ', ' ', str_replace(',', ' ', esc_attr(strip_tags(headway_get('css-classes', $block['settings'], '')))));
+
+ $block_classes = array_unique(array_filter(explode(' ', $custom_css_classes)));
+
+ $block_classes[] = 'block';
+ $block_classes[] = 'block-type-' . $block['type'];
+
+ $block_classes[] = ( headway_get('fixed-height', $block_type_settings, false) !== true ) ? 'block-fluid-height' : 'block-fixed-height';
+
+ //If the block is being displayed in the Grid, then we need to make it work with absolute positioning.
+ if ( $where == 'grid' ) {
+
+ $block_classes[] = 'grid-width-' . $original_block['dimensions']['width'];
+ $block_classes[] = 'grid-left-' . $original_block['position']['left'];
+
+ $block_style_attr = ' style="height: ' . $original_block['dimensions']['height'] . 'px; top: ' . $original_block['position']['top'] . 'px;"';
+
+ }
+
+ //If the responsive grid is active, then add the responsive block hiding classes
+ if ( HeadwayResponsiveGrid::is_enabled() ) {
+
+ $responsive_block_hiding = headway_get('responsive-block-hiding', $block['settings'], array());
+
+ if ( is_array($responsive_block_hiding) && count($responsive_block_hiding) > 0 ) {
+
+ foreach ( $responsive_block_hiding as $device )
+ $block_classes[] = 'responsive-block-hiding-device-' . $device;
+
+ }
+
+ }
+
+ //If it's a mirrored block, change $block to the mirrored block
+ if ( $mirrored_block = HeadwayBlocksData::get_block_mirror($block) ) {
+
+ $block = $mirrored_block;
+ $block['original'] = $original_block;
+
+ //Add Classes for the mirroring
+ $block_classes[] = 'block-mirrored';
+
+ if ( $where != 'grid' ) {
+
+ $block_classes[] = 'block-mirroring-' . $mirrored_block['id'];
+ $block_classes[] = 'block-original-' . $original_block_id;
+
+ }
+
+ }
+
+ //Fetch the HTML tag for the block
+ $block_tag = ( $html_tag = headway_get('html-tag', $block_type_settings) ) ? $html_tag : 'div';
+
+ //The ID attribute for the block. This will change if mirrored.
+ $block_id_for_id_attr = $where != 'grid' ? HeadwayBlocksData::get_legacy_id( $block ) : $block['id'];
+
+ //Original block ID to be used in the Visual Editor
+ if ( HeadwayRoute::is_visual_editor_iframe() ) {
+
+ $block_data_attrs = implode(' ', array(
+ 'data-id="' . str_replace('block-', '', $original_block_id) . '"',
+ 'data-type="' . headway_get('type', $block) . '"',
+ 'data-block-mirror="' . (isset($mirrored_block) ? $mirrored_block['id'] : '') . '"',
+ 'data-block-mirror-layout-name="' . (isset($mirrored_block) ? HeadwayLayout::get_name($mirrored_block['layout']) : '') . '"',
+ 'data-grid-left="' . $original_block['position']['left'] . '"',
+ 'data-grid-top="' . $original_block['position']['top'] . '"',
+ 'data-width="' . $original_block['dimensions']['width'] . '"',
+ 'data-height="' . $original_block['dimensions']['height'] . '"',
+ 'data-alias="' . headway_get('alias', headway_get('settings', $block, array())) . '"'
+ ));
+
+ } else {
+
+ $block_data_attrs = implode( ' ', array(
+ ' data-alias="' . esc_attr(headway_get( 'alias', headway_get( 'settings', $block, array() ) )) . '"'
+ ) );
+
+ }
+
+ //The grid will display blocks entirely differently and not use hooks.
+ if ( $where != 'grid' ) {
+
+ /* Use legacy ID if present */
+ $block['id'] = HeadwayBlocksData::get_legacy_id( $block );
+
+ do_action('headway_before_block', $block);
+ do_action('headway_before_block_' . $block['id'], $block);
+
+ echo '<' . $block_tag . ' id="block-' . $block_id_for_id_attr . '" class="' . implode(' ', array_filter(apply_filters('headway_block_class', $block_classes, $block))) . '"' . $block_style_attr . $block_data_attrs . self::block_attr( $block_type_settings ) . '>';
+
+ do_action('headway_block_open', $block);
+ do_action('headway_block_open_' . $block['id'], $block);
+
+ echo "\n" . '<div class="block-content">' . "\n";
+
+ do_action('headway_block_content_open', $block);
+ do_action('headway_block_content_open_' . $block['id'], $block);
+
+ do_action('headway_block_content_' . $block['type'], $block);
+
+ do_action('headway_block_content_close', $block);
+ do_action('headway_block_content_close_' . $block['id'], $block);
+
+ echo "\n" . '</div><!-- .block-content -->' . "\n";
+
+ do_action('headway_block_close', $block);
+ do_action('headway_block_close_' . $block['id'], $block);
+
+ echo "\n" . '</' . $block_tag . '><!-- #block-' . $block_id_for_id_attr . ' -->' . "\n";
+
+ do_action('headway_after_block', $block);
+ do_action('headway_after_block_' . $block['id'], $block);
+
+ //Show the block in the grid
+ } else {
+
+ $show_content_in_grid = self::block_type_exists($block['type']) ? headway_get('show-content-in-grid', $block_type_settings, false) : false;
+
+ if ( !$show_content_in_grid )
+ $block_classes[] = 'hide-content-in-grid';
+
+ if ( !self::block_type_exists($block['type']) )
+ $block_classes[] = 'block-error';
+
+ echo '<' . $block_tag . ' id="block-' . $block_id_for_id_attr . '" class="' . implode(' ', array_filter($block_classes)) . '"' . $block_style_attr . $block_data_attrs . '>';
+
+ echo '<div class="block-content-fade block-content">';
+
+ if ( !self::block_type_exists($block['type']) ) {
+
+ self::unknown_block_content($block);
+
+ }
+
+ echo '</div><!-- .block-content-fade -->' . "\n";
+
+ echo '</' . $block_tag . '><!-- #block-' . $block_id_for_id_attr . ' -->' . "\n";
+
+ }
+
+ //Spit the ID back out
+ return $block['id'];
+
+ }
+
+ public static function block_attr( $block_type_settings ) {
+
+ if ( !$attributes = headway_get('attributes', $block_type_settings) )
+ return;
+
+ $output = '';
+
+ foreach ( $attributes as $key => $value ) {
+
+ if ( is_numeric($key) )
+ $output .= esc_html($value);
+ else
+ $output .= sprintf( '%s="%s" ', esc_html($key), esc_attr($value) );
+
+ }
+
+ return trim( $output );
+
+ }
+
+
+ public static function get_block_types() {
+
+ global $headway_block_types;
+
+ if ( !isset($headway_block_types) || empty($headway_block_types) )
+ return null;
+
+ return $headway_block_types;
+
+ }
+
+
+ public static function block_type_nice($type) {
+
+ $block_types = self::get_block_types();
+
+ return headway_get('name', headway_get($type, $block_types));
+
+ }
+
+
+ public static function block_type_exists($type) {
+
+ $block_types = self::get_block_types();
+
+ //If, for some reason, the blocks array isn't set, just return false.
+ if ( !is_array($block_types) )
+ return new WP_Error('blocks_array_does_not_exist', __('The Headway blocks array does not exist.', 'headway'));
+
+ //Check for the actual block type
+ if ( isset($block_types[$type]) )
+ return true;
+
+ //Return false if everything else fails
+ return false;
+
+ }
+
+
+ public static function unknown_block_content($block = null) {
+
+ echo '<div class="alert alert-red block-type-unknown-notice"><p>The requested block type of \'' . $block['requested-type'] . '\' does not exist. Please re-activate the block plugin or child theme if you wish to use this block again.</p></div>';
+
+ }
+
+
+}
\ No newline at end of file
--- /dev/null
+<?php
+headway_register_block('HeadwayBreadcrumbsBlock', headway_url() . '/library/blocks/breadcrumbs');
+
+class HeadwayBreadcrumbsBlock extends HeadwayBlockAPI {
+
+
+ public $id = 'breadcrumbs';
+
+ public $name = 'Breadcrumbs';
+
+ public $fixed_height = true;
+
+ public $description = 'Breadcrumbs aid in the navigation of your site by showing a visual hierarchy of where your visitor is.<br /><strong>Example:</strong> Home » Blog » Sample Blog Post';
+
+ public $options_class = 'HeadwayBreadcrumbsBlockOptions';
+
+
+ function setup_elements() {
+
+ $this->register_block_element(array(
+ 'id' => 'text',
+ 'name' => 'Text',
+ 'selector' => 'p'
+ ));
+
+ $this->register_block_element(array(
+ 'id' => 'hyperlinks',
+ 'name' => 'Hyperlinks',
+ 'selector' => 'p a'
+ ));
+
+ $this->register_block_element(array(
+ 'id' => 'separators',
+ 'name' => 'Separators',
+ 'selector' => 'span.sep'
+ ));
+
+ }
+
+
+ function content($block) {
+
+ /* If Yoast's breadcrumbs are activated then use them instead */
+ if ( function_exists('yoast_breadcrumb') ) {
+
+ $yoast_breadcrumb = yoast_breadcrumb( '<p class="breadcrumbs yoastbreadcrumb">', '</p>' );
+
+ if ( is_string($yoast_breadcrumb) && $yoast_breadcrumb ) {
+ echo $yoast_breadcrumb;
+ return;
+ }
+
+ }
+
+ wp_reset_query();
+
+ /* Set up variables */
+ global $post;
+
+ $breadcrumbs = array();
+ $breadcrumbs[home_url()] = __('Home', 'headway');
+
+ /* Handle blogs that aren't set to the homepage */
+ if ( get_option('show_on_front') == 'page' && get_option('page_for_posts') !== get_option('page_on_front') ) {
+
+ /* If the blog is set to a page rather than homepage, then don't show that fragment if it's a 404, search, or non-post singular */
+ if ( !is_404() && !is_search() && !(is_singular() && get_post_type() != 'post') )
+ $breadcrumbs[get_page_link(get_option('page_for_posts'))] = get_the_title(get_option('page_for_posts'));
+
+ }
+
+ /* Single Posts */
+ if ( is_single() && get_post_type() == 'post' ) {
+
+ $breadcrumbs[] = get_the_category_list(', ');
+ $breadcrumbs[] = get_the_title();
+
+ }
+
+ /* Pages/Custom Post Type */
+ else if ( is_singular() && !is_home() && !is_front_page() ) {
+
+ $current_page = array($post);
+
+ /* Get the parent pages of the current page if they exist */
+ if ( isset($current_page[0]->post_parent) )
+ while ( $current_page[0]->post_parent )
+ array_unshift($current_page, get_post($current_page[0]->post_parent));
+
+ /* Add returned pages to breadcrumbs */
+ foreach ( $current_page as $page )
+ $breadcrumbs[get_page_link($page->ID)] = $page->post_title;
+
+ /* Categories */
+ } else if ( is_category() ) {
+
+ $breadcrumbs[] = single_cat_title('', false);
+
+ }
+
+ /* Searches */
+ else if ( is_search() ) {
+
+ $breadcrumbs[] = __('Search Results For:', 'headway') . ' ' . get_search_query();
+
+ }
+
+ /* Author Archives */
+ else if ( is_author() ) {
+
+ $author = get_queried_object();
+
+ $breadcrumbs[] = __('Author Archives:', 'headway') . ' ' . $author->display_name;
+
+ }
+
+ /* Tag Archives */
+ else if ( is_tag() ) {
+
+ $breadcrumbs[] = __('Tag Archives:', 'headway') . ' ' . single_tag_title('', false);
+
+ }
+
+ /* Date Archives */
+ else if ( is_date() ) {
+
+ $breadcrumbs[] = __('Archives:', 'headway') . ' ' . get_the_time('F Y');
+
+ }
+
+ /* 404's */
+ else if ( is_404() ) {
+
+ $breadcrumbs[] = __('Whoops! Page Not Found...', 'headway');
+
+ }
+
+ /* Display the breadcrumbs */
+ echo '<p class="breadcrumbs" xmlns:v="http://rdf.data-vocabulary.org/#">';
+
+ if ( parent::get_setting($block, 'show-prefix', false) )
+ echo '<span class="breadcrumbs-prefix">' . parent::get_setting($block, 'prefix-text', __('You Are Here:', 'headway')) . '</span> ';
+
+ $breadcrumbs = apply_filters('headway_breadcrumbs', $breadcrumbs);
+
+ $breadcrumbs_length = count($breadcrumbs);
+ $breadcrumbs_loop_counter = 0;
+
+ foreach ( $breadcrumbs as $breadcrumb_url => $breadcrumb ) {
+
+ /* Do not show separator before first item */
+ if ( $breadcrumbs_loop_counter != 0 )
+ echo ' <span class="sep">' . parent::get_setting($block, 'separator', '»') . '</span> ';
+
+ echo '<span typeof="v:Breadcrumb" class="breadcrumb">';
+
+ if ( !is_numeric($breadcrumb_url) && ($breadcrumbs_loop_counter != $breadcrumbs_length - 1) ) {
+
+ echo '<a href="' . $breadcrumb_url . '" rel="v:url" property="v:title">' . $breadcrumb . '</a></span>';
+
+ } else {
+
+ echo $breadcrumb;
+
+ }
+
+ echo '</span><!-- .breadcrumb -->';
+
+ $breadcrumbs_loop_counter++;
+
+ }
+
+ echo "\n</p>\n\n";
+
+ }
+
+
+}
+
+
+class HeadwayBreadcrumbsBlockOptions extends HeadwayBlockOptionsAPI {
+
+ public $tabs = array(
+ 'general' => 'General'
+ );
+
+ public $inputs = array(
+ 'general' => array(
+ 'show-prefix' => array(
+ 'name' => 'show-prefix',
+ 'label' => 'Show "You Are Here" prefix',
+ 'type' => 'checkbox',
+ 'tooltip' => 'If you would like the breadcrumbs to show "You Are Here:" or anything similar in front of the breadcrumb trail, then check this.',
+ 'default' => false
+ ),
+
+ 'prefix-text' => array(
+ 'name' => 'prefix-text',
+ 'label' => 'Prefix Text',
+ 'type' => 'text',
+ 'tooltip' => 'If the previous checkbox is checked, then you may customize the prefix text.',
+ 'default' => 'You Are Here:'
+ ),
+
+ 'separator' => array(
+ 'name' => 'separator',
+ 'label' => 'Separator',
+ 'type' => 'text',
+ 'tooltip' => 'This will be shown between each breadcrumb. e.g. If the separator is "»" then it will be shown as Home » Page Name.',
+ 'default' => '»'
+ )
+ )
+ );
+
+}
\ No newline at end of file
--- /dev/null
+<?php
+global $post;
+global $headway_comments_template_args;
+
+echo '<div id="comments">';
+
+ if ( !post_password_required() ) {
+
+ if ( have_comments() ) {
+
+ /* Comments Area Heading */
+ echo '<h3 id="comments">';
+
+ /* Comments Area Responses Formatting */
+ $comments_number = (int)get_comments_number($post->ID);
+
+ if ( $comments_number == 1 )
+ $comments_heading_responses_format = stripslashes(headway_get('comments-area-heading-responses-number-1', $headway_comments_template_args, 'One Response'));
+ else
+ $comments_heading_responses_format = stripslashes(headway_get('comments-area-heading-responses-number', $headway_comments_template_args, '%num% Responses'));
+
+ $comments_heading_replacements = array(
+ 'responses' => str_replace('%num%', $comments_number, $comments_heading_responses_format),
+ 'title' => get_the_title()
+ );
+ /* End Comments Area Responses Formatting */
+
+ echo str_replace(array('%responses%', '%title%'), $comments_heading_replacements, headway_get('comments-area-heading', $headway_comments_template_args, '%responses% to <em>%title%</em>'));
+
+ echo '</h3>';
+ /* End Comments Area Heading */
+
+ echo '<ol class="commentlist">';
+
+ wp_list_comments(apply_filters('headway_comments_args', array(
+ 'avatar_size' => 44,
+ 'format' => 'html5'
+ )));
+
+ echo '</ol><!-- .commentlist -->';
+
+ echo '<div class="comments-navigation">';
+ echo '<div class="alignleft">';
+ paginate_comments_links();
+ echo '</div>';
+ echo '</div>';
+
+ } else {
+
+ if ( $post->comment_status != 'open' ) {
+
+ if ( is_single() ) {
+
+ $comments_closed = apply_filters('headway_comments_closed', __('Sorry, comments are closed for this post.', 'headway'));
+
+ echo '<p class="comments-closed">' . $comments_closed . '</p>';
+
+ }
+
+ }
+
+ }
+
+ comment_form(apply_filters('headway_comment_form_args', array()));
+
+ } else {
+
+ echo '<p class="nocomments">' . __('This post is password protected. Please enter the password to view the comments.', 'headway') . '</p>';
+
+ }
+
+echo '</div><!-- #comments -->';
\ No newline at end of file
--- /dev/null
+<?php
+class HeadwayContentBlockDisplay {
+
+ var $count = 0;
+
+ var $query = array();
+
+
+ function __construct($block) {
+
+ $this->block = $block;
+
+ /* Bring in the WordPress pagination variable. */
+ $this->paged = get_query_var('paged') ? get_query_var('paged') : 1;
+
+ $this->add_hooks();
+
+ }
+
+
+ /**
+ * Created this function to make the call a little shorter.
+ **/
+ function get_setting($setting, $default = null) {
+
+ return HeadwayBlockAPI::get_setting($this->block, $setting, $default);
+
+ }
+
+
+ function add_hooks() {
+
+ if ( !class_exists('pluginbuddy_loopbuddy') ) {
+
+ add_filter('the_content_more_link', array($this, 'more_link'));
+
+ add_filter('excerpt_more', array($this, 'filter_add_auto_excerpt_more_link'));
+ add_filter('get_the_excerpt', array($this, 'filter_add_custom_excerpt_more_link'));
+
+ }
+
+ add_filter('the_content', array($this, 'filter_nofollow_links_in_post'));
+
+ }
+
+
+ function remove_hooks() {
+
+ remove_filter('the_content_more_link', array($this, 'more_link'));
+
+ remove_filter('excerpt_more', array($this, 'filter_add_auto_excerpt_more_link'));
+ remove_filter('get_the_excerpt', array($this, 'filter_add_custom_excerpt_more_link'));
+
+ remove_filter('the_content', array($this, 'filter_nofollow_links_in_post'));
+
+ }
+
+
+ function display($args = array()) {
+
+ /* Use the generic_content action if it's set. See http://core.trac.wordpress.org/ticket/20509 */
+ if ( $this->get_setting('mode', 'default') == 'default' && has_action('generic_content') && !did_action('generic_content') )
+ return do_action('generic_content');
+
+ /* Since it's impossible to get the $wp_query in its correct form when loading the content from admin-ajax.php, we will display this notice. */
+ if (
+ (headway_get('ve-live-content-query', $this->block, false))
+ && $this->get_setting('mode', 'default') == 'default'
+ )
+ echo '<div class="alert alert-yellow" style="margin: 5px;"><p><strong>Please note:</strong> What\'s being displayed here in the Content Block may not be correct. When viewing the site outside of the Visual Editor, you will see the correct content.</p></div>';
+
+ /* If LoopBuddy is activated, we'll strictly rely on it for the query setup and how the content is displayed. */
+ if (class_exists('pluginbuddy_loopbuddy')) {
+
+ global $pluginbuddy_loopbuddy;
+
+ $loopbuddy_query = $this->get_setting('loopbuddy-query', -1);
+ $loopbuddy_layout = $this->get_setting('loopbuddy-layout', -1);
+
+ if ( isset($pluginbuddy_loopbuddy) && $loopbuddy_query !== -1 ) {
+ echo $pluginbuddy_loopbuddy->render_loop($loopbuddy_query, $loopbuddy_layout);
+
+ $this->remove_hooks();
+
+ return;
+ }
+
+ }
+
+ /* Display the 404 text if it's a 404 (has to be default behavior) */
+ if ( is_404() && $this->get_setting('mode', 'default') == 'default' && !headway_get('ve-live-content-query', $this->block, false) ) {
+ $this->remove_hooks();
+
+ return $this->display_404();
+ }
+
+ /* Display loop like normal if nothing else fires first */
+ $this->loop($args);
+ $this->remove_hooks();
+
+ wp_reset_query();
+
+ }
+
+
+ function loop($args = array()) {
+
+ $defaults = array('archive' => false);
+ extract($defaults);
+ extract($args, EXTR_OVERWRITE);
+
+ if ( !dynamic_loop() ) {
+
+ $this->setup_query();
+
+ $this->show_query_title();
+
+ echo '<div class="loop">';
+
+ if ( !$this->query->have_posts() && is_search() && $this->get_setting('mode', 'default') == 'default' ) {
+
+ echo '<div class="entry-content">';
+ echo apply_filters('headway_search_no_results', __('<p>Sorry, there was no content that matched your search.</p>', 'headway'));
+ echo '</div>';
+
+ }
+
+ while ( $this->query->have_posts() ) {
+
+ $this->query->the_post();
+
+ $this->count++;
+
+ $this->possible_row_open();
+
+ $this->display_entry(array('count' => $this->count));
+
+ $this->possible_row_close();
+
+ }
+
+ echo '</div>';
+
+ $this->display_pagination();
+
+ }
+
+ }
+
+
+ function possible_row_open() {
+
+ if ( isset($this->row_open) && $this->row_open )
+ return;
+
+ if ( $this->get_setting('mode', 'default') == 'default' && is_singular() )
+ return;
+
+ if ( !(is_search() || $this->paged > 1) && $this->count <= $this->get_setting('featured-posts', 1) )
+ return;
+
+ echo "\n\n" . '<div class="entry-row">' . "\n\n";
+
+ $this->row_open = true;
+
+ }
+
+
+ function possible_row_close() {
+
+ /* If a row isn't open then we don't have anything to close */
+ if ( !isset($this->row_open) || !$this->row_open )
+ return false;
+
+ $featured_posts_on_page = !(is_search() || $this->paged > 1) ? $this->get_setting('featured-posts', 1) : 0;
+
+ /* Only run the every nth post check if it's not the last post. If it is the last post, then we have to close the row no matter what. */
+ if ( $this->count < $this->query->post_count ) {
+
+ /* Normal check to close. Close every nth post */
+ if ( ($this->count - $featured_posts_on_page) % $this->get_setting('posts-per-row', '2') !== 0 )
+ return false;
+
+ }
+
+ echo "\n\n" . '</div><!-- .entry-row -->' . "\n\n";
+
+ $this->row_open = false;
+
+ }
+
+
+ function show_query_title() {
+
+ /* Stop this function if it's a custom query, index, front page, or singular. */
+ if ( $this->get_setting('mode', 'default') != 'default' || is_home() || is_front_page() || is_singular() || get_post_type() == 'forum' )
+ return;
+
+ $queried_object = get_queried_object();
+
+ $return = '';
+
+ /* Date Archives */
+ if ( is_date() ) {
+
+ $return .= '<h1 class="archive-title date-archive-title">';
+
+ if ( is_day() )
+ $return .= apply_filters('headway_archive_title', sprintf( __( 'Daily Archives: %s', 'headway' ), '<span>' . get_the_date() . '</span>'));
+
+ elseif ( is_month() )
+ $return .= apply_filters('headway_archive_title', sprintf( __( 'Monthly Archives: %s', 'headway' ), '<span>' . get_the_date('F Y') . '</span>'));
+
+ elseif ( is_year() )
+ $return .= apply_filters('headway_archive_title', sprintf( __( 'Yearly Archives: %s', 'headway' ), '<span>' . get_the_date('Y') . '</span>' ));
+
+ else
+ $return .= apply_filters('headway_archive_title', __( 'Blog Archives', 'headway'));
+
+ $return .= '</h1><!-- .archive-title -->';
+
+ }
+
+ /* Category Archives */
+ else if ( is_category() ) {
+
+ $return .= '<h1 class="archive-title category-title">';
+ $return .= apply_filters('headway_category_title', sprintf(__('Category Archives: %s', 'headway'), '<span>' . single_cat_title('', false) . '</span>'));
+ $return .= '</h1><!-- .archive-title -->';
+
+ $category_description = category_description();
+ if ( !empty($category_description) )
+ $return .= apply_filters('headway_category_archive_meta', '<div class="archive-meta category-archive-meta">' . $category_description . '</div>');
+
+ }
+
+ /* Author Archives */
+ else if ( is_author() ) {
+
+ $author = $queried_object;
+ $author_url = esc_url(get_the_author_meta('google_profile', $author->ID));
+
+ $return .= '<h1 class="archive-title author-title">';
+
+ if ( strpos($author_url, 'http') === 0 )
+ $return .= sprintf(__( 'Author Archives: %s', 'headway'), '<span class="vcard"><a class="url fn n" href="' . $author_url . '" title="' . esc_attr($author->display_name) . '" rel="author">' . $author->display_name . '</a></span>');
+
+ else
+ $return .= sprintf(__( 'Author Archives: %s', 'headway'), '<span class="vcard">' . $author->display_name . '</span>');
+
+ $return .= '</h1><!-- .archive-title -->';
+
+ }
+
+ /* Search */
+ else if ( is_search() ) {
+
+ $return .= '<h1 class="archive-title search-title">';
+ $return .= apply_filters('headway_search_title', sprintf(__('Search Results for: %s', 'headway'), '<span>' . get_search_query() . '</span>'));
+ $return .= '</h1><!-- .archive-title -->';
+
+ }
+
+ /* Tag Archives */
+ else if ( is_tag() ) {
+
+ $return .= '<h1 class="archive-title search-title">';
+ $return .= apply_filters('headway_tag_title', sprintf(__('Tag Archives: %s', 'headway'), '<span>' . single_tag_title('', false) . '</span>'));
+ $return .= '</h1><!-- .archive-title -->';
+
+ $tag_description = tag_description();
+ if ( !empty($tag_description) )
+ $return .= apply_filters('headway_tag_archive_meta', '<div class="archive-meta tag-archive-meta">' . $tag_description . '</div>');
+
+ }
+
+ /* Custom Post Type Archives */
+ else if ( is_post_type_archive() ) {
+
+ $return .= '<h1 class="archive-title post-type-archive-title">';
+ $return .= apply_filters('headway_post_type_archive_title', $queried_object->labels->name);
+ $return .= '</h1><!-- .archive-title -->';
+
+ }
+
+ /* Custom Taxonomy Archives */
+ else if ( is_tax() ) {
+
+ $taxonomy = get_taxonomy($queried_object->taxonomy);
+ $term = get_term($queried_object->term_id, $queried_object->taxonomy);
+
+ $return .= '<h1 class="archive-title taxonomy-archive-title">';
+ $return .= apply_filters('headway_taxonomy_archive_title', $taxonomy->labels->singular_name . ': <span>' . $term->name . '</span>');
+ $return .= '</h1><!-- .archive-title -->';
+
+ $term_description = term_description();
+ if ( !empty($term_description) )
+ $return .= apply_filters('headway_term_archive_meta', '<div class="archive-meta term-archive-meta">' . $term_description . '</div>');
+
+ }
+
+ echo apply_filters('headway_query_title', $return);
+
+ }
+
+
+ function setup_query() {
+
+ //If the query mode is default, just use $wp_query global and do what WordPress would normally do.
+ //ALSO: if a block is brand new and just created in the visual editor (and hasn't been saved), then we'll force it into
+ //custom query.
+ if ( $this->get_setting('mode', 'default') == 'default' && !headway_get('ve-live-content-query', $this->block, false) ) {
+
+ global $wp_query;
+
+ $this->query = $wp_query;
+
+ //The mode is custom query so we have to set it all up.
+ } else {
+
+ /* Setup Query Options */
+ $query_options = array();
+
+ if ( $this->get_setting('mode', 'default') == 'custom-query' ) {
+
+ //If we're just fetching a page, we can simply do that. Otherwise, we have to use all of the query filters.
+ if ( $this->get_setting('fetch-page-content', false) ) {
+
+ $query_options['page_id'] = $this->get_setting('fetch-page-content', false);
+
+ } else {
+
+ //Categories
+ if($this->get_setting('categories-mode', 'include') == 'include')
+ $query_options['category__in'] = $this->get_setting('categories', array());
+
+ if($this->get_setting('categories-mode', 'include') == 'exclude')
+ $query_options['category__not_in'] = $this->get_setting('categories', array());
+ //Categories
+
+ $query_options['post_type'] = $this->get_setting('post-type', false);
+
+ //Post Limit
+ $query_options['posts_per_page'] = $this->get_setting('number-of-posts', 10);
+ //End Post Limit
+
+ if ( is_array($this->get_setting('author')) )
+ $query_options['author'] = trim(implode(',', $this->get_setting('author')), ', ');
+
+ //Order by
+ $query_options['orderby'] = $this->get_setting('order-by', 'date');
+ $query_options['order'] = $this->get_setting('order', 'desc');
+ //End order by
+
+ $query_options['offset'] = $this->get_setting('offset', 0);
+
+ if ( $this->get_setting('paginate', true) ) {
+
+ $query_options['paged'] = $this->paged;
+
+ if ($this->get_setting('offset', 0) >= 1 && $query_options['paged'] > 1){
+ $query_options['offset'] = $this->get_setting('offset', 0) + $this->get_setting('number-of-posts', 10) * ($query_options['paged'] - 1);
+ }
+
+ }
+
+ } //End else conditional for either page fetching or custom query filters
+
+ //End if conditional checking that the mode is custom query.
+ //If the mode isn't a custom query, then this is a ve-live-content-query so we can just simulate $wp_query.
+ } else {
+
+ $query_options = array(
+ 'showposts' => 10,
+ 'posts_per_page' => 10
+ );
+
+ }
+
+ //Initiate query instance
+ $this->query = new WP_Query($query_options);
+
+ }
+
+ }
+
+
+ function display_entry($args = array()) {
+
+ global $post;
+
+ $defaults = array(
+ 'count' => false,
+ 'single' => false
+ );
+
+ $args = array_merge($defaults, $args);
+
+ if ( $this->get_setting('show-entry', true) ) {
+
+ /* Setup generic variables */
+ $post_id = get_the_id();
+ $post_class = $this->entry_class();
+ $post_permalink = get_permalink();
+ $post_type = get_post_type();
+ /* End generic variables */
+
+ /* Meta */
+ $entry_meta_display_post_types = $this->get_setting('show-entry-meta-post-types', array('post'));
+
+ if ( is_array($entry_meta_display_post_types) && in_array($post_type, $entry_meta_display_post_types) ) {
+
+ $entry_meta_above = $this->parse_meta($this->get_setting('entry-meta-above', 'Posted on %date% by %author% • %comments%'));
+ $entry_utility_below = $this->parse_meta($this->get_setting('entry-utility-below', 'Filed Under: %categories%'));
+
+ if ( $entry_meta_above )
+ $entry_meta_above = '<div class="entry-meta entry-meta-above">' . headway_parse_php($entry_meta_above) . '</div><!-- .entry-meta -->';
+
+ if ( $entry_utility_below )
+ $entry_utility_below = '<footer class="entry-utility entry-utility-below entry-meta">' . headway_parse_php($entry_utility_below) . '</footer><!-- .entry-utility -->';
+
+ } else {
+
+ $entry_meta_above = null;
+ $entry_utility_below = null;
+
+ }
+ /* End Meta */
+
+ /* Setup Titles */
+ $hide_title = HeadwayLayoutOption::get($post_id, 'hide-title', false, true, false);
+
+ $alternate_title = HeadwayLayoutOption::get($post_id, 'alternate-title', false, true);
+
+ $post_title = (isset($alternate_title) && $alternate_title) ? $alternate_title : get_the_title();
+ $post_title_tooltip = sprintf(esc_attr__('%s', 'headway'), the_title_attribute('echo=0'));
+
+ /* Show <h1> for titles if it's a singlular page, use <h3> for archives, and <h2> for everything else. */
+ if ( is_singular() && $this->get_setting('mode', 'default') == 'default' )
+ $title_tag = 'h1';
+ elseif ( is_archive() || is_search() )
+ $title_tag = 'h3';
+ else
+ $title_tag = 'h2';
+
+ /* If the post is singular or the post type is a page being displayed through content fetching, don't put a link in the title. */
+ if (( is_singular() && $this->get_setting('mode', 'default') != 'custom-query' ) || !$this->get_setting('link-titles', true))
+ $post_title_link = $post_title;
+ else
+ $post_title_link = '<a href="' . $post_permalink . '" title="' . $post_title_tooltip . '" rel="bookmark">' . $post_title . '</a>';
+ /* End Titles */
+
+ do_action('headway_before_entry', $args);
+
+ echo '<article id="post-' . $post_id . '" class="' . $post_class . '" itemscope itemtype="http://schema.org/BlogPosting">';
+
+ do_action('headway_entry_open', $args);
+
+ //Show post thumbnail
+ $this->display_thumbnail($post, 'above-title');
+
+ echo '<header>';
+
+ do_action('headway_before_entry_title', $args);
+
+ //Show the title based on the Show Titles option
+ if (
+ $this->get_setting('show-titles', true)
+ && !($hide_title == 'singular' && $title_tag == 'h1')
+ && !($hide_title == 'list' && $title_tag != 'h1')
+ && !($hide_title == 'both')
+ ) {
+
+ echo '<' . $title_tag . ' class="entry-title" itemprop="headline">';
+
+ echo $post_title_link;
+
+ if ( apply_filters('headway_show_edit_link', $this->get_setting('show-edit-link', true)) )
+ edit_post_link('Edit Entry');
+
+ echo '</' . $title_tag . '>';
+
+ }
+
+ do_action('headway_after_entry_title', $args);
+
+ echo $entry_meta_above;
+
+ echo '</header>';
+
+ $this->display_thumbnail($post, 'above-content');
+
+ $this->display_entry_content($args);
+
+ echo $entry_utility_below;
+
+ do_action('headway_entry_close', $args);
+
+ echo '</article><!-- #post-' . $post_id . ' -->';
+
+ do_action('headway_after_entry', $args);
+
+ $this->display_post_navigation();
+
+ } //show-entry check
+
+ $this->display_comments($args);
+
+ }
+
+
+ function display_entry_content($args) {
+
+ $entry_content_display = $this->get_setting('entry-content-display', 'normal');
+
+ $show_full_entries = false;
+ $show_excerpts = false;
+
+ if ( $entry_content_display == 'hide' )
+ return null;
+
+ /* Figure out whether the full entry or excerpt should be displayed */
+ if ( $entry_content_display == 'full-entries' ) {
+
+ $show_full_entries = true;
+
+ } elseif ( $entry_content_display == 'excerpts' ) {
+
+ $show_excerpts = true;
+
+ } elseif ( $args['count'] > $this->get_setting('featured-posts', 1) && !(is_singular() && $this->get_setting('mode', 'default') == 'default') ) {
+
+ $show_excerpts = true;
+
+ } elseif ( is_search() || $this->paged > 1 ) {
+
+ $show_excerpts = true;
+
+ } else {
+
+ $show_full_entries = true;
+
+ }
+
+ do_action('headway_before_entry_content', $args);
+
+ if ( $show_full_entries || get_post_type() == 'forum' ) {
+
+ echo '<div class="entry-content" itemprop="text">';
+
+ /* Force WordPress to respect the <!--more--> tag if using a custom query */
+ if ( $this->get_setting('mode', 'default') == 'custom-query' ) {
+
+ global $more;
+ $more = false;
+ the_content();
+ $more = true;
+
+ } else {
+
+ the_content();
+
+ }
+
+ wp_link_pages(array( 'before' => '<div class="page-link">' . __( 'Pages:', 'headway' ), 'after' => '</div>' ));
+
+ echo '</div><!-- .entry-content -->';
+
+ } elseif ( $show_excerpts ) {
+
+ echo '<div class="entry-summary entry-content" itemprop="text">';
+
+ the_excerpt();
+
+ echo '</div><!-- .entry-summary.entry-content -->';
+ }
+
+ do_action('headway_after_entry_content', $args);
+
+ }
+
+
+ function display_404() {
+
+ $args = array(
+ '404' => true
+ );
+
+ $post_id = 'system-404';
+ $post_class = 'page system-page system-404 hentry';
+
+ do_action('headway_before_entry', $args);
+
+ echo '<div id="post-' . $post_id . '" class="' . $post_class . '">';
+
+ do_action('headway_entry_open', $args);
+
+ do_action('headway_before_entry_title', $args);
+
+ echo '<h1 class="entry-title">' . __('Whoops! Page Not Found', 'headway') . '</h1>';
+
+ do_action('headway_after_entry_title', $args);
+
+ do_action('headway_before_entry_content', $args);
+
+ echo '<div class="entry-content">';
+
+ echo __('<p>Don\'t fret, you didn\'t do anything wrong. It appears that the page you are looking for does not exist or has been moved elsewhere.</p>', 'headway');
+
+ echo sprintf(__('<p>If you keep ending up here, please head back to our <a href="%s">homepage</a> or try the search form below.</p>', 'headway'), home_url());
+
+ get_search_form(true);
+
+ echo '</div><!-- .entry-content -->';
+
+ do_action('headway_after_entry_content', $args);
+
+ do_action('headway_entry_close', $args);
+
+ echo '</div><!-- #post-' . $post_id . ' -->';
+
+ do_action('headway_after_entry', $args);
+
+ }
+
+
+ function display_comments($hook_args) {
+
+ global $post;
+ global $withcomments;
+ global $headway_comments_template_args;
+
+ add_filter('headway_comment_form_args', array($this, 'modify_comment_args'));
+
+ /* If the block is set to always hide the comments, then don't do any more checks. */
+ if ( $this->get_setting('comments-visibility', 'auto') == 'hide' )
+ return false;
+
+
+ /* Only do these checks if the visibility is set to auto. */
+ if ( $this->get_setting('comments-visibility', 'auto') == 'auto' ) {
+
+ $post_type = get_post_type();
+
+ if ( !is_singular() )
+ return false;
+
+ if ( $post_type != 'post' )
+ return false;
+
+ if ( $this->get_setting('mode', 'default') == 'custom-query' )
+ return false;
+
+ }
+
+ /* We're all good. Show the comments. */
+ do_action('headway_before_entry_comments', $hook_args);
+
+ $withcomments = true;
+
+ /* Display Headway comments and send args to the comments_template() via a global variable */
+ $headway_comments_template_args = array(
+ 'comments-area-heading-responses-number-1' => $this->get_setting('comments-area-heading-responses-number-1', 'One Response'),
+ 'comments-area-heading-responses-number' => $this->get_setting('comments-area-heading-responses-number', '%num% Responses'),
+ 'comments-area-heading' => $this->get_setting('comments-area-heading', '%responses% to <em>%title%</em>')
+ );
+
+ comments_template();
+
+ do_action('headway_after_entry_comments', $hook_args);
+
+ }
+
+
+ function modify_comment_args() {
+
+ $leave_reply = $this->get_setting('leave-reply', 'Leave a reply');
+ $title_reply_to = $this->get_setting('leave-reply-to', 'Leave a Reply to %s');
+ $cancel_reply_text = $this->get_setting('cancel-reply-link', 'Cancel reply');
+ $submit_text = $this->get_setting('label-submit-text', 'Post Comment');
+
+ $comments_args = array(
+ 'comment_notes_before' => null,
+ 'comment_notes_after' => null,
+ 'cancel_reply_link' => __('Discard Reply', 'headway'),
+ 'title_reply' => $leave_reply,
+ 'title_reply_to' => $title_reply_to,
+ 'cancel_reply_link' => $cancel_reply_text,
+ 'label_submit' => $submit_text
+ );
+
+ return $comments_args;
+
+ }
+
+
+ function display_pagination($position = 'below') {
+
+ if ( $this->query->max_num_pages <= 1 || !$this->get_setting('paginate', true) )
+ return;
+
+ echo '<div id="nav-' . $position . '" class="loop-navigation loop-utility loop-utility-' . $position . '" itemscope itemtype="http://schema.org/SiteNavigationElement">';
+
+ /* If wp_pagenavi() plugin is activated, just use it. */
+ if ( function_exists('wp_pagenavi') ) {
+
+ wp_pagenavi();
+
+ } else {
+
+ $older_posts_text = __('<span class="meta-nav">←</span> Older posts', 'headway');
+ $newer_posts_text = __('Newer posts <span class="meta-nav">→</span>', 'headway');
+
+ echo '<div class="nav-previous" itemprop="url">' . get_next_posts_link($older_posts_text, $this->query->max_num_pages) . '</div>';
+ echo '<div class="nav-next" itemprop="url">' . get_previous_posts_link($newer_posts_text) . '</div>';
+
+ }
+
+ echo '</div><!-- #nav-' . $position . ' -->';
+
+
+ }
+
+
+ function display_thumbnail($post, $area = 'above-title') {
+
+ if ( !has_post_thumbnail() || !$this->get_setting('show-post-thumbnails', true) || !apply_filters('headway_featured_image_src', wp_get_attachment_image_src(get_post_thumbnail_id(), 'full')) )
+ return;
+
+ $entry_thumbnail_position = $this->get_setting('use-entry-thumbnail-position', true) ? HeadwayLayoutOption::get($post->ID, 'position', null, true, 'post-thumbnail') : false;
+ $position = $entry_thumbnail_position ? $entry_thumbnail_position : $this->get_setting('post-thumbnail-position', 'left');
+
+ if ( ($area == 'above-content' && $position != 'above-content') || ($area == 'above-title' && $position == 'above-content') )
+ return;
+
+ /* Get the size for cropping */
+ if ( $position == 'left' || $position == 'right' ) {
+ $thumbnail_width = $this->get_setting('post-thumbnail-size', 125);
+ $thumbnail_height = $thumbnail_width;
+ } else {
+ $thumbnail_width = ($this->get_setting('enable-column-layout', false) === true ) ? HeadwayContentBlock::get_column_width($this->block) : HeadwayBlocksData::get_block_width($this->block);
+ $thumbnail_height = $thumbnail_width * ($this->get_setting('post-thumbnail-height-ratio', 35) * .01);
+ }
+
+ /* Get the image URL */
+ if ( $this->get_setting('crop-post-thumbnails', true) ) {
+
+ $thumbnail = apply_filters('headway_featured_image_src', wp_get_attachment_image_src(get_post_thumbnail_id(), 'full'));
+
+ $thumbnail_url = apply_filters('headway_featured_image_url', headway_resize_image($thumbnail[0], $thumbnail_width, $thumbnail_height));
+
+ } else {
+
+ $thumbnail = apply_filters('headway_featured_image_src', wp_get_attachment_image_src(get_post_thumbnail_id(), array(
+ $thumbnail_width,
+ $thumbnail_height
+ )));
+
+ $thumbnail_url = apply_filters('headway_featured_image_url', $thumbnail[0]);
+
+ $thumbnail_width = 'auto';
+ $thumbnail_height = 'auto';
+
+ }
+
+ echo '
+ <a href="' . get_permalink() . '" class="post-thumbnail post-thumbnail-' . $position . '">
+ <img src="' . esc_url($thumbnail_url) . '" alt="' . the_title_attribute('echo=0') . '" width="' . $thumbnail_width . '" height="' . $thumbnail_height . '" itemprop="image" />
+ </a>
+ ';
+
+ }
+
+
+ function display_post_navigation() {
+
+ if ( !is_single() )
+ return false;
+
+ if ( !$this->get_setting('show-single-post-navigation', true) )
+ return false;
+
+ if ( $this->get_setting('mode', 'default') == 'custom-query' )
+ return false;
+
+ echo '<div id="nav-below" class="loop-navigation single-post-navigation loop-utility loop-utility-below" itemscope itemtype="http://schema.org/SiteNavigationElement">';
+
+ /* If wp_pagenavi() plugin is activated, just use it. */
+ if ( function_exists('wp_pagenavi') ) {
+
+ wp_pagenavi();
+
+ } else {
+
+ echo '<div class="nav-previous" itemprop="url">';
+ previous_post_link('%link', '<span class="meta-nav">←</span> %title', false);
+ echo '</div>';
+
+ echo '<div class="nav-next" itemprop="url">';
+ next_post_link('%link', '%title <span class="meta-nav">→</span>', false);
+ echo '</div>';
+
+ }
+
+ echo '</div><!-- #nav-below -->';
+
+
+ }
+
+
+ function parse_meta($meta) {
+
+ global $post, $authordata;
+
+ $variables = array(
+ 'date',
+ 'time',
+ 'comments',
+ 'comments_no_link',
+ 'respond',
+ 'author',
+ 'author_no_link',
+ 'categories',
+ 'tags',
+ 'edit'
+ );
+
+ foreach ( $variables as $variable ) {
+
+ if ( strpos($meta, '%' . $variable . '%') === false )
+ continue;
+
+ switch ( $variable ) {
+
+ case 'date':
+
+ $date_format = $this->get_setting('date-format', 'wordpress-default');
+ $date = ($date_format != 'wordpress-default') ? get_the_time($date_format) : get_the_date();
+
+ $replacement['date'] = '<time class="entry-date published updated" itemprop="datePublished" datetime="' . get_the_time( 'c' ) . '">' . $date . '</time>';
+
+ break;
+
+ case 'time':
+
+ $time_format = $this->get_setting('time-format', 'wordpress-default');
+ $time = ($date_format != 'wordpress-default') ? get_the_time($time_format) : get_the_time();
+
+ $replacement['time'] = '<time class="entry-time" datetime="' . get_the_time( 'c' ) . '">' . $time . '</time>';
+
+ break;
+
+ case 'comments':
+ case 'comments_no_link':
+
+ $comments_number = (int)get_comments_number($post->ID);
+
+ if ( $comments_number === 0 )
+ $comments_format = stripslashes($this->get_setting('comment-format-0', '%num% Comments'));
+ elseif ( $comments_number == 1 )
+ $comments_format = stripslashes($this->get_setting('comment-format-1', '%num% Comment'));
+ elseif ( $comments_number > 1 )
+ $comments_format = stripslashes($this->get_setting('comment-format', '%num% Comments'));
+
+ $comments = str_replace('%num%', $comments_number, $comments_format);
+
+ $replacement['comments'] = '<a href="' . get_comments_link() . '" title="' . sprintf(__('%s – Comments', 'headway'), the_title_attribute('echo=0')) . '" class="entry-comments">' . $comments . '</a>';
+ $replacement['comments_no_link'] = $comments;
+
+ break;
+
+ case 'respond':
+
+ $respond_format = stripslashes($this->get_setting('respond-format', 'Leave a comment!'));
+
+ $replacement['respond'] = '<a href="' . get_permalink() . '#respond" title="' . sprintf(__('Respond to %s', 'headway'), the_title_attribute('echo=0')) . '" class="entry-respond">' . $respond_format . '</a>';
+
+ break;
+
+ case 'author':
+ case 'author_no_link':
+
+ $replacement['author'] = '<span class="entry-author vcard" itemprop="author" itemscope itemptype="http://schema.org/Person"><a class="author-link fn nickname url" href="' . get_author_posts_url($authordata->ID) . '" title="' . sprintf(__('View all posts by %s', 'headway'), $authordata->display_name) . '" itemprop="url"><span class="entry-author-name" itemprop="name">' . $authordata->display_name . '</span></a></span>';
+ $replacement['author_no_link'] = $authordata->display_name;
+
+ break;
+
+ case 'categories':
+ $replacement['categories'] = get_the_category_list(', ');
+ break;
+
+ case 'tags':
+ $replacement['tags'] = (get_the_tags() != NULL) ? get_the_tag_list('<span class="tag-links" itemprop="keywords">','<span class="tag-sep">, </span>','</span>') : '';
+ break;
+
+ case 'edit':
+ $replacement['edit'] = null;
+ break;
+
+
+ }
+
+ $meta = str_replace('%' . $variable . '%', $replacement[$variable], $meta);
+
+ }
+
+ return apply_filters('headway_meta', $meta);
+
+ }
+
+
+ /**
+ * Assembles the classes for the posts.
+ *
+ * @global object $post
+ * @global int $blog_post_alt
+ *
+ * @param bool $print Determines whether or not to echo the post classes.
+ *
+ * @return bool|string If $print is true, then echo the classes, otherwise just return them as a string.
+ **/
+ function entry_class() {
+
+ global $post, $blog_post_alt, $authordata;
+
+ $c = get_post_class();
+
+ if ( !isset($blog_post_alt) )
+ $blog_post_alt = 1;
+
+ if ( is_object($authordata) )
+ $c[] = 'author-' . sanitize_title_with_dashes(strtolower($authordata->user_login));
+
+ if ( ++$blog_post_alt % 2 )
+ $c[] = 'alt';
+
+ //Add the custom classes from the meta box
+ if ( $custom_css_class = HeadwayLayoutOption::get(get_the_id(), 'css-class', null, true) ) {
+
+ $custom_css_classes = str_replace(' ', ' ', str_replace(',', ' ', esc_attr(strip_tags($custom_css_class))));
+
+ $c = array_merge($c, array_filter(explode(' ', $custom_css_classes)));
+
+ }
+
+ $c[] = $this->get_setting('mode');
+
+ $c = join(' ', $c);
+
+ return $c;
+
+ }
+
+
+ function more_link($more_link) {
+
+ global $post;
+
+ if ( !$this->get_setting('show-readmore', true) )
+ return false;
+
+ $more_text = $this->get_setting('read-more-text', 'Continue Reading');
+ $more_link = '<a href="'. get_permalink($post->ID) . '" class="more-link">' . $more_text . '</a>';
+
+ return apply_filters('headway_more_link', '<span class="more-link-ellipsis">... </span>' . $more_link);
+
+ }
+
+
+ function filter_add_auto_excerpt_more_link($more_link) {
+
+ if ( !$more_link )
+ return null;
+
+ return apply_filters('the_content_more_link', $more_link);
+
+ }
+
+
+ function filter_add_custom_excerpt_more_link($output) {
+
+ global $post;
+
+ if ( (strpos($post->post_content, '<!--more-->') === false && !has_excerpt()) || is_attachment() )
+ return $output;
+
+ $more_link = apply_filters('the_content_more_link', 'More');
+
+ return $output . $more_link;
+
+ }
+
+
+ function filter_nofollow_links_in_post($text) {
+
+ global $post;
+
+ if ( !is_object($post) || empty($post->ID) || !HeadwaySEO::is_seo_checkbox_enabled('nofollow', $post->ID) )
+ return $text;
+
+ preg_match_all("/<a.*? href=\"(.*?)\".*?>(.*?)<\/a>/i", $text, $links);
+ $match_count = count($links[0]);
+
+ for ( $i=0; $i < $match_count; $i++ ) {
+
+ if ( !preg_match("/rel=[\"\']*nofollow[\"\']*/",$links[0][$i]) ) {
+
+ preg_match_all("/<a.*? href=\"(.*?)\"(.*?)>(.*?)<\/a>/i", $links[0][$i], $link_text);
+
+ $text = str_replace('>' . $link_text[3][0] . '</a>', ' rel="nofollow">' . $link_text[3][0] . '</a>', $text);
+
+ }
+
+ }
+
+ return $text;
+
+ }
+
+
+}
--- /dev/null
+<?php
+headway_register_block('HeadwayContentBlock', headway_url() . '/library/blocks/content');
+
+class HeadwayContentBlock extends HeadwayBlockAPI {
+
+
+ public $id = 'content';
+
+ public $name = 'Content';
+
+ public $options_class = 'HeadwayContentBlockOptions';
+
+ public $description = 'Main content area to show the current page\'s content or the latest posts. This is considered the "Loop" in other themes.';
+
+
+ function init() {
+
+ /* Load dependencies */
+ require_once HEADWAY_LIBRARY_DIR . '/blocks/content/content-display.php';
+
+ /* Set up the comments template */
+ add_filter('comments_template', array(__CLASS__, 'add_blank_comments_template'), 5);
+
+ /* Set up editor style */
+ add_filter('mce_css', array(__CLASS__, 'add_editor_style'));
+
+ /* Add .comment class to all pingbacks */
+ add_filter('comment_class', array(__CLASS__, 'add_comment_class_to_all_types'));
+
+ }
+
+
+ public static function add_blank_comments_template() {
+
+ return HEADWAY_LIBRARY_DIR . '/blocks/content/comments-template.php';
+
+ }
+
+
+ public static function add_comment_class_to_all_types($classes) {
+
+ if ( !is_array($classes) )
+ $classes = implode(' ', trim($classes));
+
+ $classes[] = 'comment';
+
+ return array_filter(array_unique($classes));
+
+ }
+
+
+ public static function add_editor_style($css) {
+
+ if ( HeadwayOption::get('disable-editor-style', false, false) )
+ return $css;
+
+ if ( !current_theme_supports('editor-style') )
+ return $css;
+
+ if ( !current_theme_supports('headway-design-editor') )
+ return $css;
+
+ HeadwayCompiler::register_file(array(
+ 'name' => 'editor-style',
+ 'format' => 'css',
+ 'fragments' => array(
+ 'headway_content_block_editor_style'
+ ),
+ 'dependencies' => array(HEADWAY_LIBRARY_DIR . '/blocks/content/editor-style.php'),
+ 'enqueue' => false
+ ));
+
+ return $css . ',' . HeadwayCompiler::get_url('editor-style');
+
+ }
+
+ public static function dynamic_css($block_id, $block) {
+
+ $css = '';
+
+ if ( parent::get_setting($block, 'enable-column-layout') ) {
+
+ $gutter_width = parent::get_setting($block, 'post-gutter-width', '20');
+
+ $css = '';
+
+ if ( HeadwayResponsiveGrid::is_enabled() ) {
+ $css .= '@media only screen and (min-width: ' . HeadwayBlocksData::get_block_width($block) . 'px) {';
+ }
+
+ $css .= '#block-' . $block_id . ' .loop .entry-row .hentry {';
+
+ $css .= 'margin-left: ' . self::width_as_percentage($gutter_width, $block) . '%;';
+ $css .= 'width: ' . self::width_as_percentage(self::get_column_width($block), $block) . '%;';
+
+ $css .= '}';
+
+ if ( HeadwayResponsiveGrid::is_enabled() ) {
+ $css .= '}';
+ }
+
+ }
+
+ return $css . "\n";
+
+
+ }
+
+ static function get_column_width($block) {
+
+ $block_width = HeadwayBlocksData::get_block_width($block);
+
+ $columns = parent::get_setting($block, 'posts-per-row', '2');
+ $gutter_width = parent::get_setting($block, 'post-gutter-width', '20');
+
+ $total_gutter = $gutter_width * ($columns-1);
+
+ $columns_width = (($block_width - $total_gutter) / $columns);
+
+ return $columns_width;
+ }
+
+ /* To make the layout responsive
+ * Works out a percentage value equivalent of the px value
+ * using common responsive formula: target_width / container_width * 100
+ */
+ static function width_as_percentage($target = '', $block) {
+ $block_width = HeadwayBlocksData::get_block_width($block);
+
+ if ($block_width > 0 )
+ return ($target / $block_width)*100;
+
+ return false;
+ }
+
+
+ function setup_elements() {
+
+ $this->register_block_element(array(
+ 'id' => 'entry-container-hentry',
+ 'name' => 'Entry Container',
+ 'selector' => '.hentry',
+ 'properties' => array('background', 'borders', 'padding', 'corners', 'box-shadow')
+ ));
+
+ $this->register_block_element(array(
+ 'id' => 'page-container',
+ 'name' => 'Page Entry Container',
+ 'parent' => 'entry-container-hentry',
+ 'selector' => '.type-page'
+ ));
+
+ $this->register_block_element(array(
+ 'id' => 'entry-container',
+ 'name' => 'Post Entry Container',
+ 'parent' => 'entry-container-hentry',
+ 'selector' => '.type-post'
+ ));
+
+ $this->register_block_element(array(
+ 'id' => 'entry-row',
+ 'name' => 'Entry Row',
+ 'selector' => '.entry-row'
+ ));
+
+ $this->register_block_element(array(
+ 'id' => 'title',
+ 'name' => 'Title',
+ 'selector' => '.entry-title',
+ 'states' => array(
+ 'Hover' => '.entry-title:hover',
+ 'Clicked' => '.entry-title:active'
+ )
+ ));
+
+ $this->register_block_element(array(
+ 'id' => 'archive-title',
+ 'name' => 'Archive Title',
+ 'selector' => '.archive-title'
+ ));
+
+ $this->register_block_element(array(
+ 'id' => 'entry-content',
+ 'name' => 'Body Text',
+ 'description' => 'All text including <p> elements',
+ 'selector' => 'div.entry-content, div.entry-content p'
+ ));
+
+ $this->register_block_element(array(
+ 'id' => 'entry-content-hyperlinks',
+ 'name' => 'Body Hyperlinks',
+ 'selector' => 'div.entry-content a',
+ 'properties' => array('fonts'),
+ 'states' => array(
+ 'Hover' => 'div.entry-content a:hover',
+ 'Clicked' => 'div.entry-content a:active'
+ )
+ ));
+
+ $this->register_block_element(array(
+ 'id' => 'entry-content-images',
+ 'name' => 'Images',
+ 'selector' => 'div.entry-content img',
+ 'properties' => array('background', 'borders', 'padding', 'corners', 'box-shadow')
+ ));
+
+ $this->register_block_element( array(
+ 'id' => 'entry-content-image-captions',
+ 'name' => 'Image Captions',
+ 'selector' => 'div.entry-content .wp-caption',
+ 'properties' => array( 'background', 'borders', 'padding', 'corners', 'box-shadow' )
+ ) );
+
+ $this->register_block_element( array(
+ 'id' => 'entry-content-image-caption-image',
+ 'parent' => 'entry-content-image-captions',
+ 'name' => 'Images in Captions',
+ 'selector' => 'div.entry-content .wp-caption img',
+ 'properties' => array( 'background', 'borders', 'padding', 'corners', 'box-shadow' )
+ ) );
+
+ $this->register_block_element( array(
+ 'id' => 'entry-content-image-caption-text',
+ 'parent' => 'entry-content-image-captions',
+ 'name' => 'Caption Text',
+ 'selector' => 'div.entry-content .wp-caption .wp-caption-text'
+ ) );
+
+ $this->register_block_element(array(
+ 'id' => 'entry-meta',
+ 'name' => 'Meta',
+ 'selector' => 'div.entry-meta'
+ ));
+
+ $this->register_block_element(array(
+ 'id' => 'entry-meta-above',
+ 'name' => 'Meta Above Content',
+ 'selector' => 'div.entry-meta-above',
+ 'parent' => 'entry-meta'
+ ));
+
+
+
+ $this->register_block_element(array(
+ 'id' => 'entry-meta-below',
+ 'name' => 'Meta Below Content',
+ 'selector' => 'footer.entry-utility-below',
+ 'parent' => 'entry-meta'
+ ));
+
+
+
+ $this->register_block_element(array(
+ 'id' => 'entry-meta-links',
+ 'name' => 'Meta Hyperlinks',
+ 'selector' => 'div.entry-meta a, footer.entry-meta a',
+ 'parent' => 'entry-meta',
+ 'properties' => array('fonts'),
+ 'states' => array(
+ 'Hover' => 'div.entry-meta a:hover, footer.entry-meta a:hover',
+ 'Clicked' => 'div.entry-meta a:active, footer.entry-meta a:active'
+ )
+ ));
+
+
+ $this->register_block_element(array(
+ 'id' => 'entry-meta-author',
+ 'name' => 'Author Avatar Image',
+ 'selector' => '.avatar',
+ 'parent' => 'entry-meta'
+ ));
+
+ $this->register_block_element(array(
+ 'id' => 'entry-date',
+ 'name' => 'Post Entry Date',
+ 'parent' => 'entry-meta',
+ 'selector' => '.entry-date'
+ ));
+
+ $this->register_block_element(array(
+ 'id' => 'heading',
+ 'name' => 'Heading',
+ 'selector' => 'div.entry-content h3, div.entry-content h2, div.entry-content h1'
+ ));
+
+ $this->register_block_element(array(
+ 'id' => 'heading-h1',
+ 'parent' => 'heading',
+ 'name' => 'H1',
+ 'selector' => 'div.entry-content h1',
+ 'parent' => 'heading'
+ ));
+
+ $this->register_block_element(array(
+ 'id' => 'heading-h2',
+ 'parent' => 'heading',
+ 'name' => 'H2',
+ 'selector' => 'div.entry-content h2'
+ ));
+
+ $this->register_block_element(array(
+ 'id' => 'heading-h3',
+ 'parent' => 'heading',
+ 'name' => 'H3',
+ 'selector' => 'div.entry-content h3'
+ ));
+
+ $this->register_block_element(array(
+ 'id' => 'sub-heading',
+ 'name' => 'Sub Heading',
+ 'selector' => 'div.entry-content h4, div.entry-content h5'
+ ));
+
+ $this->register_block_element(array(
+ 'id' => 'sub-heading-h4',
+ 'parent' => 'sub-heading',
+ 'name' => 'H4',
+ 'selector' => 'div.entry-content h4'
+ ));
+
+ $this->register_block_element(array(
+ 'id' => 'sub-heading-h5',
+ 'parent' => 'sub-heading',
+ 'name' => 'H5',
+ 'selector' => 'div.entry-content h5'
+ ));
+
+ $this->register_block_element(array(
+ 'id' => 'content-ul-lists',
+ 'name' => 'Unordered Lists',
+ 'description' => '<UL>',
+ 'selector' => 'div.entry-content ul',
+ 'properties' => array('fonts', 'background', 'borders', 'padding', 'corners', 'box-shadow'),
+ ));
+
+ $this->register_block_element(array(
+ 'id' => 'content-ul-list-item',
+ 'name' => 'Unordered List Items',
+ 'description' => '<LI>',
+ 'selector' => 'div.entry-content ul li',
+ 'properties' => array('fonts', 'lists', 'background', 'borders', 'padding', 'corners', 'box-shadow'),
+ ));
+
+ $this->register_block_element(array(
+ 'id' => 'content-ol-lists',
+ 'name' => 'Ordered Lists',
+ 'description' => '<OL>',
+ 'selector' => 'div.entry-content ol',
+ 'properties' => array('fonts', 'background', 'borders', 'padding', 'corners', 'box-shadow'),
+ ));
+
+ $this->register_block_element(array(
+ 'id' => 'content-list-item',
+ 'name' => 'Ordered List Items',
+ 'description' => '<LI>',
+ 'selector' => 'div.entry-content ol li',
+ 'properties' => array('fonts', 'lists', 'background', 'borders', 'padding', 'corners', 'box-shadow'),
+ ));
+
+ $this->register_block_element(array(
+ 'id' => 'post-thumbnail',
+ 'name' => 'Featured Image',
+ 'selector' => '.block-type-content a.post-thumbnail img',
+ 'properties' => array('background', 'borders', 'padding', 'corners', 'box-shadow')
+ ));
+
+ $this->register_block_element(array(
+ 'id' => 'more-link',
+ 'name' => 'Continue Reading Button',
+ 'selector' => 'div.entry-content a.more-link',
+ 'states' => array(
+ 'Hover' => 'div.entry-content a.more-link:hover',
+ 'Clicked' => 'div.entry-content a.more-link:active'
+ )
+ ));
+
+ $this->register_block_element(array(
+ 'id' => 'loop-navigation-link',
+ 'name' => 'Loop Navigation Button',
+ 'selector' => 'div.loop-navigation div.nav-previous a, div.loop-navigation div.nav-next a',
+ 'states' => array(
+ 'Hover' => 'div.loop-navigation div.nav-previous a:hover, div.loop-navigation div.nav-next a:hover',
+ 'Clicked' => 'div.loop-navigation div.nav-previous a:active, div.loop-navigation div.nav-next a:active'
+ )
+ ));
+
+ $this->register_block_element(array(
+ 'id' => 'comments-wrapper',
+ 'name' => 'Comments',
+ 'selector' => 'div#comments'
+ ));
+
+ $this->register_block_element(array(
+ 'id' => 'comments-area',
+ 'name' => 'Comments Area',
+ 'selector' => 'ol.commentlist',
+ 'properties' => array('background', 'borders', 'padding', 'corners', 'box-shadow'),
+ 'parent' => 'comments-wrapper'
+ ));
+
+ $this->register_block_element(array(
+ 'id' => 'comments-area-headings',
+ 'name' => 'Comments Area Headings',
+ 'selector' => 'div#comments h3',
+ 'parent' => 'comments-wrapper'
+ ));
+
+ $this->register_block_element(array(
+ 'id' => 'comment-container',
+ 'name' => 'Comment Container',
+ 'selector' => 'li.comment',
+ 'properties' => array('background', 'borders', 'padding', 'corners', 'box-shadow'),
+ 'parent' => 'comments-wrapper'
+ ));
+
+ $this->register_block_element(array(
+ 'id' => 'comments-textarea',
+ 'name' => 'Add Comment Textarea',
+ 'selector' => '#comment',
+ 'parent' => 'comments-wrapper'
+ ));
+
+ $this->register_block_element(array(
+ 'id' => 'comment-author',
+ 'name' => 'Comment Author',
+ 'selector' => 'li.comment .comment-author',
+ 'parent' => 'comments-wrapper'
+ ));
+
+ $this->register_block_element(array(
+ 'id' => 'comment-meta',
+ 'name' => 'Comment Meta',
+ 'selector' => 'li.comment .comment-meta',
+ 'parent' => 'comments-wrapper'
+ ));
+
+ $this->register_block_element(array(
+ 'id' => 'comment-meta-count',
+ 'name' => 'Comment Meta Count',
+ 'selector' => 'a.entry-comments',
+ 'parent' => 'comments-wrapper'
+ ));
+
+ $this->register_block_element(array(
+ 'id' => 'comment-body',
+ 'name' => 'Comment Body',
+ 'selector' => 'li.comment .comment-body p',
+ 'properties' => array('fonts'),
+ 'parent' => 'comments-wrapper'
+ ));
+
+ $this->register_block_element(array(
+ 'id' => 'comment-reply-link',
+ 'name' => 'Comment Reply Link',
+ 'selector' => 'a.comment-reply-link',
+ 'states' => array(
+ 'Hover' => 'a.comment-reply-link:hover',
+ 'Clicked' => 'a.comment-reply-link:active'
+ ),
+ 'parent' => 'comments-wrapper'
+ ));
+
+ $this->register_block_element(array(
+ 'id' => 'comment-form-input-label',
+ 'name' => 'Comment Form Input Label',
+ 'selector' => 'div#respond label',
+ 'properties' => array('fonts'),
+ 'parent' => 'comments-wrapper'
+ ));
+
+ }
+
+
+ function content($block) {
+
+ $content_block_display = new HeadwayContentBlockDisplay($block);
+ $content_block_display->display();
+
+ }
+
+
+}
+
+
+class HeadwayContentBlockOptions extends HeadwayBlockOptionsAPI {
+
+
+ public $tab_notices = array(
+ 'mode' => 'The content block is extremely versatile. If the default mode is selected, it will do what you expect it to do. For example, if you add this on a page, it will display that page\'s content. If you add it on the Blog Index layout, it will list the posts like a normal blog template and if you add this box on a category layout, it will list posts of that category. If you wish to change what the content block displays, change the mode to <em>Custom Query</em> and use the settings in the <em>Query Filters</em> tab.',
+ 'query-setup' => 'For more control over queries and how the query is displayed, Headway works perfectly out-of-the-box with <a href="http://pluginbuddy.com/purchase/loopbuddy/" target="_blank">LoopBuddy</a>.',
+ 'meta' => '
+ <p>The entry meta is the information that appears below the post title and below the post content. By default, it will contain information about the entry author, the categories, and comments.</p>
+ <p><strong>Available Variables:</strong></p>
+ <p>%date% • %time% • %comments% • %comments_no_link% • %respond% • %author% • %author_no_link% • %categories% • %tags%</p>
+ '
+ );
+
+
+ public $tabs = array(
+ 'mode' => 'Mode',
+ 'query-filters' => 'Query Filters',
+ 'display' => 'Display',
+ 'meta' => 'Meta',
+ 'comments' => 'Comments',
+ 'post-thumbnails' => 'Featured Images'
+ );
+
+
+ public $inputs = array(
+
+ 'mode' => array(
+ 'mode' => array(
+ 'type' => 'select',
+ 'name' => 'mode',
+ 'label' => 'Query Mode',
+ 'tooltip' => '',
+ 'options' => array(
+ 'default' => 'Default Behavior',
+ 'custom-query' => 'Custom Query'
+ ),
+ 'toggle' => array(
+ 'custom-query' => array(
+ 'show' => array(
+ 'li#sub-tab-query-filters'
+ )
+ ),
+ 'default' => array(
+ 'hide' => array(
+ 'li#sub-tab-query-filters'
+ )
+ )
+ )
+ )
+ ),
+
+ 'query-filters' => array(
+ 'fetch-page-content' => array(
+ 'type' => 'select',
+ 'name' => 'fetch-page-content',
+ 'label' => 'Fetch Page Content',
+ 'tooltip' => '',
+ 'options' => 'get_pages()'
+ ),
+
+ 'categories' => array(
+ 'type' => 'multi-select',
+ 'name' => 'categories',
+ 'label' => 'Categories',
+ 'tooltip' => '',
+ 'options' => 'get_categories()'
+ ),
+
+ 'categories-mode' => array(
+ 'type' => 'select',
+ 'name' => 'categories-mode',
+ 'label' => 'Categories Mode',
+ 'tooltip' => '',
+ 'options' => array(
+ 'include' => 'Include',
+ 'exclude' => 'Exclude'
+ )
+ ),
+
+ 'post-type' => array(
+ 'type' => 'multi-select',
+ 'name' => 'post-type',
+ 'label' => 'Post Type',
+ 'tooltip' => '',
+ 'options' => 'get_post_types()'
+ ),
+
+ 'author' => array(
+ 'type' => 'multi-select',
+ 'name' => 'author',
+ 'label' => 'Author',
+ 'tooltip' => '',
+ 'options' => 'get_authors()'
+ ),
+
+ 'number-of-posts' => array(
+ 'type' => 'integer',
+ 'name' => 'number-of-posts',
+ 'label' => 'Number of Posts',
+ 'tooltip' => '',
+ 'default' => 10
+ ),
+
+ 'offset' => array(
+ 'type' => 'integer',
+ 'name' => 'offset',
+ 'label' => 'Offset',
+ 'tooltip' => 'The offset is the number of entries or posts you would like to skip. If the offset is 1, then the first post will be skipped.',
+ 'default' => 0
+ ),
+
+ 'order-by' => array(
+ 'type' => 'select',
+ 'name' => 'order-by',
+ 'label' => 'Order By',
+ 'tooltip' => '',
+ 'options' => array(
+ 'date' => 'Date',
+ 'title' => 'Title',
+ 'rand' => 'Random',
+ 'comment_count' => 'Comment Count',
+ 'ID' => 'ID'
+ )
+ ),
+
+ 'order' => array(
+ 'type' => 'select',
+ 'name' => 'order',
+ 'label' => 'Order',
+ 'tooltip' => '',
+ 'options' => array(
+ 'desc' => 'Descending',
+ 'asc' => 'Ascending',
+ )
+ )
+ ),
+
+ 'display' => array(
+ 'read-more-text' => array(
+ 'type' => 'text',
+ 'label' => 'Read More Text',
+ 'name' => 'read-more-text',
+ 'default' => 'Continue Reading',
+ 'tooltip' => 'If excerpts are being shown or a featured post is truncated using WordPress\' read more shortcode, then this will be shown after the excerpt or truncated content.'
+ ),
+
+ 'show-titles' => array(
+ 'type' => 'checkbox',
+ 'name' => 'show-titles',
+ 'label' => 'Show Titles',
+ 'default' => true,
+ 'tooltip' => 'If you wish to only show the content and meta of the entry, you can hide the entry (post or page) titles with this option.'
+ ),
+
+ 'link-titles' => array(
+ 'type' => 'checkbox',
+ 'name' => 'link-titles',
+ 'label' => 'Link Titles?',
+ 'default' => true,
+ 'tooltip' => 'If you wish to turn off the link to Post/Page titles, uncheck this'
+ ),
+
+
+ 'show-readmore' => array(
+ 'type' => 'checkbox',
+ 'name' => 'show-readmore',
+ 'label' => 'Show Read More',
+ 'default' => true,
+ 'tooltip' => 'Show and hide the continue reading or read more text/button.'
+ ),
+
+ 'entry-content-display' => array(
+ 'type' => 'select',
+ 'name' => 'entry-content-display',
+ 'label' => 'Entry Content Display',
+ 'tooltip' => 'The entry content is the actual body of the entry. This is what you enter in the rich text area when creating an entry (post or page). When set to normal, Headway will determine if full entries or excerpts should be displayed based off of the <em>Featured Posts</em> setting and what page is being displayed.<br /><br /><strong>Tip:</strong> Set this to <em>Hide Entry Content</em> to create a simple listing of posts.',
+ 'default' => 'normal',
+ 'options' => array(
+ 'normal' => 'Normal',
+ 'full-entries' => 'Show Full Entries',
+ 'excerpts' => 'Show Excerpts',
+ 'hide' => 'Hide Entry Content'
+ )
+ ),
+
+ 'show-entry' => array(
+ 'type' => 'checkbox',
+ 'name' => 'show-entry',
+ 'label' => 'Show Entry',
+ 'default' => true,
+ 'tooltip' => 'By default, the entries will always be shown. However, there may be certain cases where you wish to show the entry content in one Content Block, but the comments in another. With this option, you can do that.'
+ ),
+
+ 'comments-visibility' => array(
+ 'type' => 'select',
+ 'name' => 'comments-visibility',
+ 'label' => 'Comments Visibility',
+ 'default' => 'auto',
+ 'options' => array(
+ 'auto' => 'Automatic',
+ 'hide' => 'Always Hide Comments',
+ 'show' => 'Always Show Comments'
+ ),
+ 'tooltip' => 'When set to automatic, the comments will only show on single post pages. However, there may be times where you want to force comment visibility to allow comments on pages. Or, you may hide the comments if you wish to not see them at all.<br /><br /><strong>Tip:</strong> Create unique layouts by using this option in conjunction with the Show Entry option to show the entry content in one Content Block and show the comments in another Content Block.'
+ ),
+
+ 'featured-posts' => array(
+ 'type' => 'integer',
+ 'name' => 'featured-posts',
+ 'label' => 'Featured Posts',
+ 'default' => 1,
+ 'tooltip' => 'Featured posts are the posts where all of the content is displayed, unless limited by using the WordPress more tag. After the featured posts are displayed, the content will automatically switch to showing automatically truncated excerpts.'
+ ),
+
+ 'paginate' => array(
+ 'type' => 'checkbox',
+ 'name' => 'paginate',
+ 'label' => 'Show Older/Newer Posts Navigation',
+ 'tooltip' => 'Show links at the bottom of the loop for the visitor to view older or newer posts.',
+ 'default' => true
+ ),
+
+ 'show-single-post-navigation' => array(
+ 'type' => 'checkbox',
+ 'name' => 'show-single-post-navigation',
+ 'label' => 'Show Single Post Navigation',
+ 'default' => true,
+ 'tooltip' => 'By default, Headway will show links to the previous and next posts below an entry when viewing only one entry at a time. You can choose to hide those links with this option.'
+ ),
+
+ 'show-edit-link' => array(
+ 'type' => 'checkbox',
+ 'name' => 'show-edit-link',
+ 'label' => 'Show Edit Link',
+ 'default' => true,
+ 'tooltip' => 'The edit link is a convenient link that will be shown next to the post title. It will take you straight to the WordPress admin to edit the entry.'
+ ),
+
+ 'column-layout-heading' => array(
+ 'name' => 'column-layout-heading',
+ 'type' => 'heading',
+ 'label' => 'Column Layout'
+ ),
+
+ 'enable-column-layout' => array(
+ 'type' => 'checkbox',
+ 'name' => 'enable-column-layout',
+ 'label' => 'Enable Column Layout',
+ 'default' => false,
+ 'tooltip' => 'Enable this option to display articles side by side as columns.',
+ 'toggle' => array(
+ 'true' => array(
+ 'show' => array(
+ '#input-posts-per-row',
+ '#input-post-gutter-width',
+ '#input-post-bottom-margin'
+ )
+ ),
+ 'false' => array(
+ 'hide' => array(
+ '#input-posts-per-row',
+ '#input-post-gutter-width',
+ '#input-post-bottom-margin'
+ )
+ )
+ )
+ ),
+
+ 'posts-per-row' => array(
+ 'type' => 'slider',
+ 'name' => 'posts-per-row',
+ 'label' => 'Posts Per Row',
+ 'slider-min' => 1,
+ 'slider-max' => 10,
+ 'slider-interval' => 1,
+ 'tooltip' => '',
+ 'default' => 2,
+ 'tooltip' => 'How many posts to show per row.',
+ 'callback' => ''
+ ),
+
+ 'post-gutter-width' => array(
+ 'type' => 'slider',
+ 'name' => 'post-gutter-width',
+ 'label' => 'Gutter Width',
+ 'slider-min' => 0,
+ 'slider-max' => 100,
+ 'slider-interval' => 1,
+ 'default' => 15,
+ 'unit' => 'px',
+ 'tooltip' => 'The amount of horizontal spacing between posts.'
+ )
+ ),
+
+ 'meta' => array(
+ 'show-entry-meta-post-types' => array(
+ 'type' => 'multi-select',
+ 'name' => 'show-entry-meta-post-types',
+ 'label' => 'Entry Meta Display (Per Post Type)',
+ 'tooltip' => 'Choose which post types you wish for the entry meta to appear on.',
+ 'options' => 'get_post_types()',
+ 'default' => array('post')
+ ),
+
+ 'entry-meta-above' => array(
+ 'type' => 'textarea',
+ 'label' => 'Meta Above Content',
+ 'name' => 'entry-meta-above',
+ 'default' => 'Posted on %date% by %author% • %comments%'
+ ),
+
+ 'entry-utility-below' => array(
+ 'type' => 'textarea',
+ 'label' => 'Meta Below Content',
+ 'name' => 'entry-utility-below',
+ 'default' => 'Filed Under: %categories%'
+ ),
+
+ 'date-format' => array(
+ 'type' => 'select',
+ 'name' => 'date-format',
+ 'label' => 'Date Format'
+ ),
+
+ 'time-format' => array(
+ 'type' => 'select',
+ 'name' => 'time-format',
+ 'label' => 'Time Format'
+ ),
+
+ 'comments-meta-heading' => array(
+ 'name' => 'comments-meta-heading',
+ 'type' => 'heading',
+ 'label' => 'Comments Meta'
+ ),
+
+ 'comment-format' => array(
+ 'type' => 'text',
+ 'label' => 'Comment Format – More Than 1 Comment',
+ 'name' => 'comment-format',
+ 'default' => '%num% Comments',
+ 'tooltip' => 'Controls what the %comments% and %comments_no_link% variables will output in the entry meta if there is <strong>more than 1 comment</strong> on the entry.'
+ ),
+
+ 'comment-format-1' => array(
+ 'type' => 'text',
+ 'label' => 'Comment Format – 1 Comment',
+ 'name' => 'comment-format-1',
+ 'default' => '%num% Comment',
+ 'tooltip' => 'Controls what the %comments% and %comments_no_link% variables will output in the entry meta if there is <strong>just 1 comment</strong> on the entry.'
+ ),
+
+ 'comment-format-0' => array(
+ 'type' => 'text',
+ 'label' => 'Comment Format – 0 Comments',
+ 'name' => 'comment-format-0',
+ 'default' => '%num% Comments',
+ 'tooltip' => 'Controls what the %comments% and %comments_no_link% variables will output in the entry meta if there are <strong>0 comments</strong> on the entry.'
+
+ ),
+
+ 'respond-format' => array(
+ 'type' => 'text',
+ 'label' => 'Respond Format',
+ 'name' => 'respond-format',
+ 'default' => 'Leave a comment!',
+ 'tooltip' => 'Determines the %respond% variable for the entry meta.'
+ )
+ ),
+
+ 'comments' => array(
+ 'comments-area' => array(
+ 'name' => 'comments-area',
+ 'type' => 'heading',
+ 'label' => 'Comments Area Heading'
+ ),
+
+ 'comments-area-heading' => array(
+ 'type' => 'text',
+ 'label' => 'Comments Area Heading Format',
+ 'name' => 'comments-area-heading',
+ 'default' => '%responses% to <em>%title%</em>',
+ 'tooltip' => 'Heading above all comments.
+ <br />
+ <br /><strong>Available Variables:</strong>
+ <ul>
+ <li>%responses%</li>
+ <li>%title%</li>
+ </ul>'
+ ),
+
+ 'comments-area-heading-responses-number' => array(
+ 'type' => 'text',
+ 'label' => 'Responses Format – More Than 1 Comment',
+ 'name' => 'comments-area-heading-responses-number',
+ 'default' => '%num% Responses',
+ 'tooltip' => 'Controls what the %responses% variable will output in the comments area heading if there is <strong>more than 1 comment</strong> on the entry.'
+ ),
+
+ 'comments-area-heading-responses-number-1' => array(
+ 'type' => 'text',
+ 'label' => 'Responses Format – 1 Comment',
+ 'name' => 'comments-area-heading-responses-number-1',
+ 'default' => 'One Response',
+ 'tooltip' => 'Controls what the %responses% variable will output in the comments area heading if there is <strong>just 1 comment</strong> on the entry.'
+ ),
+
+ 'reply-area-heading' => array(
+ 'name' => 'reply-area-heading',
+ 'type' => 'heading',
+ 'label' => 'Reply Area'
+ ),
+
+ 'leave-reply' => array(
+ 'type' => 'text',
+ 'label' => 'Comment Form Title',
+ 'name' => 'leave-reply',
+ 'default' => 'Leave a reply',
+ 'tooltip' => 'This is the text that displays above the comment form.'
+ ),
+
+ 'leave-reply-to' => array(
+ 'type' => 'text',
+ 'label' => 'Reply Form Title',
+ 'name' => 'leave-reply-to',
+ 'default' => 'Leave a Reply to %s',
+ 'tooltip' => 'The title of comment form when replying to a comment.'
+ ),
+
+ 'cancel-reply-link' => array(
+ 'type' => 'text',
+ 'label' => 'Cancel Reply Text',
+ 'name' => 'cancel-reply-link',
+ 'default' => 'Cancel reply',
+ 'tooltip' => 'The text for the cancel reply button.'
+ ),
+
+ 'label-submit-text' => array(
+ 'type' => 'text',
+ 'label' => 'Submit Text',
+ 'name' => 'label-submit-text',
+ 'default' => 'Post Comment',
+ 'tooltip' => 'The submit button text.'
+ )
+ ),
+
+ 'post-thumbnails' => array(
+ 'show-post-thumbnails' => array(
+ 'type' => 'checkbox',
+ 'name' => 'show-post-thumbnails',
+ 'label' => 'Show Featured Images',
+ 'default' => true
+ ),
+
+ 'post-thumbnail-position' => array(
+ 'type' => 'select',
+ 'name' => 'post-thumbnail-position',
+ 'label' => 'Image Position',
+ 'default' => 'left',
+ 'options' => array(
+ 'left' => 'Left',
+ 'right' => 'Right',
+ 'above-title' => 'Above Title',
+ 'above-content' => 'Above Content'
+ )
+ ),
+
+ 'use-entry-thumbnail-position' => array(
+ 'type' => 'checkbox',
+ 'name' => 'use-entry-thumbnail-position',
+ 'label' => 'Use Per-Entry Featured Image Positions',
+ 'default' => true,
+ 'tooltip' => 'In the WordPress write panel, there is a Headway meta box that allows you to change the featured image position for the entry being edited.<br /><br />By default, the block will use that value, but you may uncheck this so that the blocks thumbnail position is always used.'
+ ),
+
+ 'thumbnail-sizing-heading' => array(
+ 'name' => 'thumbnail-sizing-heading',
+ 'type' => 'heading',
+ 'label' => 'Featured Image Sizing'
+ ),
+
+ 'post-thumbnail-size' => array(
+ 'type' => 'slider',
+ 'name' => 'post-thumbnail-size',
+ 'label' => 'Featured Image Size (Left/Right)',
+ 'default' => 125,
+ 'slider-min' => 20,
+ 'slider-max' => 400,
+ 'slider-interval' => 1,
+ 'tooltip' => 'Adjust the size of the featured image sizes. This is used for both the width and height of the images.',
+ 'unit' => 'px'
+ ),
+
+ 'post-thumbnail-height-ratio' => array(
+ 'type' => 'slider',
+ 'name' => 'post-thumbnail-height-ratio',
+ 'label' => 'Featured Image Height Ratio (Above Title/Content)',
+ 'default' => 35,
+ 'slider-min' => 10,
+ 'slider-max' => 200,
+ 'slider-interval' => 5,
+ 'tooltip' => 'Adjust the height of feature images when set to the above title or above content positions. This value controls what percent the height of the image will be in regards to the width of the block.<br /><br />Example: If the block width is 500 pixels and the ratio is 50% then the feature image size will be 500px by 250px.',
+ 'unit' => '%'
+ ),
+
+ 'crop-post-thumbnails' => array(
+ 'type' => 'checkbox',
+ 'name' => 'crop-post-thumbnails',
+ 'label' => 'Crop Featured Images',
+ 'default' => true
+ )
+ )
+
+ );
+
+
+ function modify_arguments($args = false) {
+
+ global $pluginbuddy_loopbuddy;
+
+ if ( class_exists('pluginbuddy_loopbuddy') && isset($pluginbuddy_loopbuddy) ) {
+
+ //Remove the old tabs
+ unset($this->tabs['mode']);
+ unset($this->tabs['meta']);
+ unset($this->tabs['display']);
+ unset($this->tabs['query-filters']);
+ unset($this->tabs['post-thumbnails']);
+
+ unset($this->inputs['mode']);
+ unset($this->inputs['meta']);
+ unset($this->inputs['display']);
+ unset($this->inputs['query-filters']);
+ unset($this->inputs['post-thumbnails']);
+
+ //Add in new tabs
+ $this->tabs['loopbuddy'] = 'LoopBuddy';
+
+ $this->inputs['loopbuddy'] = array(
+ 'loopbuddy-query' => array(
+ 'type' => 'select',
+ 'name' => 'loopbuddy-query',
+ 'label' => 'LoopBuddy Query',
+ 'options' => 'get_loopbuddy_queries()',
+ 'tooltip' => 'Select a LoopBuddy query to the right. Queries determine what content (posts, pages, etc) will be displayed. You can modify/add queries in the WordPress admin under LoopBuddy.',
+ 'default' => ''
+ ),
+
+ 'loopbuddy-layout' => array(
+ 'type' => 'select',
+ 'name' => 'loopbuddy-layout',
+ 'label' => 'LoopBuddy Layout',
+ 'options' => 'get_loopbuddy_layouts()',
+ 'tooltip' => 'Select a LoopBuddy layout to the right. Layouts determine how the query will be displayed. This includes the order of the content in relation to the title, meta, and so on. You can modify/add layouts in the WordPress admin under LoopBuddy.',
+ 'default' => ''
+ )
+ );
+
+ $this->tab_notices = array(
+ 'loopbuddy' => '<strong>Even though we have the options to choose a LoopBuddy layout and query here, we recommend you configure LoopBuddy using its <a href="' . admin_url('admin.php?page=pluginbuddy_loopbuddy'). '" target="_blank">options panel</a>.</strong><br /><br />The options below are more useful if you\'re using two Content Blocks on one layout and wish to configure them separately. <strong>Note:</strong> You MUST have a query selected in order to also select a LoopBuddy layout.'
+ );
+
+ return;
+
+ }
+
+ $this->inputs['meta']['date-format']['options'] = array(
+ 'wordpress-default' => 'WordPress Default',
+ 'F j, Y' => date('F j, Y'),
+ 'm/d/y' => date('m/d/y'),
+ 'd/m/y' => date('d/m/y'),
+ 'M j' => date('M j'),
+ 'M j, Y' => date('M j, Y'),
+ 'F j' => date('F j'),
+ 'F jS' => date('F jS'),
+ 'F jS, Y' => date('F jS, Y')
+ );
+
+ $this->inputs['meta']['time-format']['options'] = array(
+ 'wordpress-default' => 'WordPress Default',
+ 'g:i A' => date('g:i A'),
+ 'g:i A T' => date('g:i A T'),
+ 'g:i:s A' => date('g:i:s A'),
+ 'G:i' => date('G:i'),
+ 'G:i T' => date('G:i T')
+ );
+
+ }
+
+
+ function get_pages() {
+
+ $page_options = array('– Do Not Fetch –');
+
+ $page_select_query = get_pages();
+
+ foreach ($page_select_query as $page)
+ $page_options[$page->ID] = $page->post_title;
+
+ return $page_options;
+
+ }
+
+
+ function get_categories() {
+
+ $category_options = array();
+
+ $categories_select_query = get_categories();
+
+ foreach ($categories_select_query as $category)
+ $category_options[$category->term_id] = $category->name;
+
+ return $category_options;
+
+ }
+
+
+ function get_authors() {
+
+ $author_options = array();
+
+ $authors = get_users(array(
+ 'orderby' => 'post_count',
+ 'order' => 'desc',
+ 'who' => 'authors'
+ ));
+
+ foreach ( $authors as $author )
+ $author_options[$author->ID] = $author->display_name;
+
+ return $author_options;
+
+ }
+
+
+ function get_post_types() {
+
+ $post_type_options = array();
+
+ $post_types = get_post_types(false, 'objects');
+
+ foreach($post_types as $post_type_id => $post_type){
+
+ //Make sure the post type is not an excluded post type.
+ if(in_array($post_type_id, array('revision', 'nav_menu_item')))
+ continue;
+
+ $post_type_options[$post_type_id] = $post_type->labels->name;
+
+ }
+
+ return $post_type_options;
+
+ }
+
+
+ function get_loopbuddy_queries() {
+
+ $loopbuddy_options = get_option('pluginbuddy_loopbuddy');
+
+ $queries = array(
+ '' => '– Use Default Query –'
+ );
+
+ foreach ( $loopbuddy_options['queries'] as $query_id => $query ) {
+
+ $queries[$query_id] = $query['title'];
+
+ }
+
+ return $queries;
+
+ }
+
+
+ function get_loopbuddy_layouts() {
+
+ $loopbuddy_options = get_option('pluginbuddy_loopbuddy');
+
+ $layouts = array(
+ '' => '– Use Default Layout –'
+ );
+
+ foreach ( $loopbuddy_options['layouts'] as $layout_id => $layout ) {
+
+ $layouts[$layout_id] = $layout['title'];
+
+ }
+
+ return $layouts;
+
+ }
+
+
+}
\ No newline at end of file
--- /dev/null
+<?php
+function headway_content_block_editor_style() {
+
+ $body_bg = HeadwayElementsData::get_property('block-content-entry-container', 'background-color', 'ffffff');
+ $body_color = HeadwayElementsData::get_property('block-content-entry-content', 'color', '333333');
+ $body_font_family = HeadwayElementsData::get_property('block-content-entry-content', 'font-family', 'helvetica, sans-serif');
+ $body_font_size = HeadwayElementsData::get_property('block-content-entry-content', 'font-size', '13');
+ $body_line_height = HeadwayElementsData::get_property('block-content-entry-content', 'line-height', '180');
+
+ if ( !($body_hyperlink_color = HeadwayElementsData::get_property('block-content-entry-content-hyperlinks', 'color', null)) )
+ $body_hyperlink_color = $body_color;
+
+ return '
+ * {
+ font-size: ' . $body_font_size . 'px;
+ font-family: ' . $body_font_family . ';
+ font-style: inherit;
+ font-weight: inherit;
+ line-height: ' . $body_line_height . '%;
+ color: inherit;
+ }
+ body {
+ background: #' . $body_bg . ';
+ color: #' . $body_color . ';
+ font-size: ' . $body_font_size . 'px;
+ font-family: ' . $body_font_family . ';
+ line-height: ' . $body_line_height . '%;
+ }
+
+ /* Headings */
+ h1,h2,h3,h4,h5,h6 {
+ clear: both;
+ }
+ h1,
+ h2 {
+ color: #000;
+ font-size: 15px;
+ font-weight: bold;
+ margin: 0 0 20px;
+ }
+ h3, h4, h5, h6 {
+ font-size: 10px;
+ letter-spacing: 0.1em;
+ line-height: 2.6em;
+ text-transform: uppercase;
+ margin: 0 0 15px;
+ }
+ hr {
+ background-color: #ccc;
+ border: 0;
+ height: 1px;
+ margin: 0 0 15px;
+ }
+
+ /* Text elements */
+ p {
+ margin: 0 0 15px;
+ }
+
+ /* Lists */
+ ul, ol {
+ padding: 0 0 0 40px;
+ margin: 15px 0;
+ }
+
+ ul ul, ol ol { margin: 0; } /* Lists inside lists should not have the margin on them. */
+
+ ul li { list-style: disc; }
+ ul ul li { list-style: circle; }
+ ul ul ul li { list-style: square; }
+
+ ol li { list-style: decimal; }
+ ol ol li { list-style: lower-alpha; }
+ ol ol ol li { list-style: lower-roman; }
+
+ strong {
+ font-weight: bold;
+ }
+ cite, em, i {
+ font-style: italic;
+ }
+ cite {
+ border: none;
+ }
+ pre {
+ background: #f4f4f4;
+ font: 13px "Courier 10 Pitch", Courier, monospace;
+ line-height: 1.5;
+ margin-bottom: 1.625em;
+ padding: 0.75em 1.625em;
+ }
+ code {
+ font: 13px Monaco, Consolas, "Andale Mono", "DejaVu Sans Mono", monospace;
+ }
+ abbr, acronym {
+ border-bottom: 1px dotted #666;
+ cursor: help;
+ }
+
+ /* Links */
+ a,
+ a em,
+ a strong {
+ color: #' . $body_hyperlink_color . ';
+ text-decoration: underline;
+ cursor: pointer;
+ }
+ a:focus,
+ a:active,
+ a:hover {
+ text-decoration: none;
+ }
+
+ /* Alignment */
+ .alignleft {
+ display: inline;
+ float: left;
+ margin-right: 1.625em;
+ }
+ .alignright {
+ display: inline;
+ float: right;
+ margin-left: 1.625em;
+ }
+ .aligncenter {
+ clear: both;
+ display: block;
+ margin-left: auto;
+ margin-right: auto;
+ }';
+
+}
\ No newline at end of file
--- /dev/null
+<?php
+headway_register_block('HeadwayCustomCodeBlock', headway_url() . '/library/blocks/custom-code');
+
+class HeadwayCustomCodeBlock extends HeadwayBlockAPI {
+
+
+ public $id = 'custom-code';
+
+ public $name = 'Custom Code';
+
+ public $options_class = 'HeadwayCustomCodeBlockOptions';
+
+ public $description = 'Place in custom HTML, PHP, or even WordPress shortcodes into this block.';
+
+
+ function content($block) {
+
+ $content = parent::get_setting($block, 'content');
+
+ if ( $content != null )
+ echo headway_parse_php(do_shortcode(stripslashes($content)));
+ else
+ echo '<p>There is no custom code to display.</p>';
+
+ }
+
+
+}
+
+
+class HeadwayCustomCodeBlockOptions extends HeadwayBlockOptionsAPI {
+
+ public $tabs = array(
+ 'content' => 'Content'
+ );
+
+ public $inputs = array(
+ 'content' => array(
+ 'content' => array(
+ 'type' => 'textarea',
+ 'name' => 'content',
+ 'label' => 'Content',
+ 'default' => null
+ )
+ )
+ );
+
+}
\ No newline at end of file
--- /dev/null
+<?php
+headway_register_block('HeadwayEmbedBlock', headway_url() . '/library/blocks/embed');
+class HeadwayEmbedBlock extends HeadwayBlockAPI {
+
+
+ public $id = 'embed';
+
+ public $name = 'Embed';
+
+ public $options_class = 'HeadwayEmbedBlockOptions';
+
+ public $description = 'The Embed block allows you to embed YouTube, Vimeo, or any other popular oEmbed supported service.';
+
+
+ function init() {
+
+ add_filter('oembed_result', array(__CLASS__, 'add_embed_wmode_transparent'));
+ add_filter('oembed_result', array(__CLASS__, 'add_iframe_wmode_transparent'));
+
+ }
+
+
+ function content($block) {
+
+ if ( $embed_url = parent::get_setting($block, 'embed-url', false) ) {
+
+ $block_width = HeadwayBlocksData::get_block_width($block);
+ $block_height = HeadwayBlocksData::get_block_height($block);
+
+ $embed_code = wp_oembed_get($embed_url, array(
+ 'width' => $block_width,
+ 'height' => $block_height,
+ ));
+
+ //Make the width and height exactly what the block's dimensions are.
+ $embed_code = preg_replace(array('/width="\d+"/i', '/height="\d+"/i'), array('width="' . $block_width . '"', 'height="' . $block_height . '"'), $embed_code);
+
+ echo $embed_code;
+
+ } else {
+
+ echo '<div class="alert alert-yellow"><p>There is no content to display. Please enter a valid embed URL in the visual editor.</p></div>';
+
+ }
+
+ }
+
+
+ /**
+ * Added to fix the issue of Flash appearing over drop down menus.
+ **/
+ public static function add_embed_wmode_transparent($html) {
+
+ //If no <embed> exists, don't do anything.
+ if ( strpos($html, '<embed ') === false )
+ return $html;
+
+ return str_replace('</param><embed', '</param><param name="wmode" value="transparent"></param><embed wmode="transparent" ', $html);
+
+ }
+
+
+ /**
+ * If the oEmbed HTML is using an iframe instead of <embed>, add a query var to the URL of the iframe to tell it to use wmode=transparent.
+ **/
+ public static function add_iframe_wmode_transparent($html) {
+
+ //If no iframe exists, don't do anything.
+ if ( strpos($html, '<iframe') === false )
+ return $html;
+
+ $url_search = preg_match_all('/src=[\'\"](.*?)[\'\"]/', $html, $url);
+ $url = $url[1][0];
+
+ //Add the query var
+ $url = add_query_arg(array('wmode' => 'transparent'), $url);
+
+ //Place the URL back in
+ return preg_replace('/src=[\'\"](.*?)[\'\"]/', 'src="' . $url . '"', $html);
+
+ }
+
+
+}
+
+
+class HeadwayEmbedBlockOptions extends HeadwayBlockOptionsAPI {
+
+ public $tabs = array(
+ 'embed-options' => 'Embed Options'
+ );
+
+ public $inputs = array(
+ 'embed-options' => array(
+ 'embed-notice' => array(
+ 'name' => 'embed-notice',
+ 'type' => 'notice',
+ 'notice' => 'Enter the URL <strong>(No HTML)</strong> to the media you wish to embed. We support most major video and photo sites including (but not limited to) YouTube, Vimeo, Flickr, blip.tv, Hulu, and more. <em>Need more info about oEmbed? <a href="http://codex.wordpress.org/Embeds" target="_blank">Read More →</a></em>'
+ ),
+
+ 'embed-url' => array(
+ 'type' => 'text',
+ 'name' => 'embed-url',
+ 'label' => 'Embed URL',
+ 'default' => null,
+ 'placeholder' => 'URL of Media'
+ )
+ )
+ );
+
+}
\ No newline at end of file
--- /dev/null
+<?php
+headway_register_block('HeadwayFooterBlock', headway_url() . '/library/blocks/footer');
+
+class HeadwayFooterBlock extends HeadwayBlockAPI {
+
+
+ public $id = 'footer';
+
+ public $name = 'Footer';
+
+ public $options_class = 'HeadwayFooterBlockOptions';
+
+ public $html_tag = 'footer';
+
+ public $attributes = array(
+ 'itemscope' => '',
+ 'itemtype' => 'http://schema.org/WPFooter'
+ );
+
+ public $description = 'This typically goes at the bottom of your site and will display the copyright, and miscellaneous links.';
+
+ public $allow_titles = false;
+
+ protected $show_content_in_grid = true;
+
+
+ function setup_elements() {
+
+ $this->register_block_element(array(
+ 'id' => 'copyright',
+ 'name' => 'Copyright',
+ 'selector' => 'p.copyright',
+ 'properties' => array('fonts')
+ ));
+
+ $this->register_block_element(array(
+ 'id' => 'headway-attribution',
+ 'name' => 'Headway Attribution',
+ 'selector' => 'p.footer-headway-link',
+ 'properties' => array('fonts')
+ ));
+
+ $this->register_block_element(array(
+ 'id' => 'administration-panel',
+ 'name' => 'Administration Panel',
+ 'selector' => 'a.footer-admin-link',
+ 'properties' => array('fonts')
+ ));
+
+ $this->register_block_element(array(
+ 'id' => 'go-to-top',
+ 'name' => 'Go To Top Link',
+ 'selector' => 'a.footer-go-to-top-link',
+ 'states' => array(
+ 'Hover' => 'a.footer-go-to-top-link:hover'
+ )
+ ));
+
+ $this->register_block_element(array(
+ 'id' => 'responsive-grid-link',
+ 'name' => 'Responsive Grid Toggle Link',
+ 'selector' => 'a.footer-responsive-grid-link',
+ 'properties' => array('fonts')
+ ));
+
+ }
+
+
+ function content($block) {
+
+ //Add action for footer
+ do_action('headway_before_footer');
+
+ echo "\n" . '<div class="footer-container">' . "\n";
+
+ echo "\n" . '<div class="footer">' . "\n";
+
+ do_action('headway_footer_open');
+
+ //Headway Attribution
+ if ( parent::get_setting($block, 'hide-headway-attribution', false) == false )
+ self::show_headway_link();
+
+ //Go To Top Link
+ if ( parent::get_setting($block, 'show-go-to-top-link', true) == true )
+ self::show_go_to_top_link();
+
+ //Admin Link
+ if ( parent::get_setting($block, 'show-admin-link', true) == true )
+ self::show_admin_link();
+
+ //Copyright
+ if ( parent::get_setting($block, 'show-copyright', true) == true )
+ self::show_copyright(parent::get_setting($block, 'custom-copyright'));
+
+ if ( parent::get_setting($block, 'show-responsive-grid-link', true) == true )
+ self::show_responsive_grid_toggle_link();
+
+ do_action('headway_footer_close');
+
+ echo "\n" . '</div><!-- .footer -->';
+
+ echo "\n" . '</div><!-- .footer-container -->';
+
+ do_action('headway_after_footer');
+
+ }
+
+
+ /**
+ * Displays an admin link or admin login.
+ *
+ * @uses HeadwayOption::get()
+ *
+ * @return void
+ **/
+ public static function show_admin_link() {
+
+ if ( is_user_logged_in() )
+ echo apply_filters('headway_admin_link', '<a href="' . admin_url() . '" class="footer-right footer-admin-link footer-link">'.__('Administration Panel', 'headway') . '</a>');
+ else
+ echo apply_filters('headway_admin_link', '<a href="' . admin_url() . '" class="footer-right footer-admin-link footer-link">'.__('Administration Login', 'headway') . '</a>');
+
+ }
+
+
+ /**
+ * Echos the Powered By Headway link.
+ *
+ * @uses HeadwayOption::get()
+ *
+ * @param string $text The name of the program to be displayed. Defaults to Headway (obviously).
+ *
+ * @return mixed
+ **/
+ public static function show_headway_link() {
+
+ if ( HeadwayOption::get('affiliate-link') )
+ $headway_location = strip_tags(HeadwayOption::get('affiliate-link'));
+ else
+ $headway_location = 'http://headwaythemes.com/';
+
+ echo apply_filters('headway_link', '<p class="footer-left footer-headway-link footer-link">' . __('Powered by Headway, the ', 'headway') . ' <a href="' . $headway_location . '" title="Headway Premium WordPress Theme">drag and drop WordPress theme</a></p>');
+
+ }
+
+
+ /**
+ * Shows a simple copyright paragraph.
+ *
+ * @return mixed
+ **/
+ public static function show_copyright($custom_copyright = false) {
+
+ $default_copyright = __('Copyright', 'headway') . ' © ' . date('Y') . ' ' . get_bloginfo('name');
+
+ $copyright = $custom_copyright ? $custom_copyright : $default_copyright;
+
+ echo apply_filters('headway_copyright', headway_parse_php('<p class="copyright footer-copyright">' . $copyright . '</p>'));
+
+ }
+
+
+ /**
+ * Shows a simple go to top link.
+ *
+ * @return mixed
+ **/
+ public static function show_go_to_top_link() {
+
+ echo apply_filters('headway_go_to_top_link', '<a href="#" class="footer-right footer-go-to-top-link footer-link">' . __('Go To Top', 'headway') . '</a>');
+
+ }
+
+
+ /**
+ * Shows a link to either view the full site or view the mobile site.
+ *
+ * This will only show if the responsive grid is enabled.
+ **/
+ public static function show_responsive_grid_toggle_link() {
+
+ if ( !HeadwayResponsiveGrid::is_enabled() )
+ return false;
+
+ $current_url = headway_get_current_url();
+
+ if ( HeadwayResponsiveGrid::is_active() ) {
+
+ $url = add_query_arg(array('full-site' => 'true'), $current_url);
+ $classes = 'footer-responsive-grid-link footer-responsive-grid-disable footer-link';
+
+ echo apply_filters('headway_responsive_disable_link', '<p class="footer-responsive-grid-link-container footer-responsive-grid-link-disable-container"><a href="' . $url . '" rel="nofollow" class="' . $classes . '">' . __('View Full Site', 'headway') . '</a></p>');
+
+ } elseif ( HeadwayResponsiveGrid::is_user_disabled() ) {
+
+ $url = add_query_arg(array('full-site' => 'false'), $current_url);
+ $classes = 'footer-responsive-grid-link footer-responsive-grid-enable footer-link';
+
+ echo apply_filters('headway_responsive_enable_link', '<p class="footer-responsive-grid-link-container footer-responsive-grid-link-enable-container"><a href="' . $url . '" rel="nofollow" class="' . $classes . '">' . __('View Mobile Site', 'headway') . '</a></p>');
+
+ }
+
+ }
+
+
+}
+
+class HeadwayFooterBlockOptions extends HeadwayBlockOptionsAPI {
+
+ public $tabs = array(
+ 'nav-menu-content' => 'Content'
+ );
+
+ public $inputs = array(
+ 'nav-menu-content' => array(
+ 'show-admin-link' => array(
+ 'type' => 'checkbox',
+ 'name' => 'show-admin-link',
+ 'label' => 'Show Admin Link/Login',
+ 'default' => true
+ ),
+
+ 'show-go-to-top-link' => array(
+ 'name' => 'show-go-to-top-link',
+ 'label' => 'Show Go To Top Link',
+ 'type' => 'checkbox',
+ 'default' => true
+ ),
+
+ 'hide-headway-attribution' => array(
+ 'name' => 'hide-headway-attribution',
+ 'label' => 'Hide Headay Attribution',
+ 'type' => 'checkbox',
+ 'default' => false
+ ),
+
+ 'show-copyright' => array(
+ 'name' => 'show-copyright',
+ 'label' => 'Show Copyright',
+ 'type' => 'checkbox',
+ 'default' => true
+ ),
+
+ 'custom-copyright' => array(
+ 'name' => 'custom-copyright',
+ 'label' => 'Custom Copyright',
+ 'type' => 'text',
+ 'tooltip' => 'If you would like to change the copyright in the footer to say something different, enter it here.'
+ )
+ )
+ );
+
+}
\ No newline at end of file
--- /dev/null
+<?php
+//Check that Gravity Forms is even enabled
+if ( class_exists('RGForms'))
+ headway_register_block('HeadwayGravityFormsBlock', headway_url() . '/library/blocks/gravity-forms');
+
+class HeadwayGravityFormsBlock extends HeadwayBlockAPI {
+
+
+ public $id = 'gravity-forms';
+
+ public $name = 'Gravity Forms';
+
+ public $options_class = 'HeadwayGravityFormsBlockOptions';
+
+
+ public static function enqueue_action($block_id) {
+
+ $block = HeadwayBlocksData::get_block($block_id);
+
+ return gravity_form_enqueue_scripts(parent::get_setting($block, 'form-id', null), parent::get_setting($block, 'use-ajax', false));
+
+ }
+
+
+ function content($block) {
+
+ $form_id = parent::get_setting($block, 'form-id', null);
+
+ //If no form ID is present, display the message and stop this function.
+ if ( !$form_id ) {
+
+ echo '<p>There is no form to display.</p>';
+
+ return;
+
+ }
+
+ $display_title = parent::get_setting($block, 'display-title', true);
+ $display_description = parent::get_setting($block, 'display-description', true);
+ $force_display = true;
+ $field_values = null;
+ $use_ajax = parent::get_setting($block, 'use-ajax', false);
+
+ echo RGForms::get_form($form_id, $display_title, $display_description, $force_display, null, $use_ajax);
+
+ }
+
+
+}
+
+
+class HeadwayGravityFormsBlockOptions extends HeadwayBlockOptionsAPI {
+
+
+ public $tabs = array(
+ 'form-setup' => 'Form Setup'
+ );
+
+ public $inputs = array(
+ 'form-setup' => array(
+
+ 'form-id' => array(
+ 'type' => 'select',
+ 'name' => 'form-id',
+ 'label' => 'Form To Display',
+ 'default' => '',
+ 'tooltip' => 'Select which form you would like this block to display.',
+ 'options' => 'get_forms()'
+ ),
+
+ 'display-title' => array(
+ 'type' => 'checkbox',
+ 'name' => 'display-title',
+ 'label' => 'Display Form Title',
+ 'default' => true
+ ),
+
+ 'display-description' => array(
+ 'type' => 'checkbox',
+ 'name' => 'display-description',
+ 'label' => 'Display Form Description',
+ 'default' => true
+ ),
+
+ 'use-ajax' => array(
+ 'type' => 'checkbox',
+ 'name' => 'use-ajax',
+ 'label' => 'Use AJAX',
+ 'default' => false,
+ 'tooltip' => 'AJAX is a technology that will allow faster submission on your forms.'
+ ),
+
+ )
+ );
+
+
+ function get_forms() {
+
+ $forms = RGFormsModel::get_forms();
+
+ $options = array('' => '– Select a Form –');
+
+ foreach ( $forms as $form ) {
+
+ $options[$form->id] = $form->title;
+
+ }
+
+ return $options;
+
+ }
+
+
+}
\ No newline at end of file
--- /dev/null
+<?php
+headway_register_block('HeadwayHeaderBlock', headway_url() . '/library/blocks/header');
+
+class HeadwayHeaderBlock extends HeadwayBlockAPI {
+
+
+ public $id = 'header';
+
+ public $name = 'Header';
+
+ public $options_class = 'HeadwayHeaderBlockOptions';
+
+ public $fixed_height = true;
+
+ public $html_tag = 'header';
+
+ public $attributes = array(
+ 'itemscope' => '',
+ 'itemtype' => 'http://schema.org/WPHeader'
+ );
+
+ public $description = 'Display your banner, logo, or site title and tagline. This typically goes at the top of your website.';
+
+ public $allow_titles = false;
+
+ protected $show_content_in_grid = true;
+
+
+ function setup_elements() {
+
+ $this->register_block_element(array(
+ 'id' => 'site-title',
+ 'name' => 'Site Title',
+ 'selector' => 'span.banner a',
+ 'states' => array(
+ 'Hover' => 'span.banner a:hover',
+ 'Clicked' => 'span.banner a:active'
+ )
+ ));
+
+ $this->register_block_element(array(
+ 'id' => 'banner-image',
+ 'name' => 'Banner/Logo Link',
+ 'selector' => 'a.banner-image',
+ 'states' => array(
+ 'Clicked' => 'a.banner-image:active',
+ 'Hover' => 'a.banner-image:hover'
+ )
+ ));
+
+ $this->register_block_element(array(
+ 'id' => 'banner-image-img',
+ 'name' => 'Banner Image',
+ 'selector' => 'a.banner-image img'
+ ));
+
+ $this->register_block_element(array(
+ 'id' => 'site-tagline',
+ 'name' => 'Site Tagline',
+ 'selector' => '.tagline'
+ ));
+
+ }
+
+
+ function content($block) {
+
+ //Use header image if there is one
+ if ( $header_image_src = parent::get_setting($block, 'header-image') ) {
+
+ do_action('headway_before_header_link');
+
+ if ( parent::get_setting($block, 'resize-header-image', true) ) {
+
+ $block_width = HeadwayBlocksData::get_block_width($block);
+ $block_height = HeadwayBlocksData::get_block_height($block);
+
+ $header_image_url = headway_resize_image($header_image_src, $block_width, $block_height);
+
+ } else {
+
+ $header_image_url = $header_image_src;
+
+ }
+
+ echo '<a href="' . home_url() . '" class="banner-image"><img src="' . $header_image_url . '" alt="' . get_bloginfo('name') . '" /></a>';
+
+ do_action('headway_after_header_link');
+
+
+ //No image present
+ } else {
+
+ do_action('headway_before_header_link');
+
+ echo '<span class="banner" itemprop="headline"><a href="' . home_url() . '">' . get_bloginfo('name') . '</a></span>';
+
+ do_action('headway_after_header_link');
+
+ if ( !parent::get_setting($block, 'hide-tagline', false) ) {
+
+ if ( (is_front_page() || is_home()) && get_option('show_on_front') != 'page' ) {
+
+ echo '<h1 class="tagline" itemprop="headline">' . get_bloginfo('description') . '</h1>' . "\n";
+
+ } else {
+
+ echo '<span class="tagline" itemprop="description">' . get_bloginfo('description') . '</span>' . "\n";
+
+ }
+
+ do_action('headway_after_tagline');
+
+ }
+
+ }
+
+ }
+
+}
+
+
+class HeadwayHeaderBlockOptions extends HeadwayBlockOptionsAPI {
+
+ public $tabs = array(
+ 'general' => 'General'
+ );
+
+ public $inputs = array(
+ 'general' => array(
+ 'header-image' => array(
+ 'type' => 'image',
+ 'name' => 'header-image',
+ 'label' => 'Banner/Logo',
+ 'default' => null
+ ),
+
+ 'resize-header-image' => array(
+ 'name' => 'resize-header-image',
+ 'label' => 'Automatically Resize Header Image',
+ 'type' => 'checkbox',
+ 'tooltip' => 'If you would like Headway to automatically scale and crop your header image to the correct dimensions, keep this checked.<br /><br /><em><strong>Important:</strong> In order for the image to be resized and cropped it must be uploaded <strong>From Computer</strong>. <strong>NOT</strong> <strong>From URL</strong>.</em>',
+ 'default' => true
+ ),
+
+ 'hide-tagline' => array(
+ 'name' => 'hide-tagline',
+ 'label' => 'Hide Tagline',
+ 'type' => 'checkbox',
+ 'tooltip' => 'Check this to hide the tagline in your header. The tagline will sit beneath your site title.<br /><br /><em><strong>Important:</strong> The tagline will <strong>NOT</strong> show if a Header Image is added.</em>',
+ 'default' => false
+ )
+ )
+ );
+
+}
\ No newline at end of file
--- /dev/null
+<?php
+headway_register_block('HeadwayImageBlock', headway_url() . '/library/blocks/image');
+
+class HeadwayImageBlock extends HeadwayBlockAPI {
+
+ public $id = 'image';
+
+ public $name = 'Image';
+
+ public $options_class = 'HeadwayImageBlockOptions';
+
+ public $fixed_height = true;
+
+ public $html_tag = 'figure';
+
+ public $attributes = array(
+ 'itemscope' => '',
+ 'itemtype' => 'http://schema.org/ImageObject'
+ );
+
+ public $description = 'Display an image';
+
+ protected $show_content_in_grid = true;
+
+ function setup_elements() {
+
+ $this->register_block_element(array(
+ 'id' => 'image',
+ 'name' => 'Image',
+ 'selector' => 'img'
+ ));
+
+ $this->register_block_element(array(
+ 'id' => 'image-link',
+ 'name' => 'Image Link',
+ 'selector' => 'a img',
+ 'states' => array(
+ 'Hover' => 'a:hover img',
+ 'Clicked' => 'a:active img'
+ )
+ ));
+
+ }
+
+ public static function dynamic_css($block_id, $block = false) {
+
+ if ( !$block )
+ $block = HeadwayBlocksData::get_block($block_id);
+
+ if ( !$position = parent::get_setting($block, 'image-position') )
+ return;
+
+ $position_properties = array(
+ 'top_left' => 'left: 0; top: 0;',
+ 'top_center' => 'left: 0; top: 0; right: 0;',
+ 'top_right' => 'top: 0; right: 0;',
+
+ 'center_center' => 'bottom: 0; left: 0; top: 0; right: 0;',
+ 'center_left' => 'bottom: 0; left: 0; top: 0;',
+ 'center_right' => 'bottom: 0; top: 0; right: 0;',
+
+ 'bottom_left' => 'bottom: 0; left: 0;',
+ 'bottom_center' => 'bottom: 0; left: 0; right: 0;',
+ 'bottom_right' => 'bottom: 0;right: 0;'
+ );
+
+ $css = '
+ #block-' . $block['id'] . ' .block-content { position: relative; }
+ #block-' . $block['id'] . ' img {
+ margin: auto;
+ position: absolute;
+ ' . headway_get($position, $position_properties) . '
+ }
+ ';
+
+ return $css;
+
+ }
+
+ function content($block) {
+
+ //Display image if there is one
+ if ( $image_src = parent::get_setting($block, 'image') ) {
+
+ $url = parent::get_setting($block, 'link-url');
+ $alt = parent::get_setting($block, 'image-alt');
+ $title = parent::get_setting($block, 'image-title');
+ $target = parent::get_setting($block, 'link-target', false) ? $target = 'target="_blank"' : '';
+
+ if ( parent::get_setting($block, 'resize-image', true) ) {
+
+ $block_width = HeadwayBlocksData::get_block_width($block);
+ $block_height = HeadwayBlocksData::get_block_height($block);
+
+ $image_url = headway_resize_image($image_src, $block_width, $block_height);
+
+ } else {
+
+ $image_url = $image_src;
+
+ }
+
+ if ( $image_src = parent::get_setting($block, 'link-image', false) ) {
+
+ echo '<a href="' . $url . '" class="image" '.$target.'><img src="' . $image_url . '" alt="' . $alt . '" title="' . $title . '" itemprop="contentURL"/></a>';
+
+ } else {
+
+ echo '<img src="' . $image_url . '" alt="' . $alt . '" title="' . $title . '" itemprop="contentURL"/>';
+
+ }
+
+ } else {
+
+ echo '<div style="margin: 5px;" class="alert alert-yellow"><p>You have not added an image yet. Please upload and apply an image.</p></div>';
+ }
+
+ /* Output position styling for Grid mode */
+ if ( headway_get('ve-live-content-query', $block) && headway_post('mode') == 'grid' ) {
+ echo '<style type="text/css">';
+ echo self::dynamic_css(false, $block);
+ echo '</style>';
+ }
+
+
+ }
+
+}
+
+
+class HeadwayImageBlockOptions extends HeadwayBlockOptionsAPI {
+
+ public $tabs = array(
+ 'general' => 'General'
+ );
+
+ public $inputs = array(
+ 'general' => array(
+
+ 'image-heading' => array(
+ 'name' => 'image-heading',
+ 'type' => 'heading',
+ 'label' => 'Add an Image'
+ ),
+
+ 'image' => array(
+ 'type' => 'image',
+ 'name' => 'image',
+ 'label' => 'Image',
+ 'default' => null
+ ),
+
+ 'resize-image' => array(
+ 'name' => 'resize-image',
+ 'label' => 'Automatically Resize Image',
+ 'type' => 'checkbox',
+ 'tooltip' => 'If you would like Headway to automatically scale and crop the image to the blocks dimensions, keep this checked.<br /><br /><em><strong>Important:</strong> In order for the image to be resized and cropped it must be uploaded <strong>From Computer</strong>. <strong>NOT</strong> <strong>From URL</strong>.</em>',
+ 'default' => true
+ ),
+
+ 'image-title' => array(
+ 'name' => 'image-title',
+ 'label' => 'Image Title',
+ 'type' => 'text',
+ 'tooltip' => 'This will be used as the "title" attribute for the image. The title attribute is beneficial for SEO (Search Engine Optimization) and will allow your visitors to move their mouse over the image and read about it.',
+ ),
+
+ 'image-alt' => array(
+ 'name' => 'image-alt',
+ 'label' => 'Image Alternate Text',
+ 'type' => 'text',
+ 'tooltip' => 'This will be used as the "alt" attribute for the image. The alt attribute is <em>hugely</em> beneficial for SEO (Search Engine Optimization) and for general accessibility.',
+ ),
+
+ 'link-heading' => array(
+ 'name' => 'link-heading',
+ 'type' => 'heading',
+ 'label' => 'Link Image'
+ ),
+
+ 'link-image' => array(
+ 'name' => 'link-image',
+ 'label' => 'Link the image?',
+ 'type' => 'checkbox',
+ 'tooltip' => 'If you would like to link the image to a url activate this setting. Must add http:// first',
+ 'default' => false,
+ 'toggle' => array(
+ 'true' => array(
+ 'show' => array(
+ '#input-link-url',
+ '#input-link-target'
+ )
+ ),
+ 'false' => array(
+ 'hide' => array(
+ '#input-link-url',
+ '#input-link-target'
+ )
+ )
+ )
+ ),
+
+ 'link-url' => array(
+ 'name' => 'link-url',
+ 'label' => 'Link image URL?',
+ 'type' => 'text',
+ 'tooltip' => 'Set the URL for the image to link to'
+ ),
+
+ 'link-target' => array(
+ 'name' => 'link-target',
+ 'label' => 'Open in a new window?',
+ 'type' => 'checkbox',
+ 'tooltip' => 'If you would like to open the link in a new window check this option',
+ 'default' => false,
+ ),
+
+ 'position-heading' => array(
+ 'name' => 'position-heading',
+ 'type' => 'heading',
+ 'label' => 'Position Image'
+ ),
+
+ 'image-position' => array(
+ 'name' => 'image-position',
+ 'label' => 'Position image inside container',
+ 'type' => 'select',
+ 'tooltip' => 'You can position this image in relation to the block using the positions provided',
+ 'default' => 'none',
+ 'options' => array(
+ '' => 'None',
+ 'top_left' => 'Top Left',
+ 'top_center' => 'Top Center',
+ 'top_right' => 'Top Right',
+ 'center_left' => 'Center Left',
+ 'center_center' => 'Center Center',
+ 'center_right' => 'Center Right',
+ 'bottom_left' => 'Bottom Left',
+ 'bottom_center' => 'Bottom Center',
+ 'bottom_right' => 'Bottom Right'
+ )
+ )
+
+ )
+ );
+
+}
\ No newline at end of file
--- /dev/null
+<?php
+
+class HeadwayListingsBlockOptions extends HeadwayBlockOptionsAPI {
+
+ function modify_arguments($args = false) {
+
+ $block = $args['block'];
+
+ /* Content Options */
+ $taxomomy = HeadwayBlockAPI::get_setting($block, 'post-taxonomy-filter');
+
+ $terms = self::get_listing_terms($taxomomy);
+ $label = self::get_taxonomy_label($taxomomy);
+ $post_type = HeadwayBlockAPI::get_setting($block, 'post-type');
+ $taxonomies = self::get_taxonomies($post_type);
+
+ $this->inputs['posts-pages-filters']['terms']['options'] = $terms;
+ $this->inputs['posts-pages-filters']['terms']['label'] = $label;
+ $this->inputs['posts-pages-filters']['post-taxonomy-filter']['options'] = $taxonomies;
+
+ /* Taxonomy Options */
+ $this->inputs['taxonomy-options']['select-taxonomy']['options'] = self::get_taxonomies();
+
+ $taxomomy = HeadwayBlockAPI::get_setting($block, 'select-taxonomy');
+
+ $terms = self::get_listing_terms($taxomomy);
+ $label = self::get_taxonomy_label($taxomomy);
+ $this->inputs['taxonomy-options']['terms']['label'] = $label;
+ $this->inputs['taxonomy-options']['terms-child-of']['options'] = $terms;
+ $this->inputs['taxonomy-options']['terms-exclude']['options'] = $terms;
+ $this->inputs['taxonomy-options']['terms-include']['options'] = $terms;
+
+ }
+
+ public $tabs = array(
+ 'listing-type' => 'Select Listing Type',
+ 'posts-pages-filters' => 'Posts & Pages Filters',
+ 'taxonomy-options' => 'Taxonomy Options'
+ );
+
+ public $inputs = array(
+ 'listing-type' => array(
+
+ 'listing-type' => array(
+ 'type' => 'select',
+ 'name' => 'listing-type',
+ 'label' => 'List?',
+ 'tooltip' => 'Select a type of list output and then configure it with the options on the left.',
+ 'options' => array(
+ 'taxonomy' => 'Taxonomy (category, tag etc)',
+ 'content' => 'Posts or Pages (custom posts)',
+ 'authors' => 'Authors'
+ ),
+ 'default' => 'taxonomy',
+ 'toggle' => array(
+ 'taxonomy' => array(
+ 'show' => array(
+ '#sub-tab-taxonomy-options'
+ ),
+ 'hide' => array(
+ '#sub-tab-posts-pages-filters'
+ )
+ ),
+ 'content' => array(
+ 'hide' => array(
+ '#sub-tab-taxonomy-options'
+ ),
+ 'show' => array(
+ '#sub-tab-posts-pages-filters'
+ )
+ )
+ )
+ )
+
+ ),
+
+ 'taxonomy-options' => array(
+
+ 'terms-select-taxonomy-heading' => array(
+ 'name' => 'terms-select-taxonomy-heading',
+ 'type' => 'heading',
+ 'label' => 'Select Taxonomy'
+ ),
+
+ 'select-taxonomy' => array(
+ 'label' => 'Select Taxonomy to display',
+ 'type' => 'select',
+ 'name' => 'select-taxonomy',
+ 'options' => 'get_taxonomies()',
+ 'default' => 'category',
+ ),
+
+ 'terms-options-sorting-heading' => array(
+ 'name' => 'terms-options-sorting-heading',
+ 'type' => 'heading',
+ 'label' => 'Sort Taxonomy'
+ ),
+
+ 'terms-orderby' => array(
+ 'type' => 'select',
+ 'name' => 'terms-orderby',
+ 'label' => 'Order By?',
+ 'tooltip' => 'Sort term alphabetically, by unique Term ID, or by the count of items in that Term',
+ 'options' => array(
+ 'none' => 'None',
+ 'ID' => 'ID',
+ 'name' => 'Name',
+ 'slug' => 'Slug',
+ 'count' => 'Count',
+ //'term_group' => 'Term Group'
+ ),
+ 'default' => 'name'
+ ),
+
+ 'terms-order' => array(
+ 'type' => 'select',
+ 'name' => 'terms-order',
+ 'label' => 'Order?',
+ 'tooltip' => 'Sort order for term (either ascending or descending).',
+ 'options' => array(
+ 'DESC' => 'Descending',
+ 'ASC' => 'Ascending'
+ ),
+ 'default' => 'ASC'
+ ),
+
+ 'terms-options-filter-heading' => array(
+ 'name' => 'terms-options-filter-heading',
+ 'type' => 'heading',
+ 'label' => 'Filter Taxonomy'
+ ),
+
+ 'terms-number' => array(
+ 'type' => 'slider',
+ 'slider-min' => 0,
+ 'slider-max' => 30,
+ 'slider-interval' => 1,
+ 'name' => 'terms-number',
+ 'label' => 'Number of terms',
+ 'default' => '10',
+ 'tooltip' => 'Sets the number of terms to display. Default 0 for no limit.'
+ ),
+
+ 'terms-child-of' => array(
+ 'type' => 'select',
+ 'name' => 'terms-child-of',
+ 'label' => 'Child Of',
+ 'options' => 'get_listing_terms()',
+ 'default' => '',
+ 'tooltip' => 'Only display terms that are children of what you specify here.'
+ ),
+
+ 'terms-exclude' => array(
+ 'type' => 'multi-select',
+ 'name' => 'terms-exclude',
+ 'label' => 'Exclude',
+ 'options' => 'get_listing_terms()',
+ 'default' => '',
+ 'tooltip' => 'Exclude one or more term from the results.'
+ ),
+
+ 'terms-include' => array(
+ 'type' => 'multi-select',
+ 'name' => 'terms-include',
+ 'label' => 'Include',
+ 'options' => 'get_listing_terms()',
+ 'default' => '',
+ 'tooltip' => 'Only include certain terms in the list.'
+ ),
+
+ 'terms-slug' => array(
+ 'name' => 'terms-slug',
+ 'type' => 'text',
+ 'label' => 'Slug',
+ 'tooltip' => 'Returns terms whose "slug" matches this value. Default is empty string.'
+ ),
+
+ 'terms-options-display-heading' => array(
+ 'name' => 'terms-options-display-heading',
+ 'type' => 'heading',
+ 'label' => 'Display Taxonomy'
+ ),
+
+ 'terms-hide-empty' => array(
+ 'type' => 'checkbox',
+ 'name' => 'terms-hide-empty',
+ 'label' => 'Hide Empty?',
+ 'tooltip' => 'Toggles the display of term with no posts.',
+ 'default' => true
+ ),
+
+ 'terms-hierarchical' => array(
+ 'type' => 'checkbox',
+ 'name' => 'terms-hierarchical',
+ 'label' => 'Hierarchical?',
+ 'tooltip' => 'Whether to include terms that have non-empty descendants .',
+ 'default' => true
+ )
+
+ ),
+
+ 'posts-pages-filters' => array(
+
+ 'number-of-posts' => array(
+ 'type' => 'integer',
+ 'name' => 'number-of-posts',
+ 'label' => 'Number of Posts',
+ 'tooltip' => '',
+ 'default' => 5
+ ),
+
+ 'posts-pages-post-type-heading' => array(
+ 'name' => 'posts-pages-post-type-heading',
+ 'type' => 'heading',
+ 'label' => 'Filter Content'
+ ),
+
+ 'post-type' => array(
+ 'type' => 'select',
+ 'name' => 'post-type',
+ 'label' => 'Post Type',
+ 'tooltip' => '',
+ 'options' => 'get_post_types()',
+ 'toggle' => array(
+ '0' => array(
+ 'hide' => array(
+ '#input-post-taxonomy-filter',
+ '#input-terms'
+ )
+ )
+ ),
+ 'callback' => '
+ reloadBlockOptions()'
+ ),
+
+ 'post-taxonomy-filter' => array(
+ 'label' => 'Select Taxonomy to filter',
+ 'type' => 'select',
+ 'name' => 'post-taxonomy-filter',
+ 'options' => 'get_taxonomies()',
+ 'default' => 'category',
+ 'toggle' => array(
+ '0' => array(
+ 'hide' => array(
+ '#input-terms'
+ )
+ )
+ ),
+ 'callback' => '
+ reloadBlockOptions()'
+ ),
+
+ 'terms' => array(
+ 'type' => 'multi-select',
+ 'name' => 'terms',
+ 'tooltip' => ''
+ ),
+
+ 'author' => array(
+ 'type' => 'multi-select',
+ 'name' => 'author',
+ 'label' => 'Author',
+ 'tooltip' => '',
+ 'options' => 'get_authors()'
+ ),
+
+ 'offset' => array(
+ 'type' => 'integer',
+ 'name' => 'offset',
+ 'label' => 'Offset',
+ 'tooltip' => 'The offset is the number of entries or posts you would like to skip. If the offset is 1, then the first post will be skipped.',
+ 'default' => 0
+ ),
+
+ 'posts-pages-sort-heading' => array(
+ 'name' => 'posts-pages-sort-heading',
+ 'type' => 'heading',
+ 'label' => 'Sort Content'
+ ),
+
+ 'order-by' => array(
+ 'type' => 'select',
+ 'name' => 'order-by',
+ 'label' => 'Order By',
+ 'tooltip' => '',
+ 'options' => array(
+ 'date' => 'Date',
+ 'title' => 'Title',
+ 'rand' => 'Random',
+ 'comment_count' => 'Comment Count',
+ 'ID' => 'ID'
+ )
+ ),
+
+ 'order' => array(
+ 'type' => 'select',
+ 'name' => 'order',
+ 'label' => 'Order',
+ 'tooltip' => '',
+ 'options' => array(
+ 'desc' => 'Descending',
+ 'asc' => 'Ascending',
+ )
+ )
+ ),
+ );
+
+ function get_taxonomies($post_type='') {
+
+ if (!empty($post_type)) {
+ $post_type = array($post_type);
+ $args=array(
+ 'object_type' => $post_type
+ );
+ } else {
+ $args = '';
+ }
+
+ $output = 'objects';
+ $operator = 'and';
+
+ $taxonomy_options = array('– Do not filter –');
+
+ $taxonomy_select_query=get_taxonomies($args,$output,$operator);
+
+ if ($taxonomy_select_query) {
+ foreach ($taxonomy_select_query as $taxonomy)
+ $taxonomy_options[$taxonomy->name] = $taxonomy->label;
+ }
+
+ return $taxonomy_options;
+
+ }
+
+ function get_listing_terms($taxonomy='category') {
+
+ if ( !$taxonomy )
+ $taxonomy = 'category';
+
+ $taxonomy_label = $this->get_taxonomy_label($taxonomy);
+
+ $terms_options = array('– Select '. $taxonomy_label .' –');
+
+ $terms = get_terms( $taxonomy, 'orderby=id&hide_empty=0' );
+
+ if ( !$terms )
+ return;
+
+ foreach ($terms as $term)
+ $terms_options[$term->term_id] = $term->name;
+
+ return $terms_options;
+
+ }
+
+ function get_taxonomy_label($taxonomy) {
+
+ if ( !$taxonomy )
+ $taxonomy = 'category';
+
+ $args = array(
+ 'name' => $taxonomy
+ );
+ $output = 'objects'; // or objects
+ $taxonomy_select_query=get_taxonomies($args,$output);;
+
+ if ($taxonomy_select_query) {
+ foreach ($taxonomy_select_query as $taxonomy)
+ return $taxonomy->label;
+ }
+
+ }
+
+ function get_authors() {
+
+ $author_options = array();
+
+ $authors = get_users(array(
+ 'orderby' => 'post_count',
+ 'order' => 'desc',
+ 'who' => 'authors'
+ ));
+
+ foreach ( $authors as $author )
+ $author_options[$author->ID] = $author->display_name;
+
+ return $author_options;
+
+ }
+
+ function get_pages() {
+
+ $page_options = array('– Default –');
+
+ $page_select_query = get_pages();
+
+ foreach ($page_select_query as $page)
+ $page_options[$page->ID] = $page->post_title;
+
+ return $page_options;
+
+ }
+
+ function get_post_types() {
+
+ $post_type_options = array('– All Post Types –');
+
+ $post_types = get_post_types(false, 'objects');
+
+ foreach($post_types as $post_type_id => $post_type){
+
+ //Make sure the post type is not an excluded post type.
+ if(in_array($post_type_id, array('revision', 'nav_menu_item')))
+ continue;
+
+ $post_type_options[$post_type_id] = $post_type->labels->name;
+
+ }
+
+ return $post_type_options;
+
+ }
+
+}
\ No newline at end of file
--- /dev/null
+<?php
+class HeadwayListingBlockDisplay {
+
+ var $count = 0;
+
+ var $query = array();
+
+
+ function __construct($block) {
+
+ $this->block = $block;
+
+ /* Bring in the WordPress pagination variable. */
+ $this->paged = get_query_var('paged') ? get_query_var('paged') : 1;
+
+ }
+
+
+ /**
+ * Created this function to make the call a little shorter.
+ **/
+ function get_setting($setting, $default = null) {
+
+ return HeadwayBlockAPI::get_setting($this->block, $setting, $default);
+
+ }
+
+ function display($args = array()) {
+
+ $block = $this->block;
+
+ $listing_type = HeadwayBlockAPI::get_setting($block, 'listing-type', 'taxonomy');
+
+ echo '<ul class="list-items">';
+
+ switch ($listing_type) {
+ case 'taxonomy':
+
+ $this->display_taxonomy($args);
+
+ break;
+
+ case 'content':
+
+ $this->loop($args);
+
+ wp_reset_query();
+
+ break;
+
+ default:
+ break;
+ }
+
+ echo '</ul>';
+
+ }
+
+
+ function loop($args = array()) {
+
+ if ( !dynamic_loop() ) {
+
+ $this->setup_query();
+
+ if ( !$this->query->have_posts() ) {
+
+ echo '<div class="entry-content">';
+ echo apply_filters('headway_search_no_results', __('<p>Sorry, there was no content that matched your search.</p>', 'headway'));
+ echo '</div>';
+
+ }
+
+ while ( $this->query->have_posts() ) {
+
+ $this->query->the_post();
+
+ $this->count++;
+
+ $this->display_entry(array('count' => $this->count));
+
+ }
+
+ }
+
+ }
+
+ function display_taxonomy($args = array()) {
+
+ $block = $this->block;
+
+ $taxonomy = HeadwayBlockAPI::get_setting($block, 'select-taxonomy', 'category');
+
+ $args = array(
+ 'orderby' => HeadwayBlockAPI::get_setting($block, 'terms-orderby', 'name'),
+ 'order' => HeadwayBlockAPI::get_setting($block, 'terms-order', 'ASC'),
+ 'hide_empty' => HeadwayBlockAPI::get_setting($block, 'terms-hide-empty', 0),
+ 'exclude' => HeadwayBlockAPI::get_setting($block, 'terms-exclude', array()),
+ 'exclude_tree' => array(),
+ 'include' => HeadwayBlockAPI::get_setting($block, 'terms-include', array()),
+ 'number' => HeadwayBlockAPI::get_setting($block, 'terms-number', '10'),
+ 'fields' => 'all',
+ 'slug' => HeadwayBlockAPI::get_setting($block, 'terms-slug', ''),
+ 'parent' => '',
+ 'hierarchical' => HeadwayBlockAPI::get_setting($block, 'terms-hierarchical', true),
+ 'child_of' => 0,
+ 'get' => '',
+ 'name__like' => '',
+ 'pad_counts' => false,
+ 'offset' => '',
+ 'search' => '',
+ 'cache_domain' => 'core'
+ );
+
+ $terms = get_terms( $taxonomy, $args );
+
+ $count = count($terms);
+ if ( $count > 0 ){
+ foreach ( $terms as $term ) {
+ $term_link = get_term_link( $term, $taxonomy );
+ if( is_wp_error( $term_link ) )
+ continue;
+ //We successfully got a link. Print it out.
+ echo '<li><a href="' . $term_link . '">' . $term->name . '</a></li>';
+ }
+ }
+ }
+
+ function setup_query() {
+
+ /* Setup Query Options */
+ $query_options = array();
+
+ $query_options['post_type'] = $this->get_setting('post-type', false);
+
+ $taxonomy = $this->get_setting('post-taxonomy-filter', 'category');
+
+ /* Set taxonomy query if specific terms set */
+ $terms = $this->get_setting('terms', array());
+
+ if (empty($terms)) {
+
+ $terms = get_terms($taxonomy,
+ array(
+ 'orderby' => 'slug',
+ 'order' => 'ASC',
+ 'fields' => 'ids',
+ ));
+
+ } else {
+ $query_options['tax_query'] = array(
+ array(
+ 'taxonomy' => $taxonomy,
+ 'field' => 'id',
+ 'terms' => $terms,
+ ),
+ );
+ }
+
+
+
+ //Post Limit
+ $query_options['posts_per_page'] = $this->get_setting('number-of-posts', '5');
+ //End Post Limit
+
+ if ( is_array($this->get_setting('author')) )
+ $query_options['author'] = trim(implode(',', $this->get_setting('author')), ', ');
+
+ //Order by
+ $query_options['orderby'] = $this->get_setting('order-by', 'date');
+ $query_options['order'] = $this->get_setting('order', 'desc');
+ //End order by
+
+ //Initiate query instance
+ $this->query = new WP_Query($query_options);
+
+ }
+
+
+ function display_entry($args = array()) {
+
+ global $post;
+
+ /* Setup generic variables */
+ $post_id = get_the_id();
+ $post_class = $this->entry_class();
+ $post_permalink = get_permalink();
+ $post_type = get_post_type();
+ /* End generic variables */
+
+ /* Setup Titles */
+ $hide_title = HeadwayLayoutOption::get($post_id, 'hide-title', false, true);
+
+ $alternate_title = HeadwayLayoutOption::get($post_id, 'alternate-title', false, true);
+
+ $post_title = (isset($alternate_title) && $alternate_title) ? $alternate_title : get_the_title();
+ $post_title_tooltip = sprintf(esc_attr__('%s', 'headway'), the_title_attribute('echo=0'));
+
+ $post_title_link = '<a href="' . $post_permalink . '" title="' . $post_title_tooltip . '" rel="bookmark">' . $post_title . '</a>';
+ /* End Titles */
+
+
+ echo '<li id="post-' . $post_id . '" class="' . $post_class . '">';
+
+
+ echo $post_title_link;
+
+
+ echo '</li><!-- #post-' . $post_id . ' -->';
+ }
+
+ /**
+ * Assembles the classes for the posts.
+ *
+ * @global object $post
+ * @global int $blog_post_alt
+ *
+ * @param bool $print Determines whether or not to echo the post classes.
+ *
+ * @return bool|string If $print is true, then echo the classes, otherwise just return them as a string.
+ **/
+ function entry_class() {
+
+ global $post, $blog_post_alt, $authordata;
+
+ $c = get_post_class();
+
+ if ( !isset($blog_post_alt) )
+ $blog_post_alt = 1;
+
+ if ( is_object($authordata) )
+ $c[] = 'author-' . sanitize_title_with_dashes(strtolower($authordata->user_login));
+
+ if ( ++$blog_post_alt % 2 )
+ $c[] = 'alt';
+
+ //Add the custom classes from the meta box
+ if ( $custom_css_class = HeadwayLayoutOption::get(get_the_id(), 'css-class', null, true) ) {
+
+ $custom_css_classes = str_replace(' ', ' ', str_replace(',', ' ', esc_attr(strip_tags($custom_css_class))));
+
+ $c = array_merge($c, array_filter(explode(' ', $custom_css_classes)));
+
+ }
+
+ //Add column class only if layout enabled and it is not singular in default mode
+ if ( $this->get_setting('enable-column-layout', false) ) {
+ if ( is_singular() && $this->get_setting('mode') == 'default') {
+ exit;
+ } else {
+ $c[] = 'post-column column-' . $this->count;
+ }
+ }
+
+ $c[] = $this->get_setting('mode');
+
+ $c = join(' ', $c);
+
+ return $c;
+
+ }
+
+}
\ No newline at end of file
--- /dev/null
+<?php
+
+headway_register_block('HeadwayListingsBlock', headway_url() . '/library/blocks/listings');
+
+class HeadwayListingsBlock extends HeadwayBlockAPI {
+
+
+ public $id = 'listings';
+
+ public $name = 'Listings';
+
+ public $options_class = 'HeadwayListingsBlockOptions';
+
+ public $description = 'List out your categories, authors, pages, comments and comments.';
+
+ static $block = null;
+
+
+ function init() {
+
+ require_once 'block-options.php';
+
+ require_once HEADWAY_LIBRARY_DIR . '/blocks/listings/content-display.php';
+
+
+ }
+
+ function setup_elements() {
+
+ $this->register_block_element(array(
+ 'id' => 'list-items',
+ 'name' => 'List Container',
+ 'selector' => 'ul.list-items'
+ ));
+
+ $this->register_block_element(array(
+ 'id' => 'list-item',
+ 'name' => 'List Item',
+ 'selector' => 'ul.list-items li'
+ ));
+
+ $this->register_block_element(array(
+ 'id' => 'list-item-link',
+ 'name' => 'List Item Link',
+ 'selector' => 'ul.list-items li a'
+ ));
+
+ }
+
+ function content($block) {
+
+ $listing_block_display = new HeadwayListingBlockDisplay($block);
+ $listing_block_display->display();
+
+ }
+
+
+
+
+}
\ No newline at end of file
--- /dev/null
+/*
+ * jQuery Superfish Menu Plugin
+ * Copyright (c) 2013 Joel Birch
+ *
+ * Dual licensed under the MIT and GPL licenses:
+ * http://www.opensource.org/licenses/mit-license.php
+ * http://www.gnu.org/licenses/gpl.html
+ */
+
+(function ($) {
+ "use strict";
+
+ var methods = (function () {
+ // private properties and methods go here
+ var c = {
+ bcClass: 'sf-breadcrumb',
+ menuClass: 'sf-js-enabled',
+ anchorClass: 'sf-with-ul',
+ menuArrowClass: 'sf-arrows'
+ },
+ ios = (function () {
+ var ios = /iPhone|iPad|iPod/i.test(navigator.userAgent);
+ if (ios) {
+ // iOS clicks only bubble as far as body children
+ $(window).load(function () {
+ $('body').children().on('click', $.noop);
+ });
+ }
+ return ios;
+ })(),
+ wp7 = (function () {
+ var style = document.documentElement.style;
+ return ('behavior' in style && 'fill' in style && /iemobile/i.test(navigator.userAgent));
+ })(),
+ toggleMenuClasses = function ($menu, o) {
+ var classes = c.menuClass;
+ if (o.cssArrows) {
+ classes += ' ' + c.menuArrowClass;
+ }
+ $menu.toggleClass(classes);
+ },
+ setPathToCurrent = function ($menu, o) {
+ return $menu.find('li.' + o.pathClass).slice(0, o.pathLevels)
+ .addClass(o.hoverClass + ' ' + c.bcClass)
+ .filter(function () {
+ return ($(this).children(o.popUpSelector).hide().show().length);
+ }).removeClass(o.pathClass);
+ },
+ toggleAnchorClass = function ($li) {
+ $li.children('a').toggleClass(c.anchorClass);
+ },
+ toggleTouchAction = function ($menu) {
+ var touchAction = $menu.css('ms-touch-action');
+ touchAction = (touchAction === 'pan-y') ? 'auto' : 'pan-y';
+ $menu.css('ms-touch-action', touchAction);
+ },
+ applyHandlers = function ($menu, o) {
+ var targets = 'li:has(' + o.popUpSelector + ')';
+ if ($.fn.hoverIntent && !o.disableHI) {
+ $menu.hoverIntent(over, out, targets);
+ }
+ else {
+ $menu
+ .on('mouseenter.superfish', targets, over)
+ .on('mouseleave.superfish', targets, out);
+ }
+ var touchevent = 'MSPointerDown.superfish';
+ if (!ios) {
+ touchevent += ' touchend.superfish';
+ }
+ if (wp7) {
+ touchevent += ' mousedown.superfish';
+ }
+ $menu
+ .on('focusin.superfish', 'li', over)
+ .on('focusout.superfish', 'li', out)
+ .on(touchevent, 'a', o, touchHandler);
+ },
+ touchHandler = function (e) {
+ var $this = $(this),
+ $ul = $this.siblings(e.data.popUpSelector);
+
+ if ($ul.length > 0 && $ul.is(':hidden')) {
+ $this.one('click.superfish', false);
+ if (e.type === 'MSPointerDown') {
+ $this.trigger('focus');
+ } else {
+ $.proxy(over, $this.parent('li'))();
+ }
+ }
+ },
+ over = function () {
+ var $this = $(this),
+ o = getOptions($this);
+ clearTimeout(o.sfTimer);
+ $this.siblings().superfish('hide').end().superfish('show');
+ },
+ out = function () {
+ var $this = $(this),
+ o = getOptions($this);
+ if (ios) {
+ $.proxy(close, $this, o)();
+ }
+ else {
+ clearTimeout(o.sfTimer);
+ o.sfTimer = setTimeout($.proxy(close, $this, o), o.delay);
+ }
+ },
+ close = function (o) {
+ o.retainPath = ($.inArray(this[0], o.$path) > -1);
+ this.superfish('hide');
+
+ if (!this.parents('.' + o.hoverClass).length) {
+ o.onIdle.call(getMenu(this));
+ if (o.$path.length) {
+ $.proxy(over, o.$path)();
+ }
+ }
+ },
+ getMenu = function ($el) {
+ return $el.closest('.' + c.menuClass);
+ },
+ getOptions = function ($el) {
+ return getMenu($el).data('sf-options');
+ };
+
+ return {
+ // public methods
+ hide: function (instant) {
+ if (this.length) {
+ var $this = this,
+ o = getOptions($this);
+ if (!o) {
+ return this;
+ }
+ var not = (o.retainPath === true) ? o.$path : '',
+ $ul = $this.find('li.' + o.hoverClass).add(this).not(not).removeClass(o.hoverClass).children(o.popUpSelector),
+ speed = o.speedOut;
+
+ if (instant) {
+ $ul.show();
+ speed = 0;
+ }
+ o.retainPath = false;
+ o.onBeforeHide.call($ul);
+ $ul.stop(true, true).animate(o.animationOut, speed, function () {
+ var $this = $(this);
+ o.onHide.call($this);
+ });
+ }
+ return this;
+ },
+ show: function () {
+ var o = getOptions(this);
+ if (!o) {
+ return this;
+ }
+ var $this = this.addClass(o.hoverClass),
+ $ul = $this.children(o.popUpSelector);
+
+ o.onBeforeShow.call($ul);
+ $ul.stop(true, true).animate(o.animation, o.speed, function () {
+ o.onShow.call($ul);
+ });
+ return this;
+ },
+ destroy: function () {
+ return this.each(function () {
+ var $this = $(this),
+ o = $this.data('sf-options'),
+ $hasPopUp;
+ if (!o) {
+ return false;
+ }
+ $hasPopUp = $this.find(o.popUpSelector).parent('li');
+ clearTimeout(o.sfTimer);
+ toggleMenuClasses($this, o);
+ toggleAnchorClass($hasPopUp);
+ toggleTouchAction($this);
+ // remove event handlers
+ $this.off('.superfish').off('.hoverIntent');
+ // clear animation's inline display style
+ $hasPopUp.children(o.popUpSelector).attr('style', function (i, style) {
+ return style.replace(/display[^;]+;?/g, '');
+ });
+ // reset 'current' path classes
+ o.$path.removeClass(o.hoverClass + ' ' + c.bcClass).addClass(o.pathClass);
+ $this.find('.' + o.hoverClass).removeClass(o.hoverClass);
+ o.onDestroy.call($this);
+ $this.removeData('sf-options');
+ });
+ },
+ init: function (op) {
+ return this.each(function () {
+ var $this = $(this);
+ if ($this.data('sf-options')) {
+ return false;
+ }
+ var o = $.extend({}, $.fn.superfish.defaults, op),
+ $hasPopUp = $this.find(o.popUpSelector).parent('li');
+ o.$path = setPathToCurrent($this, o);
+
+ $this.data('sf-options', o);
+
+ toggleMenuClasses($this, o);
+ toggleAnchorClass($hasPopUp);
+ toggleTouchAction($this);
+ applyHandlers($this, o);
+
+ $hasPopUp.not('.' + c.bcClass).superfish('hide', true);
+
+ o.onInit.call(this);
+ });
+ }
+ };
+ })();
+
+ $.fn.superfish = function (method, args) {
+ if (methods[method]) {
+ return methods[method].apply(this, Array.prototype.slice.call(arguments, 1));
+ }
+ else if (typeof method === 'object' || ! method) {
+ return methods.init.apply(this, arguments);
+ }
+ else {
+ return $.error('Method ' + method + ' does not exist on jQuery.fn.superfish');
+ }
+ };
+
+ $.fn.superfish.defaults = {
+ popUpSelector: 'ul,.sf-mega', // within menu context
+ hoverClass: 'sfHover',
+ pathClass: 'overrideThisToUse',
+ pathLevels: 1,
+ delay: 800,
+ animation: {opacity: 'show'},
+ animationOut: {opacity: 'hide'},
+ speed: 'normal',
+ speedOut: 'fast',
+ cssArrows: true,
+ disableHI: false,
+ onInit: $.noop,
+ onBeforeShow: $.noop,
+ onShow: $.noop,
+ onBeforeHide: $.noop,
+ onHide: $.noop,
+ onIdle: $.noop,
+ onDestroy: $.noop
+ };
+
+ // soon to be deprecated
+ $.fn.extend({
+ hideSuperfishUl: methods.hide,
+ showSuperfishUl: methods.show
+ });
+
+})(jQuery);
\ No newline at end of file
--- /dev/null
+/**
+ * @preserve SelectNav.js (v. 0.1)
+ * Converts your <ul>/<ol> navigation into a dropdown list for small screens
+ * https://github.com/lukaszfiszer/selectnav.js
+ */
+
+window.selectnav = (function(){
+
+"use strict";
+
+ var selectnav = function(element,options){
+
+ if ( typeof element == 'string' )
+ element = document.getElementById(element);
+
+ // return immediately if element doesn't exist
+ if( ! element){
+ return;
+ }
+
+ // return immediately if element is not a list
+ if( ! islist(element) ){
+ return;
+ }
+
+ // return immediately if no support for insertAdjacentHTML (Firefox 7 and under)
+ if( ! ('insertAdjacentHTML' in window.document.documentElement) ){
+ return;
+ }
+
+ // add a js class to <html> tag
+ document.documentElement.className += " js";
+
+ // retreive options and set defaults
+ var o = options || {},
+
+ activeclass = o.activeclass || 'active',
+ autoselect = typeof(o.autoselect) === "boolean" ? o.autoselect : true,
+ nested = typeof(o.nested) === "boolean" ? o.nested : true,
+ indent = o.indent || "→",
+ label = o.label || "- Navigation -",
+
+ // helper variables
+ level = 0,
+ selected = " selected ";
+
+ // insert the freshly created dropdown navigation after the existing navigation
+ element.insertAdjacentHTML('afterend', parselist(element) );
+
+ var nav = document.getElementById(id());
+
+ // autoforward on click
+ if (nav.addEventListener) {
+ nav.addEventListener('change',goTo);
+ }
+ if (nav.attachEvent) {
+ nav.attachEvent('onchange', goTo);
+ }
+
+ return nav;
+
+ function goTo(e){
+
+ // Crossbrowser issues - http://www.quirksmode.org/js/events_properties.html
+ var targ;
+ if (!e) e = window.event;
+ if (e.target) targ = e.target;
+ else if (e.srcElement) targ = e.srcElement;
+ if (targ.nodeType === 3) // defeat Safari bug
+ targ = targ.parentNode;
+
+ if(targ.value) window.location.href = targ.value;
+ }
+
+ function islist(list){
+ var n = list.nodeName.toLowerCase();
+ return (n === 'ul' || n === 'ol');
+ }
+
+ function id(nextId){
+ for(var j=1; document.getElementById('selectnav'+j);j++);
+ return (nextId) ? 'selectnav'+j : 'selectnav'+(j-1);
+ }
+
+ function parselist(list){
+
+ // go one level down
+ level++;
+
+ var length = list.children.length,
+ html = '',
+ prefix = '',
+ k = level-1
+ ;
+
+ // return immediately if has no children
+ if (!length) {
+ return;
+ }
+
+ if(k) {
+ while(k--){
+ prefix += indent;
+ }
+ prefix += " ";
+ }
+
+ for(var i=0; i < length; i++){
+
+ var link = list.children[i].children[0];
+ if(typeof(link) !== 'undefined'){
+ var linkToGetText = jQuery(link);
+ linkToGetText.find('.sf-sub-indicator').remove();
+
+ var text = linkToGetText.text();
+ var isselected = '';
+
+ if(activeclass){
+ isselected = link.className.search(activeclass) !== -1 || link.parentNode.className.search(activeclass) !== -1 ? selected : '';
+ }
+
+ if(autoselect && !isselected){
+ isselected = link.href === document.URL ? selected : '';
+ }
+
+ html += '<option value="' + link.href + '" ' + isselected + '>' + prefix + text +'</option>';
+
+ if(nested){
+ var subElement = list.children[i].children[1];
+ if( subElement && islist(subElement) ){
+ html += parselist(subElement);
+ }
+ }
+ }
+ }
+
+ // adds label
+ if(level === 1 && label) {
+ html = '<option value="">' + label + '</option>' + html;
+ }
+
+ // add <select> tag to the top level of the list
+ if(level === 1) {
+ html = '<select class="selectnav" id="'+id(true)+'">' + html + '</select>';
+ }
+
+ // go 1 level up
+ level--;
+
+ return html;
+ }
+
+ };
+
+ return function (element,options) {
+ selectnav(element,options);
+ };
+
+
+})();
\ No newline at end of file
--- /dev/null
+<?php
+headway_register_block('HeadwayNavigationBlock', headway_url() . '/library/blocks/navigation');
+
+class HeadwayNavigationBlock extends HeadwayBlockAPI {
+
+
+ public $id = 'navigation';
+
+ public $name = 'Navigation';
+
+ public $options_class = 'HeadwayNavigationBlockOptions';
+
+ public $fixed_height = false;
+
+ public $html_tag = 'nav';
+
+ public $attributes = array(
+ 'itemscope' => '',
+ 'itemtype' => 'http://schema.org/SiteNavigationElement'
+ );
+
+ public $description = 'The navigation is the menu that will display all of the pages in your site.';
+
+ protected $show_content_in_grid = true;
+
+ /* Use this to pass the block from static function to static function */
+ static public $block = null;
+
+ static private $menu_sub_check_cache = array();
+
+
+ public static function init_action($block_id, $block = false) {
+
+ if ( !$block )
+ $block = HeadwayBlocksData::get_block($block_id);
+
+ $name = HeadwayBlocksData::get_block_name($block) . ' — ' . 'Layout: ' . HeadwayLayout::get_name($block['layout']);
+
+ register_nav_menu('navigation_block_' . $block_id, $name);
+
+ wp_register_script('jquery-hoverintent', headway_url() . '/library/media/js/jquery.hoverintent.js', array('jquery'));
+
+ }
+
+
+ public static function enqueue_action($block_id, $block, $original_block = null) {
+
+ $dependencies = array();
+
+ /* Handle sub menus with super fish */
+ if ( self::does_menu_have_subs('navigation_block_' . $block_id) ) {
+
+ $dependencies[] = 'jquery';
+
+ if ( parent::get_setting($block, 'hover-intent', true) )
+ $dependencies[] = 'jquery-hoverintent';
+
+ wp_enqueue_script('headway-superfish', headway_url() . '/library/blocks/navigation/js/jquery.superfish.js', array_unique($dependencies));
+
+ }
+
+ /* SelectNav... Responsive Select */
+ if ( HeadwayResponsiveGrid::is_active() && parent::get_setting($block, 'responsive-select', true) ) {
+
+ wp_enqueue_script('headway-selectnav', headway_url() . '/library/blocks/navigation/js/selectnav.js', array('jquery'));
+
+ }
+
+ }
+
+
+ function content($block) {
+
+ self::$block = $block;
+
+ /* Add filter to add home link */
+ add_filter('wp_nav_menu_items', array(__CLASS__, 'home_link_filter'));
+ add_filter('wp_list_pages', array(__CLASS__, 'home_link_filter'));
+ add_filter('wp_page_menu', array(__CLASS__, 'fix_legacy_nav'));
+
+ /* Variables */
+ $vertical = parent::get_setting($block, 'vert-nav-box', false);
+ $alignment = parent::get_setting($block, 'alignment', 'left');
+
+ $search = parent::get_setting($block, 'enable-nav-search', false);
+ $search_position = parent::get_setting($block, 'nav-search-position', 'right');
+ $hide_home_link = parent::get_setting($block, 'hide-home-link', false);
+
+ /* Classes */
+ $nav_classes = array();
+
+ $nav_classes[] = $vertical ? 'nav-vertical' : 'nav-horizontal';
+ $nav_classes[] = 'nav-align-' . $alignment;
+
+ if ( $search && !$vertical ) {
+
+ $nav_classes[] = 'nav-search-active';
+ $nav_classes[] = 'nav-search-position-' . $search_position;
+
+ }
+
+ $nav_classes = trim(implode(' ', array_unique($nav_classes)));
+
+ /* Use legacy ID */
+ $block['id'] = HeadwayBlocksData::get_legacy_id( $block );
+
+ $nav_location = 'navigation_block_' . $block['id'];
+
+ echo '<div class="' . $nav_classes . '">';
+
+ $nav_menu_args = array(
+ 'theme_location' => $nav_location,
+ 'container' => false,
+ );
+
+ if ( HeadwayRoute::is_grid() || headway_get('ve-live-content-query', $block) ) {
+
+ $nav_menu_args['link_before'] = '<span>';
+ $nav_menu_args['link_after'] = '</span>';
+
+ }
+
+ wp_nav_menu(apply_filters('headway_navigation_block_query_args', $nav_menu_args, $block));
+
+ if ( $search && !$vertical ) {
+
+ echo '<div class="nav-search">';
+
+ echo headway_get_search_form(parent::get_setting($block, 'nav-search-placeholder', null));
+
+ echo '</div>';
+
+ }
+
+ echo '</div><!-- .' . $nav_classes . ' -->';
+
+ /* Remove filter for home link so other non-navigation blocks are modified */
+ remove_filter('wp_nav_menu_items', array(__CLASS__, 'home_link_filter'));
+ remove_filter('wp_list_pages', array(__CLASS__, 'home_link_filter'));
+ remove_filter('wp_page_menu', array(__CLASS__, 'fix_legacy_nav'));
+
+ }
+
+
+ public static function dynamic_css($block_id, $block, $original_block = null) {
+
+ $selector = '#block-' . $block_id;
+
+ /* If this block is a mirror, then pull the settings from the block that's mirroring that way the dimensions are correct */
+ if ( is_array($original_block) ) {
+
+ $block_id = $original_block['id'];
+ $block = $original_block;
+
+ $selector .= '.block-original-' . $block_id;
+
+ }
+
+ $block_height = HeadwayBlocksData::get_block_height($block);
+
+ return '
+ ' . $selector . ' .nav-horizontal ul.menu > li > a,
+ ' . $selector . ' .nav-search-active .nav-search {
+ height: ' . $block_height . 'px;
+ line-height: ' . $block_height . 'px;
+ }';
+
+ }
+
+
+ public static function dynamic_js($block_id, $block, $original_block = null) {
+
+ $js = null;
+
+ /* Superfish */
+ if ( self::does_menu_have_subs('navigation_block_' . $block_id) ) {
+
+ switch ( parent::get_setting($block, 'effect', 'fade') ) {
+ case 'none':
+ $animation = '{height:"show"}';
+ $speed = '0';
+ break;
+
+ case 'fade':
+ $animation = '{opacity:"show"}';
+ $speed = "'fast'";
+ break;
+
+ case 'slide':
+ $animation = '{height:"show"}';
+ $speed = "'fast'";
+ break;
+ }
+
+ $js .= 'jQuery(document).ready(function(){
+ if ( typeof jQuery().superfish != "function" )
+ return false;
+
+ jQuery("#block-' . $block_id . '").find("ul.menu").superfish({
+ delay: 200,
+ animation: ' . $animation . ',
+ speed: ' . $speed . ',
+ onBeforeShow: function() {
+ var parent = jQuery(this).parent();
+
+ var subMenuParentLink = jQuery(this).siblings(\'a\');
+ var subMenuParents = jQuery(this).parents(\'.sub-menu\');
+
+ if ( subMenuParents.length > 0 || jQuery(this).parents(\'.nav-vertical\').length > 0 ) {
+ jQuery(this).css(\'marginLeft\', parent.outerWidth());
+ jQuery(this).css(\'marginTop\', -subMenuParentLink.outerHeight());
+ }
+ }
+ });
+ });' . "\n\n";
+
+ }
+
+ /* SelectNav */
+ if ( HeadwayResponsiveGrid::is_active() && parent::get_setting($block, 'responsive-select', true) ) {
+
+ $js .= 'jQuery(document).ready(function(){
+
+ if ( typeof window.selectnav != "function" )
+ return false;
+
+ selectnav(jQuery("#block-' . $block_id . '").find("ul.menu")[0], {
+ label: "-- ' . __('Navigation', 'headway') . ' --",
+ nested: true,
+ indent: "-",
+ activeclass: "current-menu-item"
+ });
+
+ jQuery("#block-' . $block_id . '").find("ul.menu").addClass("selectnav-active");
+
+ });' . "\n\n";
+
+ }
+
+ return $js;
+
+ }
+
+
+ public static function does_menu_have_subs($location) {
+
+ /*
+ * Running wp_nav_menu() is a little taxing when not needed.
+ * Sometimes self::does_menu_have_subs() is called multiple times on the same location and this is wasting resources.
+ * This is what the cache is here to resolve.
+ */
+
+ if ( headway_get($location, self::$menu_sub_check_cache) !== null ) {
+ return headway_get($location, self::$menu_sub_check_cache);
+ }
+
+ $menu = wp_nav_menu(array(
+ 'theme_location' => $location,
+ 'echo' => false
+ ));
+
+ $result = false;
+
+ if ( preg_match('/class=[\'"]sub-menu[\'"]/', $menu) || preg_match('/class=[\'"]children[\'"]/', $menu) )
+ $result = true;
+
+ self::$menu_sub_check_cache[$location] = $result;
+
+ return self::$menu_sub_check_cache[$location];
+
+ }
+
+
+ function setup_elements() {
+
+ $this->register_block_element(array(
+ 'id' => 'menu-item',
+ 'name' => 'Menu Item',
+ 'selector' => 'ul.menu li > a',
+ 'properties' => array(
+ 'fonts',
+ 'background',
+ 'borders',
+ 'padding',
+ 'corners',
+ 'box-shadow',
+ 'text-shadow'
+ ),
+ 'states' => array(
+ 'Selected' => '
+ ul.menu li.current_page_item > a,
+ ul.menu li.current_page_parent > a,
+ ul.menu li.current_page_ancestor > a,
+ ul.menu li.current_page_item > a:hover,
+ ul.menu li.current_page_parent > a:hover,
+ ul.menu li.current_page_ancestor > a:hover,
+ ul.menu li.current-menu-item > a,
+ ul.menu li.current-menu-parent > a,
+ ul.menu li.current-menu-ancestor > a,
+ ul.menu li.current-menu-item > a:hover,
+ ul.menu li.current-menu-parent > a:hover,
+ ul.menu li.current-menu-ancestor > a:hover
+ ',
+ 'Hover' => 'ul.menu li > a:hover',
+ 'Clicked' => 'ul.menu li > a:active',
+ 'Dropdown Open' => 'ul.menu li.sfHover > a'
+ )
+ ));
+
+
+ $this->register_block_element(array(
+ 'id' => 'sub-nav-menu',
+ 'name' => 'Sub Menu',
+ 'selector' => 'ul.sub-menu',
+ 'properties' => array('background', 'borders', 'padding', 'corners', 'box-shadow', 'margins'),
+ 'disallow-nudging' => true
+ ));
+
+
+ $this->register_block_element(array(
+ 'id' => 'sub-menu-item',
+ 'name' => 'Sub Menu Item',
+ 'selector' => 'ul.sub-menu li > a',
+ 'properties' => array(
+ 'fonts',
+ 'background',
+ 'borders',
+ 'padding',
+ 'corners',
+ 'box-shadow',
+ 'text-shadow'
+ ),
+ 'states' => array(
+ 'Selected' => '
+ ul.sub-menu li.current_page_item > a,
+ ul.sub-menu li.current_page_parent > a,
+ ul.sub-menu li.current_page_ancestor > a,
+ ul.sub-menu li.current_page_item > a:hover,
+ ul.sub-menu li.current_page_parent > a:hover,
+ ul.sub-menu li.current_page_ancestor > a:hover
+ ',
+ 'Hover' => 'ul.sub-menu li > a:hover',
+ 'Clicked' => 'ul.sub-menu li > a:active',
+ 'Dropdown Open' => 'ul.sub-menu li.sfHover > a'
+ )
+ ));
+
+ $this->register_block_element(array(
+ 'id' => 'search-input',
+ 'name' => 'Search Input',
+ 'selector' => '#searchform input[type="text"]',
+ 'states' => array(
+ 'Focused' => '#searchform input[type="text"]:focus'
+ )
+ ));
+
+ }
+
+
+ public static function home_link_filter($menu) {
+
+ $block = self::$block;
+
+ if ( parent::get_setting($block, 'hide-home-link') )
+ return $menu;
+
+ if ( get_option('show_on_front') == 'posts' ) {
+
+ $current = (is_home() || is_front_page()) ? ' current_page_item' : null;
+ $home_text = ( parent::get_setting($block, 'home-link-text') ) ? parent::get_setting($block, 'home-link-text') : 'Home';
+
+ /* If it's not the grid, then do not add the extra <span>'s */
+ if ( !HeadwayRoute::is_grid() && !headway_get('ve-live-content-query', $block) )
+ $home_link = '<li class="menu-item-home headway-home-link' . $current . '"><a href="' . home_url() . '">' . $home_text . '</a></li>';
+
+ /* If it IS the grid, add extra <span>'s so it can be automatically vertically aligned */
+ else
+ $home_link = '<li class="menu-item-home headway-home-link' . $current . '"><a href="' . home_url() . '"><span>' . $home_text . '</span></a></li>';
+
+ } else {
+
+ $home_link = null;
+
+ }
+
+ return $home_link . $menu;
+
+ }
+
+
+ public static function fix_legacy_nav($menu) {
+
+ $menu = preg_replace('/<ul class=[\'"]children[\'"]/', '<ul class="sub-menu"', trim($menu)); //Change sub menu class
+ $menu = preg_replace('/<div class=[\'"]menu[\'"]>/', '', $menu, 1); //Remove opening <div>
+ $menu = str_replace('<ul>', '<ul class="menu">', $menu); //Add menu class to main <ul>
+ $menu = str_replace('current_page_item', 'current_page_item current-menu-item', $menu); //Add current-menu-item wherever current_page_item is to make legacy nav more consistent with wp_nav_menu()
+
+ return substr(trim($menu), 0, -6); //Remove the closing </div>
+
+ }
+
+
+}
+
+
+class HeadwayNavigationBlockOptions extends HeadwayBlockOptionsAPI {
+
+ public $tabs = array(
+ 'nav-menu-content' => 'Content',
+ 'search' => 'Search',
+ 'home-link' => 'Home Link',
+ 'orientation' => 'Orientation',
+ 'dropdowns' => 'Dropdowns',
+ 'responsiveness' => 'Responsiveness'
+ );
+
+ public $inputs = array(
+ 'search' => array(
+ 'enable-nav-search' => array(
+ 'type' => 'checkbox',
+ 'name' => 'enable-nav-search',
+ 'label' => 'Enable Navigation Search',
+ 'default' => false,
+ 'tooltip' => 'If you wish to have a simple search form in the navigation bar, then check this box. <em><strong>Note:</strong> the search form will not show if the Vertical Navigation option is enabled for this block.</em>'
+ ),
+
+ 'nav-search-position' => array(
+ 'type' => 'select',
+ 'name' => 'nav-search-position',
+ 'label' => 'Search Position',
+ 'default' => 'right',
+ 'options' => array(
+ 'left' => 'Left',
+ 'right' => 'Right'
+ ),
+ 'tooltip' => 'If you would like the navigation search input to snap to the left instead of the right, you can use this option.'
+ ),
+
+ 'nav-search-placeholder' => array(
+ 'type' => 'text',
+ 'name' => 'nav-search-placeholder',
+ 'label' => 'Search Placeholder',
+ 'default' => 'Type to search, then press enter',
+ 'tooltip' => 'This will be the text inside the search input telling the visitor how to interact with the search input.'
+ )
+ ),
+
+ 'home-link' => array(
+ 'hide-home-link' => array(
+ 'type' => 'checkbox',
+ 'name' => 'hide-home-link',
+ 'label' => 'Hide Home Link',
+ 'default' => false,
+ 'tooltip' => 'If you do not have a static page as the front page, Headway will add a home item to the navigation menu by default.',
+ ),
+
+ 'home-link-text' => array(
+ 'name' => 'home-link-text',
+ 'label' => 'Home Link Text',
+ 'type' => 'text',
+ 'tooltip' => 'If you would like the link to your homepage to say something other than <em>Home</em>, enter it here!',
+ 'default' => 'Home'
+ )
+ ),
+
+ 'orientation' => array(
+ 'alignment' => array(
+ 'type' => 'select',
+ 'name' => 'alignment',
+ 'label' => 'Alignment',
+ 'default' => 'left',
+ 'options' => array(
+ 'left' => 'Left',
+ 'right' => 'Right',
+ 'center' => 'Center'
+ )
+ ),
+
+ 'vert-nav-box' => array(
+ 'type' => 'checkbox',
+ 'name' => 'vert-nav-box',
+ 'label' => 'Vertical Navigation',
+ 'default' => false,
+ 'tooltip' => 'Instead of showing navigation horizontally, you can make the navigation show vertically. <em><strong>Note:</strong> You may have to resize the block to make the navigation items fit correctly.</em>'
+ )
+ ),
+
+ 'dropdowns' => array(
+ 'effect' => array(
+ 'type' => 'select',
+ 'name' => 'effect',
+ 'label' => 'Drop Down Effect',
+ 'default' => 'fade',
+ 'options' => array(
+ 'none' => 'No Effect',
+ 'fade' => 'Fade',
+ 'slide' => 'Slide'
+ ),
+ 'tooltip' => 'This is the effect that will be used when the drop downs are shown and hidden.'
+ ),
+
+ 'hover-intent' => array(
+ 'type' => 'checkbox',
+ 'name' => 'hover-intent',
+ 'label' => 'Hover Intent',
+ 'default' => true,
+ 'tooltip' => 'Hover Intent makes it so if a navigation item with a drop down is hovered then the drop down will only be shown if the visitor has their mouse over the item for more than a split second.<br /><br />This reduces drop-downs from sporatically showing if the visitor makes fast movements over the navigation.'
+ )
+ ),
+
+ 'responsiveness' => array(
+ 'responsiveness-notice' => array(
+ 'name' => 'responsiveness-notice',
+ 'type' => 'notice',
+ 'notice' => 'You must have Responsive Grid enabled to take advantage of these options. Responsive Grid can be enabled under Setup » Responsive Grid in the Grid mode.'
+ ),
+
+ 'responsive-select' => array(
+ 'type' => 'checkbox',
+ 'name' => 'responsive-select',
+ 'label' => 'Responsive Select',
+ 'default' => true,
+ 'tooltip' => 'When enabled, your navigation will turn into a mobile-friendly select menu when your visitors are viewing your site on a mobile device (phones, not tablets).'
+ )
+ )
+ );
+
+
+ function modify_arguments($args = false) {
+
+ $this->tab_notices['nav-menu-content'] = 'To add items to this navigation menu, go to <a href="' . admin_url('nav-menus.php') . '" target="_blank">WordPress Admin » Appearance » Menus</a>. Then, create a menu and assign it to <em>' . HeadwayBlocksData::get_block_name($args['blockID']) . '</em> in the <strong>Theme Locations</strong> box.';
+
+ }
+
+}
\ No newline at end of file
--- /dev/null
+.pin-board {
+ opacity: 0;
+ width: 100%;
+}
+
+.block-type-pin-board {
+ overflow: visible !important;
+}
+
+/* Pins */
+ .pin-board-pin {
+ width: 30%;
+ word-wrap: break-word;
+
+ margin: 0;
+
+ box-sizing: border-box;
+ -moz-box-sizing: border-box;
+ }
+
+/* Titles */
+ .pin-board-pin h3 {
+ margin: 0;
+ }
+
+ .pin-board-pin h3 a {
+ display: block;
+ }
+
+ .pin-board-pin h3:last-child {
+ margin-bottom: 12px;
+ }
+/* Meta */
+ .pin-board-pin .entry-meta {
+ margin: 15px 0;
+ }
+
+ .pin-board-pin .entry-title + .entry-meta {
+ margin-top: 5px;
+ }
+
+/* Text */
+ .pin-board-pin-text {
+ margin: 15px 0;
+ }
+
+ .pin-board-pin-text :last-child {
+ margin-bottom: 0;
+ }
+
+/* Social */
+ .pin-board-pin .twitter-share-button,
+ .pin-board-pin .facebook-share-button,
+ .pin-board-pin .pin-it-button img {
+ opacity: 0;
+ }
+
+ /* Secondary social area */
+ .pin-board-pin-social {
+ float: left;
+ padding: 0 15px 15px;
+ }
+
+ .pin-board-pin-social > * {
+ float: left;
+ margin: 0 3px;
+ }
+
+ /* Facebook iframe */
+ .pin-board-pin .facebook-share-button {
+ border: none;
+ overflow: hidden;
+ width: 90px;
+ height: 21px;
+ }
+
+ .pin-board-pin .facebook-recommend-button {
+ width: 140px;
+ }
+
+ /* Twitter iframe */
+ .pin-board-pin .twitter-share-button {
+ width: 56px;
+ height: 20px;
+ }
+
+/* Thumbnails */
+ .pin-board-pin-thumbnail {
+ position: relative;
+ }
+
+ .pin-board-pin .post-thumbnail {
+ display: block;
+ }
+
+ .pin-board-pin .post-thumbnail img {
+ width: 100%;
+ display: block;
+ }
+
+ /* Thumbnail Social */
+ .pin-board-pin-thumbnail-social {
+ position: absolute;
+ top: 10px;
+ left: 10px;
+ right: 10px;
+ opacity: 0;
+
+ transition: opacity 250ms linear;
+ -moz-transition: opacity 250ms linear;
+ -webkit-transition: opacity 250ms linear;
+ -ms-transition: opacity 250ms linear;
+ }
+
+ .pin-board-pin-thumbnail-social .twitter-share-button,
+ .pin-board-pin-thumbnail-social .pin-it-button {
+ float: right;
+ margin: 0 3px;
+ }
+
+ .pin-board-pin-thumbnail-social .facebook-share-button {
+ float: left;
+ }
+
+ .pin-board-pin:hover .pin-board-pin-thumbnail .pin-board-pin-thumbnail-social {
+ opacity: .6;
+ }
+
+ .pin-board-pin:hover .pin-board-pin-thumbnail:hover .pin-board-pin-thumbnail-social {
+ opacity: 1;
+ }
+
+/* Hover Effect */
+ .pin-board-hover-focus .pin-board-pin {
+ -moz-transition: opacity 220ms linear, margin 220ms linear;
+ -webkit-transition: opacity 220ms linear, margin 220ms linear;
+ transition: opacity 220ms linear, margin 220ms linear;
+ opacity: 1;
+ }
+
+ .pin-board-hover-focus .pin-board-pin-blur {
+ opacity: .6;
+ }
+
+ .pin-board-hover-focus .pin-board-pin-hover {
+ margin-top: -3px;
+ }
+
+/* Pagination */
+ .pin-board-pagination {
+ text-align: center;
+ margin: 10px 0;
+ }
+
+ .pin-board-pagination a {
+ margin: 0 5px;
+ }
+
+/* Infinite Scroll */
+ .pin-board-infinite-scroll {
+ position: relative;
+ }
+
+ .pin-board-infinite-scroll + .pin-board-pagination {
+ opacity: 0;
+ }
+
+ .pin-board-infinite-scroll .pin-board-scroll-loading {
+ display: block;
+ clear: both;
+ position: absolute;
+ bottom: 15px;
+ left: 0;
+ z-index: 5;
+ width: 100%;
+ text-align: center;
+ }
+
+ .pin-board-infinite-scroll .pin-board-scroll-loading span {
+ background: rgba(0, 0, 0, .4);
+ color: rgba(255, 255, 255, .85);
+ border-radius: 5px;
+ -webkit-border-radius: 5px;
+ -moz-border-radius: 5px;
+ width: auto;
+ display: inline-block;
+ padding: 7px 10px;
+ font-family: helvetica, sans-serif;
+ }
+
+/* DESIGN EDITOR DEFAULTS FOR CHILD THEMES */
+ body.design-editor-disabled .pin-board-pin {
+ padding: 1px;
+ border: 1px solid #eee;
+ background-color: #fff;
+ box-shadow: 0 2px 3px #eee;
+ }
+
+ body.design-editor-disabled .pin-board-pin .entry-title a {
+ padding: 15px 15px 0;
+ font-size: 18px;
+ line-height: 120%;
+ text-decoration: none;
+ }
+
+ body.design-editor-disabled .pin-board-pin .entry-title a:hover {
+ text-decoration: underline;
+ }
+
+ body.design-editor-disabled .pin-board-pin .entry-meta {
+ font-size: 12px;
+ line-height: 120%;
+ padding: 0 15px;
+ color: #888;
+ }
+
+ body.design-editor-disabled .pin-board-pin .entry-content {
+ padding: 0 15px;
+ color: #555;
+ font-size: 13px;
+ line-height: 20px;
+ }
+
+ body.design-editor-disabled .pin-board-pagination a {
+ text-decoration: none;
+ background-color: #eee;
+ border-radius: 4px;
+ padding: 5px 9px;
+ }
+
+ body.design-editor-disabled .pin-board-pagination a:hover {
+ background-color: #e7e7e7;
+ }
\ No newline at end of file
--- /dev/null
+/**
+ * jQuery Masonry v2.1.05
+ * A dynamic layout plugin for jQuery
+ * The flip-side of CSS Floats
+ * http://masonry.desandro.com
+ *
+ * Licensed under the MIT license.
+ * Copyright 2012 David DeSandro
+ */
+(function(a,b,c){"use strict";var d=b.event,e;d.special.smartresize={setup:function(){b(this).bind("resize",d.special.smartresize.handler)},teardown:function(){b(this).unbind("resize",d.special.smartresize.handler)},handler:function(a,c){var d=this,f=arguments;a.type="smartresize",e&&clearTimeout(e),e=setTimeout(function(){b.event.handle.apply(d,f)},c==="execAsap"?0:100)}},b.fn.smartresize=function(a){return a?this.bind("smartresize",a):this.trigger("smartresize",["execAsap"])},b.Mason=function(a,c){this.element=b(c),this._create(a),this._init()},b.Mason.settings={isResizable:!0,isAnimated:!1,animationOptions:{queue:!1,duration:500},gutterWidth:0,isRTL:!1,isFitWidth:!1,containerStyle:{position:"relative"}},b.Mason.prototype={_filterFindBricks:function(a){var b=this.options.itemSelector;return b?a.filter(b).add(a.find(b)):a},_getBricks:function(a){var b=this._filterFindBricks(a).css({position:"absolute"}).addClass("masonry-brick");return b},_create:function(c){this.options=b.extend(!0,{},b.Mason.settings,c),this.styleQueue=[];var d=this.element[0].style;this.originalStyle={height:d.height||""};var e=this.options.containerStyle;for(var f in e)this.originalStyle[f]=d[f]||"";this.element.css(e),this.horizontalDirection=this.options.isRTL?"right":"left",this.offset={x:parseInt(this.element.css("padding-"+this.horizontalDirection),10),y:parseInt(this.element.css("padding-top"),10)},this.isFluid=this.options.columnWidth&&typeof this.options.columnWidth=="function";var g=this;setTimeout(function(){g.element.addClass("masonry")},0),this.options.isResizable&&b(a).bind("smartresize.masonry",function(){g.resize()}),this.reloadItems()},_init:function(a){this._getColumns(),this._reLayout(a)},option:function(a,c){b.isPlainObject(a)&&(this.options=b.extend(!0,this.options,a))},layout:function(a,b){for(var c=0,d=a.length;c<d;c++)this._placeBrick(a[c]);var e={};e.height=Math.max.apply(Math,this.colYs);if(this.options.isFitWidth){var f=0;c=this.cols;while(--c){if(this.colYs[c]!==0)break;f++}e.width=(this.cols-f)*this.columnWidth-this.options.gutterWidth}this.styleQueue.push({$el:this.element,style:e});var g=this.isLaidOut?this.options.isAnimated?"animate":"css":"css",h=this.options.animationOptions,i;for(c=0,d=this.styleQueue.length;c<d;c++)i=this.styleQueue[c],i.$el[g](i.style,h);this.styleQueue=[],b&&b.call(a),this.isLaidOut=!0},_getColumns:function(){var a=this.options.isFitWidth?this.element.parent():this.element,b=a.width();this.columnWidth=this.isFluid?this.options.columnWidth(b):this.options.columnWidth||this.$bricks.outerWidth(!0)||b,this.columnWidth+=this.options.gutterWidth,this.cols=Math.floor((b+this.options.gutterWidth)/this.columnWidth),this.cols=Math.max(this.cols,1)},_placeBrick:function(a){var c=b(a),d,e,f,g,h;d=Math.ceil(c.outerWidth(!0)/this.columnWidth),d=Math.min(d,this.cols);if(d===1)f=this.colYs;else{e=this.cols+1-d,f=[];for(h=0;h<e;h++)g=this.colYs.slice(h,h+d),f[h]=Math.max.apply(Math,g)}var i=Math.min.apply(Math,f),j=0;for(var k=0,l=f.length;k<l;k++)if(f[k]===i){j=k;break}var m={top:i+this.offset.y};m[this.horizontalDirection]=this.columnWidth*j+this.offset.x,this.styleQueue.push({$el:c,style:m});var n=i+c.outerHeight(!0),o=this.cols+1-l;for(k=0;k<o;k++)this.colYs[j+k]=n},resize:function(){var a=this.cols;this._getColumns(),(this.isFluid||this.cols!==a)&&this._reLayout()},_reLayout:function(a){var b=this.cols;this.colYs=[];while(b--)this.colYs.push(0);this.layout(this.$bricks,a)},reloadItems:function(){this.$bricks=this._getBricks(this.element.children())},reload:function(a){this.reloadItems(),this._init(a)},appended:function(a,b,c){if(b){this._filterFindBricks(a).css({top:this.element.height()});var d=this;setTimeout(function(){d._appended(a,c)},1)}else this._appended(a,c)},_appended:function(a,b){var c=this._getBricks(a);this.$bricks=this.$bricks.add(c),this.layout(c,b)},remove:function(a){this.$bricks=this.$bricks.not(a),a.remove()},destroy:function(){this.$bricks.removeClass("masonry-brick").each(function(){this.style.position="",this.style.top="",this.style.left=""});var c=this.element[0].style;for(var d in this.originalStyle)c[d]=this.originalStyle[d];this.element.unbind(".masonry").removeClass("masonry").removeData("masonry"),b(a).unbind(".masonry")}},b.fn.imagesLoaded=function(a){function h(){a.call(c,d)}function i(a){var c=a.target;c.src!==f&&b.inArray(c,g)===-1&&(g.push(c),--e<=0&&(setTimeout(h),d.unbind(".imagesLoaded",i)))}var c=this,d=c.find("img").add(c.filter("img")),e=d.length,f="data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///ywAAAAAAQABAAACAUwAOw==",g=[];return e||h(),d.bind("load.imagesLoaded error.imagesLoaded",i).each(function(){var a=this.src;this.src=f,this.src=a}),c};var f=function(b){a.console&&a.console.error(b)};b.fn.masonry=function(a){if(typeof a=="string"){var c=Array.prototype.slice.call(arguments,1);this.each(function(){var d=b.data(this,"masonry");if(!d){f("cannot call methods on masonry prior to initialization; attempted to call method '"+a+"'");return}if(!b.isFunction(d[a])||a.charAt(0)==="_"){f("no such method '"+a+"' for masonry instance");return}d[a].apply(d,c)})}else this.each(function(){var c=b.data(this,"masonry");c?(c.option(a||{}),c._init()):b.data(this,"masonry",new b.Mason(a,this))});return this}})(window,jQuery);
+
+
+/*
+jQuery Waypoints - v1.1.7
+Copyright (c) 2011-2012 Caleb Troughton
+Dual licensed under the MIT license and GPL license.
+https://github.com/imakewebthings/jquery-waypoints/blob/master/MIT-license.txt
+https://github.com/imakewebthings/jquery-waypoints/blob/master/GPL-license.txt
+*/
+(function($,k,m,i,d){var e=$(i),g="waypoint.reached",b=function(o,n){o.element.trigger(g,n);if(o.options.triggerOnce){o.element[k]("destroy")}},h=function(p,o){if(!o){return -1}var n=o.waypoints.length-1;while(n>=0&&o.waypoints[n].element[0]!==p[0]){n-=1}return n},f=[],l=function(n){$.extend(this,{element:$(n),oldScroll:0,waypoints:[],didScroll:false,didResize:false,doScroll:$.proxy(function(){var q=this.element.scrollTop(),p=q>this.oldScroll,s=this,r=$.grep(this.waypoints,function(u,t){return p?(u.offset>s.oldScroll&&u.offset<=q):(u.offset<=s.oldScroll&&u.offset>q)}),o=r.length;if(!this.oldScroll||!q){$[m]("refresh")}this.oldScroll=q;if(!o){return}if(!p){r.reverse()}$.each(r,function(u,t){if(t.options.continuous||u===o-1){b(t,[p?"down":"up"])}})},this)});$(n).bind("scroll.waypoints",$.proxy(function(){if(!this.didScroll){this.didScroll=true;i.setTimeout($.proxy(function(){this.doScroll();this.didScroll=false},this),$[m].settings.scrollThrottle)}},this)).bind("resize.waypoints",$.proxy(function(){if(!this.didResize){this.didResize=true;i.setTimeout($.proxy(function(){$[m]("refresh");this.didResize=false},this),$[m].settings.resizeThrottle)}},this));e.load($.proxy(function(){this.doScroll()},this))},j=function(n){var o=null;$.each(f,function(p,q){if(q.element[0]===n){o=q;return false}});return o},c={init:function(o,n){this.each(function(){var u=$.fn[k].defaults.context,q,t=$(this);if(n&&n.context){u=n.context}if(!$.isWindow(u)){u=t.closest(u)[0]}q=j(u);if(!q){q=new l(u);f.push(q)}var p=h(t,q),s=p<0?$.fn[k].defaults:q.waypoints[p].options,r=$.extend({},s,n);r.offset=r.offset==="bottom-in-view"?function(){var v=$.isWindow(u)?$[m]("viewportHeight"):$(u).height();return v-$(this).outerHeight()}:r.offset;if(p<0){q.waypoints.push({element:t,offset:null,options:r})}else{q.waypoints[p].options=r}if(o){t.bind(g,o)}if(n&&n.handler){t.bind(g,n.handler)}});$[m]("refresh");return this},remove:function(){return this.each(function(o,p){var n=$(p);$.each(f,function(r,s){var q=h(n,s);if(q>=0){s.waypoints.splice(q,1);if(!s.waypoints.length){s.element.unbind("scroll.waypoints resize.waypoints");f.splice(r,1)}}})})},destroy:function(){return this.unbind(g)[k]("remove")}},a={refresh:function(){$.each(f,function(r,s){var q=$.isWindow(s.element[0]),n=q?0:s.element.offset().top,p=q?$[m]("viewportHeight"):s.element.height(),o=q?0:s.element.scrollTop();$.each(s.waypoints,function(u,x){if(!x){return}var t=x.options.offset,w=x.offset;if(typeof x.options.offset==="function"){t=x.options.offset.apply(x.element)}else{if(typeof x.options.offset==="string"){var v=parseFloat(x.options.offset);t=x.options.offset.indexOf("%")?Math.ceil(p*(v/100)):v}}x.offset=x.element.offset().top-n+o-t;if(x.options.onlyOnScroll){return}if(w!==null&&s.oldScroll>w&&s.oldScroll<=x.offset){b(x,["up"])}else{if(w!==null&&s.oldScroll<w&&s.oldScroll>=x.offset){b(x,["down"])}else{if(!w&&s.element.scrollTop()>x.offset){b(x,["down"])}}}});s.waypoints.sort(function(u,t){return u.offset-t.offset})})},viewportHeight:function(){return(i.innerHeight?i.innerHeight:e.height())},aggregate:function(){var n=$();$.each(f,function(o,p){$.each(p.waypoints,function(q,r){n=n.add(r.element)})});return n}};$.fn[k]=function(n){if(c[n]){return c[n].apply(this,Array.prototype.slice.call(arguments,1))}else{if(typeof n==="function"||!n){return c.init.apply(this,arguments)}else{if(typeof n==="object"){return c.init.apply(this,[null,n])}else{$.error("Method "+n+" does not exist on jQuery "+k)}}}};$.fn[k].defaults={continuous:true,offset:0,triggerOnce:false,context:i};$[m]=function(n){if(a[n]){return a[n].apply(this)}else{return a.aggregate()}};$[m].settings={resizeThrottle:200,scrollThrottle:100};e.load(function(){$[m]("refresh")})})(jQuery,"waypoint","waypoints",window);
+
+
+/* Pin Board Stuffs */
+(function($) {
+
+ setupPinBoardBlock = function(args) {
+
+ var pinBoardBlock = $('#block-' + args.blockID);
+ var pinBoard = pinBoardBlock.find('.pin-board');
+
+ if ( args.effects.hoverFocus )
+ pinBoard.addClass('pin-board-hover-focus');
+
+ if ( args.effects.infiniteScroll )
+ pinBoard.addClass('pin-board-infinite-scroll');
+
+ /* Masonry */
+ var setPinWidth = function(containerWidth, pins) {
+
+ if ( $(window).width() > 620 ) {
+ var columns = args.columns;
+ } else {
+ var columns = args.columnsSmartphone;
+ }
+
+ if ( typeof args.gutterWidth != 'undefined' ) {
+ var gutterWidth = args.gutterWidth;
+ } else if ( typeof pinBoard.data('masonry').options.gutterWidth != 'undefined' ) {
+ var gutterWidth = pinBoard.data('masonry').options.gutterWidth;
+ } else {
+ return;
+ }
+
+ var columnWidth = (containerWidth / columns) - ((gutterWidth * (columns - 1)) / columns);
+
+ if ( typeof pins == 'undefined' )
+ var pins = pinBoard.find('.pin-board-pin');
+
+ pins.css({width: columnWidth});
+
+ return columnWidth;
+
+ }
+
+ pinBoard.imagesLoaded(function() {
+
+ pinBoard.masonry({
+ itemSelector: '.pin-board-pin',
+ gutterWidth: args.gutterWidth,
+ columnWidth: setPinWidth
+ });
+
+ pinBoard.animate({opacity: 1}, 300);
+
+ });
+ /* End Masonry */
+
+
+ /* Infinite Scroll */
+ if ( pinBoard.hasClass('pin-board-infinite-scroll') ) {
+
+ var waypointArgs = {
+ handler: function(event, direction) {
+
+ if ( direction != 'down' )
+ return;
+
+ pinBoardBlock.find('.pin-board-pagination').waypoint('remove');
+
+ $('<div class="pin-board-scroll-loading"></div>')
+ .appendTo(pinBoard)
+ .html('<span>Loading...</span>')
+ .fadeIn(100);
+
+ var pinBoardPage = pinBoard.data('pin-board-page');
+ pinBoard.data('pin-board-page', parseInt(pinBoardPage) + 1);
+
+ $.ajax(HeadwayPinBoard.ajaxURL + '?action=headway_pin_board_infinite_scroll&block=' + args.blockID + '&pin-board-page=' + (parseInt(pinBoardPage) + 1),
+ {
+ continuous: false,
+ success: function(data) {
+
+ var loadedPins = $(data).find('.pin-board-pin');
+ var pagination = $(data).filter('.pin-board-pagination');
+
+ if ( !loadedPins.length ) {
+
+ pinBoard.find('.pin-board-scroll-loading').fadeOut(100, function() {
+ $(this).remove();
+ });
+
+ return;
+
+ }
+
+ loadedPins
+ .css({display: 'none', opacity: 0})
+ .appendTo(pinBoard);
+
+ setPinWidth(pinBoard.width(), $(loadedPins));
+ pinLoadSocialIframes(loadedPins);
+
+ pinBoard.imagesLoaded(function() {
+
+ pinBoard.masonry('appended', loadedPins);
+ loadedPins.show().animate({opacity: 1}, 300);
+
+ pinBoard.find('.pin-board-scroll-loading').fadeOut(100, function() {
+ $(this).remove();
+ });
+
+ var newPagination = pinBoardBlock.find('.pin-board-pagination')
+ .replaceWith(pagination);
+
+ pinBoardBlock.find('.pin-board-pagination').waypoint(waypointArgs);
+
+ });
+
+ } //end success
+ }
+ );
+
+ },
+ offset: '100%'
+ };
+
+ pinBoardBlock.find('.pin-board-pagination').waypoint(waypointArgs);
+
+ }
+ /* End Infinite Scroll */
+
+
+ /* Hover Effects */
+ if ( pinBoard.hasClass('pin-board-hover-focus') ) {
+
+ pinBoard.delegate('.pin-board-pin', 'mouseenter', function() {
+
+ $(this).siblings()
+ .removeClass('pin-board-pin-hover')
+ .addClass('pin-board-pin-blur');
+
+ $(this)
+ .removeClass('pin-board-pin-blur')
+ .addClass('pin-board-pin-hover');
+
+ });
+
+ pinBoard.bind('mouseleave', function() {
+
+ $(this).find('.pin-board-pin')
+ .removeClass('pin-board-pin-blur')
+ .removeClass('pin-board-pin-hover');
+
+ });
+
+ }
+ /* End Hover Effects */
+
+
+ /* Social */
+ pinLoadSocialIframes = function(context) {
+
+ $(context).find('.facebook-share-button, .twitter-share-button, .pin-it-button img').each(function() {
+
+ $(this).bind('load', function() {
+ $(this).animate({opacity: 1}, 300);
+ });
+
+ $(this).attr('src', $(this).data('src'));
+
+ });
+
+ return true;
+
+ }
+
+ pinLoadSocialIframes(pinBoard);
+ /* End Social */
+
+ }
+
+})(jQuery);
\ No newline at end of file
--- /dev/null
+<?php
+if ( !class_exists('HeadwayPinBoardCoreBlock') ) {
+
+ headway_register_block('HeadwayPinBoardCoreBlock', headway_url() . '/library/blocks/pin-board');
+ class HeadwayPinBoardCoreBlock extends HeadwayBlockAPI {
+
+
+ public $id = 'pin-board';
+
+ public $name = 'Pin Board';
+
+ public $options_class = 'HeadwayPinBoardCoreBlockOptions';
+
+
+ public static function init() {
+
+ add_action('wp_ajax_headway_pin_board_infinite_scroll', array(__CLASS__, 'infinite_scroll_content'));
+ add_action('wp_ajax_nopriv_headway_pin_board_infinite_scroll', array(__CLASS__, 'infinite_scroll_content'));
+
+ }
+
+
+ public static function enqueue_action($block_id, $block = false) {
+
+ if ( parent::get_setting($block, 'paginate', true) ) {
+ add_filter('redirect_canonical', array(__CLASS__, 'disable_redirect_canonical'));
+ }
+
+ /* CSS */
+ wp_enqueue_style('headway-pin-board', headway_url() . '/library/blocks/pin-board/css/pin-board.css');
+
+ /* JS */
+ wp_enqueue_script('headway-pin-board', headway_url() . '/library/blocks/pin-board/js/pin-board.js', array('jquery'));
+
+ /* Variables */
+ wp_localize_script('headway-pin-board', 'HeadwayPinBoard', array(
+ 'ajaxURL' => admin_url('admin-ajax.php'),
+ 'isArchive' => is_archive(),
+ 'isSearch' => is_search()
+ ));
+
+ }
+
+
+ public static function disable_redirect_canonical($redirect_url) {
+
+ return false;
+
+ }
+
+
+ public static function dynamic_js($block_id, $block = false) {
+
+ if ( !$block )
+ $block = HeadwayBlocksData::get_block($block_id);
+
+ $infinite_scroll = intval(parent::get_setting($block, 'infinite-scroll', true));
+
+ $js = "
+ jQuery(document).ready(function() {
+ setupPinBoardBlock({
+ blockID: '" . $block_id . "',
+ effects: {
+ hoverFocus: " . (parent::get_setting($block, 'hover-focus', false) ? 'true' : 'false') . ",
+ infiniteScroll: ( !!HeadwayPinBoard.isArchive || !!HeadwayPinBoard.isSearch ) ? 0 : " . $infinite_scroll . "
+ },
+ columns: " . parent::get_setting($block, 'columns', 3) . ",
+ columnsSmartphone: " . parent::get_setting($block, 'columns-smartphone', 2) . ",
+ gutterWidth: " . parent::get_setting($block, 'gutter-width', 15) . "
+ });
+ });
+ ";
+
+ return $js;
+
+ }
+
+
+ public static function dynamic_css($block_id) {
+
+ return '#block-' . $block_id . ' .pin-board-pin { margin-bottom: ' . parent::get_setting($block_id, 'pin-bottom-margin', 15) . 'px; }';
+
+ }
+
+
+ /**
+ * Anything in here will be displayed when the block is being displayed.
+ **/
+ public function content($block) {
+
+ global $wp_query;
+
+ $columns = parent::get_setting($block, 'columns', 3);
+ $approx_pin_width = (HeadwayBlocksData::get_block_width($block) / $columns);
+
+ /* Element Visibility */
+ $show_images = parent::get_setting($block, 'show-images', true);
+ $show_titles = parent::get_setting($block, 'show-titles', true);
+
+ /* Meta */
+ $show_author = parent::get_setting($block, 'show-author', false);
+ $show_categories = parent::get_setting($block, 'show-category', false);
+ $show_datetime = parent::get_setting($block, 'show-datetime', false);
+ $datetime_verb = parent::get_setting($block, 'datetime-verb', 'Posted');
+ $relative_times = parent::get_setting($block, 'relative-times', true);
+
+ /* Content */
+ $show_continue = parent::get_setting($block, 'show-continue', false);
+ $content_to_show = parent::get_setting($block, 'content-to-show', 'excerpt');
+ $show_text_when_no_image = parent::get_setting($block, 'show-text-if-no-image', false);
+ $titles_position = parent::get_setting($block, 'titles-position', 'below');
+ $titles_link_to_post = parent::get_setting($block, 'titles-link-to-post', true);
+
+ /* Images */
+ $crop_images_vertically = parent::get_setting($block, 'crop-vertically', false);
+ $image_click_action = parent::get_setting($block, 'image-click-action', 'post');
+
+ if ( $image_click_action == 'popup' ) {
+ add_thickbox();
+ }
+
+ /* Social Stuff */
+ /* Pinterest */
+ $show_pinterest_button = parent::get_setting($block, 'show-pinterest-button', false);
+
+ /* Twitter */
+ $show_twitter_button = parent::get_setting($block, 'show-twitter-button', false);
+
+ $twitter_username = parent::get_setting($block, 'twitter-username', null);
+ $twitter_hashtag = parent::get_setting($block, 'twitter-hashtag', null);
+
+ /* Facebook */
+ $show_facebook_button = parent::get_setting($block, 'show-facebook-button', false);
+ $facebook_button_verb = parent::get_setting($block, 'facebook-button-verb', 'like');
+ /* End Social Stuff */
+
+ $infinite_scroll = (is_archive() || is_search()) ? 0 : intval(parent::get_setting($block, 'infinite-scroll', true));
+
+ /* Setup Query */
+ // If it's an archive or search page, we need to use its query as the base and extend where possible
+ if (is_archive() || is_search()) {
+ $query_args = $wp_query->query_vars;
+ } else {
+ $query_args = array();
+ }
+
+ /* Pagination */
+ $paged_var = get_query_var('paged') ? get_query_var('paged') : get_query_var('page');
+
+ if ( (parent::get_setting($block, 'paginate', true) || $infinite_scroll) && (headway_get('pin-board-page') || $paged_var) )
+ $query_args['paged'] = headway_get('pin-board-page') ? headway_get('pin-board-page') : $paged_var;
+
+ /* Pin limit */
+ $query_args['posts_per_page'] = parent::get_setting($block, 'pins-per-page', 10);
+
+ /* Status */
+ $query_args['post_status'] = 'publish';
+
+ /* Order */
+ $query_args['orderby'] = parent::get_setting($block, 'order-by', 'date');
+ $query_args['order'] = parent::get_setting($block, 'order', 'DESC');
+
+ /* Custom query overrides */
+ if ( parent::get_setting($block, 'mode', 'default') == 'custom' ) {
+
+ /* Post type */
+ if ( parent::get_setting( $block, 'post-type' ) )
+ $query_args['post_type'] = parent::get_setting( $block, 'post-type' );
+
+
+ /* Taxonomies */
+ $terms_list = parent::get_setting($block, 'categories', false);
+
+ if ( $terms_list ) {
+
+ $query_args['tax_query'] = array(
+ array(
+ 'taxonomy' => parent::get_setting( $block, 'taxonomies', 'category' ),
+ 'field' => 'slug',
+ 'terms' => parent::get_setting( $block, 'categories', 'category' ),
+ 'operator' => parent::get_setting( $block, 'categories-mode', 'include' ) == 'exclude' ? 'NOT IN' : 'IN'
+ ),
+ );
+
+ }
+
+ /* Author Filter */
+ if ( is_array(parent::get_setting($block, 'author')) )
+ $query_args['author'] = trim(implode(',', parent::get_setting($block, 'author')), ', ');
+
+ /* Offset */
+ if ( parent::get_setting( $block, 'offset' ) !== null ) {
+
+ if ( !empty($query_args['paged']) ) {
+ $query_args['offset'] = parent::get_setting( $block, 'offset' ) + ( ( $query_args['paged'] - 1 ) * parent::get_setting( $block, 'pins-per-page', 10 ) );
+ } else {
+ $query_args['offset'] = parent::get_setting( $block, 'offset' );
+ }
+
+ }
+
+ }
+
+ /* Query! */
+ $original_wp_query = $wp_query;
+ $wp_query = new WP_Query($query_args);
+ /* End Query Setup */
+
+ echo '<div class="pin-board" data-pin-board-page="' . headway_get('paged', $query_args, 1) . '">';
+
+ while ( $wp_query->have_posts() ) {
+
+ $wp_query->the_post();
+
+ /* If only images are being shown and there's no thumbnail, then don't show the pin. */
+ if ( !($show_images && has_post_thumbnail()) && !$content_to_show && !$show_titles && !$show_text_when_no_image )
+ continue;
+
+ echo '<div class="pin-board-pin ' . implode(' ', get_post_class()) . '">';
+
+ /* Titles above */
+ if ( $show_titles && $titles_position == 'above') {
+
+ echo '<h3 class="entry-title">';
+ if ($titles_link_to_post) {
+ echo '<a href="' . get_permalink() . '">' . get_the_title() . '</a>';
+ } else {
+ echo get_the_title();
+ }
+ echo '</h3>';
+
+ }
+ /* End Titles below */
+
+ /* Thumbnail */
+ if ( has_post_thumbnail() && $show_images ) {
+
+ $thumbnail_id = get_post_thumbnail_id();
+
+ $thumbnail_width = $approx_pin_width + 30; /* Add a 30px buffer to insure that image will be large enough */
+
+ //$crop_vertically
+ if ( $crop_images_vertically ) {
+
+ $thumbnail_height = round($approx_pin_width * 0.75);
+
+ $thumbnail_object = wp_get_attachment_image_src($thumbnail_id, 'full');
+ $thumbnail_url = headway_resize_image($thumbnail_object[0], $thumbnail_width, $thumbnail_height);
+ $full_image_url = $thumbnail_object[0];
+
+ } else {
+
+ $thumbnail_object = wp_get_attachment_image_src($thumbnail_id, 'full');
+ $thumbnail_url = headway_resize_image($thumbnail_object[0], $thumbnail_width);
+ $full_image_url = $thumbnail_object[0];
+
+ }
+
+ do_action('headway_before_pin_thumbnail');
+
+ echo '<div class="pin-board-pin-thumbnail">';
+
+ if ( $image_click_action == 'post' ) {
+
+ echo '<a href="' . get_permalink() . '" class="post-thumbnail" title="' . get_the_title() . '">';
+ echo '<img src="' . esc_url($thumbnail_url) . '" alt="' . get_the_title() . '" />';
+ echo '</a><!-- .post-thumbnail -->';
+
+ } elseif ($image_click_action == 'popup') {
+
+ echo '<a href="' . esc_url($full_image_url) . '" class="thickbox post-thumbnail" rel="pinboard-'.$block['id'].'" title="' . get_the_title() . '">';
+ echo '<img src="' . esc_url($thumbnail_url) . '" alt="' . get_the_title() . '" />';
+ echo '</a><!-- .post-thumbnail -->';
+
+ } else {
+
+ echo '<a class="post-thumbnail"><img src="' . esc_url($thumbnail_url) . '" alt="' . get_the_title() . '" /></a>';
+
+ }
+ if ( $show_pinterest_button || $show_twitter_button || $show_facebook_button ) {
+
+ echo '<div class="pin-board-pin-thumbnail-social">';
+
+ if ( $show_facebook_button )
+ self::facebook_button(get_permalink(), $facebook_button_verb);
+
+ if ( $show_twitter_button )
+ self::twitter_button(get_permalink(), get_the_title(), $twitter_username, $twitter_hashtag);
+
+ if ( $show_pinterest_button ) {
+
+ $full_size_image = wp_get_attachment_image_src($thumbnail_id, 'full');
+ $full_size_image_url = $full_size_image[0];
+
+ self::pinterest_button(get_permalink(), $full_size_image_url);
+
+ }
+
+ echo '</div><!-- .pin-board-pin-thumbnail-social -->';
+
+ }
+
+ echo '</div><!-- .pin-board-pin-thumbnail -->';
+
+ do_action('headway_after_pin_thumbnail');
+
+ }
+ /* End Thumbnail */
+
+ echo '<div class="below-thumb">';
+
+ /* Titles below */
+ if ( $show_titles && $titles_position == 'below') {
+
+ echo '<h3 class="entry-title">';
+ if ($titles_link_to_post) {
+ echo '<a href="' . get_permalink() . '">' . get_the_title() . '</a>';
+ } else {
+ echo get_the_title();
+ }
+ echo '</h3>';
+
+ }
+ /* End Titles below */
+
+ /* Meta */
+ if ( $show_author || $show_datetime || $show_categories ) {
+
+ global $authordata;
+
+ do_action('headway_before_pin_meta');
+
+ echo '<div class="entry-meta">';
+
+ if ( $show_datetime ) {
+ echo '<span class="entry-date published" title="' . get_the_time('c') . '">' . ($datetime_verb ? $datetime_verb . ' ' : '') . self::relative_time($relative_times) . '</span> ';
+ }
+
+ if ( $show_author ) {
+ echo '<em class="author-by">by</em> <a class="author-link fn nickname url" href="' . get_author_posts_url($authordata->ID) . '" title="View all entries by ' . $authordata->display_name . '">' . $authordata->display_name . '</a>';
+ }
+
+ if ( $show_categories ) {
+ echo '<div class="entry-categories">' . get_the_category_list(', ') . '</div>';
+ }
+
+ echo '</div><!-- .entry-meta -->';
+
+ do_action('headway_after_pin_meta');
+
+ }
+ /* End Meta */
+
+ /* Excerpts/Content */
+ do_action('headway_before_pin_content');
+
+ if ( ($show_text_when_no_image && !has_post_thumbnail()) || ($content_to_show && !$show_text_when_no_image)) {
+
+ echo '<div class="pin-board-pin-text entry-content">';
+
+ if ($content_to_show == 'excerpt') {
+ add_filter('excerpt_more', array(__CLASS__, 'excerpt_more'));
+ the_excerpt();
+ remove_filter('excerpt_more', array(__CLASS__, 'excerpt_more'));
+ } elseif ( $content_to_show == 'content') {
+ the_content();
+ }
+
+ echo '</div><!-- .pin-board-pin-text -->';
+
+ }
+
+ do_action('headway_after_pin_content');
+
+ /* End Excerpts */
+
+
+ /* Backup social buttons if no image is present */
+ if ( (!has_post_thumbnail() || !$show_images) && ($show_twitter_button || $show_facebook_button) ) {
+
+ echo '<div class="pin-board-pin-social">';
+
+ if ( $show_twitter_button )
+ self::twitter_button(get_permalink(), get_the_title(), $twitter_username, $twitter_hashtag);
+
+ if ( $show_facebook_button )
+ self::facebook_button(get_permalink(), $facebook_button_verb);
+
+ echo '</div><!-- .pin-board-pin-social -->';
+
+ }
+ /* End backup social buttons */
+
+ echo '</div>';
+
+ echo '</div><!-- .pin-board-pin -->';
+ } // End while loop
+
+ echo '</div><!-- .pin-board -->';
+
+ if ( parent::get_setting($block, 'paginate', true) || $infinite_scroll ) {
+
+ do_action('headway_before_pin_board_pagination');
+ self::pagination($wp_query, $infinite_scroll, parent::get_setting($block, 'enumerate', false));
+ do_action('headway_after_pin_board_pagination');
+ }
+
+ $wp_query = $original_wp_query;
+
+ }
+
+
+ public static function infinite_scroll_content() {
+
+ $block = HeadwayBlocksData::get_block(headway_get('block'));
+
+ if ( is_array($block) && $block['type'] == 'pin-board' )
+ self::content($block);
+
+ die();
+
+ }
+
+
+ /**
+ * Register elements to be edited by the Headway Design Editor
+ **/
+
+ public function setup_elements() {
+
+ $this->register_block_element(array(
+ 'id' => 'pin',
+ 'name' => 'Pin',
+ 'selector' => '.pin-board-pin',
+ 'properties' => array('background', 'borders', 'padding', 'rounded-corners', 'box-shadow')
+ ));
+
+ $this->register_block_element(array(
+ 'id' => 'pin-title',
+ 'name' => 'Pin Title',
+ 'selector' => '.pin-board-pin .entry-title, .pin-board-pin .entry-title a',
+ 'properties' => array('fonts', 'background', 'borders', 'padding', 'rounded-corners', 'box-shadow', 'text-shadow'),
+ 'states' => array(
+ 'Hover' => '.pin-board-pin .entry-title a:hover',
+ )
+ ));
+
+ $this->register_block_element(array(
+ 'id' => 'pin-meta',
+ 'name' => 'Pin Meta',
+ 'selector' => '.pin-board-pin .entry-meta',
+ 'properties' => array('fonts', 'background', 'borders', 'padding', 'rounded-corners', 'box-shadow', 'text-shadow')
+ ));
+
+ $this->register_block_element(array(
+ 'parent' => 'pin-meta',
+ 'id' => 'pin-meta-categories',
+ 'name' => 'Categories',
+ 'selector' => '.pin-board-pin .entry-meta .entry-categories',
+ 'properties' => array('fonts', 'background', 'borders', 'padding', 'rounded-corners', 'box-shadow', 'text-shadow')
+ ));
+
+ $this->register_block_element(array(
+ 'parent' => 'pin-meta',
+ 'id' => 'pin-meta-categories-link',
+ 'name' => 'Categories Link',
+ 'selector' => '.pin-board-pin .entry-meta .entry-categories a',
+ 'properties' => array('fonts', 'background', 'borders', 'padding', 'rounded-corners', 'box-shadow', 'text-shadow')
+ ));
+
+ $this->register_block_element(array(
+ 'id' => 'pin-text',
+ 'name' => 'Pin Text',
+ 'selector' => '.pin-board-pin .entry-content',
+ 'properties' => array('fonts', 'background', 'borders', 'padding', 'rounded-corners', 'box-shadow', 'text-shadow')
+ ));
+
+ $this->register_block_element(array(
+ 'id' => 'pagination-button',
+ 'name' => 'Pagination Button',
+ 'selector' => '.pin-board-pagination a',
+ 'properties' => array('fonts', 'background', 'borders', 'padding', 'rounded-corners', 'box-shadow', 'text-shadow'),
+ 'states' => array(
+ 'Hover' => '.pin-board-pagination a:hover',
+ )
+ ));
+ $this->register_block_element(array(
+ 'id' => 'pagination-text',
+ 'name' => 'Pagination Current Page',
+ 'selector' => '.pin-board-pagination span.page-numbers.current',
+ 'properties' => array('fonts', 'background', 'borders', 'padding', 'rounded-corners', 'box-shadow', 'text-shadow'),
+ ));
+
+ }
+
+
+ private static function pinterest_button($url, $image_url) {
+
+ if ( !$url || !$image_url )
+ return;
+
+ echo '<a href="http://pinterest.com/pin/create/button/?url=' . rawurlencode($url) . '&media=' . rawurlencode($image_url) . '" class="pin-it-button" count-layout="horizontal"><img border="0" src="" data-src="//assets.pinterest.com/images/PinExt.png" title="Pin It" /></a>';
+
+ }
+
+
+ private static function twitter_button($url, $title, $username = '', $hashtag = '') {
+
+ if ( !$url )
+ return;
+
+ echo '<iframe allowtransparency="true" frameborder="0" scrolling="no" data-src="http://platform.twitter.com/widgets/tweet_button.1340179658.html#_=1343335678535&count=none&hashtags=' . str_replace('#', '', $hashtag) . '&id=twitter-widget-0&lang=en&original_referer=' . rawurlencode($url) . '&related=' . $username . '&size=m&text=' . rawurlencode($title) . '&url=' . rawurlencode($url) . '" class="twitter-share-button" title="Twitter Tweet Button"></iframe>';
+
+ }
+
+
+ private static function facebook_button($url, $verb = 'like') {
+
+ if ( !$url )
+ return;
+
+ echo '<iframe class="facebook-share-button facebook-' . $verb . '-button" data-src="//www.facebook.com/plugins/like.php?href=' . rawurlencode($url) . '&send=false&layout=button_count&width=90&show_faces=false&action=' . strtolower($verb) . '&colorscheme=light&font=lucida+grande&height=21" scrolling="no" frameborder="0" allowTransparency="true"></iframe>';
+
+ }
+
+
+ private static function pagination($query, $infinite_scroll = true,$enumerate) {
+ echo '<div class="pin-board-pagination">';
+ echo '<span class="nav-next">';
+ echo get_next_posts_link('← Older', $query->max_num_pages);
+ echo '</span><!-- .next -->';
+ if ($enumerate) {
+ $big = 999999999; // need an unlikely integer
+ echo paginate_links( array(
+ 'base' => str_replace( $big, '%#%', esc_url( get_pagenum_link( $big ) ) ),
+ 'format' => '?paged=%#%',
+ 'current' => max( 1, get_query_var('paged') ),
+ 'total' => $query->max_num_pages,
+ 'prev_next' => false
+ ) );
+ }
+ echo '<span class="nav-previous">';
+ echo self::previous_posts_link('Newer →');
+ echo '</span><!-- .previous -->';
+ echo '</div><!-- .pin-board-pagination -->';
+ }
+
+
+ private static function previous_posts_link($label) {
+
+ global $paged;
+
+ if ( null === $label )
+ $label = __( '« Previous Page' );
+
+ if ( $paged > 1 ) {
+ $attr = apply_filters( 'previous_posts_link_attributes', '' );
+ return '<a href="' . previous_posts( false ) . "\" $attr>". preg_replace( '/&([^#])(?![a-z]{1,8};)/i', '&$1', $label ) .'</a>';
+ }
+
+ }
+
+
+ private static function relative_time($relative = true) {
+
+ if ( $relative ) {
+
+ $post_date = get_the_time('U');
+ $delta = time() - $post_date;
+
+ if ( $delta < 60 ) {
+ return 'less than a minute ago';
+
+ } elseif ($delta >= 60 && $delta <= 120){
+ return 'about a minute ago';
+
+ } elseif ($delta >= 120 && $delta <= (60*60)) {
+ return strval(round(($delta/60),0)) . ' minutes ago';
+
+ } elseif ($delta >= (60*60) && $delta <= (120*60)){
+ return 'about an hour ago';
+
+ } elseif ($delta >= (120*60) && $delta <= (24*60*60)){
+ return strval(round(($delta/3600),0)) . ' hours ago';
+
+ }
+
+ }
+
+ return get_the_date('M j, Y');
+
+ }
+
+
+ public static function excerpt_more($more) {
+
+ return '...';
+
+ }
+
+
+ }
+
+
+ class HeadwayPinBoardCoreBlockOptions extends HeadwayBlockOptionsAPI {
+
+ public $taxonomy_list;
+
+ public $terms_list;
+
+ public $tabs = array(
+ 'pin-setup' => 'Pin Setup',
+ 'query-filters' => 'Query Filters',
+ 'text' => 'Text',
+ 'images' => 'Images',
+ 'effects' => 'Effects',
+ 'social' => 'Social'
+ );
+
+ // This acgtivates a callback when the block edito0r opens as callbacks in fields are not activated unti8l changed.
+ public $open_js_callback = '
+ if ( $(\'div#block-\' + blockID + \'-tab\').find(\'select#input-\' + blockID + \'-mode\').val() != \'custom\' )
+ $(\'div#block-\' + blockID + \'-tab li#sub-tab-query-filters\').hide();
+ ';
+
+ public $inputs = array(
+ 'pin-setup' => array(
+ 'mode' => array(
+ 'type' => 'select',
+ 'name' => 'mode',
+ 'label' => 'Mode',
+ 'tooltip' => 'If you would like to modify the default behaviour, select custom query. <br/><strong>Note:</strong>On archive pages, it\'s not advisable to use a custom query if the block is displaying the archive results.<br/>On search pages, it may be necessary to limit results to only certain content types.',
+ 'options' => array(
+ 'default' => 'Default behaviour',
+ 'custom' => 'Custom query',
+ ),
+ 'toggle' => array(
+ 'default' => array(
+ 'hide' => 'li#sub-tab-query-filters'
+ ),
+ 'custom' => array(
+ 'show' => 'li#sub-tab-query-filters'
+ )
+ )
+ ),
+ 'layout-heading' => array(
+ 'name' => 'layout-heading',
+ 'type' => 'heading',
+ 'label' => 'Layout',
+ ),
+ 'columns' => array(
+ 'type' => 'slider',
+ 'name' => 'columns',
+ 'label' => 'Columns',
+ 'slider-min' => 1,
+ 'slider-max' => 7,
+ 'slider-interval' => 1,
+ 'default' => 3,
+ 'tooltip' => 'Set how many pins to display horizontally'
+ ),
+
+ 'columns-smartphone' => array(
+ 'type' => 'slider',
+ 'name' => 'columns-smartphone',
+ 'label' => 'Columns (iPhone/Smartphone)',
+ 'slider-min' => 1,
+ 'slider-max' => 7,
+ 'slider-interval' => 1,
+ 'default' => 2,
+ 'tooltip' => 'Set how many pins to display horizontally for iPhones and smartphones. <strong>Recommended setting: 1 or 2</strong>'
+ ),
+
+ 'gutter-width' => array(
+ 'type' => 'slider',
+ 'name' => 'gutter-width',
+ 'label' => 'Gutter Width',
+ 'slider-min' => 0,
+ 'slider-max' => 100,
+ 'slider-interval' => 1,
+ 'default' => 15,
+ 'unit' => 'px',
+ 'tooltip' => 'The amount in space between pins horizontally.'
+ ),
+
+ 'pin-bottom-margin' => array(
+ 'type' => 'slider',
+ 'name' => 'pin-bottom-margin',
+ 'label' => 'Pin Bottom Margin',
+ 'slider-min' => 0,
+ 'slider-max' => 50,
+ 'slider-interval' => 1,
+ 'default' => 15,
+ 'unit' => 'px',
+ 'tooltip' => 'The amount of space on the bottom of each pin.'
+ ),
+ 'pagination-heading' => array(
+ 'name' => 'pagination-heading',
+ 'type' => 'heading',
+ 'label' => 'Pagination',
+ ),
+ 'pins-per-page' => array(
+ 'type' => 'integer',
+ 'name' => 'pins-per-page',
+ 'label' => 'Pins Per Page',
+ 'default' => 10,
+ 'tooltip' => 'Determines how many pins to load at one time before loading more via pagination or <em>infinite scrolling</em>.'
+ ),
+
+ 'paginate' => array(
+ 'type' => 'checkbox',
+ 'name' => 'paginate',
+ 'label' => 'Paginate Pins',
+ 'default' => true,
+ 'tooltip' => 'Enabling pagination adds buttons to the bottom of the pin board to go to the next/previous page. <strong>Note:</strong> If infinite scrolling is enabled, pagination will be hidden.'
+ ),
+ 'enumerate' => array(
+ 'type' => 'checkbox',
+ 'name' => 'enumerate',
+ 'label' => 'Enumerate pagination',
+ 'default' => false,
+ 'tooltip' => 'If pagination is displayed, enabling this will also show page number navigation.'
+ ),
+ 'order-heading' => array(
+ 'name' => 'order-heading',
+ 'type' => 'heading',
+ 'label' => 'Order',
+ ),
+ 'order-by' => array(
+ 'type' => 'select',
+ 'name' => 'order-by',
+ 'label' => 'Order By',
+ 'tooltip' => '',
+ 'options' => array(
+ 'date' => 'Date',
+ 'title' => 'Title',
+ 'rand' => 'Random',
+ 'ID' => 'ID'
+ )
+ ),
+
+ 'order' => array(
+ 'type' => 'select',
+ 'name' => 'order',
+ 'label' => 'Order',
+ 'tooltip' => '',
+ 'options' => array(
+ 'desc' => 'Descending',
+ 'asc' => 'Ascending',
+ )
+ )
+ ),
+
+ 'query-filters' => array(
+ 'post-type' => array(
+ 'type' => 'multi-select',
+ 'name' => 'post-type',
+ 'label' => 'Post Type',
+ 'tooltip' => 'Choose a post type to display. If none are selected, it will automatically default to all.',
+ 'default' => 'any',
+ 'options' => 'get_post_types()'
+ ),
+
+
+ 'taxonomies' => array(
+ 'type' => 'select',
+ 'name' => 'taxonomies',
+ 'label' => 'Taxonomy',
+ 'default' => 'category',
+ 'options' => array('none' => 'No taxonomies'),
+ 'tooltip' => 'Select the taxonomy to filter pins on .',
+ 'callback' => 'reloadBlockOptions()'
+ ),
+
+ // For simplicity with migrating from categories to all taxonomies, these next two have kept the same names. In the future a function could be written to port them to a correctly named variable
+ 'categories' => array(
+ 'type' => 'multi-select',
+ 'name' => 'categories',
+ 'label' => 'Terms',
+ 'default' => '',
+ 'options' => array('none' => 'No terms'),
+ 'tooltip' => 'Filter the pins that are shown by the selected taxonomy\'s terms.'
+ ),
+
+ 'categories-mode' => array(
+ 'type' => 'select',
+ 'name' => 'categories-mode',
+ 'label' => 'Terms Mode',
+ 'tooltip' => '',
+ 'options' => array(
+ 'include' => 'Include',
+ 'exclude' => 'Exclude'
+ ),
+ 'tooltip' => 'If this is set to <em>include</em>, then only the pins that match the terms filter will be shown. If set to <em>exclude</em>, all pins that match the selected terms will not be shown.'
+ ),
+
+ 'author' => array(
+ 'type' => 'multi-select',
+ 'name' => 'author',
+ 'label' => 'Author',
+ 'tooltip' => '',
+ 'options' => 'get_authors()'
+ ),
+
+ 'offset' => array(
+ 'type' => 'integer',
+ 'name' => 'offset',
+ 'label' => 'Offset',
+ 'tooltip' => 'The offset is the number of entries or posts you would like to skip. If the offset is 1, then the first post will be skipped.',
+ 'default' => 0
+ )
+ ),
+
+ 'text' => array(
+ 'show-titles' => array(
+ 'type' => 'checkbox',
+ 'name' => 'show-titles',
+ 'label' => 'Show Titles',
+ 'default' => true
+ ),
+
+ 'titles-position' => array(
+ 'type' => 'select',
+ 'name' => 'titles-position',
+ 'label' => 'Titles position',
+ 'default' => 'below',
+ 'options' => array('above' => 'Above','below' => 'Below')
+ ),
+
+ 'titles-link-to-post' => array(
+ 'type' => 'checkbox',
+ 'name' => 'titles-link-to-post',
+ 'label' => 'Titles link to post',
+ 'default' => true,
+ 'tooltip' => 'Open the post when the user clicks on the title'
+ ),
+
+ 'content-to-show' => array(
+ 'type' => 'select',
+ 'name' => 'content-to-show',
+ 'label' => 'Content To Show',
+ 'options' => array(
+ '' => '– Do Not Show Content –',
+ 'excerpt' => 'Excerpts',
+ 'content' => 'Full Content'
+ ),
+ 'default' => 'excerpt',
+ 'tooltip' => 'The content is the written text or HTML for the entry. This is edited in the WordPress admin panel.'
+ ),
+
+ 'show-text-if-no-image' => array(
+ 'type' => 'checkbox',
+ 'name' => 'show-text-if-no-image',
+ 'label' => 'Only show content when no featured image',
+ 'default' => false,
+ 'tooltip' => 'If enabled, regardless of the content chosen in <em>Content to Show</em> will only show content for pins with no featured image.'
+ ),
+
+ 'show-author' => array(
+ 'type' => 'checkbox',
+ 'name' => 'show-author',
+ 'label' => 'Meta: Show Author "byline"',
+ 'default' => false,
+ 'tooltip' => '<strong>Example:</strong> <em>by</em> Author Name'
+ ),
+
+ 'show-category' => array(
+ 'type' => 'checkbox',
+ 'name' => 'show-category',
+ 'label' => 'Meta: Show Categories',
+ 'default' => false
+ ),
+
+ 'show-datetime' => array(
+ 'type' => 'checkbox',
+ 'name' => 'show-datetime',
+ 'label' => 'Meta: Show Date/Time',
+ 'default' => false
+ ),
+
+ 'datetime-verb' => array(
+ 'type' => 'text',
+ 'name' => 'datetime-verb',
+ 'label' => 'Meta: Posted Verb',
+ 'default' => 'Posted',
+ 'tooltip' => 'The posted verb will be placed before the time. For instance, you may want to use "Listed" for real estate rather than "Posted"'
+ ),
+
+ 'relative-times' => array(
+ 'type' => 'checkbox',
+ 'name' => 'relative-times',
+ 'label' => 'Meta: Use Relative Times',
+ 'default' => true,
+ 'tooltip' => '<strong>Example:</strong> 8 hours ago'
+ )
+ ),
+
+ 'images' => array(
+ 'show-images' => array(
+ 'type' => 'checkbox',
+ 'name' => 'show-images',
+ 'label' => 'Show Images',
+ 'default' => true,
+ ),
+ 'images-click-action' => array(
+ 'type' => 'select',
+ 'name' => 'image-click-action',
+ 'label' => 'Image click action',
+ 'default' => 'link',
+ 'tooltip' => 'Choose the action when user clicks on an image.',
+ 'options' => array(
+ 'post' => 'Open post',
+ 'popup' => 'Popup original image',
+ 'none' => 'Do nothing'
+ )
+ ),
+
+ 'crop-vertically' => array(
+ 'type' => 'checkbox',
+ 'name' => 'crop-vertically',
+ 'label' => 'Crop Vertically',
+ 'default' => false,
+ 'tooltip' => 'Trim all images to have the same height. The trimmed/cropped height is roughly 75% of the width.'
+ )
+ ),
+
+ 'effects' => array(
+ 'infinite-scroll' => array(
+ 'type' => 'checkbox',
+ 'name' => 'infinite-scroll',
+ 'label' => 'Infinite Scrolling',
+ 'default' => true,
+ 'tooltip' => 'Infinite scrolling allows your visitors to view all of your pins without the need for them to click a button to continue to the next page. The pins will be loaded automatically simply by scrolling. Note: On archives and search result pages, infinite scrolling is disabled as it will not work correctly.'
+ ),
+
+ 'hover-focus' => array(
+ 'type' => 'checkbox',
+ 'name' => 'hover-focus',
+ 'label' => 'Hover Focus',
+ 'default' => false,
+ 'tooltip' => 'If enabled, the hovered pin will be focused while all others will be faded out.'
+ ),
+ ),
+
+ 'social' => array(
+ 'show-pinterest-button' => array(
+ 'type' => 'checkbox',
+ 'name' => 'show-pinterest-button',
+ 'label' => 'Pinterest: Show "Pin It" Button',
+ 'default' => false,
+ 'tooltip' => 'Show a Pinterest "Pin It" button inside of the images.',
+ ),
+
+ 'show-twitter-button' => array(
+ 'type' => 'checkbox',
+ 'name' => 'show-twitter-button',
+ 'label' => 'Twitter: Show Tweet Button',
+ 'default' => false,
+ 'tooltip' => 'Show a tweet button either inside of the post image or by the title.',
+ ),
+
+ 'twitter-username' => array(
+ 'type' => 'text',
+ 'name' => 'twitter-username',
+ 'label' => 'Twitter: Your Username'
+ ),
+
+ 'twitter-hashtag' => array(
+ 'type' => 'text',
+ 'name' => 'twitter-hashtag',
+ 'label' => 'Twitter: Hashtag to put in tweets (Optional)'
+ ),
+
+ 'show-facebook-button' => array(
+ 'type' => 'checkbox',
+ 'name' => 'show-facebook-button',
+ 'label' => 'Facebook: Show Like/Share Button',
+ 'default' => false,
+ 'tooltip' => 'Show a Facebook share/like button either inside of the post image or by the title.',
+ ),
+
+ 'facebook-button-verb' => array(
+ 'type' => 'select',
+ 'label' => 'Facebook: Button Verb',
+ 'name' => 'facebook-button-verb',
+ 'options' => array(
+ 'like' => 'Like',
+ 'recommend' => 'Recommend'
+ ),
+ 'default' => 'like'
+ )
+ )
+ );
+
+
+ public function modify_arguments($args = false) {
+ $block = $args['block'];
+
+ $this->taxonomy_list = self::get_taxonomy_list();
+ $this->inputs['query-filters']['taxonomies']['options'] = $this->taxonomy_list;
+
+ $tax_slug = HeadwayBlockAPI::get_setting($block, 'taxonomies', 'category');
+ $this->terms_list = self::get_tax_terms($tax_slug);
+
+ $this->inputs['query-filters']['categories'] = array(
+ 'type' => 'multi-select',
+ 'name' => 'categories',
+ 'label' => 'Terms',
+ 'default' => '',
+ 'options' => $this->terms_list[$tax_slug],
+ 'tooltip' => 'Filter the pins that are shown by the selected taxonomy\'s terms.'
+ );
+
+ $callback = '
+ if ( !$("body").hasClass("visual-editor-mode-grid") ) {
+ window.frames[\'content\'].setupPinBoardBlock({
+ blockID: getBlockID(block),
+ effects: {
+ hoverFocus: input.parents(".sub-tabs-content-container").find("#input-hover-focus input[type=\'hidden\']").val().toBool(),
+ infiniteScroll: input.parents(".sub-tabs-content-container").find("#input-infinite-scroll input[type=\'hidden\']").val().toBool(),
+ },
+ columns: parseInt(input.parents(".sub-tabs-content-container").find("#input-columns input[type=\'hidden\']").val()),
+ columnsSmartphone: parseInt(input.parents(".sub-tabs-content-container").find("#input-columns-smartphone input[type=\'hidden\']").val()),
+ gutterWidth: parseInt(input.parents(".sub-tabs-content-container").find("#input-gutter-width input[type=\'hidden\']").val())
+ });
+ }
+ ';
+
+ /* Add the callback to all options */
+ foreach ( $this->inputs as $tab_id => $inputs )
+ foreach ( $this->inputs[$tab_id] as $input_id => $input_options )
+ if ( !headway_get('callback', $this->inputs[$tab_id][$input_id]) )
+ $this->inputs[$tab_id][$input_id]['callback'] = $callback;
+
+ }
+
+
+ public static function get_categories() {
+
+ $category_options = array();
+
+ $categories_select_query = get_categories();
+
+ foreach ($categories_select_query as $category)
+ $category_options[$category->term_id] = $category->name;
+
+ return $category_options;
+
+ }
+
+
+ public static function get_authors() {
+
+ $author_options = array();
+
+ $authors = get_users(array(
+ 'orderby' => 'post_count',
+ 'order' => 'desc',
+ 'who' => 'authors'
+ ));
+
+ foreach ( $authors as $author )
+ $author_options[$author->ID] = $author->display_name;
+
+ return $author_options;
+
+ }
+
+
+ public static function get_post_types() {
+
+ $post_type_options = array();
+
+ $post_types = get_post_types(false, 'objects');
+
+ foreach($post_types as $post_type_id => $post_type){
+
+ //Make sure the post type is not an excluded post type.
+ if(in_array($post_type_id, array('revision', 'nav_menu_item')))
+ continue;
+
+ $post_type_options[$post_type_id] = $post_type->labels->name;
+
+ }
+
+ return $post_type_options;
+
+ }
+
+ public static function get_taxonomy_list() {
+
+ $custom_tax = get_taxonomies();
+ $exclude_list = array('nav_menu','link_category','post_format');
+ $tax_array = array();
+
+ foreach ($custom_tax as $tax) {
+ if (!in_array($tax, $exclude_list)) {
+ $tax_array[$tax] = ucwords(str_replace(array('_','-'), ' ', $tax));
+ }
+ }
+
+ return $tax_array;
+
+ }
+
+ public static function get_tax_terms($taxonomies, $keys_only = false) {
+
+ if ( !is_array($taxonomies) )
+ $taxonomies = array($taxonomies => $taxonomies);
+
+ $terms = array();
+
+ foreach ( $taxonomies as $key => $tax_name ) {
+
+ $term_list = get_terms($key, 'hide_empty=0');
+
+ foreach ($term_list as $term) {
+
+ if ( $keys_only ) {
+ $terms[] = $term->slug;
+ } else {
+ $terms[$key][$term->slug] = $term->name;
+ }
+
+ }
+
+ if ( !$keys_only && count($terms[$key]) == 0 ) {
+ $terms[$key]['none'] = 'No terms found for this taxonomy';
+ }
+
+ }
+
+ return $terms;
+
+ }
+
+ }
+
+
+ /**
+ * Prevent 404ing from breaking Infinite Scrolling
+ **/
+ add_action('status_header', 'hw_pin_board_block_prevent_404');
+ function hw_pin_board_block_prevent_404($status) {
+
+ if ( strpos($status, '404') && get_query_var('paged') && headway_get('pb') )
+ return 'HTTP/1.1 200 OK';
+
+ return $status;
+
+ }
+
+
+ /**
+ * Prevent WordPress redirect from messing up pin board infinite scroll
+ */
+ add_filter('redirect_canonical', 'hw_pin_board_block_redirect');
+ function hw_pin_board_block_redirect($redirect_url) {
+
+ if ( headway_get('pb') )
+ return false;
+
+ return $redirect_url;
+
+ }
+
+}
--- /dev/null
+<?php
+headway_register_block('HeadwaySearchBlock', headway_url() . '/library/blocks/search');
+
+class HeadwaySearchBlock extends HeadwayBlockAPI {
+
+
+ public $id = 'search';
+
+ public $name = 'Search';
+
+ public $fixed_height = false;
+
+ public $description = 'This will output the default search form';
+
+ public $options_class = 'HeadwaySearchBlockOptions';
+
+
+ function setup_elements() {
+
+ $this->register_block_element(array(
+ 'id' => 'search_wrap',
+ 'name' => 'Search Form',
+ 'selector' => '.search-form'
+ ));
+
+ $this->register_block_element(array(
+ 'id' => 'search_input',
+ 'name' => 'Search Input',
+ 'selector' => '.search-form input.field'
+ ));
+
+ $this->register_block_element(array(
+ 'id' => 'search_button',
+ 'name' => 'Search Button',
+ 'selector' => '.search-form .submit'
+ ));
+
+ }
+
+
+ function content($block) {
+
+ $search_query = get_search_query();
+
+ $button_hidden_class = parent::get_setting( $block, 'show-button', true ) ? 'search-button-visible' : 'search-button-hidden';
+
+ echo '<form method="get" id="searchform-' . $block['id'] . '" class="search-form ' . $button_hidden_class . '" action="' . esc_url(home_url('/')) . '">' . "\n";
+
+ if ( parent::get_setting( $block, 'show-button', true ) ) {
+ echo '<input type="submit" class="submit" name="submit" id="searchsubmit-' . $block['id'] . '" value="' . esc_attr( parent::get_setting( $block, 'search-button', 'Search' ) ) . '" />' . "\n";
+ }
+
+ printf('<div><input id="search-' . $block['id'] . '" class="field" type="text" name="s" value="%1$s" placeholder="%2$s" /></div>' . "\n",
+ $search_query ? esc_attr($search_query) : '',
+ esc_attr(parent::get_setting($block, 'search-placeholder', 'Enter search term and hit enter.'))
+ );
+
+ echo '</form>' . "\n";
+
+ }
+
+}
+
+
+class HeadwaySearchBlockOptions extends HeadwayBlockOptionsAPI {
+
+ public $tabs = array(
+ 'general' => 'General'
+ );
+
+ public $inputs = array(
+ 'general' => array(
+ 'search-placeholder' => array(
+ 'name' => 'search-placeholder',
+ 'label' => 'Input Text Placeholder',
+ 'type' => 'text',
+ 'tooltip' => 'The placeholder is text that will be shown in the Search input and immediately removed after you start typing in the search input.',
+ 'default' => 'Enter search term and hit enter.'
+ ),
+
+ 'show-button' => array(
+ 'name' => 'show-button',
+ 'label' => 'Show Search Button',
+ 'type' => 'checkbox',
+ 'default' => true,
+ 'toggle' => array(
+ 'true' => array(
+ 'show' => '#input-search-button'
+ ),
+ 'false' => array(
+ 'hide' => '#input-search-button'
+ )
+ )
+ ),
+
+ 'search-button' => array(
+ 'name' => 'search-button',
+ 'label' => 'Button Text',
+ 'type' => 'text',
+ 'tooltip' => 'This will update the Search button text.',
+ 'default' => 'Search'
+ )
+ )
+ );
+
+}
\ No newline at end of file
--- /dev/null
+<?php
+if ( isset($GLOBALS['SlideDeckPlugin']) && is_object($GLOBALS['SlideDeckPlugin']) )
+ headway_register_block('HeadwaySlideDeckBlock', headway_url() . '/library/blocks/slidedeck');
+
+class HeadwaySlideDeckBlock extends HeadwayBlockAPI {
+
+
+ public $id = 'slidedeck';
+
+ public $name = 'SlideDeck 2';
+
+ public $options_class = 'HeadwaySlideDeckBlockOptions';
+
+ public $description = 'Conveniently add SlideDecks anywhere on any layout.'; /* This will be shown in the block type selector */
+
+
+ /**
+ * Anything in here will be displayed when the block is being displayed.
+ **/
+ function content($block) {
+
+ global $SlideDeckPlugin;
+
+ /* Make sure SlideDeck is activated and working */
+ if ( !is_object($SlideDeckPlugin) ) {
+
+ echo '<div class="alert alert-red"><p>SlideDeck must be installed and activated in order for the SlideDeck block to work properly.</p></div>';
+ return;
+
+ }
+
+ /* Get the chosen SlideDeck ID */
+ $slidedeck_id = parent::get_setting($block, 'slidedeck-id', null);
+
+ /* Make sure that there's a selected SlideDeck */
+ if ( empty($slidedeck_id) ) {
+
+ echo '<div class="alert alert-red"><p>Please choose a SlideDeck to display.</p></div>';
+ return;
+
+ }
+
+ $slidedeck_query = $SlideDeckPlugin->SlideDeck->get($slidedeck_id);
+
+ if ( empty($slidedeck_query) ) {
+
+ echo '<div class="alert alert-red"><p>The SlideDeck you previously chose must\'ve been deleted or moved elsewhere. Please select another SlideDeck to display.</p></div>';
+ return;
+
+ }
+
+ /* Setup arguments */
+ $args = array(
+ 'id' => $slidedeck_id,
+ 'width' => null,
+ 'height' => null
+ );
+
+ if ( parent::get_setting($block, 'use-block-size', true) ) {
+
+ $args['width'] = HeadwayBlocksData::get_block_width($block);
+ $args['height'] = HeadwayBlocksData::get_block_height($block);
+ $args['proportional'] = false;
+
+ }
+
+
+ if ( HeadwayRoute::is_visual_editor_iframe() )
+ $args['iframe'] = true;
+
+ if ( !HeadwayRoute::is_visual_editor_iframe() && HeadwayResponsiveGrid::is_active() )
+ $args['ress'] = true;
+
+ /* Work around for iframe dimensions */
+ $GLOBALS['slidedeck-width'] = $args['width'];
+ $GLOBALS['slidedeck-height'] = $args['height'];
+
+ add_filter('slidedeck_dimensions', array(__CLASS__, 'modify_slidedeck_iframe_size_for_ajax'), 10, 5);
+ /* End work around for iframe dimensions */
+
+ /* Show the SlideDeck! */
+ echo $SlideDeckPlugin->shortcode($args);
+
+ /* Remove any filters if necessary */
+ remove_filter('slidedeck_dimensions', array(__CLASS__, 'modify_slidedeck_iframe_size_for_ajax'));
+
+ if ( isset($GLOBALS['slidedeck-width']) )
+ unset($GLOBALS['slidedeck-width']);
+
+ if ( isset($GLOBALS['slidedeck-height']) )
+ unset($GLOBALS['slidedeck-height']);
+ /* End removing filters */
+
+ }
+
+
+ public static function modify_slidedeck_iframe_size_for_ajax(&$width, &$height, &$outer_width, &$outer_height, &$slidedeck) {
+
+ $width = $GLOBALS['slidedeck-width'];
+ $height = $GLOBALS['slidedeck-height'];
+
+ $outer_width = $GLOBALS['slidedeck-width'];
+ $outer_height = $GLOBALS['slidedeck-height'];
+
+ return true;
+
+ }
+
+
+}
+
+
+class HeadwaySlideDeckBlockOptions extends HeadwayBlockOptionsAPI {
+
+
+ public $tabs = array(
+ 'settings-tab' => 'Settings'
+ );
+
+ public $inputs = array(
+ 'settings-tab' => array(
+ 'slidedeck-dashboard-link' => array(
+ 'type' => 'notice',
+ 'name' => 'slidedeck-dashboard-link',
+ 'notice' => ''
+ ),
+ 'slidedeck-id' => array(
+ 'type' => 'select',
+ 'name' => 'slidedeck-id', //This will be the setting you retrieve from the database.
+ 'label' => 'Choose a SlideDeck to Display',
+ 'default' => '',
+ 'options' => 'get_slidedecks()',
+ 'tooltip' => 'Select the SlideDeck you wish to display',
+ ),
+
+ 'use-block-size' => array(
+ 'type' => 'checkbox',
+ 'name' => 'use-block-size',
+ 'label' => 'Use Block Size for SlideDeck',
+ 'default' => true,
+ 'tooltip' => 'Choose whether or not you\'d like to use the block\'s size to dictate the SlideDeck\'s size. If you choose not to, it will use the size defined in the SlideDeck\'s settings.'
+ )
+ )
+ );
+
+
+ function get_slidedecks() {
+
+ global $SlideDeckPlugin;
+
+ $slidedecks = $SlideDeckPlugin->SlideDeck->get(null, 'post_title', 'ASC', 'publish');
+
+ $options = array(
+ '' => '– Select a SlideDeck –'
+ );
+
+ foreach ( $slidedecks as $slidedeck )
+ $options[$slidedeck['id']] = $slidedeck['title'];
+
+ return $options;
+
+ }
+
+
+ function modify_arguments($args = false) {
+
+ /* Since we can't call functions when declaring a property, we must put in the admin links here that way we can use admin_url() */
+ $this->inputs['settings-tab']['slidedeck-dashboard-link']['notice'] = '
+ <strong>SlideDeck Quick Links:</strong>
+ <a href="' . admin_url('admin.php?page=' . SLIDEDECK2_BASENAME) . '" target="_blank">Add/Manage SlideDecks</a> |
+ <a href="' . admin_url('admin.php?page=' . SLIDEDECK2_BASENAME . '/lenses') . '" target="_blank">Lenses</a> |
+ <a href="' . admin_url('admin.php?page=' . SLIDEDECK2_BASENAME . '/options') . '" target="_blank">Advanced Options</a>
+ ';
+
+ }
+
+
+}
\ No newline at end of file
--- /dev/null
+/*
+ * jQuery FlexSlider v2.0
+ * http://www.woothemes.com/flexslider/
+ *
+ * Copyright 2012 WooThemes
+ * Free to use under the GPLv2 license.
+ * http://www.gnu.org/licenses/gpl-2.0.html
+ *
+ * Contributing author: Tyler Smith (@mbmufffin)
+ */
+
+
+/* Browser Resets */
+.flex-container a:active,
+.flexslider a:active,
+.flex-container a:focus,
+.flexslider a:focus {outline: none;}
+.slides,
+.flex-control-nav,
+.flex-direction-nav {margin: 0; padding: 0; list-style: none;}
+
+/* FlexSlider Necessary Styles
+*********************************/
+.flexslider {
+ margin: 0;
+ padding: 0;
+}
+.flexslider .slides > li {display: none;-webkit-backface-visibility: hidden;position:relative;} /* Hide the slides before the JS is loaded. Avoids image jumping */
+.flexslider-no-slide .slides > li {width:100%;display: block;}
+.flexslider .slides img {width: 100%; display: block;}
+.flex-pauseplay span {text-transform: capitalize;}
+
+/* Clearfix for the .slides element */
+.slides:after {content: "."; display: block; clear: both; visibility: hidden; line-height: 0; height: 0;}
+html[xmlns] .slides {display: block;}
+* html .slides {height: 1%;}
+
+/* No JavaScript Fallback */
+/* If you are not using another script, such as Modernizr, make sure you
+ * include js that eliminates this class on page load */
+.no-js .slides > li:first-child {display: block;}
+
+
+/* FlexSlider Default Theme
+*********************************/
+.flexslider {position: relative;zoom: 1;}
+.flex-viewport {max-height: 2000px; -webkit-transition: all 1s ease; -moz-transition: all 1s ease; transition: all 1s ease; -webkit-mask-image: url(data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAIAAACQd1PeAAAAGXRFWHRTb2Z0d2FyZQBBZG9iZSBJbWFnZVJlYWR5ccllPAAAAA5JREFUeNpiYGBgAAgwAAAEAAGbA+oJAAAAAElFTkSuQmCC); /* Hack to allow rounded corners on the container in WebKit */
+}
+.loading .flex-viewport {max-height: 300px;}
+.flexslider .slides {zoom: 1;}
+
+.carousel li {margin-right: 5px}
+
+
+/* Captions */
+.flex-caption {
+ width: 100%;
+ left: 0px;
+ bottom: 0px;
+ text-shadow: rgba(0, 0, 0, 0.3) 0px -1px 0px;
+}
+
+
+/* Direction Nav */
+.flex-direction-nav {*height: 0;}
+.flex-direction-nav a {width: 30px; height: 30px; display: block; top: 50%; z-index: 10; cursor: pointer; text-indent: -9999px; opacity: 0; -webkit-transition: all .3s ease;}
+.flex-direction-nav .flex-next {right: 5px; }
+.flex-direction-nav .flex-prev {left:5px;}
+.flexslider:hover .flex-next {opacity: 0.8; right: 5px;}
+.flexslider:hover .flex-prev {opacity: 0.8; left: 5px;}
+.flexslider:hover .flex-next:hover, .flexslider:hover .flex-prev:hover {opacity: 1;}
+.flex-direction-nav .flex-disabled {opacity: .3!important; filter:alpha(opacity=30); cursor: default;}
+
+/* Control Nav */
+.flex-control-nav {width: 100%;bottom: -25px;}
+.flex-control-nav li {display: inline-block; zoom: 1; *display: inline;}
+.flex-control-paging li a {display: inline-block;width: 11px; height: 11px; display: block;cursor: pointer; text-indent: -9999px; box-shadow: inset 0 0 3px rgba(0,0,0,0.3);}
+.flex-control-paging li a.flex-active { cursor: default; }
+
+.flex-control-thumbs {margin: 5px 0 0; position: static; overflow: hidden;}
+.flex-control-thumbs li {width: 25%; float: left; margin: 0;}
+.flex-control-thumbs img {width: 100%; display: block; opacity: .7; cursor: pointer;}
+.flex-control-thumbs img:hover {opacity: 1;}
+.flex-control-thumbs .flex-active {opacity: 1; cursor: default;}
+
+@media screen and (max-width: 860px) {
+ .flex-direction-nav .flex-prev {opacity: 1; left: 0;}
+ .flex-direction-nav .flex-next {opacity: 1; right: 0;}
+}
\ No newline at end of file
--- /dev/null
+/*
+ * jQuery FlexSlider v2.1
+ * Copyright 2012 WooThemes
+ * Contributing Author: Tyler Smith
+ */
+;(function(d){d.flexslider=function(i,k){var a=d(i),c=d.extend({},d.flexslider.defaults,k),e=c.namespace,p="ontouchstart"in window||window.DocumentTouch&&document instanceof DocumentTouch,t=p?"touchend":"click",l="vertical"===c.direction,m=c.reverse,h=0<c.itemWidth,r="fade"===c.animation,s=""!==c.asNavFor,f={};d.data(i,"flexslider",a);f={init:function(){a.animating=!1;a.currentSlide=c.startAt;a.animatingTo=a.currentSlide;a.atEnd=0===a.currentSlide||a.currentSlide===a.last;a.containerSelector=c.selector.substr(0,
+ c.selector.search(" "));a.slides=d(c.selector,a);a.container=d(a.containerSelector,a);a.count=a.slides.length;a.syncExists=0<d(c.sync).length;"slide"===c.animation&&(c.animation="swing");a.prop=l?"top":"marginLeft";a.args={};a.manualPause=!1;var b=a,g;if(g=!c.video)if(g=!r)if(g=c.useCSS)a:{g=document.createElement("div");var n=["perspectiveProperty","WebkitPerspective","MozPerspective","OPerspective","msPerspective"],e;for(e in n)if(void 0!==g.style[n[e]]){a.pfx=n[e].replace("Perspective","").toLowerCase();
+ a.prop="-"+a.pfx+"-transform";g=!0;break a}g=!1}b.transitions=g;""!==c.controlsContainer&&(a.controlsContainer=0<d(c.controlsContainer).length&&d(c.controlsContainer));""!==c.manualControls&&(a.manualControls=0<d(c.manualControls).length&&d(c.manualControls));c.randomize&&(a.slides.sort(function(){return Math.round(Math.random())-0.5}),a.container.empty().append(a.slides));a.doMath();s&&f.asNav.setup();a.setup("init");c.controlNav&&f.controlNav.setup();c.directionNav&&f.directionNav.setup();c.keyboard&&
+ (1===d(a.containerSelector).length||c.multipleKeyboard)&&d(document).bind("keyup",function(b){b=b.keyCode;if(!a.animating&&(39===b||37===b))b=39===b?a.getTarget("next"):37===b?a.getTarget("prev"):!1,a.flexAnimate(b,c.pauseOnAction)});c.mousewheel&&a.bind("mousewheel",function(b,g){b.preventDefault();var d=0>g?a.getTarget("next"):a.getTarget("prev");a.flexAnimate(d,c.pauseOnAction)});c.pausePlay&&f.pausePlay.setup();c.slideshow&&(c.pauseOnHover&&a.hover(function(){!a.manualPlay&&!a.manualPause&&a.pause()},
+ function(){!a.manualPause&&!a.manualPlay&&a.play()}),0<c.initDelay?setTimeout(a.play,c.initDelay):a.play());p&&c.touch&&f.touch();(!r||r&&c.smoothHeight)&&d(window).bind("resize focus",f.resize);setTimeout(function(){c.start(a)},200)},asNav:{setup:function(){a.asNav=!0;a.animatingTo=Math.floor(a.currentSlide/a.move);a.currentItem=a.currentSlide;a.slides.removeClass(e+"active-slide").eq(a.currentItem).addClass(e+"active-slide");a.slides.click(function(b){b.preventDefault();var b=d(this),g=b.index();
+ !d(c.asNavFor).data("flexslider").animating&&!b.hasClass("active")&&(a.direction=a.currentItem<g?"next":"prev",a.flexAnimate(g,c.pauseOnAction,!1,!0,!0))})}},controlNav:{setup:function(){a.manualControls?f.controlNav.setupManual():f.controlNav.setupPaging()},setupPaging:function(){var b=1,g;a.controlNavScaffold=d('<ol class="'+e+"control-nav "+e+("thumbnails"===c.controlNav?"control-thumbs":"control-paging")+'"></ol>');if(1<a.pagingCount)for(var n=0;n<a.pagingCount;n++)g="thumbnails"===c.controlNav?
+ '<img src="'+a.slides.eq(n).attr("data-thumb")+'"/>':"<a>"+b+"</a>",a.controlNavScaffold.append("<li>"+g+"</li>"),b++;a.controlsContainer?d(a.controlsContainer).append(a.controlNavScaffold):a.append(a.controlNavScaffold);f.controlNav.set();f.controlNav.active();a.controlNavScaffold.delegate("a, img",t,function(b){b.preventDefault();var b=d(this),g=a.controlNav.index(b);b.hasClass(e+"active")||(a.direction=g>a.currentSlide?"next":"prev",a.flexAnimate(g,c.pauseOnAction))});p&&a.controlNavScaffold.delegate("a",
+ "click touchstart",function(a){a.preventDefault()})},setupManual:function(){a.controlNav=a.manualControls;f.controlNav.active();a.controlNav.live(t,function(b){b.preventDefault();var b=d(this),g=a.controlNav.index(b);b.hasClass(e+"active")||(g>a.currentSlide?a.direction="next":a.direction="prev",a.flexAnimate(g,c.pauseOnAction))});p&&a.controlNav.live("click touchstart",function(a){a.preventDefault()})},set:function(){a.controlNav=d("."+e+"control-nav li "+("thumbnails"===c.controlNav?"img":"a"),
+ a.controlsContainer?a.controlsContainer:a)},active:function(){a.controlNav.removeClass(e+"active").eq(a.animatingTo).addClass(e+"active")},update:function(b,c){1<a.pagingCount&&"add"===b?a.controlNavScaffold.append(d("<li><a>"+a.count+"</a></li>")):1===a.pagingCount?a.controlNavScaffold.find("li").remove():a.controlNav.eq(c).closest("li").remove();f.controlNav.set();1<a.pagingCount&&a.pagingCount!==a.controlNav.length?a.update(c,b):f.controlNav.active()}},directionNav:{setup:function(){var b=d('<ul class="'+
+ e+'direction-nav"><li><a class="'+e+'prev" href="#">'+c.prevText+'</a></li><li><a class="'+e+'next" href="#">'+c.nextText+"</a></li></ul>");a.controlsContainer?(d(a.controlsContainer).append(b),a.directionNav=d("."+e+"direction-nav li a",a.controlsContainer)):(a.append(b),a.directionNav=d("."+e+"direction-nav li a",a));f.directionNav.update();a.directionNav.bind(t,function(b){b.preventDefault();b=d(this).hasClass(e+"next")?a.getTarget("next"):a.getTarget("prev");a.flexAnimate(b,c.pauseOnAction)});
+ p&&a.directionNav.bind("click touchstart",function(a){a.preventDefault()})},update:function(){var b=e+"disabled";1===a.pagingCount?a.directionNav.addClass(b):c.animationLoop?a.directionNav.removeClass(b):0===a.animatingTo?a.directionNav.removeClass(b).filter("."+e+"prev").addClass(b):a.animatingTo===a.last?a.directionNav.removeClass(b).filter("."+e+"next").addClass(b):a.directionNav.removeClass(b)}},pausePlay:{setup:function(){var b=d('<div class="'+e+'pauseplay"><a></a></div>');a.controlsContainer?
+ (a.controlsContainer.append(b),a.pausePlay=d("."+e+"pauseplay a",a.controlsContainer)):(a.append(b),a.pausePlay=d("."+e+"pauseplay a",a));f.pausePlay.update(c.slideshow?e+"pause":e+"play");a.pausePlay.bind(t,function(b){b.preventDefault();d(this).hasClass(e+"pause")?(a.manualPause=!0,a.manualPlay=!1,a.pause()):(a.manualPause=!1,a.manualPlay=!0,a.play())});p&&a.pausePlay.bind("click touchstart",function(a){a.preventDefault()})},update:function(b){"play"===b?a.pausePlay.removeClass(e+"pause").addClass(e+
+ "play").text(c.playText):a.pausePlay.removeClass(e+"play").addClass(e+"pause").text(c.pauseText)}},touch:function(){function b(b){j=l?d-b.touches[0].pageY:d-b.touches[0].pageX;p=l?Math.abs(j)<Math.abs(b.touches[0].pageX-e):Math.abs(j)<Math.abs(b.touches[0].pageY-e);if(!p||500<Number(new Date)-k)b.preventDefault(),!r&&a.transitions&&(c.animationLoop||(j/=0===a.currentSlide&&0>j||a.currentSlide===a.last&&0<j?Math.abs(j)/q+2:1),a.setProps(f+j,"setTouch"))}function g(){i.removeEventListener("touchmove",
+ b,!1);if(a.animatingTo===a.currentSlide&&!p&&null!==j){var h=m?-j:j,l=0<h?a.getTarget("next"):a.getTarget("prev");a.canAdvance(l)&&(550>Number(new Date)-k&&50<Math.abs(h)||Math.abs(h)>q/2)?a.flexAnimate(l,c.pauseOnAction):r||a.flexAnimate(a.currentSlide,c.pauseOnAction,!0)}i.removeEventListener("touchend",g,!1);f=j=e=d=null}var d,e,f,q,j,k,p=!1;i.addEventListener("touchstart",function(j){a.animating?j.preventDefault():1===j.touches.length&&(a.pause(),q=l?a.h:a.w,k=Number(new Date),f=h&&m&&a.animatingTo===
+ a.last?0:h&&m?a.limit-(a.itemW+c.itemMargin)*a.move*a.animatingTo:h&&a.currentSlide===a.last?a.limit:h?(a.itemW+c.itemMargin)*a.move*a.currentSlide:m?(a.last-a.currentSlide+a.cloneOffset)*q:(a.currentSlide+a.cloneOffset)*q,d=l?j.touches[0].pageY:j.touches[0].pageX,e=l?j.touches[0].pageX:j.touches[0].pageY,i.addEventListener("touchmove",b,!1),i.addEventListener("touchend",g,!1))},!1)},resize:function(){!a.animating&&a.is(":visible")&&(h||a.doMath(),r?f.smoothHeight():h?(a.slides.width(a.computedW),
+ a.update(a.pagingCount),a.setProps()):l?(a.viewport.height(a.h),a.setProps(a.h,"setTotal")):(c.smoothHeight&&f.smoothHeight(),a.newSlides.width(a.computedW),a.setProps(a.computedW,"setTotal")))},smoothHeight:function(b){if(!l||r){var c=r?a:a.viewport;b?c.animate({height:a.slides.eq(a.animatingTo).height()},b):c.height(a.slides.eq(a.animatingTo).height())}},sync:function(b){var g=d(c.sync).data("flexslider"),e=a.animatingTo;switch(b){case "animate":g.flexAnimate(e,c.pauseOnAction,!1,!0);break;case "play":!g.playing&&
+ !g.asNav&&g.play();break;case "pause":g.pause()}}};a.flexAnimate=function(b,g,n,i,k){s&&1===a.pagingCount&&(a.direction=a.currentItem<b?"next":"prev");if(!a.animating&&(a.canAdvance(b,k)||n)&&a.is(":visible")){if(s&&i)if(n=d(c.asNavFor).data("flexslider"),a.atEnd=0===b||b===a.count-1,n.flexAnimate(b,!0,!1,!0,k),a.direction=a.currentItem<b?"next":"prev",n.direction=a.direction,Math.ceil((b+1)/a.visible)-1!==a.currentSlide&&0!==b)a.currentItem=b,a.slides.removeClass(e+"active-slide").eq(b).addClass(e+
+ "active-slide"),b=Math.floor(b/a.visible);else return a.currentItem=b,a.slides.removeClass(e+"active-slide").eq(b).addClass(e+"active-slide"),!1;a.animating=!0;a.animatingTo=b;c.before(a);g&&a.pause();a.syncExists&&!k&&f.sync("animate");c.controlNav&&f.controlNav.active();h||a.slides.removeClass(e+"active-slide").eq(b).addClass(e+"active-slide");a.atEnd=0===b||b===a.last;c.directionNav&&f.directionNav.update();b===a.last&&(c.end(a),c.animationLoop||a.pause());if(r)p?(a.slides.eq(a.currentSlide).css({opacity:0,
+ zIndex:1}),a.slides.eq(b).css({opacity:1,zIndex:2}),a.animating=!1,a.currentSlide=a.animatingTo):(a.slides.eq(a.currentSlide).fadeOut(c.animationSpeed,c.easing),a.slides.eq(b).fadeIn(c.animationSpeed,c.easing,a.wrapup));else{var q=l?a.slides.filter(":first").height():a.computedW;h?(b=c.itemWidth>a.w?2*c.itemMargin:c.itemMargin,b=(a.itemW+b)*a.move*a.animatingTo,b=b>a.limit&&1!==a.visible?a.limit:b):b=0===a.currentSlide&&b===a.count-1&&c.animationLoop&&"next"!==a.direction?m?(a.count+a.cloneOffset)*
+ q:0:a.currentSlide===a.last&&0===b&&c.animationLoop&&"prev"!==a.direction?m?0:(a.count+1)*q:m?(a.count-1-b+a.cloneOffset)*q:(b+a.cloneOffset)*q;a.setProps(b,"",c.animationSpeed);if(a.transitions){if(!c.animationLoop||!a.atEnd)a.animating=!1,a.currentSlide=a.animatingTo;a.container.unbind("webkitTransitionEnd transitionend");a.container.bind("webkitTransitionEnd transitionend",function(){a.wrapup(q)})}else a.container.animate(a.args,c.animationSpeed,c.easing,function(){a.wrapup(q)})}c.smoothHeight&&
+ f.smoothHeight(c.animationSpeed)}};a.wrapup=function(b){!r&&!h&&(0===a.currentSlide&&a.animatingTo===a.last&&c.animationLoop?a.setProps(b,"jumpEnd"):a.currentSlide===a.last&&(0===a.animatingTo&&c.animationLoop)&&a.setProps(b,"jumpStart"));a.animating=!1;a.currentSlide=a.animatingTo;c.after(a)};a.animateSlides=function(){a.animating||a.flexAnimate(a.getTarget("next"))};a.pause=function(){clearInterval(a.animatedSlides);a.playing=!1;c.pausePlay&&f.pausePlay.update("play");a.syncExists&&f.sync("pause")};
+ a.play=function(){a.animatedSlides=setInterval(a.animateSlides,c.slideshowSpeed);a.playing=!0;c.pausePlay&&f.pausePlay.update("pause");a.syncExists&&f.sync("play")};a.canAdvance=function(b,g){var d=s?a.pagingCount-1:a.last;return g?!0:s&&a.currentItem===a.count-1&&0===b&&"prev"===a.direction?!0:s&&0===a.currentItem&&b===a.pagingCount-1&&"next"!==a.direction?!1:b===a.currentSlide&&!s?!1:c.animationLoop?!0:a.atEnd&&0===a.currentSlide&&b===d&&"next"!==a.direction?!1:a.atEnd&&a.currentSlide===d&&0===
+ b&&"next"===a.direction?!1:!0};a.getTarget=function(b){a.direction=b;return"next"===b?a.currentSlide===a.last?0:a.currentSlide+1:0===a.currentSlide?a.last:a.currentSlide-1};a.setProps=function(b,g,d){var e,f=b?b:(a.itemW+c.itemMargin)*a.move*a.animatingTo;e=-1*function(){if(h)return"setTouch"===g?b:m&&a.animatingTo===a.last?0:m?a.limit-(a.itemW+c.itemMargin)*a.move*a.animatingTo:a.animatingTo===a.last?a.limit:f;switch(g){case "setTotal":return m?(a.count-1-a.currentSlide+a.cloneOffset)*b:(a.currentSlide+
+ a.cloneOffset)*b;case "setTouch":return b;case "jumpEnd":return m?b:a.count*b;case "jumpStart":return m?a.count*b:b;default:return b}}()+"px";a.transitions&&(e=l?"translate3d(0,"+e+",0)":"translate3d("+e+",0,0)",d=void 0!==d?d/1E3+"s":"0s",a.container.css("-"+a.pfx+"-transition-duration",d));a.args[a.prop]=e;(a.transitions||void 0===d)&&a.container.css(a.args)};a.setup=function(b){if(r)a.slides.css({width:"100%","float":"left",marginRight:"-100%",position:"relative"}),"init"===b&&(p?a.slides.css({opacity:0,
+ display:"block",webkitTransition:"opacity "+c.animationSpeed/1E3+"s ease",zIndex:1}).eq(a.currentSlide).css({opacity:1,zIndex:2}):a.slides.eq(a.currentSlide).fadeIn(c.animationSpeed,c.easing)),c.smoothHeight&&f.smoothHeight();else{var g,n;"init"===b&&(a.viewport=d('<div class="'+e+'viewport"></div>').css({overflow:"hidden",position:"relative"}).appendTo(a).append(a.container),a.cloneCount=0,a.cloneOffset=0,m&&(n=d.makeArray(a.slides).reverse(),a.slides=d(n),a.container.empty().append(a.slides)));
+ c.animationLoop&&!h&&(a.cloneCount=2,a.cloneOffset=1,"init"!==b&&a.container.find(".clone").remove(),a.container.append(a.slides.first().clone().addClass("clone")).prepend(a.slides.last().clone().addClass("clone")));a.newSlides=d(c.selector,a);g=m?a.count-1-a.currentSlide+a.cloneOffset:a.currentSlide+a.cloneOffset;l&&!h?(a.container.height(200*(a.count+a.cloneCount)+"%").css("position","absolute").width("100%"),setTimeout(function(){a.newSlides.css({display:"block"});a.doMath();a.viewport.height(a.h);
+ a.setProps(g*a.h,"init")},"init"===b?100:0)):(a.container.width(200*(a.count+a.cloneCount)+"%"),a.setProps(g*a.computedW,"init"),setTimeout(function(){a.doMath();a.newSlides.css({width:a.computedW,"float":"left",display:"block"});c.smoothHeight&&f.smoothHeight()},"init"===b?100:0))}h||a.slides.removeClass(e+"active-slide").eq(a.currentSlide).addClass(e+"active-slide")};a.doMath=function(){var b=a.slides.first(),d=c.itemMargin,e=c.minItems,f=c.maxItems;a.w=a.width();a.h=b.height();a.boxPadding=b.outerWidth()-
+ b.width();h?(a.itemT=c.itemWidth+d,a.minW=e?e*a.itemT:a.w,a.maxW=f?f*a.itemT:a.w,a.itemW=a.minW>a.w?(a.w-d*e)/e:a.maxW<a.w?(a.w-d*f)/f:c.itemWidth>a.w?a.w:c.itemWidth,a.visible=Math.floor(a.w/(a.itemW+d)),a.move=0<c.move&&c.move<a.visible?c.move:a.visible,a.pagingCount=Math.ceil((a.count-a.visible)/a.move+1),a.last=a.pagingCount-1,a.limit=1===a.pagingCount?0:c.itemWidth>a.w?(a.itemW+2*d)*a.count-a.w-d:(a.itemW+d)*a.count-a.w-d):(a.itemW=a.w,a.pagingCount=a.count,a.last=a.count-1);a.computedW=a.itemW-
+ a.boxPadding};a.update=function(b,d){a.doMath();h||(b<a.currentSlide?a.currentSlide+=1:b<=a.currentSlide&&0!==b&&(a.currentSlide-=1),a.animatingTo=a.currentSlide);if(c.controlNav&&!a.manualControls)if("add"===d&&!h||a.pagingCount>a.controlNav.length)f.controlNav.update("add");else if("remove"===d&&!h||a.pagingCount<a.controlNav.length)h&&a.currentSlide>a.last&&(a.currentSlide-=1,a.animatingTo-=1),f.controlNav.update("remove",a.last);c.directionNav&&f.directionNav.update()};a.addSlide=function(b,e){var f=
+ d(b);a.count+=1;a.last=a.count-1;l&&m?void 0!==e?a.slides.eq(a.count-e).after(f):a.container.prepend(f):void 0!==e?a.slides.eq(e).before(f):a.container.append(f);a.update(e,"add");a.slides=d(c.selector+":not(.clone)",a);a.setup();c.added(a)};a.removeSlide=function(b){var e=isNaN(b)?a.slides.index(d(b)):b;a.count-=1;a.last=a.count-1;isNaN(b)?d(b,a.slides).remove():l&&m?a.slides.eq(a.last).remove():a.slides.eq(b).remove();a.doMath();a.update(e,"remove");a.slides=d(c.selector+":not(.clone)",a);a.setup();
+ c.removed(a)};f.init()};d.flexslider.defaults={namespace:"flex-",selector:".slides > li",animation:"fade",easing:"swing",direction:"horizontal",reverse:!1,animationLoop:!0,smoothHeight:!1,startAt:0,slideshow:!0,slideshowSpeed:7E3,animationSpeed:600,initDelay:0,randomize:!1,pauseOnAction:!0,pauseOnHover:!1,useCSS:!0,touch:!0,video:!1,controlNav:!0,directionNav:!0,prevText:"Previous",nextText:"Next",keyboard:!0,multipleKeyboard:!1,mousewheel:!1,pausePlay:!1,pauseText:"Pause",playText:"Play",controlsContainer:"",
+ manualControls:"",sync:"",asNavFor:"",itemWidth:0,itemMargin:0,minItems:0,maxItems:0,move:0,start:function(){},before:function(){},after:function(){},end:function(){},added:function(){},removed:function(){}};d.fn.flexslider=function(i){void 0===i&&(i={});if("object"===typeof i)return this.each(function(){var a=d(this),c=a.find(i.selector?i.selector:".slides > li");1===c.length?(c.fadeIn(400),i.start&&i.start(a)):void 0===a.data("flexslider")&&new d.flexslider(this,i)});var k=d(this).data("flexslider");
+ switch(i){case "play":k.play();break;case "pause":k.pause();break;case "next":k.flexAnimate(k.getTarget("next"),!0);break;case "prev":case "previous":k.flexAnimate(k.getTarget("prev"),!0);break;default:"number"===typeof i&&k.flexAnimate(i,!0)}}})(jQuery);
\ No newline at end of file
--- /dev/null
+<?php
+headway_register_block('HeadwaySliderBlock', headway_url() . '/library/blocks/slider');
+class HeadwaySliderBlock extends HeadwayBlockAPI {
+
+
+ public $id = 'slider';
+
+ public $name = 'Slider';
+
+ public $options_class = 'HeadwaySliderBlockOptions';
+
+ public $fixed_height = false;
+
+ public $description = 'Create effective responsive image slideshows.';
+
+
+ public static function enqueue_action($block_id, $block) {
+
+ $images = parent::get_setting($block, 'images', array());
+
+ wp_enqueue_style('flexslider', headway_url() . '/library/blocks/slider/assets/flexslider.css');
+
+ //If there are no images or only 1 image, do not load FlexSlider JS.
+ if ( count($images) <= 1 )
+ return false;
+
+ wp_enqueue_script('flexslider', headway_url() . '/library/blocks/slider/assets/jquery.flexslider-min.js', array('jquery'));
+
+ }
+
+
+ public static function dynamic_js($block_id, $block) {
+
+ $images = parent::get_setting($block, 'images', array());
+
+ //If there are no images or only 1 image, do not load FlexSlider.
+ if ( count($images) <= 1 )
+ return false;
+
+ return '
+jQuery(document).ready(function(){
+ jQuery(\'#block-' . $block['id'] . ' .flexslider\').flexslider({
+ animation: "' . (parent::get_setting($block, 'animation', 'slide-horizontal') == 'fade' ? 'fade' : 'slide') . '",
+ direction: "' . (parent::get_setting($block, 'animation', 'slide-horizontal') == 'slide-vertical' ? 'vertical' : 'horizontal') . '",
+ slideshow: ' . (parent::get_setting($block, 'slideshow', true) ? 'true' : 'false') . ',
+ slideshowSpeed: ' . (parent::get_setting($block, 'animation-timeout', 6) * 1000) . ',
+ animationSpeed: ' . (parent::get_setting($block, 'animation-speed', 500)) . ',
+ randomize: false,
+ controlNav: ' . (parent::get_setting($block, 'show-pager-nav', true) ? 'true' : 'false') . ',
+ directionNav: ' . (parent::get_setting($block, 'show-direction-nav', true) ? 'true' : 'false') . ',
+ randomize: ' . (parent::get_setting($block, 'randomize-order', false) ? 'true' : 'false') . '
+ });
+});' . "\n";
+
+ }
+
+
+ function content($block) {
+
+ $images = parent::get_setting($block, 'images', array());
+
+ $block_width = HeadwayBlocksData::get_block_width($block);
+ $block_height = HeadwayBlocksData::get_block_height($block);
+
+ $has_images = false;
+
+ foreach ( $images as $image )
+ if ( $image['image'] ) {
+ $has_images = true;
+ break;
+ }
+
+ if ( !$has_images ) {
+
+ echo '<div class="alert alert-yellow"><p>There are no images to display.</p></div>';
+
+ return;
+
+ }
+
+ $no_slide_class = count($images) === 1 ? ' flexslider-no-slide' : '';
+
+ echo '<div class="flexslider' . $no_slide_class . '">';
+
+ /* Put in viewport div for sliders that only have 1 image and don't slide */
+ if ( count($images) === 1 )
+ echo '<div class="flex-viewport">';
+
+ echo '<ul class="slides">';
+
+ foreach ( $images as $image ) {
+
+ if ( !$image['image'] )
+ continue;
+
+ $output = array(
+ 'image' => array(
+ 'src' => parent::get_setting($block, 'crop-resize-images', true) ? headway_resize_image($image['image'], $block_width, $block_height) : $image['image'],
+ 'alt' => headway_fix_data_type(headway_get('image-alt', $image)),
+ 'title' => headway_fix_data_type(headway_get('image-title', $image)),
+ 'caption' => headway_fix_data_type(headway_get('image-description', $image))
+ ),
+
+ 'hyperlink' => array(
+ 'href' => headway_fix_data_type(headway_get('image-hyperlink', $image)),
+ 'target' => headway_fix_data_type(headway_get('image-open-link-in-new-window', $image, false)) ? ' target="_blank"' : null
+ )
+ );
+
+ echo '<li>';
+
+ /* Open hyperlink if user added one for image */
+ if ( $output['hyperlink']['href'] )
+ echo '<a href="' . $output['hyperlink']['href'] . '"' . $output['hyperlink']['target'] . '>';
+
+ /* Don't forget to display the ACTUAL IMAGE */
+ echo '<img src="' . $output['image']['src'] . '" alt="' . $output['image']['alt'] . '" title="' . $output['image']['title'] . '" />';
+
+ /* Closing tag for hyperlink */
+ if ( $output['hyperlink']['href'] )
+ echo '</a>';
+
+ /* Caption */
+ if ( !empty($output['image']['caption']) )
+ echo '<p class="flex-caption">' . $output['image']['caption'] . '</p>';
+
+ echo '</li>';
+
+ }
+
+ echo '</ul>';
+
+ /* Put in viewport div for sliders that only have 1 image and don't slide */
+ if ( count($images) === 1 )
+ echo '</div><!-- .flex-viewport -->';
+
+ echo '</div><!-- .flexslider -->';
+
+ }
+
+
+ function setup_elements() {
+
+ $this->register_block_element(array(
+ 'id' => 'slider-container',
+ 'name' => 'Slider Container',
+ 'description' => 'Contains Viewport, Paging',
+ 'selector' => '.flexslider',
+ 'properties' => array('background', 'borders', 'padding', 'corners', 'box-shadow')
+ ));
+
+ $this->register_block_element(array(
+ 'id' => 'slider-viewport',
+ 'name' => 'Slider Viewport',
+ 'description' => 'Contains Images',
+ 'selector' => '.flex-viewport',
+ 'properties' => array('background', 'borders', 'padding', 'corners', 'box-shadow', 'overflow')
+ ));
+
+ $this->register_block_element(array(
+ 'id' => 'slider-caption',
+ 'name' => 'Slider Caption',
+ 'selector' => '.flex-caption',
+ 'properties' => array('background', 'padding', 'fonts')
+ ));
+
+ $this->register_block_element(array(
+ 'id' => 'slider-direction-nav-link',
+ 'name' => 'Slider Direction Nav Link',
+ 'selector' => '.flex-direction-nav a',
+ 'properties' => array('background', 'borders', 'padding', 'corners', 'box-shadow')
+ ));
+
+ $this->register_block_element(array(
+ 'id' => 'slider-direction-nav-next',
+ 'name' => 'Slider Direction Next',
+ 'selector' => '.flex-direction-nav a.flex-next',
+ 'properties' => array('background', 'borders', 'padding', 'corners', 'box-shadow')
+ ));
+
+ $this->register_block_element(array(
+ 'id' => 'slider-direction-nav-prev',
+ 'name' => 'Slider Direction Prev',
+ 'selector' => '.flex-direction-nav a.flex-prev',
+ 'properties' => array('background', 'borders', 'padding', 'corners', 'box-shadow')
+ ));
+
+ $this->register_block_element(array(
+ 'id' => 'slider-paging',
+ 'name' => 'Slider Paging',
+ 'selector' => '.flex-control-nav',
+ 'properties' => array('background', 'borders', 'padding', 'corners', 'box-shadow')
+ ));
+
+ $this->register_block_element(array(
+ 'id' => 'slider-paging-link',
+ 'name' => 'Slider Paging Link',
+ 'selector' => '.flex-control-paging li a',
+ 'properties' => array('background', 'borders', 'padding', 'corners', 'box-shadow'),
+ 'states' => array(
+ 'Hover' => '.flex-control-paging li a:hover',
+ 'Active' => '.flex-control-paging li a.flex-active'
+ )
+ ));
+
+ }
+
+
+}
+
+
+class HeadwaySliderBlockOptions extends HeadwayBlockOptionsAPI {
+
+ public $tabs = array(
+ 'slider-images' => 'Slider Images',
+ 'animation' => 'Animation',
+ 'ui' => 'User Interface',
+ 'advanced' => 'Advanced'
+ );
+
+ public $inputs = array(
+ 'slider-images' => array(
+ 'images' => array(
+ 'type' => 'repeater',
+ 'name' => 'images',
+ 'label' => 'Images',
+ 'tooltip' => 'Upload the images that you would like to add to the image rotator here. You can even drag and drop the images to change the order.',
+ 'inputs' => array(
+ array(
+ 'type' => 'image',
+ 'name' => 'image',
+ 'label' => 'Image',
+ 'default' => null
+ ),
+
+ array(
+ 'type' => 'text',
+ 'name' => 'image-hyperlink',
+ 'label' => 'Hyperlink',
+ 'default' => null
+ ),
+
+ array(
+ 'type' => 'checkbox',
+ 'name' => 'image-open-link-in-new-window',
+ 'label' => 'Open Link in New Window',
+ 'default' => false
+ ),
+
+ array(
+ 'type' => 'text',
+ 'name' => 'image-description',
+ 'label' => 'Caption',
+ 'placeholder' => 'Describe the Image',
+ 'tooltip' => 'This will be displayed underneath the image.'
+ ),
+
+ array(
+ 'type' => 'text',
+ 'name' => 'image-title',
+ 'label' => '"title" Attribute',
+ 'tooltip' => 'This will be used as the "title" attribute for the image. The title attribute is beneficial for SEO (Search Engine Optimization) and will allow your visitors to move their mouse over the image and read about it.'
+ ),
+
+ array(
+ 'type' => 'text',
+ 'name' => 'image-alt',
+ 'label' => '"alt" Attribute',
+ 'tooltip' => 'This will be used as the "alt" attribute for the image. The alt attribute is <em>hugely</em> beneficial for SEO (Search Engine Optimization) and for general accessibility.'
+ )
+ ),
+ 'sortable' => true,
+ 'limit' => false
+ ),
+
+ 'randomize-order' => array(
+ 'type' => 'checkbox',
+ 'name' => 'randomize-order',
+ 'label' => 'Randomize Image Order',
+ 'default' => false
+ ),
+
+ 'image-sizing-header' => array(
+ 'type' => 'heading',
+ 'name' => 'image-sizing-header',
+ 'label' => 'Image Sizing'
+ ),
+
+ 'crop-resize-images' => array(
+ 'type' => 'checkbox',
+ 'name' => 'crop-resize-images',
+ 'label' => 'Crop and Resize Images',
+ 'default' => true,
+ 'tooltip' => 'The Slider block has the ability to automatically resize and crop images to fit in the Slider if the images are too big. This will improve loading times and make the image fit better in the Slider.<br /><br />If you do not want the Slider block to do this, uncheck this option and the Slider block will insert your original uploaded images into the slider. <strong>Please note:</strong> Even with this unchecked the images will still be resized with CSS.'
+ ),
+
+ 'content-types-heading' => array(
+ 'type' => 'heading',
+ 'name' => 'content-types-heading',
+ 'label' => 'Other Content Types',
+ ),
+
+ 'content-types-text' => array(
+ 'type' => 'notice',
+ 'name' => 'content-types-text',
+ 'notice' => 'This Slider block is only capable of displaying images. If you wish to insert more content such as text, videos, etc., we recommend <a href="http://headwaythemes.com/go/slidedeck-lite" target="_blank">SlideDeck</a> and <a href="http://headwaythemes.com/extend/addon/sliderplus/" target="_blank">SliderPlus</a>.'
+ )
+ ),
+
+ 'animation' => array(
+ 'animation' => array(
+ 'type' => 'select',
+ 'name' => 'animation',
+ 'label' => 'Animation',
+ 'default' => 'slide-horizontal',
+ 'options' => array(
+ 'slide-horizontal' => 'Slide Horizontal',
+ 'slide-vertical' => 'Slide Vertical',
+ 'fade' => 'Fade'
+ )
+ ),
+
+ 'animation-speed' => array(
+ 'type' => 'slider',
+ 'name' => 'animation-speed',
+ 'label' => 'Animation Speed',
+ 'default' => 500,
+ 'slider-min' => 50,
+ 'slider-max' => 5000,
+ 'slider-interval' => 10,
+ 'tooltip' => 'Adjust this to change how long the animation lasts when fading between images.',
+ 'unit' => 'ms'
+ ),
+
+ 'slideshow' => array(
+ 'type' => 'checkbox',
+ 'name' => 'slideshow',
+ 'label' => 'Automatic Slide Advancement',
+ 'default' => true,
+ 'tooltip' => 'Act as a slideshow and automatically move to the next slide.'
+ ),
+
+ 'animation-timeout' => array(
+ 'type' => 'slider',
+ 'name' => 'animation-timeout',
+ 'label' => 'Time Between Slides',
+ 'default' => 6,
+ 'slider-min' => 1,
+ 'slider-max' => 20,
+ 'slider-interval' => 1,
+ 'tooltip' => 'This is the amount of time each image will stay visible.',
+ 'unit' => 's'
+ )
+ ),
+
+ 'ui' => array(
+ 'show-pager-nav' => array(
+ 'type' => 'checkbox',
+ 'name' => 'show-pager-nav',
+ 'label' => 'Show Pager Navigation',
+ 'default' => true,
+ 'tooltip' => 'Show dots below slider to choose specific slides.'
+ ),
+
+ 'show-direction-nav' => array(
+ 'type' => 'checkbox',
+ 'name' => 'show-direction-nav',
+ 'label' => 'Show Next/Previous Arrows',
+ 'default' => true,
+ 'tooltip' => 'Show arrows to advance to the next/previous slides.'
+ )
+ ),
+
+ 'advanced' => array(
+ 'content-types-text' => array(
+ 'type' => 'notice',
+ 'name' => 'content-types-text',
+ 'notice' => 'This Slider block is only capable of displaying images. If you wish to insert more content such as text, videos, etc., we recommend <a href="http://headwaythemes.com/go/slidedeck-lite" target="_blank">SlideDeck</a> and <a href="http://headwaythemes.com/extend/addon/sliderplus/" target="_blank">SliderPlus</a>.'
+ )
+ )
+ );
+
+}
\ No newline at end of file
--- /dev/null
+<?php
+
+headway_register_block('HeadwaySocialBlock', headway_url() . '/library/blocks/social');
+
+class HeadwaySocialBlock extends HeadwayBlockAPI {
+
+ public $id = 'social';
+
+ public $name = 'Social';
+
+ public $options_class = 'HeadwaySocialBlockOptions';
+
+ public $fixed_height = true;
+
+ public $html_tag = 'section';
+
+ public $description = 'Display a set of social icons';
+
+ protected $show_content_in_grid = false;
+
+ public function init() {
+
+ add_filter( 'upload_mimes', array($this, 'add_uploader_svg_mime' ));
+
+ }
+
+ public function setup_elements() {
+
+ $this->register_block_element(array(
+ 'id' => 'icons-wrapper',
+ 'name' => 'Icons Container',
+ 'selector' => 'ul.social-icons '
+ ));
+
+ $this->register_block_element(array(
+ 'id' => 'icon',
+ 'name' => 'Icon Container ',
+ 'selector' => 'li'
+ ));
+
+ $this->register_block_element(array(
+ 'id' => 'icon-first',
+ 'name' => 'First Icon',
+ 'selector' => 'li:first-child'
+ ));
+
+ $this->register_block_element(array(
+ 'id' => 'icon-last',
+ 'name' => 'Last Icon',
+ 'selector' => 'li:last-child'
+ ));
+
+ $this->register_block_element(array(
+ 'id' => 'image',
+ 'name' => 'Image',
+ 'selector' => 'img'
+ ));
+
+ $this->register_block_element(array(
+ 'id' => 'image-link',
+ 'name' => 'Image Link',
+ 'selector' => 'img a',
+ 'states' => array(
+ 'Hover' => 'img a:hover',
+ 'Clicked' => 'img a:active'
+ )
+ ));
+
+ }
+
+
+ public static function dynamic_css($block_id, $block = false) {
+
+ if ( !$block )
+ $block = HeadwayBlocksData::get_block($block_id);
+
+ $position = parent::get_setting($block, 'icons-position', '');
+ $orientation = parent::get_setting($block, 'orientation', 'vertical');
+
+ $css = '';
+
+ /* Stack vertical add only bottom margin */
+ if ( $orientation === 'vertical' ) {
+
+ $css .= '
+ #block-' . $block_id . ' ul.social-icons li {
+ margin-bottom: '. parent::get_setting($block, 'vertical-spacing', '10') .'px
+ }
+
+ #block-' . $block_id . ' ul.social-icons li:last-child {
+ margin-bottom: 0;
+ }
+ ';
+
+
+ }
+
+ /* Float horizontal images and add right margin on all but last*/
+ if ( $orientation === 'horizontal' ) {
+
+ $css .= '
+ #block-' . $block_id . ' ul.social-icons li {
+ display: inline-block;
+ margin-right: '. parent::get_setting($block, 'horizontal-spacing', '10') .'px
+ }
+
+ #block-' . $block_id . ' ul.social-icons li:last-child {
+ margin-right: 0;
+ }
+ ';
+
+ }
+
+
+ if ( $position ) {
+
+ $position_fragments = explode('_', $position);
+
+ $horizontal_position = $position_fragments[1];
+ $vertical_position = str_replace('center', 'middle', $position_fragments[0]);
+
+ $css .= '
+ #block-' . $block_id . ' div.social-icons-container {
+ display: table;
+ width: 100%;
+ height: 100%;
+ }
+
+ #block-' . $block_id . ' ul.social-icons {
+ display: table-cell;
+ text-align: ' . $horizontal_position . ';
+ vertical-align: ' . $vertical_position . ';
+ }
+ ';
+
+ }
+
+ return $css;
+
+ }
+
+ public function content($block) {
+
+ $icon_set = HeadwayBlockAPI::get_setting($block, 'icon-set', 'peel-icons');
+
+ $use_svg = parent::get_setting($block, 'use-svg', false);
+ $svg_width = ($use_svg && parent::get_setting($block, 'svg-width')) ? 'width="' . parent::get_setting($block, 'svg-width') . '"' : '';
+
+ if ($icon_set == 'custom') {
+ $icons = parent::get_setting($block, 'icons' , array());
+ } else {
+ $icons = parent::get_setting($block, 'icons'.$icon_set , array());
+ }
+
+ $block_width = HeadwayBlocksData::get_block_width($block);
+ $block_height = HeadwayBlocksData::get_block_height($block);
+
+ $has_icons = false;
+
+ foreach ( $icons as $icon ) {
+
+ if ( headway_get('image', $icon) || headway_get('network', $icon) ) {
+ $has_icons = true;
+ break;
+ }
+
+ }
+
+ if ( !$has_icons) {
+
+ echo '<div class="alert alert-yellow"><p>There are no icons to display.</p></div>';
+
+ return;
+
+ }
+
+ echo '<div class="social-icons-container">';
+ echo '<ul class="social-icons">';
+
+ $i = 0;
+ foreach ( $icons as $icon ) {
+
+ if ( !headway_get('image', $icon) && !headway_get('network', $icon) )
+ continue;
+
+ if ($icon_set == 'custom') {
+ $img_url = $icon['image'];
+ } else {
+ $img_url = headway_url().'/library/blocks/social/icons/' . $icon_set . '/' . headway_fix_data_type(headway_get('network', $icon));
+ }
+
+ $i++;
+ $output = array(
+ 'image' => array(
+ 'src' => $img_url,
+ 'alt' => headway_fix_data_type(headway_get('image-alt', $icon, false)) ? ' alt="' . headway_fix_data_type(headway_get('image-alt', $icon, false)) . '"' : null,
+ 'title' => headway_fix_data_type(headway_get('image-title', $icon)) ? ' title="' . headway_fix_data_type(headway_get('image-title', $icon)) . '"' : null,
+ ),
+
+ 'hyperlink' => array(
+ 'href' => headway_fix_data_type(headway_get('link-url', $icon)),
+ 'alt' => headway_fix_data_type(headway_get('link-alt', $icon, false)) ? ' alt="' . headway_fix_data_type(headway_get('link-alt', $icon, false)) . '"' : null,
+ 'target' => headway_fix_data_type(headway_get('link-target', $icon, false)) ? ' target="_blank"' : null
+ )
+ );
+
+ echo '<li>';
+
+ /* Open hyperlink if user added one for image */
+ if ( $output['hyperlink']['href'] )
+ echo '<a href="' . $output['hyperlink']['href'] . '"' . $output['hyperlink']['target'] . $output['hyperlink']['alt'] . '>';
+
+ /* Don't forget to display the ACTUAL IMAGE */
+ echo '<img src="' . $output['image']['src'] . '"' . $output['image']['alt'] . $output['image']['title'] . ' class="img-' . $i . '" ' . $svg_width . ' />';
+
+ /* Closing tag for hyperlink */
+ if ( $output['hyperlink']['href'] )
+ echo '</a>';
+
+ echo '</li>';
+
+ }
+
+ echo '</ul>';
+ echo '</div><!-- .social-icons-container -->';
+
+ }
+
+ public function add_uploader_svg_mime( $mimes ){
+ $mimes['svg'] = 'image/svg+xml';
+ return $mimes;
+ }
+
+}
+
+class HeadwaySocialBlockOptions extends HeadwayBlockOptionsAPI {
+
+ public $tabs = array(
+ 'general' => 'General',
+ 'custom-icons-set' => 'Custom Icons'
+ );
+
+ public $inputs = array(
+ 'general' => array(
+
+ 'icon-set' => array(
+ 'type' => 'select',
+ 'name' => 'icon-set',
+ 'label' => 'Icon Set',
+ 'default' => 'peel-icons',
+ 'options' => 'get_icon_sets()',
+ 'tooltip' => 'Select custom to add your own icons or select one of these sets',
+ 'toggle' => array(
+ 'custom' => array(
+ 'hide' => array(
+ 'li[id*="-set"]:not(#sub-tab-custom-icons-set)'
+ ),
+ 'show' => array(
+ 'li#sub-tab-custom-icons-set'
+ )
+ ),
+ 'peel-icons' => array(
+ 'hide' => array(
+ 'li[id*="-set"]:not(#sub-tab-peel-icons-set)'
+ ),
+ 'show' => array(
+ 'li#sub-tab-peel-icons-set'
+ )
+ ),
+ 'soft-social' => array(
+ 'hide' => array(
+ 'li[id*="-set"]:not(#sub-tab-soft-social-set)'
+ ),
+ 'show' => array(
+ 'li#sub-tab-soft-social-set'
+ )
+ )
+ ),
+ 'callback' => '
+ reloadBlockOptions()'
+
+ ),
+
+ 'layout-heading' => array(
+ 'name' => 'layout-heading',
+ 'type' => 'heading',
+ 'label' => 'Layout',
+ 'tooltip' => 'Set the position of all icons in the block and the orientation before you add your icons.'
+ ),
+
+ 'icons-position' => array(
+ 'name' => 'icons-position',
+ 'label' => 'Position icons inside container',
+ 'type' => 'select',
+ 'tooltip' => 'You can position the social icons in relation to the block using the positions provided',
+ 'default' => 'none',
+ 'options' => array(
+ '' => 'None',
+ 'top_left' => 'Top Left',
+ 'top_center' => 'Top Center',
+ 'top_right' => 'Top Right',
+ 'center_left' => 'Center Left',
+ 'center_center' => 'Center Center',
+ 'center_right' => 'Center Right',
+ 'bottom_left' => 'Bottom Left',
+ 'bottom_center' => 'Bottom Center',
+ 'bottom_right' => 'Bottom Right'
+ )
+ ),
+
+ 'orientation' => array(
+ 'type' => 'select',
+ 'name' => 'orientation',
+ 'label' => 'Orientation',
+ 'tooltip' => '',
+ 'options' => array(
+ 'vertical' => 'Vertical',
+ 'horizontal' => 'Horizontal'
+ ),
+ 'toggle' => array(
+ 'vertical' => array(
+ 'show' => array(
+ '#input-vertical-spacing'
+ ),
+ 'hide' => array(
+ '#input-horizontal-spacing'
+ ),
+ ),
+ 'horizontal' => array(
+ 'show' => array(
+ '#input-horizontal-spacing'
+ ),
+ 'hide' => array(
+ '#input-vertical-spacing'
+ ),
+ )
+ ),
+ 'tooltip' => 'Display articles on top of each other (vertical) or side by side as a grid (horizontal)'
+ ),
+
+ 'horizontal-spacing' => array(
+ 'type' => 'text',
+ 'name' => 'horizontal-spacing',
+ 'label' => 'Horizontal Spacing',
+ 'default' => '10',
+ 'unit' => 'px',
+ 'tooltip' => 'Set the px horizontal spacing between the icons.'
+ ),
+
+ 'vertical-spacing' => array(
+ 'type' => 'text',
+ 'name' => 'vertical-spacing',
+ 'label' => 'Vertical Spacing',
+ 'default' => '10',
+ 'unit' => 'px',
+ 'tooltip' => 'Set the px vertical spacing between the icons.'
+ ),
+
+ 'svg-heading' => array(
+ 'name' => 'svg-heading',
+ 'type' => 'heading',
+ 'label' => 'SVG Images',
+ 'tooltip' => 'Allows you to upload SVG Images. Many icons come with SVG versions of the icons. Using an SVG means it is easier to size the icons. With images like .png and .gif you need to manually size them in a graphics program.'
+ ),
+
+ 'use-svg' => array(
+ 'name' => 'use-svg',
+ 'label' => 'Use SVG?',
+ 'type' => 'checkbox',
+ 'tooltip' => 'If you would like to upload SVG images check this option',
+ 'default' => false,
+ 'toggle' => array(
+ 'true' => array(
+ 'show' => array(
+ '#input-svg-width',
+ '#input-svg-height'
+ )
+ ),
+ 'false' => array(
+ 'hide' => array(
+ '#input-svg-width',
+ '#input-svg-height'
+ )
+ )
+ ),
+ ),
+
+ 'svg-width' => array(
+ 'type' => 'text',
+ 'name' => 'svg-width',
+ 'label' => 'SVG Image Width',
+ 'tooltip' => 'Set the width of all SVG\'s in the block. This also controls the width with a 1:1 ratio'
+ )
+
+ ),
+
+ 'custom-icons-set' => array(
+ 'icons' => array(
+ 'type' => 'repeater',
+ 'name' => 'icons',
+ 'label' => 'Icons',
+ 'inputs' => array(
+ array(
+ 'type' => 'image',
+ 'name' => 'image',
+ 'label' => 'Image',
+ 'default' => null
+ ),
+
+ array(
+ 'type' => 'text',
+ 'name' => 'image-title',
+ 'label' => '"title"',
+ 'tooltip' => 'This will be used as the "title" attribute for the image. The title attribute is beneficial for SEO (Search Engine Optimization) and will allow your visitors to move their mouse over the image and read about it.'
+ ),
+
+ array(
+ 'type' => 'text',
+ 'name' => 'image-alt',
+ 'label' => '"alt"',
+ 'tooltip' => 'This will be used as the "alt" attribute for the image. The alt attribute is <em>hugely</em> beneficial for SEO (Search Engine Optimization) and for general accessibility.'
+ ),
+
+ array(
+ 'name' => 'link-heading',
+ 'type' => 'heading',
+ 'label' => 'Link Image'
+ ),
+
+ array(
+ 'name' => 'link-url',
+ 'label' => 'Link URL?',
+ 'type' => 'text',
+ 'tooltip' => 'Set the URL for the image to link to'
+ ),
+
+ array(
+ 'name' => 'link-alt',
+ 'label' => '"alt"',
+ 'type' => 'text',
+ 'tooltip' => 'Set alternative text for the link'
+ ),
+
+ array(
+ 'name' => 'link-target',
+ 'label' => 'New window?',
+ 'type' => 'checkbox',
+ 'tooltip' => 'If you would like to open the link in a new window check this option',
+ 'default' => false,
+ )
+
+ ),
+ 'tooltip' => 'Upload the images that you would like to add to the image block.',
+ 'sortable' => true,
+ 'limit' => false
+ ),
+ ),
+ );
+
+ public function modify_arguments($args = false) {
+
+ $block = $args['block'];
+
+ $icon_set = HeadwayBlockAPI::get_setting($block, 'icon-set', 'peel-icons');
+
+ foreach ( self::get_icon_sets() as $icon_set => $icon_set_name ) {
+
+ if ( $icon_set == 'custom' )
+ continue;
+
+ $this->tabs[$icon_set . '-set'] = ucwords(str_replace('-', ' ', $icon_set));
+
+ $this->inputs[$icon_set . '-set'] = array(
+ 'icons'.$icon_set => array(
+ 'type' => 'repeater',
+ 'name' => 'icons' . $icon_set,
+ 'label' => 'Icons',
+ 'inputs' => array(
+ array(
+ 'type' => 'select',
+ 'name' => 'network',
+ 'label' => 'Network',
+ 'default' => null,
+ 'options' => self::get_icons($block)
+ ),
+
+ array(
+ 'type' => 'text',
+ 'name' => 'image-title',
+ 'label' => '"title"',
+ 'tooltip' => 'This will be used as the "title" attribute for the image. The title attribute is beneficial for SEO (Search Engine Optimization) and will allow your visitors to move their mouse over the image and read about it.'
+ ),
+
+ array(
+ 'type' => 'text',
+ 'name' => 'image-alt',
+ 'label' => '"alt"',
+ 'tooltip' => 'This will be used as the "alt" attribute for the image. The alt attribute is <em>hugely</em> beneficial for SEO (Search Engine Optimization) and for general accessibility.'
+ ),
+
+ array(
+ 'name' => 'link-heading',
+ 'type' => 'heading',
+ 'label' => 'Link Image'
+ ),
+
+ array(
+ 'name' => 'link-url',
+ 'label' => 'Link URL?',
+ 'type' => 'text',
+ 'tooltip' => 'Set the URL for the image to link to'
+ ),
+
+ array(
+ 'name' => 'link-alt',
+ 'label' => '"alt"',
+ 'type' => 'text',
+ 'tooltip' => 'Set alternative text for the link'
+ ),
+
+ array(
+ 'name' => 'link-target',
+ 'label' => 'New window?',
+ 'type' => 'checkbox',
+ 'tooltip' => 'If you would like to open the link in a new window check this option',
+ 'default' => false,
+ )
+
+ ),
+ 'tooltip' => 'Upload the images that you would like to add to the image block.',
+ 'sortable' => true,
+ 'limit' => false
+ )
+ );
+
+ }
+
+ }
+
+ public static function get_icon_sets() {
+
+ $path = HEADWAY_LIBRARY_DIR.'/blocks/social/icons';
+ $results = scandir($path);
+
+ $icons_options = array();
+
+ foreach ($results as $result) {
+
+ if ( $result === '.' || $result === '..' || $result === '.DS_Store') {
+ continue;
+ }
+
+ if ( is_dir($path . '/' . $result) ) {
+ $icons_options[$result] = ucwords(str_replace('-', ' ', $result));
+ }
+
+ }
+
+ $icons_options['custom'] = 'Custom Icons';
+
+ return $icons_options;
+
+ }
+
+ public static function get_icons($block) {
+
+ $icon_set = HeadwayBlockAPI::get_setting($block, 'icon-set', 'peel-icons');
+
+ if ($icon_set != 'custom') {
+
+ $path = HEADWAY_LIBRARY_DIR.'/blocks/social/icons/' . $icon_set . '/';
+
+ $results = scandir($path);
+
+ foreach ($results as $result) {
+ if ($result === '.' or $result === '..' or $result === '.DS_Store') continue;
+
+ if (!is_dir($path . '/' . $result)) {
+
+ $icons[$result] = preg_replace("/\\.[^.\\s]{3,4}$/", "", $result);
+
+ }
+ }
+
+ return $icons;
+ }
+ }
+
+}
--- /dev/null
+<?php
+headway_register_block('HeadwayTextBlock', headway_url() . '/library/blocks/text');
+
+class HeadwayTextBlock extends HeadwayBlockAPI {
+
+
+ public $id = 'text';
+
+ public $name = 'Text';
+
+ public $options_class = 'HeadwayTextBlockOptions';
+
+ public $description = 'Use the built-in rich text editor to insert titles, text, and more!';
+
+
+ function content($block) {
+
+ $content = parent::get_setting($block, 'content');
+
+ echo '<div class="entry-content">';
+ if ( $content != null )
+ echo do_shortcode(stripslashes($content));
+ else
+ echo '<p>There is no content to display.</p>';
+ echo '</div><!-- .entry-content -->';
+
+ }
+
+
+ function setup_elements() {
+
+ $this->register_block_element(array(
+ 'id' => 'text',
+ 'name' => 'Text',
+ 'selector' => '.entry-content',
+ 'properties' => array('fonts', 'padding'),
+ 'inspectable' => false
+ ));
+
+ $this->register_block_element(array(
+ 'id' => 'strong',
+ 'parent' => 'text',
+ 'name' => 'Bold text',
+ 'description' => '<strong>',
+ 'selector' => 'div.entry-content strong'
+ ));
+
+ $this->register_block_element(array(
+ 'id' => 'emphasized',
+ 'parent' => 'text',
+ 'name' => 'Italic text',
+ 'selector' => 'div.entry-content em'
+ ));
+
+ $this->register_block_element(array(
+ 'id' => 'paragraphs',
+ 'name' => 'Paragraphs',
+ 'selector' => '.entry-content p'
+ ));
+
+ $this->register_block_element(array(
+ 'id' => 'paragraphs-first',
+ 'parent' => 'paragraphs',
+ 'name' => 'First Paragraphs',
+ 'selector' => '.entry-content p:first-of-type',
+ 'inspectable' => false
+ ));
+
+ $this->register_block_element(array(
+ 'id' => 'paragraphs-last',
+ 'parent' => 'paragraphs',
+ 'name' => 'Last Paragraphs',
+ 'selector' => '.entry-content p:last-of-type',
+ 'inspectable' => false
+ ));
+
+ $this->register_block_element(array(
+ 'id' => 'hyperlinks',
+ 'name' => 'Hyperlinks',
+ 'selector' => '.entry-content a',
+ 'properties' => array('fonts'),
+ 'states' => array(
+ 'Hover' => '.entry-content a:hover',
+ 'Clicked' => '.entry-content a:active'
+ )
+ ));
+
+ $this->register_block_element(array(
+ 'id' => 'heading',
+ 'name' => 'Headings',
+ 'description' => '<H3>, <H2>, <H1>',
+ 'selector' => '.entry-content h3, div.entry-content h2, div.entry-content h1'
+ ));
+
+ $this->register_block_element(array(
+ 'id' => 'heading-h1',
+ 'parent' => 'heading',
+ 'name' => 'Heading 1',
+ 'description' => '<H1>',
+ 'selector' => 'div.entry-content h1'
+ ));
+
+ $this->register_block_element(array(
+ 'id' => 'heading-h2',
+ 'parent' => 'heading',
+ 'name' => 'Heading 2',
+ 'description' => '<H2>',
+ 'selector' => 'div.entry-content h2'
+ ));
+
+ $this->register_block_element(array(
+ 'id' => 'heading-h3',
+ 'parent' => 'heading',
+ 'name' => 'Heading 3',
+ 'description' => '<H3>',
+ 'selector' => 'div.entry-content h3'
+ ));
+
+ $this->register_block_element(array(
+ 'id' => 'sub-heading',
+ 'name' => 'Sub Heading',
+ 'description' => '<H4>',
+ 'selector' => '.entry-content h4'
+ ));
+
+ $this->register_block_element(array(
+ 'id' => 'image',
+ 'name' => 'Images',
+ 'selector' => 'div.entry-content img'
+ ));
+
+ $this->register_block_element(array(
+ 'id' => 'form',
+ 'name' => 'Forms',
+ 'selector' => 'div.entry-content form'
+ ));
+
+ $this->register_block_element(array(
+ 'id' => 'buttons',
+ 'name' => 'Button',
+ 'parent' => 'form',
+ 'selector' => '
+ .entry-content input[type="submit"],
+ .entry-content input[type="button"],
+ .entry-content button,
+ .entry-content .button',
+ 'states' => array(
+ 'Hover' => '
+ .entry-content input[type="submit"]:hover,
+ .entry-content input[type="button"]:hover,
+ .entry-content button:hover,
+ .entry-content .button:hover',
+ 'Active' => '
+ .entry-content input[type="submit"]:active,
+ .entry-content input[type="button"]:active,
+ .entry-content button:active,
+ .entry-content .button:active',
+ )
+ ));
+
+ $this->register_block_element(array(
+ 'id' => 'inputs',
+ 'name' => 'Inputs',
+ 'parent' => 'form',
+ 'selector' => '
+ .entry-content input[type="text"],
+ .entry-content input[type="password"],
+ .entry-content input[type="email"],
+ .entry-content textarea,
+ .entry-content select',
+ 'states' => array(
+ 'Focus' => '
+ .entry-content input[type="text"]:focus,
+ .entry-content input[type="password"]:focus,
+ .entry-content input[type="email"]:focus,
+ .entry-content textarea:focus'
+ )
+ ));
+
+
+ }
+
+
+}
+
+
+class HeadwayTextBlockOptions extends HeadwayBlockOptionsAPI {
+
+ public $tabs = array(
+ 'content' => 'Content'
+ );
+
+ public $inputs = array(
+ 'content' => array(
+ 'content' => array(
+ 'type' => 'wysiwyg',
+ 'name' => 'content',
+ 'label' => 'Content',
+ 'default' => null
+ )
+ )
+ );
+
+}
\ No newline at end of file
--- /dev/null
+<?php
+
+headway_register_block('HeadwayWidgetAreaBlock', headway_url() . '/library/blocks/widget-area');
+
+class HeadwayWidgetAreaBlock extends HeadwayBlockAPI {
+
+ public $id = 'widget-area';
+
+ public $name = 'Widget Area';
+
+ public $options_class = 'HeadwayWidgetAreaBlockOptions';
+
+ public $html_tag = 'aside';
+
+ public $attributes = array(
+ 'itemscope' => '',
+ 'itemtype' => 'http://schema.org/WPSideBar'
+ );
+
+ public $description = 'Used typically as a sidebar or to aid the footer. The widget area will display WordPress widgets which are managed in the WordPress Appearance » Widgets panel.';
+
+ public static function init_action($block_id, $block) {
+
+ $widget_area_name = HeadwayBlocksData::get_block_name($block) . ' — ' . 'Layout: ' . HeadwayLayout::get_name($block['layout']);
+
+ $widget_area = array(
+ 'name' => $widget_area_name,
+ 'id' => 'widget-area-' . $block['id'],
+ 'before_widget' => '<li id="%1$s" class="widget %2$s">' . "\n",
+ 'after_widget' => '</li><!-- .widget -->' . "\n",
+ 'before_title' => '<h3 class="widget-title"><span class="widget-inner">',
+ 'after_title' => '</span></h3>' . "\n",
+ );
+
+ register_sidebar($widget_area);
+
+ }
+
+
+ function setup_elements() {
+
+ $this->register_block_element(array(
+ 'id' => 'widget',
+ 'name' => 'Widget',
+ 'selector' => 'li.widget'
+ ));
+
+ $this->register_block_element(array(
+ 'id' => 'widget-title',
+ 'name' => 'Widget Title',
+ 'selector' => 'li.widget .widget-title'
+ ));
+
+ $this->register_block_element(array(
+ 'id' => 'widget-title-inner',
+ 'name' => 'Widget Title Inner',
+ 'selector' => 'li.widget .widget-title span'
+ ));
+
+ $this->register_block_element(array(
+ 'id' => 'widget-links',
+ 'name' => 'Widget Links',
+ 'selector' => 'li.widget a',
+ 'states' => array(
+ 'Selected' => 'ul li.current_page_item a',
+ 'Hover' => 'ul li a:hover',
+ 'Clicked' => 'ul li a:active'
+ )
+ ));
+
+ $this->register_block_element(array(
+ 'id' => 'widget-lists',
+ 'name' => 'Widget Lists',
+ 'description' => '<UL>',
+ 'selector' => 'li.widget ul',
+ 'properties' => array('fonts', 'lists', 'background', 'borders', 'padding', 'corners', 'box-shadow'),
+ ));
+
+ $this->register_block_element(array(
+ 'id' => 'widget-list-items',
+ 'name' => 'Widget List Items',
+ 'description' => '<LI>',
+ 'selector' => 'li.widget ul li'
+ ));
+
+ }
+
+
+ function modify_default_widget_title( $title, $instance, $id_base ) {
+
+ if ( isset( $instance['title'] ) )
+ return $instance['title'];
+
+ return $title;
+
+ }
+
+
+ function content($block) {
+
+ /* Use legacy ID */
+ $block['id'] = HeadwayBlocksData::get_legacy_id( $block );
+
+ echo ( parent::get_setting( $block, 'horizontal-widgets' ) == true ) ? '<ul class="widget-area horizontal-sidebar">' : '<ul class="widget-area">';
+
+ if ( !function_exists('dynamic_sidebar') || !dynamic_sidebar('widget-area-' . $block['id']) ) {
+
+ global $sidebars_widgets, $wp_widget_factory;
+
+ $default_widgets = parent::get_setting( $block, 'default-widgets', array() );
+
+ if ( !empty($default_widgets) && empty($sidebars_widgets['widget-area-' . $block['id']]) ) {
+
+ add_filter( 'widget_title', array( $this, 'modify_default_widget_title' ), 10, 3 );
+
+ foreach ( $default_widgets as $default_widget ) {
+
+ /* check if the widget exists and set widget_obj variable */
+ if ( !is_object( $widget_obj = headway_get( $default_widget['widget'], $wp_widget_factory->widgets ) ) )
+ continue;
+
+ /* Widget Instance Parameters */
+ $instance = array();
+
+ if ( !headway_get('show-title', $default_widget, true, true) ) {
+ $instance['title'] = false;
+ } else if ( $default_widget['title'] != '%default%' ) {
+ $instance['title'] = $default_widget['title'];
+ } else {
+ $instance['title'] = $widget_obj->name;
+ }
+
+ /* WooCommerce fixes */
+ if ( stripos( $default_widget['widget'], 'WC_' ) !== false ) {
+
+ $instance += array(
+ 'number' => 5,
+ 'count' => '1',
+ 'hierarchical' => true,
+ 'dropdown' => '1',
+ 'show_variations' => true
+ );
+
+ }
+
+ the_widget(
+ $default_widget['widget'],
+ $instance,
+ array(
+ 'widget_id' => 1,// woocommerce fix
+ 'before_widget' => '<li class="widget ' . $widget_obj->widget_options['classname'] . '">' . "\n",
+ 'after_widget' => '</li><!-- .widget -->' . "\n",
+ 'before_title' => '<h3 class="widget-title"><span class="widget-inner">',
+ 'after_title' => '</span></h3>' . "\n",
+ )
+ );
+
+ }
+
+ } else {
+
+ echo '<li class="widget widget-no-widgets">';
+ echo '<h3 class="widget-title"><span class="widget-inner">No widgets!</span></h3>';
+ echo '<p>Add widgets to this sidebar in the <a href="' . admin_url('widgets.php') . '">Widgets panel</a> under Appearance in the WordPress Admin.</p>';
+ echo '</li>';
+
+ }
+
+ }
+
+ echo '</ul>';
+
+ }
+
+}
+
+
+class HeadwayWidgetAreaBlockOptions extends HeadwayBlockOptionsAPI {
+
+
+ public $tabs = array(
+ 'widget-area-content' => 'Content',
+ 'widget-layout' => 'Widget Layout'
+ );
+
+
+ public $inputs = array(
+ 'widget-layout' => array(
+ 'horizontal-widgets' => array(
+ 'type' => 'checkbox',
+ 'name' => 'horizontal-widgets',
+ 'label' => 'Horizontal Widgets',
+ 'default' => false,
+ 'tooltip' => 'Instead of showing widgets vertically, you can make them span horizontally. This is especially useful for widgetized footers.'
+ )
+ )
+ );
+
+
+ function modify_arguments($args = false) {
+
+ global $sidebars_widgets;
+
+ $sidebar_id = 'widget-area-' . $args['block_id'];
+
+ $this->tab_notices['widget-area-content'] = 'To add widgets to this widget area, go to <a href="' . admin_url('widgets.php') . '" target="_blank">WordPress Admin » Appearance » Widgets</a> and add the widgets to <em>' . HeadwayBlocksData::get_block_name( $args['block'] ) . ' — ' . 'Layout: ' . HeadwayLayout::get_name( $args['layoutID'] ) . '</em>.';
+
+ /* don't show the default widgets options if it is not going to serve any purpose */
+ if ( empty($sidebars_widgets[$sidebar_id]) ) :
+
+ $this->tabs = array_merge( $this->tabs, array( 'widget-default' => 'Default Widgets' ) );
+
+ $this->inputs['widget-default']['default-widgets'] = array(
+ 'type' => 'repeater',
+ 'name' => 'default-widgets',
+ 'label' => 'Default Widgets',
+ 'tooltip' => 'Assign default widgets to this widget area.',
+ 'inputs' => array(
+ array(
+ 'type' => 'select',
+ 'name' => 'widget',
+ 'label' => 'Widget',
+ 'default' => array( 'pages' ),
+ 'options' => 'get_widgets()',
+ ),
+ array(
+ 'type' => 'checkbox',
+ 'name' => 'show-title',
+ 'label' => 'Show Title',
+ 'default' => true,
+ 'toggle' => array(
+ 'true' => array(
+ 'show' => '#input-title'
+ ),
+ 'false' => array(
+ 'hide' => '#input-title'
+ )
+ )
+ ),
+ array(
+ 'type' => 'text',
+ 'name' => 'title',
+ 'label' => 'Title',
+ 'default' => '%default%',
+ 'tootlip' => 'This will be the title shown above the widget. If you want to use the default for the widget type, please enter <em>%default%</em>'
+ )
+ ),
+ 'sortable' => true
+ );
+
+ endif;
+
+ }
+
+
+ function get_widgets() {
+
+ global $wp_widget_factory;
+
+ if ( !isset($wp_widget_factory->widgets) )
+ return;
+
+ $options = array();
+
+ foreach ( $wp_widget_factory->widgets as $class => $widgets )
+ $options[$class] = $widgets->name;
+
+ return array_merge( array( '' => 'Make a Selection' ), $options);
+
+ }
+
+}
\ No newline at end of file
--- /dev/null
+<?php
+/**
+ * All of the global functions to be used everywhere in Headway.
+ *
+ * @package Headway
+ * @author Clay Griffiths
+ **/
+
+class Headway {
+
+
+ public static $loaded_classes = array();
+
+
+ /**
+ * Let's get Headway on the road! We'll define constants here, run the setup function and do a few other fun things.
+ *
+ * @return void
+ **/
+ public static function init() {
+
+ global $wpdb;
+
+ /* Legacy element default handling */
+ $GLOBALS['headway_default_element_data'] = array();
+
+ /* Define simple constants */
+ define('THEME_FRAMEWORK', 'headway');
+ define('HEADWAY_VERSION', '3.7.8');
+
+ /* Define directories */
+ define('HEADWAY_DIR', headway_change_to_unix_path(TEMPLATEPATH));
+ define('HEADWAY_LIBRARY_DIR', headway_change_to_unix_path(HEADWAY_DIR . '/library'));
+
+ /* Site URLs */
+ define('HEADWAY_SITE_URL', 'http://headwaythemes.com/');
+ define('HEADWAY_DASHBOARD_URL', HEADWAY_SITE_URL . 'dashboard');
+ define('HEADWAY_EXTEND_URL', HEADWAY_SITE_URL . 'extend');
+
+ /* Skins */
+ define('HEADWAY_DEFAULT_SKIN', 'base');
+
+ /* MySQL Table names */
+ $wpdb->hw_blocks = $wpdb->prefix . 'hw_blocks';
+ $wpdb->hw_wrappers = $wpdb->prefix . 'hw_wrappers';
+ $wpdb->hw_snapshots = $wpdb->prefix . 'hw_snapshots';
+ $wpdb->hw_layout_meta = $wpdb->prefix . 'hw_layout_meta';
+
+ /* Handle child themes */
+ if ( get_template_directory_uri() !== get_stylesheet_directory_uri() )
+ define('HEADWAY_CHILD_THEME_ACTIVE', true);
+ else
+ define('HEADWAY_CHILD_THEME_ACTIVE', false);
+
+ /* Handle uploads directory and cache */
+ $uploads = wp_upload_dir();
+
+ define('HEADWAY_UPLOADS_DIR', headway_change_to_unix_path($uploads['basedir'] . '/headway'));
+ define('HEADWAY_CACHE_DIR', headway_change_to_unix_path(HEADWAY_UPLOADS_DIR . '/cache'));
+
+ /* Make directories if they don't exist */
+ if ( !is_dir(HEADWAY_UPLOADS_DIR) )
+ wp_mkdir_p(HEADWAY_UPLOADS_DIR);
+
+ if ( !is_dir(HEADWAY_CACHE_DIR) )
+ wp_mkdir_p(HEADWAY_CACHE_DIR);
+
+ /* Load locale */
+ load_theme_textdomain('headway', headway_change_to_unix_path(HEADWAY_LIBRARY_DIR . '/languages'));
+
+ /* Add support for WordPress features */
+ add_action('after_setup_theme', array(__CLASS__, 'add_theme_support'), 1);
+
+ /* Setup */
+ add_action('after_setup_theme', array(__CLASS__, 'child_theme_setup'), 2);
+ add_action('after_setup_theme', array(__CLASS__, 'load_dependencies'), 3);
+ add_action('after_setup_theme', array(__CLASS__, 'maybe_db_upgrade'));
+ add_action('after_setup_theme', array(__CLASS__, 'initiate_updater'));
+
+ /* Gzip */
+ add_action('wp', 'headway_gzip');
+
+ }
+
+
+ /**
+ * Loads all of the required core classes and initiates them.
+ *
+ * Dependency array setup: class (string) => init (bool)
+ **/
+ public static function load_dependencies() {
+
+ //Load route right away so we can optimize dependency loading below
+ Headway::load(array('common/route' => true));
+
+ //Core loading set
+ $dependencies = array(
+ 'defaults/default-design-settings',
+
+ 'data/data-options' => 'Option',
+ 'data/data-layout-options' => 'LayoutOption',
+ 'data/data-skin-options',
+ 'data/data-blocks',
+ 'data/data-wrappers',
+ 'data/data-snapshots',
+
+ 'common/layout' => true,
+ 'common/capabilities' => true,
+ 'common/responsive-grid' => true,
+ 'common/seo' => true,
+ 'common/social-optimization' => true,
+ 'common/feed' => true,
+ 'common/compiler' => true,
+ 'common/templates',
+
+ 'admin/admin-bar' => true,
+
+ 'api/api-panel',
+
+ 'updater/plugin-updater',
+ 'updater/theme-updater',
+
+ 'blocks' => true,
+ 'wrappers' => true,
+ 'elements' => true,
+
+ 'fonts/web-fonts-api',
+ 'fonts/web-fonts-loader' => true,
+ 'fonts/traditional-fonts',
+ 'fonts/google-fonts',
+
+ 'display' => true,
+
+ 'widgets' => true,
+
+ 'compatibility/woocommerce/compatibility-woocommerce' => 'CompatibilityWooCommerce'
+ );
+
+ //Child theme API
+ if ( HEADWAY_CHILD_THEME_ACTIVE === true )
+ $dependencies['api/api-child-theme'] = 'ChildThemeAPI';
+
+ //Visual editor classes
+ if ( HeadwayRoute::is_visual_editor() || (defined('DOING_AJAX') && DOING_AJAX) )
+ $dependencies['visual-editor'] = true;
+
+ //Admin classes
+ if ( is_admin() )
+ $dependencies['admin'] = true;
+
+ //Load stuff now
+ Headway::load(apply_filters('headway_dependencies', $dependencies));
+
+ do_action('headway_setup');
+
+ }
+
+
+ /**
+ * Tell WordPress that Headway supports its features.
+ **/
+ public static function add_theme_support() {
+
+ /* Headway Functionality */
+ add_theme_support( 'headway-grid' );
+ add_theme_support( 'headway-responsive-grid' );
+ add_theme_support( 'headway-design-editor' );
+
+ /* Headway CSS */
+ add_theme_support( 'headway-reset-css' );
+ add_theme_support( 'headway-live-css' );
+ add_theme_support( 'headway-block-basics-css' );
+ add_theme_support( 'headway-dynamic-block-css' );
+ add_theme_support( 'headway-content-styling-css' );
+
+ /* WordPress Functionality */
+ add_theme_support( 'html5', array( 'caption' ) );
+ add_theme_support( 'post-thumbnails' );
+ add_theme_support( 'menus' );
+ add_theme_support( 'widgets' );
+ add_theme_support( 'editor-style' );
+ add_theme_support( 'automatic-feed-links' );
+
+ /* Loop Standard by PluginBuddy */
+ require_once HEADWAY_LIBRARY_DIR . '/resources/dynamic-loop.php';
+ add_theme_support('loop-standard');
+
+ }
+
+
+ /**
+ **/
+ public static function child_theme_setup() {
+
+ if ( !HEADWAY_CHILD_THEME_ACTIVE )
+ return false;
+
+ do_action('headway_setup_child_theme');
+
+ }
+
+
+ /**
+ * This will process upgrades from one version to another.
+ **/
+ public static function maybe_db_upgrade() {
+
+ $headway_settings = get_option('headway', array('version' => 0));
+ $db_version = $headway_settings['version'];
+
+ /* If this is a fresh install then we need to merge in the default design editor settings */
+ if ( $db_version === 0 && !get_option('headway_option_group_general') ) {
+
+ HeadwayElementsData::merge_core_default_design_data();
+
+ self::mysql_dbdelta();
+
+ /* Update the version here. */
+ $headway_settings = get_option('headway', array('version' => 0));
+ $headway_settings['version'] = HEADWAY_VERSION;
+
+ update_option('headway', $headway_settings);
+
+ return $headway_settings;
+
+ }
+
+ /* If the version in the database is already up to date, then there are no upgrade functions to be ran. */
+ if ( version_compare($db_version, HEADWAY_VERSION, '>=') )
+ return false;
+
+ Headway::load('maintenance/upgrades');
+
+ return HeadwayMaintenance::do_upgrades();
+
+ }
+
+
+ public static function mysql_drop_tables() {
+
+ global $wpdb;
+
+ /* Drop tables first */
+ $wpdb->query( "DROP TABLE IF EXISTS $wpdb->hw_blocks" );
+ $wpdb->query( "DROP TABLE IF EXISTS $wpdb->hw_wrappers" );
+ $wpdb->query( "DROP TABLE IF EXISTS $wpdb->hw_layout_meta" );
+ $wpdb->query( "DROP TABLE IF EXISTS $wpdb->hw_snapshots" );
+
+ }
+
+ public static function mysql_dbdelta() {
+
+ global $wpdb;
+
+ require_once( ABSPATH . 'wp-admin/includes/upgrade.php' );
+
+ $charset_collate = 'DEFAULT CHARACTER SET utf8';
+
+ if ( ! empty($wpdb->collate ) ) {
+ $charset_collate .= " COLLATE $wpdb->collate";
+ }
+
+ $hw_blocks_sql = "CREATE TABLE $wpdb->hw_blocks (
+ id char(20) NOT NULL,
+ template varchar(100) NOT NULL,
+ layout varchar(80) NOT NULL,
+ type varchar(30) NOT NULL,
+ wrapper_id char(20) NOT NULL,
+ position blob NOT NULL,
+ dimensions blob NOT NULL,
+ settings mediumblob,
+ mirror_id char(20) DEFAULT NULL,
+ legacy_id int(11) unsigned DEFAULT NULL,
+ PRIMARY KEY (id,template),
+ KEY layout (layout),
+ KEY type (type)
+ ) $charset_collate;";
+
+ dbDelta($hw_blocks_sql);
+
+
+ $hw_wrappers_sql = "CREATE TABLE $wpdb->hw_wrappers (
+ id char(20) NOT NULL,
+ template varchar(100) NOT NULL,
+ layout varchar(80) NOT NULL,
+ position tinyint(2) unsigned DEFAULT NULL,
+ settings mediumblob,
+ mirror_id char(20) DEFAULT NULL,
+ legacy_id int(11) unsigned DEFAULT NULL,
+ PRIMARY KEY (id,template),
+ KEY layout (layout)
+ ) $charset_collate;";
+
+ dbDelta($hw_wrappers_sql);
+
+
+ $hw_layout_meta_sql = "CREATE TABLE $wpdb->hw_layout_meta (
+ meta_id bigint(20) unsigned NOT NULL AUTO_INCREMENT,
+ template varchar(100) NOT NULL,
+ layout varchar(80) NOT NULL,
+ meta_key varchar(255),
+ meta_value mediumblob,
+ PRIMARY KEY (meta_id,template),
+ KEY template (layout)
+ ) $charset_collate;";
+
+ dbDelta($hw_layout_meta_sql);
+
+
+ $hw_snapshots_sql = "CREATE TABLE $wpdb->hw_snapshots (
+ id int(11) unsigned NOT NULL AUTO_INCREMENT,
+ template varchar(100) NOT NULL,
+ timestamp datetime NOT NULL,
+ comments text,
+ data_wp_options longblob,
+ data_wp_postmeta longblob,
+ data_hw_layout_meta longblob,
+ data_hw_wrappers longblob,
+ data_hw_blocks longblob,
+ data_other longblob,
+ PRIMARY KEY (id),
+ KEY template (template)
+ ) $charset_collate;";
+
+ dbDelta($hw_snapshots_sql);
+
+ }
+
+
+ /**
+ * Initiate the HeadwayUpdaterAPI class for Headway itself.
+ **/
+ public static function initiate_updater() {
+
+ $GLOBALS['headway_updater'] = new Headway_Theme_Updater(array(
+ 'remote_api_url' => HEADWAY_SITE_URL,
+ 'version' => HEADWAY_VERSION,
+ 'license' => headway_get_license_key('headway'),
+ 'slug' => 'headway',
+ 'item_name' => 'Headway',
+ 'author' => 'Headway Themes'
+ ));
+
+ }
+
+
+ /**
+ * Here's our function to load classes and files when needed from the library.
+ **/
+ public static function load($classes, $init = false) {
+
+ //Build in support to either use array or a string
+ if ( !is_array($classes) ) {
+ $load[$classes] = $init;
+ } else {
+ $load = $classes;
+ }
+
+ $classes_to_init = array();
+
+ //Remove already loaded classes from the array
+ foreach ( Headway::$loaded_classes as $class ) {
+ unset($load[$class]);
+ }
+
+ foreach ( $load as $file => $init ) {
+
+ //Check if only value is used instead of both key and value pair
+ if ( is_numeric($file) ){
+ $file = $init;
+ $init = false;
+ }
+
+ //Handle anything with .php or a full path
+ if ( strpos($file, '.php') !== false )
+ require_once HEADWAY_LIBRARY_DIR . '/' . $file;
+
+ //Handle main-helpers such as admin, data, etc.
+ elseif ( strpos($file, '/') === false )
+ require_once HEADWAY_LIBRARY_DIR . '/' . $file . '/' . $file . '.php';
+
+ //Handle anything and automatically insert .php if need be
+ elseif ( strpos($file, '/') !== false )
+ require_once HEADWAY_LIBRARY_DIR . '/' . $file . '.php';
+
+ //Add the class to the main variable so we know that it has been loaded
+ Headway::$loaded_classes[] = $file;
+
+ //Set up init, if init is true, just figure out the class name from filename. If argument is string, use that.
+ if ( $init === true ) {
+
+ $class = array_reverse(explode('/', str_replace('.php', '', $file)));
+
+ //Check for hyphens/underscores and CamelCase it
+ $class = str_replace(' ', '', ucwords(str_replace('-', ' ', str_replace('_', ' ', $class[0]))));
+
+ $classes_to_init[] = $class;
+
+ } else if ( is_string($init) ) {
+
+ $classes_to_init[] = $init;
+
+ }
+
+ }
+
+ //Init everything after dependencies have been loaded
+ foreach($classes_to_init as $class){
+
+ if ( method_exists('Headway' . $class, 'init') ) {
+
+ call_user_func(array('Headway' . $class, 'init'));
+
+ } else {
+
+ trigger_error('Headway' . $class . '::init is not a valid method', E_USER_WARNING);
+
+ }
+
+ }
+
+ }
+
+
+ public static function get() {
+ _deprecated_function(__FUNCTION__, '3.1.3', 'headway_get()');
+ $args = func_get_args();
+ return call_user_func_array('headway_get', $args);
+ }
+
+
+ public static function post() {
+ _deprecated_function(__FUNCTION__, '3.1.3', 'headway_post()');
+ $args = func_get_args();
+ return call_user_func_array('headway_post', $args);
+ }
+
+
+}
\ No newline at end of file
--- /dev/null
+<?php
+class HeadwayCapabilities {
+
+
+ public static function init() {
+
+ add_filter('members_get_capabilities', 'HeadwayCapabilities::register');
+
+ }
+
+
+ public static function register($capabilities) {
+
+ $capabilities[] = 'headway_visual_editor';
+
+ return apply_filters('headway_capabilities', $capabilities);
+
+ }
+
+
+ public static function can_user($capability) {
+
+ if ( !function_exists('members_check_for_cap') )
+ return ( current_user_can('manage_options') || is_super_admin() );
+
+ return current_user_can($capability);
+
+ }
+
+
+ /**
+ * Checks if the user can access the visual editor.
+ *
+ * @uses headway_user_level()
+ * @uses HeadwayOption::get()
+ *
+ * @return bool
+ **/
+ public static function can_user_visually_edit($ignore_debug_mode = false) {
+
+ if ( !$ignore_debug_mode && HeadwayOption::get('debug-mode') )
+ return true;
+
+ return is_user_logged_in() && self::can_user('headway_visual_editor');
+
+ }
+
+
+}
\ No newline at end of file
--- /dev/null
+<?php
+global $pagenow, $wp_version;
+
+/* Do not throw these errors if DOING_AJAX is true or the themes page is already being viewed. */
+if ( (defined('DOING_AJAX') && DOING_AJAX) || $pagenow === 'themes.php' ) {
+
+ return;
+
+/* Check WordPress */
+} elseif ( version_compare($wp_version, '3.2', '<') ) {
+
+ $message = '
+ <span style="text-align: center;font-size: 26px;width: 100%;display: block;margin-bottom: 20px;">Error</span>
+
+ Headway requires WordPress 3.2 or higher. You are running WordPress ' . $wp_version . '.<br /><br />
+
+ Please deactivate Headway by going to <a href="' . admin_url('themes.php') . '">Appearance » Themes</a> and choosing a difference theme until your WordPress installation has been updated to 3.2 or higher.<br /><br />
+
+ If the issue persists, please visit <a href="http://support.headwaythemes.com" target="_blank">Headway Support</a>.
+ ';
+
+ wp_die($message);
+
+/* Check PHP */
+} elseif ( version_compare(PHP_VERSION, '5.2', '<') ) {
+
+ $message = '
+ <span style="text-align: center;font-size: 26px;width: 100%;display: block;margin-bottom: 20px;">Error</span>
+
+ Headway requires PHP 5.2 or higher, as does WordPress 3.2 and higher. You are running PHP ' . PHP_VERSION . '.<br /><br />
+
+ Please deactivate Headway by going to <a href="' . admin_url('themes.php') . '">Appearance » Themes</a> and choosing a difference theme until your PHP has been updated to 5.2 or higher.<br /><br />
+
+ If the issue persists, please contact your web host or visit <a href="http://support.headwaythemes.com" target="_blank">Headway Support</a>.
+ ';
+
+ wp_die($message);
+
+}
\ No newline at end of file
--- /dev/null
+<?php
+class HeadwayCompiler {
+
+
+ private static $accepted_formats = array('css', 'less', 'js');
+
+
+ public static function init() {
+
+ add_action('headway_visual_editor_save', array(__CLASS__, 'flush_cache'));
+ add_action('headway_visual_editor_reset_layout', array(__CLASS__, 'flush_cache'));
+ add_action('headway_visual_editor_delete_template', array(__CLASS__, 'flush_cache'));
+ add_action('headway_visual_editor_assign_template', array(__CLASS__, 'flush_cache'));
+ add_action('headway_visual_editor_unassign_template', array(__CLASS__, 'flush_cache'));
+
+ add_action('publish_post', array(__CLASS__, 'flush_cache'));
+ add_action('delete_post', array(__CLASS__, 'flush_cache'));
+
+ add_action('headway_switch_skin', array(__CLASS__, 'flush_cache'));
+
+ add_action('activate_plugin', array(__CLASS__, 'flush_cache_hard'));
+ add_action('deactivate_plugin', array(__CLASS__, 'flush_cache_hard'));
+ add_action('switch_theme', array(__CLASS__, 'flush_cache_hard'));
+
+ add_action('headway_db_upgrade', array(__CLASS__, 'flush_cache_hard'));
+ add_action('headway_activation', array(__CLASS__, 'flush_cache_hard'));
+ add_action('headway_global_reset', array(__CLASS__, 'flush_cache_hard'));
+
+ add_action('headway_snapshot_rollback', array(__CLASS__, 'flush_cache_hard'));
+
+ }
+
+
+ /**
+ * @param string
+ * @param string
+ * @param mixed
+ * @param bool
+ *
+ * @uses HeadwayCompiler::enqueue_file()
+ *
+ * @return bool
+ **/
+ public static function register_file($args) {
+
+ $defaults = array(
+ 'name' => null,
+ 'format' => null,
+ 'fragments' => array(),
+ 'dependencies' => array(),
+ 'footer-js' => true,
+ 'enqueue' => true,
+ 'require-hard-flush' => false,
+ 'iframe-cache' => false
+ );
+
+ $args = array_merge($defaults, $args);
+
+ if ( !$cache = get_transient('hw_compiler_template_' . HeadwayOption::$current_skin) )
+ $cache = array();
+
+ if ( is_ssl() )
+ $args['name'] = $args['name'] . '-https';
+
+ $args['fragments'] = array_map('headway_change_to_unix_path', $args['fragments']);
+ $args['dependencies'] = array_map('headway_change_to_unix_path', $args['dependencies']);
+
+ if ( !in_array($args['format'], self::$accepted_formats) )
+ wp_die('<strong>' . $args['format'] .'</strong> is not an accepted filetype for the HeadwayCompiler class.');
+
+ /* Prep possibly already cached settings for comparison */
+ $already_cached = isset($cache[$args['name']]) ? $cache[$args['name']] : array();
+
+ unset($already_cached['filename']);
+ unset($already_cached['hash']);
+
+ /* If file is not registered or fragments are not the same, add it to the DB. */
+ if ( $already_cached != $args ) {
+
+ $cache[$args['name']] = $args;
+
+ $cache[$args['name']]['filename'] = null;
+ $cache[$args['name']]['hash'] = null;
+
+ //Update cache option
+ if ( !set_transient('hw_compiler_template_' . HeadwayOption::$current_skin, $cache) )
+ return false;
+
+ }
+
+ /* Enqueue script */
+ if ( $args['enqueue'] )
+ return self::enqueue_file($args['name'], $args['footer-js']);
+
+ return true;
+
+ }
+
+
+ /**
+ * @param string
+ *
+ * @return string
+ **/
+ public static function enqueue_file($file, $footer_js = true) {
+
+ $cache = get_transient('hw_compiler_template_' . HeadwayOption::$current_skin);
+
+ if ( $cache[$file]['format'] == 'js' )
+ return wp_enqueue_script('headway-' . $file, self::get_url($file), false, false, false, $footer_js);
+ elseif ( $cache[$file]['format'] == 'css' || $cache[$file]['format'] == 'less' )
+ return wp_enqueue_style('headway-' . $file, self::get_url($file));
+
+ return false;
+
+ }
+
+
+ /**
+ * @param string
+ *
+ * @return string
+ **/
+ public static function get_url($file) {
+
+ $cache = get_transient('hw_compiler_template_' . HeadwayOption::$current_skin);
+
+ if ( is_ssl() && strpos($file, '-https') === false )
+ $file = $file . '-https';
+
+ //If the file isn't in the DB at all
+ if ( !isset($cache[$file]) )
+ return false;
+
+ //If cache exists
+ if (
+ self::caching_enabled() /* Make sure caching is enabled and possible */
+ && headway_get('filename', $cache[$file]) /* Filename in DB must be present */
+ && file_exists(HEADWAY_CACHE_DIR . '/' . headway_get('filename', $cache[$file])) /* Cached file must be present */
+ && !(HeadwayRoute::is_visual_editor_iframe() && !headway_get('iframe-cache', $cache[$file])) /* Either not be iframe or if is iframe, iframe-cache must be true */
+ ) {
+
+ return apply_filters('headway_compiler_file_url', headway_cache_url() . '/' . headway_get('filename', $cache[$file]));
+
+ //Cache doesn't exist
+ } else {
+
+ //If file doesn't exist, but we can still cache, let's cache the damn thing.
+ if ( self::caching_enabled() && !(HeadwayRoute::is_visual_editor_iframe() && !headway_get('iframe-cache', $cache[$file])) ) {
+
+ return self::cache_file($file) ? self::get_url($file) : null;
+
+ //No caching available, now we have to use fallback method.
+ } else {
+
+ $query_args = array(
+ 'headway-trigger' => 'compiler',
+ 'file' => $file,
+ 'layout-in-use' => HeadwayLayout::get_current_in_use(),
+ 'rand' => rand()
+ );
+
+ if ( HeadwayRoute::is_visual_editor_iframe() )
+ $query_args['visual-editor-open'] = 'true';
+
+ if ( HeadwayRoute::is_visual_editor_iframe() && headway_get('ve-preview') )
+ $query_args['ve-preview'] = 'true';
+
+ if ( HeadwayRoute::is_theme_preview() ) {
+ $query_args['preview'] = '1';
+ $query_args['template'] = 'headway';
+ $query_args['stylesheet'] = 'headway';
+ $query_args['preview_iframe'] = '1';
+ $query_args['TB_iframe'] = 'true';
+ }
+
+ return apply_filters('headway_compiler_trigger_url', add_query_arg($query_args, home_url('/')));
+
+ }
+
+ }
+
+ }
+
+
+ /**
+ * @param string
+ *
+ * @return bool
+ **/
+ public static function cache_file($file) {
+
+ $cache = get_transient('hw_compiler_template_' . HeadwayOption::$current_skin);
+
+ //Get the current layout here directly and set is as GET since the output trigger can use POST, but this cannot.
+ $_GET['layout-in-use'] = HeadwayLayout::get_current_in_use();
+ $_GET['compiler-cache'] = true;
+
+ $content = self::combine_fragments($cache[$file]);
+
+ //If existing cache file exists, delete it.
+ self::delete_cache_file($cache[$file]['filename']);
+
+ //Change LESS extension to CSS
+ $extension = $cache[$file]['format'] != 'less' ? $cache[$file]['format'] : 'css';
+
+ //If the file is set to only clear on a hard flush, then add that to the filename
+ $hard_cache_suffix = $cache[$file]['require-hard-flush'] ? '-hard-cache' : null;
+
+ //MD5 the contents that way we can check for differences down the road
+ $cache[$file]['hash'] = md5($content);
+ $cache[$file]['filename'] = $file . '-' . substr($cache[$file]['hash'], 0, 7) . $hard_cache_suffix . '.' . $extension;
+
+ //Build file
+ $file_handle = @fopen(HEADWAY_CACHE_DIR . '/' . $cache[$file]['filename'], 'w');
+
+ if ( !@fwrite($file_handle, $content) )
+ return false;
+
+ @chmod(HEADWAY_CACHE_DIR . '/' . $cache[$file]['filename'], 0755);
+
+ @fclose($file_handle);
+
+ set_transient('hw_compiler_template_' . HeadwayOption::$current_skin, $cache);
+
+ return true;
+
+ }
+
+
+ /**
+ * @return void
+ **/
+ public static function output_trigger() {
+
+ $file = headway_get('file');
+
+ //No GET parameter set
+ if ( !$file )
+ return false;
+
+ headway_gzip();
+
+ $cache = get_transient('hw_compiler_template_' . HeadwayOption::$current_skin);
+
+ //File does not exist
+ if ( !isset($cache[$file]))
+ return;
+
+ $format = $cache[$file]['format'];
+ $expires = 60 * 60 * 24 * 30;
+
+ header("Pragma: public");
+ header("Cache-Control: maxage=".$expires);
+ header('Expires: ' . gmdate('D, d M Y H:i:s', time()+$expires) . ' GMT');
+
+ if ( $format == 'css' || $format == 'less' )
+ header("Content-type: text/css");
+ elseif ( $format == 'js' )
+ header("content-type: application/x-javascript");
+
+ echo self::combine_fragments($cache[$file]);
+
+ }
+
+
+ /**
+ * @param array
+ * @param string
+ **/
+ public static function combine_fragments($file) {
+
+ extract($file);
+
+ $num_fragments = (int)count($fragments);
+
+ $data = '';
+
+ //Load dependencies if there are dependents
+ if ( is_array($dependencies) && count($dependencies) > 0 ) {
+
+ foreach ( $dependencies as $dependent ) {
+
+ if ( !is_file($dependent) )
+ continue;
+
+ include_once $dependent;
+
+ }
+
+ }
+
+ //Go through and merge the fragments
+ foreach ( $fragments as $fragment_key => $fragment ) {
+
+ //Determine if it's a function or file
+ if ( !is_array($fragment) && strpos($fragment, '.') !== false && strpos($fragment, '()') === false && file_exists($fragment) ) {
+
+ if ( filesize($fragment) === 0 )
+ continue;
+
+ $temp_handler = fopen($fragment, 'r');
+ $data .= fread($temp_handler, filesize($fragment));
+ fclose($temp_handler);
+
+ //It's a function
+ } else {
+
+ //Remove unneeded paratheses if is a string
+ if ( is_string($fragment) )
+ $fragment = str_replace('()', '', $fragment);
+
+ //Check if method or function
+ if ( !is_callable($fragment) )
+ continue;
+
+ $data .= call_user_func($fragment);
+
+ }
+
+ if ( $format == 'js' && count($fragments) > 1 )
+ $data .= "\n\n;";
+ else
+ $data .= "\n\n";
+
+ }
+
+ return self::format_content($data, $file);
+
+ }
+
+
+ /**
+ * @param string
+ * @param string
+ **/
+ public static function format_content($content, $file) {
+
+ extract($file);
+
+ //Remove whitespace if CSS
+ if ( $format == 'css' || $format == 'less' ) {
+
+ //Do LESS
+ if ( $format == 'less' ) {
+
+ if ( !class_exists('lessc') )
+ require_once HEADWAY_LIBRARY_DIR . '/resources/lessc.inc.php';
+
+ $less = new lessc(); // a blank lessc
+
+ try {
+
+ $content = $less->compile($content);
+
+ } catch (Exception $ex) {
+
+ return new WP_Error('headway_less_error', __('There was an error while Headway tried to compile the LESS CSS. Full Error: ', 'headway') . $ex->getMessage());
+
+ }
+
+ }
+
+ //Strip whitespace if set to do so
+ $content = self::strip_whitespace($content);
+
+ }
+
+ //Time to replace variables
+ $search = array(
+ '%HEADWAY_URL%',
+ '%HEADWAY_LIBRARY_URL%',
+ '%VISUALEDITOR%',
+ '%SITE_URL%',
+ '%HOME_URL%'
+ );
+
+ $replace = array(
+ headway_url(),
+ headway_url() . '/library',
+ headway_url() . '/library/visual-editor',
+ site_url(),
+ home_url()
+ );
+
+ $content = str_replace($search, $replace, $content);
+
+ //SSL URL fixing
+ if ( is_ssl() || strpos($file['name'], '-https') !== false )
+ $content = str_replace('http://', 'https://', $content);
+
+ return $content;
+
+ }
+
+
+ public static function strip_whitespace($content) {
+
+ if ( defined('HEADWAY_COMPILER_STRIP_WHITESPACE') && HEADWAY_COMPILER_STRIP_WHITESPACE === false )
+ return $content;
+
+ $replace = array(
+ "#/\*.*?\*/#s" => '', // Strip comments.
+ "#\s\s+#" => ' ', // Strip excess whitespace.
+ );
+
+ $search = array_keys($replace);
+ $content = preg_replace($search, $replace, $content);
+
+ $replace = array(
+ ": " => ":",
+ "; " => ";",
+ " {" => "{",
+ " }" => "}",
+ ", " => ",",
+ "{ " => "{",
+ ";}" => "}", // Strip optional semicolons.
+ ",\n" => ",", // Don't wrap multiple selectors.
+ "\n}" => "}", // Don't wrap closing braces.
+ "} " => "}\n", // Put each rule on it's own line.
+ "\n" => "" //Take out all line breaks
+ );
+
+ $search = array_keys($replace);
+
+ return trim(str_replace($search, $replace, $content));
+
+ }
+
+
+ /**
+ * @return bool
+ **/
+ public static function caching_enabled() {
+
+ //If cache is disabled from a constant, then return false
+ if ( defined('HEADWAY_DISABLE_CACHE') && HEADWAY_DISABLE_CACHE === true )
+ return false;
+
+ //Force cache set, try it no matter what
+ if ( defined('HEADWAY_FORCE_CACHE') && HEADWAY_FORCE_CACHE === true )
+ return true;
+
+ //WP_DEBUG is true, don't allow caching
+ if ( defined('WP_DEBUG') && WP_DEBUG === true )
+ return false;
+
+ //Caching is disabled... don't cache.
+ if ( HeadwayOption::get('disable-caching') )
+ return false;
+
+ //Cache folder doesn't exist or isn't writable, don't cache
+ if ( !self::can_cache() )
+ return false;
+
+ return true;
+
+ }
+
+
+ /**
+ * @return bool
+ **/
+ public static function can_cache() {
+
+ //Cache folder doesn't exist or isn't writable, don't cache
+ if ( !is_dir(HEADWAY_CACHE_DIR) || !is_writable(HEADWAY_CACHE_DIR) )
+ return false;
+
+ return true;
+
+ }
+
+
+ /**
+ * @return bool
+ **/
+ public static function flush_cache($hard = false) {
+
+ //Flush Headway cache if it is active.
+ if ( self::can_cache() ) {
+
+ //Delete the Headway cache option if hard flush otherwise delete the ones that aren't set to stay with soft flush
+ if ( $hard ) {
+
+ delete_transient('hw_compiler_template_' . HeadwayOption::$current_skin);
+
+ } else {
+
+ $cache = get_transient('hw_compiler_template_' . HeadwayOption::$current_skin);
+
+ if ( is_array($cache) ) {
+
+ foreach ( $cache as $cached_file_id => $cached_file )
+ if ( !headway_get('require-hard-flush', $cached_file, false) )
+ unset($cache[$cached_file_id]);
+
+ }
+
+ set_transient('hw_compiler_template_' . HeadwayOption::$current_skin, $cache);
+
+ }
+
+ //Set do not delete list
+ $no_delete = array(
+ '..',
+ '.'
+ );
+
+ if ( $handle = opendir(HEADWAY_CACHE_DIR) ) {
+
+ while (false !== ($file = readdir($handle)) ) {
+
+ if ( in_array($file, $no_delete) || (strpos($file, 'hard-cache') !== false && !$hard) )
+ continue;
+
+ @unlink(HEADWAY_CACHE_DIR . '/' . $file);
+
+ }
+
+ closedir($handle);
+
+ }
+
+ }
+
+ //Flush plugin caches
+ self::flush_plugin_caches();
+
+ //Flush WP object cache
+ wp_cache_flush();
+
+ return true;
+
+ }
+
+
+ public static function flush_cache_hard() {
+
+ return self::flush_cache(true);
+
+ }
+
+
+ /**
+ * @param string
+ * @param string
+ *
+ * @return bool
+ **/
+ public static function delete_cache_file($filename) {
+
+ if ( !$filename || !file_exists(HEADWAY_CACHE_DIR . '/' . $filename) )
+ return false;
+
+ return @unlink(HEADWAY_CACHE_DIR . '/' . $filename);
+
+ }
+
+
+ /**
+ * Check if W3 Total Cache or if WP Super Cache are running.
+ *
+ * @return bool
+ **/
+ public static function is_plugin_caching() {
+
+ if ( class_exists('W3_Plugin_TotalCache') )
+ return 'W3 Total Cache';
+
+ elseif ( function_exists('prune_super_cache'))
+ return 'WP Super Cache';
+
+ elseif ( class_exists( 'WpeCommon' ) )
+ return 'WPEngine';
+
+ elseif ( class_exists('GD_System_Plugin_Cache_Purge') )
+ return 'GoDaddy or MediaTemple';
+
+ else
+ return false;
+
+ }
+
+
+ /**
+ * Flush Super Cache and W3 Total Cache
+ *
+ * @return void
+ **/
+ public static function flush_plugin_caches() {
+
+ if ( function_exists('prune_super_cache') ) {
+
+ global $cache_path;
+ prune_super_cache($cache_path . 'supercache/', true );
+ prune_super_cache($cache_path, true );
+
+ }
+
+ if ( class_exists('W3_Plugin_TotalCache') ) {
+
+ if ( function_exists('w3_instance') )
+ $w3_plugin_totalcache =& w3_instance('W3_Plugin_TotalCache');
+ elseif ( is_callable(array('W3_Plugin_TotalCache', 'instance')) )
+ $w3_plugin_totalcache =& W3_Plugin_TotalCache::instance();
+
+ if ( method_exists($w3_plugin_totalcache, 'flush') )
+ $w3_plugin_totalcache->flush();
+ elseif ( method_exists($w3_plugin_totalcache, 'flush_all') )
+ $w3_plugin_totalcache->flush_all();
+
+ /* Flush varnish */
+ if ( function_exists('w3tc_varnish_flush') )
+ w3tc_varnish_flush();
+
+ }
+
+ if ( class_exists( 'WpeCommon' ) ) {
+
+ if ( method_exists( 'WpeCommon', 'purge_memcached' ) )
+ WpeCommon::purge_memcached();
+
+ if ( method_exists( 'WpeCommon', 'purge_varnish_cache' ) )
+ WpeCommon::purge_varnish_cache();
+
+ }
+
+ if ( class_exists('GD_System_Plugin_Cache_Purge') ) {
+
+ if ( method_exists( 'GD_System_Plugin_Cache_Purge', 'do_ban_cache' ) )
+ GD_System_Plugin_Cache_Purge::do_ban_cache();
+
+ }
+
+ }
+
+}
\ No newline at end of file
--- /dev/null
+<?php
+class HeadwayFeed {
+
+
+ public static function init() {
+
+ add_filter('feed_link', array(__CLASS__, 'feed_url'));
+
+ }
+
+
+ public static function feed_url($feed) {
+
+ //Do not change the URL of comment feed URLs.
+ if ( strpos($feed, 'comment') !== false )
+ return $feed;
+
+ $feed_url = HeadwayOption::get('feed-url');
+
+ //If the feed URL option doesn't have http[://] at the beginning, then we're a no go on changing the feed URL.
+ if ( !$feed_url || strpos($feed_url, 'http') !== 0 )
+ return $feed;
+
+ return $feed_url;
+
+ }
+
+
+}
\ No newline at end of file
--- /dev/null
+<?php
+/**
+ * Regular functions to be used throughout Headway. This file has absolutely no organizational pattern.
+ **/
+
+/**
+ * Returns the Headway License Key from the options or constant if define.
+ **/
+function headway_get_license_key($slug = false) {
+
+ if ( !$slug )
+ return false;
+
+ if ( defined('HEADWAY_LICENSE_KEY') && $slug == 'headway' )
+ return apply_filters('headway_license_key', trim(HEADWAY_LICENSE_KEY), $slug);
+
+ return apply_filters('headway_license_key', trim(HeadwayOption::get_from_main_site('license-key-' . $slug)), $slug);
+
+}
+
+
+function headway_get_license_status($slug = false) {
+
+ if ( !$slug )
+ return false;
+
+ return HeadwayOption::get_from_main_site('license-status-' . $slug);
+
+}
+
+
+function headway_activate_license($item_slug, $item_name = null) {
+
+ $license = headway_get_license_key($item_slug);
+
+ $api_params = array(
+ 'edd_action' => 'activate_license',
+ 'license' => $license,
+ 'item_name' => urlencode($item_name)
+ );
+
+ $response = wp_remote_get( add_query_arg( $api_params, HEADWAY_SITE_URL ), array( 'timeout' => 15, 'sslverify' => false ) );
+
+ if ( is_wp_error( $response ) ) {
+ return $response;
+ }
+
+ $license_data = json_decode( wp_remote_retrieve_body( $response ) );
+
+ // $license_data->license will be either "active" or "inactive"
+
+ HeadwayOption::set('license-status-' . $item_slug, $license_data->license);
+
+ return $license_data->license;
+
+}
+
+
+function headway_deactivate_license($item_slug, $item_name = null) {
+
+ $license = headway_get_license_key($item_slug);
+
+ $api_params = array(
+ 'edd_action' => 'deactivate_license',
+ 'license' => $license,
+ 'item_name' => urlencode($item_name)
+ );
+
+ $response = wp_remote_get( add_query_arg( $api_params, HEADWAY_SITE_URL ), array( 'timeout' => 15, 'sslverify' => false ) );
+
+ if ( is_wp_error( $response ) )
+ return false;
+
+ $license_data = json_decode( wp_remote_retrieve_body( $response ) );
+
+ // $license_data->license will be either "deactivated" or "failed"
+ if( $license_data->license == 'deactivated' )
+ HeadwayOption::delete('license-status-' . $item_slug);
+
+ return $license_data->license;
+
+}
+
+
+/**
+ * Attempt to unserialize string. If there's an error then do the preg_replace trick to correct the serialization.
+ *
+ * @param $string
+ */
+function headway_maybe_unserialize($data) {
+
+ try {
+
+ $result = maybe_unserialize($data);
+
+ } catch ( Exception $e ) {
+
+ if ( is_string($data) ) {
+
+ $data = preg_replace( '!s:(\d+):"(.*?)";!e', "'s:'.strlen('$2').':\"$2\";'", $data );
+ $result = maybe_unserialize( $data );
+
+ } else {
+
+ $result = $data;
+
+ }
+
+ }
+
+ return $result;
+
+}
+
+
+/**
+ * Wrapper of maybe_serialize() but does an is_serialized check first so it's not double serialized
+ */
+function headway_maybe_serialize($data) {
+
+ if ( is_serialized($data) )
+ return $data;
+
+ return maybe_serialize($data);
+
+}
+
+
+/**
+ * Simple alias for get_template_directory_uri()
+ *
+ * @uses get_template_directory_uri()
+ **/
+function headway_url() {
+
+ return apply_filters('headway_url', get_template_directory_uri());
+
+}
+
+
+/**
+ * @todo Document
+ **/
+ function headway_cache_url() {
+
+ $uploads = wp_upload_dir();
+
+ return apply_filters('headway_cache_url', headway_format_url_ssl($uploads['baseurl'] . '/headway/cache'));
+
+ }
+
+
+/**
+ * Starts the GZIP output buffer.
+ *
+ * @return bool
+ **/
+function headway_gzip() {
+
+ //If zlib is not loaded, we can't gzip.
+ if ( !extension_loaded('zlib') )
+ return false;
+
+ //If zlib.output_compression is on, do not gzip
+ if ( ini_get('zlib.output_compression') == 1 )
+ return false;
+
+ //If a cache system is active then do not gzip
+ if ( defined('WP_CACHE') && WP_CACHE )
+ return false;
+
+ //Allow headway_gzip filter to cancel gzip compression.
+ if ( !$gzip = apply_filters('headway_gzip', HeadwayOption::get('enable-gzip', false, true)) )
+ return false;
+
+ //If gzip has already happened, then just return.
+ if ( in_array('ob_gzhandler', ob_list_handlers()) )
+ return;
+
+ ob_start('ob_gzhandler');
+
+ return true;
+
+}
+
+
+/**
+ * A simple function to retrieve a key/value pair from the $_GET array or any other user-specified array. This will automatically return false if the key is not set.
+ *
+ * @param string Key to retrieve
+ * @param array Optional array to retrieve from. Default is $_GET
+ *
+ * @return mixed
+ **/
+function headway_get($name, $array = false, $default = null, $fix_data_type = false) {
+
+ if ( $array === false )
+ $array = $_GET;
+
+ if ( (is_string($name) || is_numeric($name)) && !is_float($name) ) {
+
+ if ( is_array($array) && isset($array[$name]) )
+ $result = $array[$name];
+ elseif ( is_object($array) && isset($array->$name) )
+ $result = $array->$name;
+
+ }
+
+ if ( !isset($result) )
+ $result = $default;
+
+ return !$fix_data_type ? $result : headway_fix_data_type($result);
+
+}
+
+
+/**
+ * Extension of headway_get(). Use this to fetch a key/value pair from the $_POST array.
+ *
+ * @uses headway_get()
+ *
+ * @param string Key to retrieve
+ *
+ * @return mixed
+ **/
+function headway_post($name, $default = null) {
+
+ return headway_get($name, $_POST, $default);
+
+}
+
+
+/**
+ * @todo Document
+ **/
+function headway_format_url_ssl($url) {
+
+ if ( !is_ssl() )
+ return $url;
+
+ return str_replace('http://', 'https://', $url);
+
+}
+
+
+/**
+ * Retrieves the current URL.
+ *
+ * @return string
+ **/
+function headway_get_current_url() {
+
+ $prefix = headway_get('HTTPS', $_SERVER) != 'on' ? 'http://' : 'https://';
+ $http_host = !isset($_SERVER['HTTP_X_FORWARDED_HOST']) ? $_SERVER['HTTP_HOST'] : $_SERVER['HTTP_X_FORWARDED_HOST'];
+
+ return $prefix . $http_host . $_SERVER['REQUEST_URI'];
+
+}
+
+
+/**
+ * @todo Document
+ **/
+function headway_change_to_unix_path($path) {
+
+ return str_replace('\\', '/', $path);
+
+}
+
+
+/**
+ * @todo Document
+ **/
+function headway_fix_data_type($data) {
+
+ if ( is_numeric($data) ) {
+
+ if ( floatval($data) == intval($data) )
+ return (int)$data;
+ else
+ return (float)$data;
+
+ } elseif ( $data === 'true' ) {
+
+ return true;
+
+ } elseif ( $data === 'false' ) {
+
+ return false;
+
+ } elseif ( $data === '' || $data === 'null' ) {
+
+ return null;
+
+ } else {
+
+ $data = headway_maybe_unserialize($data);
+
+ if ( !is_array($data) ) {
+ return stripslashes($data);
+
+ //If it's an array, run this function across all of the nodes in the array.
+ } else {
+
+ return array_map('headway_maybe_unserialize', $data);
+
+ }
+
+ }
+
+}
+
+
+/**
+ * Generates the URL for the image resizer.
+ *
+ * @param string $url URL to original image.
+ * @param int $w Width to resize to.
+ * @param int $h Height to resize to.
+ * @param int $zc Determines whether or not to zoom/crop the image.
+ * @uses wp_upload_dir()
+ * @uses image_resize_dimensions()
+ * @uses image_resize()
+ *
+ * @return string|array The URL to the image.
+ *
+ * Title : Aqua Resizer
+ * Description : Resizes WordPress images on the fly
+ * Version : 1.1
+ * Author : Syamil MJ
+ * Author URI : http://aquagraphite.com
+ * License : WTFPL - http://sam.zoy.org/wtfpl/
+ * Documentation : https://github.com/sy4mil/Aqua-Resizer/
+ **/
+function headway_thumbnail() {
+ _deprecated_function(__FUNCTION__, '3.1.3', 'headway_resize_image()');
+ $args = func_get_args();
+ return call_user_func_array('headway_resize_image', $args);
+}
+
+function headway_resize_image($url, $width = null, $height = null, $crop = true, $single = true, $upscale = true ) {
+
+ if ( !$url )
+ return null;
+
+ Headway::load('common/image-resizer');
+
+ $HeadwayImageResize = HeadwayImageResize::getInstance();
+ $resized_image = $HeadwayImageResize->process($url, $width, $height, $crop, false, $upscale);
+
+ if ( is_wp_error($resized_image) )
+ return $url . '#' . $resized_image->get_error_code();
+
+ return $resized_image['url'];
+
+}
+
+
+/**
+ * Detects if the browser is Internet Explorer. Will also check if a specific version of MSIE.
+ *
+ * @param int $version
+ *
+ * @return bool
+ **/
+function headway_is_ie($version_check = false) {
+
+ $agent = $_SERVER['HTTP_USER_AGENT'];
+
+ preg_match('/MSIE\s([\d.]+)/', $_SERVER['HTTP_USER_AGENT'], $matches);
+
+ if ( count($matches) === 0 || !is_array($matches) )
+ return false;
+
+ /* The user agent has a version with a decimal in it so it needs to be changed to an integer so it's 9 rather than 9.0 */
+ $version = (int)$matches[1];
+
+ if ( $version_check !== false )
+ return $version_check == $version;
+
+ return $version;
+
+}
+
+/**
+ * Parses PHP using eval.
+ *
+ * @param string $content PHP to be parsed.
+ *
+ * @return mixed PHP that has been parsed.
+ **/
+function headway_parse_php($content) {
+
+ /* If Headway PHP parsing is disabled, then return the content now. */
+ if ( defined('HEADWAY_DISABLE_PHP_PARSING') && HEADWAY_DISABLE_PHP_PARSING === true )
+ return $content;
+
+ /* If it's a WordPress Network setup and the current site being viewed isn't the main site,
+ then don't parse unless HEADWAY_ALLOW_NETWORK_PHP_PARSING is true. */
+ if ( !is_main_site() && (!defined('HEADWAY_ALLOW_NETWORK_PHP_PARSING') || HEADWAY_ALLOW_NETWORK_PHP_PARSING === false) )
+ return $content;
+
+ ob_start();
+
+ $eval = eval("?>$content<?php ");
+
+ if ( $eval === null ) {
+
+ $parsed = ob_get_contents();
+
+ } else {
+
+ $error = error_get_last();
+ $parsed = '<p><strong>Error while parsing PHP:</strong> ' . $error['message'] . '</p>';
+
+ }
+
+ ob_end_clean();
+
+ return $parsed;
+
+}
+
+
+function wp_enqueue_multiple_scripts($scripts, $in_footer = true) {
+
+ if ( !is_array($scripts) || count($scripts) === 0 )
+ return false;
+
+ foreach ($scripts as $script => $src) {
+
+ if ( is_string($script) && is_string($src) ) {
+ wp_enqueue_script($script, $src, false, false, $in_footer);
+ } else {
+ wp_enqueue_script($src, false, false, false, $in_footer);
+ }
+
+ }
+
+}
+
+
+function wp_enqueue_multiple_styles($styles) {
+
+ if ( !is_array($styles) || count($styles) === 0 )
+ return false;
+
+ foreach ($styles as $style => $src) {
+
+ if ( is_string($style) && is_string($src) ) {
+ wp_enqueue_style($style, $src);
+ } else {
+ wp_enqueue_style($src);
+ }
+
+ }
+
+}
+
+
+function headway_in_numeric_range($check, $begin, $end, $allow_equals = true) {
+
+ if ( $allow_equals && ($begin <= $check && $check <= $end) )
+ return true;
+
+ if ( !$allow_equals && ($begin < $check && $check < $end) )
+ return true;
+
+ return false;
+
+}
+
+
+function headway_remove_from_array(array &$array, $value) {
+
+ $array = array_diff($array, array($value));
+
+ return $array;
+
+}
+
+
+function headway_array_insert(array &$array, array $insert, $position) {
+
+ settype($position, 'int');
+
+ //if pos is start, just merge them
+ if ( $position === 0 ) {
+
+ $array = array_merge($insert, $array);
+
+ } else {
+
+ //if pos is end just merge them
+ if( $position >= (count($array)-1) ) {
+
+ $array = array_merge($array, $insert);
+
+ } else {
+
+ //split into head and tail, then merge head+inserted bit+tail
+ $head = array_slice($array, 0, $position);
+ $tail = array_slice($array, $position);
+ $array = array_merge($head, $insert, $tail);
+
+ }
+
+ }
+
+ return $array;
+
+}
+
+
+function headway_array_key_neighbors($array, $findKey, $valueOnly = true) {
+
+ if ( ! array_key_exists($findKey, $array))
+ return FALSE;
+
+ $select = $previous = $next = NULL;
+
+ foreach($array as $key => $value) {
+
+ $thisValue = $valueOnly ? $value : array($key => $value);
+
+ if ($key === $findKey) {
+ $select = $thisValue;
+ continue;
+ }
+
+ if ($select !== NULL) {
+ $next = $thisValue;
+ break;
+ }
+
+ $previous = $thisValue;
+
+ }
+
+ return array(
+ 'prev' => $previous,
+ 'current' => $select,
+ 'next' => $next
+ );
+
+}
+
+
+/**
+ * http://www.php.net/manual/en/function.array-merge-recursive.php#104145
+ **/
+function headway_array_merge_recursive_simple() {
+
+ // handle the arguments, merge one by one
+ $args = func_get_args();
+ $array = $args[0];
+
+ if (!is_array($array)) {
+ return $array;
+ }
+
+ for ($i = 1; $i < count($args); $i++) {
+
+ if (is_array($args[$i])) {
+ $array = headway_array_merge_recursive_simple_recurse($array, $args[$i]);
+ }
+
+ }
+
+ return $array;
+
+}
+
+
+ function headway_array_merge_recursive_simple_recurse($array, $array1) {
+
+ foreach ($array1 as $key => $value) {
+
+ // create new key in $array, if it is empty or not an array
+ if (!isset($array[$key]) || (isset($array[$key]) && !is_array($array[$key]))) {
+ $array[$key] = array();
+ }
+
+ // overwrite the value in the base array
+ if (is_array($value)) {
+ $value = headway_array_merge_recursive_simple_recurse($array[$key], $value);
+ }
+
+ $array[$key] = $value;
+
+ }
+
+ return $array;
+
+ }
+
+
+function headway_format_color($color, $pound_sign = true) {
+
+ /* Start by removing any pound sign that exists */
+ $color = str_replace('#', '', $color);
+
+ /* If the color is a hex, then re-add the pound sign */
+ if ( strlen($color) == 6 && $pound_sign )
+ return '#' . $color;
+
+ return $color;
+
+}
+
+
+/**
+ * http://www.php.net/manual/en/function.get-browser.php#101125
+ **/
+function headway_get_browser() {
+
+ $u_agent = $_SERVER['HTTP_USER_AGENT'];
+ $bname = 'Unknown';
+ $platform = 'Unknown';
+ $version = '';
+
+ /* First get the platform */
+ if ( preg_match('/linux/i', $u_agent) )
+ $platform = 'linux';
+
+ elseif ( preg_match('/macintosh|mac os x/i', $u_agent) )
+ $platform = 'mac';
+
+ elseif ( preg_match('/windows|win32/i', $u_agent) )
+ $platform = 'windows';
+
+ /* Next get the name of the useragent yes seperately and for good reason */
+ if ( preg_match('/MSIE/i', $u_agent) && !preg_match('/Opera/i', $u_agent) ) {
+
+ $bname = 'Internet Explorer';
+ $ub = 'MSIE';
+
+ } elseif ( preg_match('/Firefox/i', $u_agent) ) {
+
+ $bname = 'Mozilla Firefox';
+ $ub = 'Firefox';
+
+ } elseif ( preg_match('/Chrome/i', $u_agent) ) {
+
+ $bname = 'Google Chrome';
+ $ub = 'Chrome';
+
+ } elseif ( preg_match('/Safari/i', $u_agent) ) {
+
+ $bname = 'Apple Safari';
+ $ub = 'Safari';
+
+ } elseif ( preg_match('/Opera/i', $u_agent) ) {
+
+ $bname = 'Opera';
+ $ub = 'Opera';
+
+ } elseif ( preg_match('/Netscape/i', $u_agent) ) {
+
+ $bname = 'Netscape';
+ $ub = 'Netscape';
+
+ }
+
+ /* Get the correct version number */
+ $known = array('Version', $ub, 'other');
+ $pattern = '#(?P<browser>' . join('|', $known) . ')[/ ]+(?P<version>[0-9.|a-zA-Z.]*)#';
+
+ if ( !preg_match_all($pattern, $u_agent, $matches) ) {
+ // we have no matching number just continue
+ }
+
+ // see how many we have
+ $i = count($matches['browser']);
+
+ if ($i != 1) {
+
+ //we will have two since we are not using 'other' argument yet
+ //see if version is before or after the name
+ if ( strripos($u_agent, 'Version') < strripos($u_agent, $ub) )
+ $version = $matches['version'][0];
+ else
+ $version = $matches['version'][1];
+
+ } else {
+ $version = $matches['version'][0];
+ }
+
+ //Check if we have a number
+ if ( $version == null || $version == '' )
+ $version = '?';
+
+ return array(
+ 'userAgent' => $u_agent,
+ 'name' => $bname,
+ 'version' => $version,
+ 'platform' => $platform,
+ 'pattern' => $pattern
+ );
+
+}
+
+
+function headway_str_replace_json($search, $replace, $subject) {
+
+ return json_decode(str_replace($search, $replace, json_encode($subject)), true);
+
+}
+
+function headway_preg_replace_json($pattern, $replace, $subject) {
+
+ return json_decode(preg_replace($pattern, $replace, json_encode($subject)), true);
+
+}
+
+
+/* Search Form */
+function headway_get_search_form($placeholder = null) {
+
+ if ( !$placeholder )
+ $placeholder = __('Type to search, then press enter', 'headway');
+
+ $placeholder = apply_filters('headway_search_form_placeholder', $placeholder);
+ $search_query = get_search_query();
+ $search_input_attributes = array(
+ 'type' => 'text',
+ 'class' => 'field',
+ 'name' => 's',
+ 'id' => 's'
+ );
+
+ /* Handle the placeholder and value */
+ //$search_input_attributes['placeholder'] = $placeholder;
+
+ $search_input_attributes['value'] = $search_query ? $search_query : $placeholder;
+
+ $search_input_attributes['onclick'] = 'if(this.value==\'' . $placeholder . '\')this.value=\'\';';
+ $search_input_attributes['onblur'] = 'if(this.value==\'\')this.value=\'' . $placeholder . '\';';
+
+ /* Turn the array into real HTML attributes */
+ $search_input_attributes = apply_filters('headway_search_input_attributes', $search_input_attributes);
+ $search_input_attributes_string = '';
+
+ foreach ( $search_input_attributes as $attribute => $value )
+ $search_input_attributes_string .= $attribute . '="' . $value . '" ';
+
+ return '
+ <form method="get" id="searchform" action="' . esc_url(home_url('/')) . '">
+ <label for="s" class="assistive-text">' . __('Search', 'headway') . '</label>
+ <input ' . trim($search_input_attributes_string) .' />
+ <input type="submit" class="submit" name="submit" id="searchsubmit" value="' . esc_attr__('Search', 'headway') . '" />
+ </form>
+ ';
+
+}
\ No newline at end of file
--- /dev/null
+<?php
+/**
+ * Title : Aqua Resizer
+ * Description : Resizes WordPress images on the fly
+ * Version : 1.2.0
+ * Author : Syamil MJ
+ * Author URI : http://aquagraphite.com
+ * License : WTFPL - http://sam.zoy.org/wtfpl/
+ * Documentation : https://github.com/sy4mil/Aqua-Resizer/
+ *
+ * @param string $url - (required) must be uploaded using wp media uploader
+ * @param int $width - (required)
+ * @param int $height - (optional)
+ * @param bool $crop - (optional) default to soft crop
+ * @param bool $single - (optional) returns an array if false
+ * @uses wp_upload_dir()
+ * @uses image_resize_dimensions()
+ * @uses wp_get_image_editor()
+ *
+ * @return str|array
+ */
+
+if(!class_exists('HeadwayImageResize')) {
+ class HeadwayImageResize
+ {
+ /**
+ * The singleton instance
+ */
+ static private $instance = null;
+
+ /**
+ * No initialization allowed
+ */
+ private function __construct() {}
+
+ /**
+ * No cloning allowed
+ */
+ private function __clone() {}
+
+ /**
+ * For your custom default usage you may want to initialize an HeadwayImageResize object by yourself and then have own defaults
+ */
+ static public function getInstance() {
+ if(self::$instance == null) {
+ self::$instance = new self;
+ }
+
+ return self::$instance;
+ }
+
+ /**
+ * Run, forest.
+ */
+ public function process( $url, $width = null, $height = null, $crop = null, $single = true, $upscale = false ) {
+ // Validate inputs.
+ if ( ! $url || ( ! $width && ! $height ) ) return new WP_Error('aqua_resizer_invalid_image_url_or_size', __('Error: Invalid image URL or size inputs', 'headway'), __CLASS__);
+
+ // Caipt'n, ready to hook.
+ if ( true === $upscale ) add_filter( 'image_resize_dimensions', array($this, 'aq_upscale'), 10, 6 );
+
+ // Define upload path & dir.
+ $upload_info = wp_upload_dir();
+ $upload_dir = $upload_info['basedir'];
+ $upload_url = $upload_info['baseurl'];
+
+ $http_prefix = "http://";
+ $https_prefix = "https://";
+
+ /* if the $url scheme differs from $upload_url scheme, make them match
+ if the schemes differe, images don't show up. */
+ if(!strncmp($url,$https_prefix,strlen($https_prefix))){ //if url begins with https:// make $upload_url begin with https:// as well
+ $upload_url = str_replace($http_prefix,$https_prefix,$upload_url);
+ }
+ elseif(!strncmp($url,$http_prefix,strlen($http_prefix))){ //if url begins with http:// make $upload_url begin with http:// as well
+ $upload_url = str_replace($https_prefix,$http_prefix,$upload_url);
+ }
+
+
+ // Check if $img_url is local.
+ if ( false === strpos( $url, $upload_url ) ) return new WP_Error('aqua_resizer_image_not_local', __('Error: Image not local', 'headway'), __CLASS__);
+
+ // Define path of image.
+ $rel_path = str_replace( $upload_url, '', $url );
+ $img_path = $upload_dir . $rel_path;
+
+ // Check if img path exists, and is an image indeed.
+ if ( ! file_exists( $img_path ) or ! getimagesize( $img_path ) ) return new WP_Error('aqua_resizer_image_not_accessible', __('Error: Image does not exist or not accessible', 'headway'), __CLASS__);;
+
+ // Get image info.
+ $info = pathinfo( $img_path );
+ $ext = $info['extension'];
+ list( $orig_w, $orig_h ) = getimagesize( $img_path );
+
+ // Get image size after cropping.
+ $dims = image_resize_dimensions( $orig_w, $orig_h, $width, $height, $crop );
+ $dst_w = $dims[4];
+ $dst_h = $dims[5];
+
+ // Return the original image only if it exactly fits the needed measures.
+ if ( ! $dims && ( ( ( null === $height && $orig_w == $width ) xor ( null === $width && $orig_h == $height ) ) xor ( $height == $orig_h && $width == $orig_w ) ) ) {
+ $img_url = $url;
+ $dst_w = $orig_w;
+ $dst_h = $orig_h;
+ } else {
+ // Use this to check if cropped image already exists, so we can return that instead.
+ $suffix = "{$dst_w}x{$dst_h}";
+ $dst_rel_path = str_replace( '.' . $ext, '', $rel_path );
+ $destfilename = "{$upload_dir}{$dst_rel_path}-{$suffix}.{$ext}";
+
+ if ( ! $dims || ( true == $crop && false == $upscale && ( $dst_w < $width || $dst_h < $height ) ) ) {
+ // Can't resize, so return false saying that the action to do could not be processed as planned.
+ return new WP_Error('aqua_resizer_cannot_resize_check_upscale', __('Error: Cannot resize, check if $upscale is enabled', 'headway'), __CLASS__);
+ }
+ // Else check if cache exists.
+ elseif ( file_exists( $destfilename ) && getimagesize( $destfilename ) ) {
+ $img_url = "{$upload_url}{$dst_rel_path}-{$suffix}.{$ext}";
+ }
+ // Else, we resize the image and return the new resized image url.
+ else {
+
+ $editor = wp_get_image_editor( $img_path );
+
+ if ( is_wp_error( $editor ) || is_wp_error( $editor->resize( $width, $height, $crop ) ) )
+ return new WP_Error('aqua_resizer_cannot_resize_with_wp_image_editor', __('Error: Cannot resize image with WP_Image_Editor class', 'headway'), __CLASS__);
+
+ $resized_file = $editor->save();
+
+ if ( ! is_wp_error( $resized_file ) ) {
+ $resized_rel_path = str_replace( $upload_dir, '', $resized_file['path'] );
+ $img_url = $upload_url . $resized_rel_path;
+ } else {
+ return new WP_Error('aqua_resizer_unable_to_save_with_wp_image_editor', __('Error: Unable to save image with WP_Image_Editor class', 'headway'), __CLASS__);
+ }
+
+ }
+ }
+
+ // Okay, leave the ship.
+ if ( true === $upscale ) remove_filter( 'image_resize_dimensions', array( $this, 'aq_upscale' ) );
+
+ // Return the output.
+ if ( $single ) {
+ // str return.
+ $image = $img_url;
+ } else {
+ // array return.
+ $image = array (
+ 'url' => $img_url,
+ 'w' => $dst_w,
+ 'h' => $dst_h
+ );
+ }
+
+ return $image;
+ }
+
+ /**
+ * Callback to overwrite WP computing of thumbnail measures
+ */
+ function aq_upscale( $default, $orig_w, $orig_h, $dest_w, $dest_h, $crop ) {
+ if ( ! $crop ) return null; // Let the wordpress default function handle this.
+
+ // Here is the point we allow to use larger image size than the original one.
+ $aspect_ratio = $orig_w / $orig_h;
+ $new_w = $dest_w;
+ $new_h = $dest_h;
+
+ if ( ! $new_w ) {
+ $new_w = intval( $new_h * $aspect_ratio );
+ }
+
+ if ( ! $new_h ) {
+ $new_h = intval( $new_w / $aspect_ratio );
+ }
+
+ $size_ratio = max( $new_w / $orig_w, $new_h / $orig_h );
+
+ $crop_w = round( $new_w / $size_ratio );
+ $crop_h = round( $new_h / $size_ratio );
+
+ $s_x = floor( ( $orig_w - $crop_w ) / 2 );
+ $s_y = floor( ( $orig_h - $crop_h ) / 2 );
+
+ return array( 0, 0, (int) $s_x, (int) $s_y, (int) $new_w, (int) $new_h, (int) $crop_w, (int) $crop_h );
+ }
+ }
+}
\ No newline at end of file
--- /dev/null
+<?php
+class HeadwayLayout {
+
+
+ public static $sep = '||';
+
+
+ public static function init() {
+
+ add_action('headway_visual_editor_save', array(__CLASS__, 'clear_status_transient'));
+ add_action('headway_visual_editor_reset_layout', array(__CLASS__, 'clear_status_transient'));
+ add_action('headway_visual_editor_delete_template', array(__CLASS__, 'clear_status_transient'));
+ add_action('headway_visual_editor_assign_template', array(__CLASS__, 'clear_status_transient'));
+ add_action('headway_visual_editor_unassign_template', array(__CLASS__, 'clear_status_transient'));
+
+ add_action('headway_db_upgrade', array(__CLASS__, 'clear_status_transient'));
+
+ add_action('save_post', array(__CLASS__, 'clear_status_transient'));
+ add_action('delete_post', array(__CLASS__, 'clear_status_transient'));
+
+ }
+
+
+ public static function clear_status_transient() {
+
+ delete_transient('hw_customized_layouts_template_' . HeadwayOption::$current_skin);
+ delete_transient('hw_layouts_with_templates_template_' . HeadwayOption::$current_skin);
+
+ }
+
+
+ public static function format_old_id($old_id) {
+
+ $layout_fragments = explode('-', $old_id);
+ $last_layout_fragment = end($layout_fragments);
+
+ /* Don't touch template IDs */
+ if ( strpos($old_id, 'template-') === 0 )
+ return $old_id;
+
+ /* If only a numeric ID is provided then turn it into new format */
+ if ( is_numeric($old_id) || is_numeric($last_layout_fragment) ) {
+
+ $post_id = is_numeric($old_id) ? $old_id : $last_layout_fragment;
+
+ $post = get_post($post_id);
+
+ if ( $post ) {
+
+ return implode(self::$sep, array(
+ 'single',
+ $post->post_type,
+ $post_id
+ ));
+
+ }
+
+ }
+
+ /* Replace underscores with separator */
+ $old_id = str_replace(array(
+ 'single_',
+ 'archive_',
+ 'post_type_',
+ 'post_tag_'
+ ), array(
+ 'single' . self::$sep,
+ 'archive' . self::$sep,
+ 'post_type' . self::$sep,
+ 'post_tag' . self::$sep
+ ), $old_id);
+
+ /* Change all hyphens to separator */
+ return str_replace('-', self::$sep, $old_id);
+
+ }
+
+
+ /**
+ * Check if layout exists via HeadwayLayout::get_name()
+ **/
+ public static function exists($layout_id) {
+
+ $name = self::get_name($layout_id);
+
+ if ( !$name || $name == '(No Title)' || strpos($name, '(Unregistered Post Type: ') === 0 )
+ return false;
+
+ return true;
+
+ }
+
+
+ /**
+ * Returns current layout
+ *
+ * @return mixed
+ **/
+ public static function get_current() {
+
+ //If the user is viewing the site through the iframe and the mode is set to Layout, then display that exact layout.
+ if ( headway_get('ve-layout') && (HeadwayRoute::is_visual_editor_iframe() || HeadwayRoute::is_visual_editor()) )
+ return headway_get('ve-layout');
+
+ $current_hierarchy = self::get_current_hierarchy();
+
+ return end($current_hierarchy);
+
+ }
+
+
+ /**
+ * Traverses up the hierarchy tree to figure out which layout is being used.
+ *
+ * @return mixed
+ **/
+ public static function get_current_in_use() {
+
+ //If the user is viewing the site through the iframe and the mode is set to Layout, then display that exact layout.
+ if ( headway_get('ve-layout') ) {
+
+ if ( HeadwayRoute::is_visual_editor_iframe('grid') || HeadwayRoute::is_visual_editor() )
+ return headway_get('ve-layout');
+
+ if ( HeadwayRoute::is_visual_editor_iframe('design') && strpos(headway_get('ve-layout'), 'template-') === 0 )
+ return headway_get('ve-layout');
+
+ }
+
+ //Get hierarchy
+ $hierarchy = array_reverse(self::get_current_hierarchy());
+
+ //Loop through entire hierarchy to find which one is customized or has a template
+ foreach ( $hierarchy as $layout ) {
+
+ $status = self::get_status($layout);
+
+ //If the layout isn't customized or using a template, skip to next, otherwise we return the current layout in the next line.
+ if ( $status['customized'] === false && $status['template'] === false )
+ continue;
+
+ //If the layout has a template assigned to it, use the template. Templates will take precedence over customized status.
+ if ( $status['template'] )
+ return 'template-' . $status['template'];
+
+ //If it's a customized layout, then use the layout itself after making sure there are blocks on the layout
+ if ( $status['customized'] )
+ return $layout;
+
+ }
+
+ //If there's still not a customized layout, loop through the top-level layouts and find the first one that's customized.
+ $top_level_layouts = array(
+ 'index',
+ 'single',
+ 'archive',
+ 'four04'
+ );
+
+ if ( get_option('show_on_front') == 'page' )
+ $top_level_layouts[] = 'front_page';
+
+ foreach ( $top_level_layouts as $top_level_layout ) {
+
+ $status = self::get_status($top_level_layout);
+
+ if ( $status['customized'] === false && $status['template'] === false )
+ continue;
+
+ //If the layout has a template assigned to it, use the template. Templates will take precedence over customized status.
+ if ( $status['template'] )
+ return 'template-' . $status['template'];
+
+ //If it's a customized layout and the layout has blocks, then use the layout itself
+ if ( $status['customized'] && count(HeadwayBlocksData::get_blocks_by_layout($top_level_layout)) > 0 )
+ return $top_level_layout;
+
+ }
+
+ //If there STILL isn't a customized layout, just return the top level of the current layout.
+ return end($hierarchy);
+
+ }
+
+
+ /**
+ * Returns name of the current layout being viewed.
+ *
+ * @return string
+ **/
+ public static function get_current_name() {
+
+ return self::get_name(self::get_current());
+
+ }
+
+
+ /**
+ * Returns the current hierarchy.
+ *
+ * @return array
+ **/
+ public static function get_current_hierarchy() {
+
+ $current_layout = array();
+ $queried_object = get_queried_object();
+
+ //Now the fun begins
+ if ( is_home() || ( get_option('show_on_front') == 'posts' && is_front_page() ) ) {
+
+ $current_layout[] = 'index';
+
+ } elseif ( is_front_page() && !is_home() ) {
+
+ $current_layout[] = 'front_page';
+
+ } elseif ( is_singular() ) {
+
+ $post = $queried_object;
+ $post_type = get_post_type_object($post->post_type);
+
+ $current_layout[] = 'single';
+
+ if ( $post_type->name )
+ $current_layout[] = 'single' . self::$sep . $post_type->name;
+
+ $posts = array(
+ $post->ID
+ );
+
+ while ( $post->post_parent != 0 ) {
+
+ $post = get_post($post->post_parent);
+ $posts[] = $post->ID;
+
+ }
+
+ foreach ( array_reverse($posts) as $post_id )
+ if ( $post_type->name && $post_id )
+ $current_layout[] = 'single' . self::$sep . $post_type->name . self::$sep . $post_id;
+
+ } elseif ( is_archive() || is_search() ) {
+
+ $current_layout[] = 'archive';
+
+ if ( is_date() ) {
+
+ $current_layout[] = 'archive' . self::$sep . 'date';
+
+ } elseif ( is_author() ) {
+
+ $current_layout[] = 'archive' . self::$sep . 'author';
+ $current_layout[] = 'archive' . self::$sep . 'author' . self::$sep . $queried_object->ID;
+
+ } elseif ( is_category() ) {
+
+ $category = $queried_object;
+ $ancestor_categories = array();
+
+ $current_layout[] = 'archive' . self::$sep . 'category';
+
+ /* Ancestor categories */
+ while ( $category->category_parent != 0 ) {
+ $category = get_category($category->category_parent);
+ $ancestor_categories[] = $category->term_id;
+ }
+
+ foreach ( array_reverse($ancestor_categories) as $ancestor_category_id )
+ $current_layout[] = 'archive' . self::$sep . 'category' . self::$sep . $ancestor_category_id;
+
+ /* Original queried category */
+ $current_layout[] = 'archive' . self::$sep . 'category' . self::$sep . $queried_object->term_id;
+
+ } elseif ( is_search() ) {
+
+ $current_layout[] = 'archive' . self::$sep . 'search';
+
+ } elseif ( is_tag() ) {
+
+ $current_layout[] = 'archive' . self::$sep . 'post_tag';
+ $current_layout[] = 'archive' . self::$sep . 'post_tag' . self::$sep . $queried_object->term_id;
+
+ } elseif ( is_tax() ) {
+
+ $current_layout[] = 'archive' . self::$sep . 'taxonomy';
+ $current_layout[] = 'archive' . self::$sep . 'taxonomy' . self::$sep . $queried_object->taxonomy;
+ $current_layout[] = 'archive' . self::$sep . 'taxonomy' . self::$sep . $queried_object->taxonomy . self::$sep . $queried_object->term_id;
+
+ } elseif ( is_post_type_archive() ) {
+
+ $current_layout[] = 'archive' . self::$sep . 'post_type';
+ $current_layout[] = 'archive' . self::$sep . 'post_type' . self::$sep . $queried_object->name;
+
+ }
+
+ } elseif ( is_404() ) {
+
+ $current_layout[] = 'four04';
+
+ }
+
+ //I think we're finally done.
+ return $current_layout;
+
+ }
+
+
+ /**
+ * Returns friendly name of the layout specified.
+ *
+ * @return string
+ **/
+ public static function get_name($layout, $retry = false) {
+
+ if ( !$layout )
+ return null;
+
+ $layout_parts = explode(self::$sep, $layout);
+ $id = end($layout_parts);
+
+ if ( is_numeric($layout_parts[0]) )
+ return get_the_title($id) ? stripslashes(get_the_title($id)) : '(No Title)';
+
+ switch ( $layout_parts[0] ) {
+
+ case 'front_page':
+ return 'Front Page';
+ break;
+
+ case 'index':
+ return 'Blog Index';
+ break;
+
+ case 'single':
+ if ( $id == 'single' )
+ return 'Single';
+
+ if ( is_numeric($id) )
+ return get_the_title($id) ? stripslashes(get_the_title($id)) : '(No Title)';
+
+ //If everything else hasn't triggered, then it's a post type
+ $id = str_replace('single' . self::$sep, '', $layout);
+ $post_type = get_post_type_object($id);
+
+ if ( !is_object($post_type) )
+ return '(Unregistered Post Type: ' . $id . ')';
+
+ return stripslashes($post_type->labels->singular_name);
+ break;
+
+ case 'archive':
+ if ( $id == 'archive' )
+ return 'Archive';
+
+ switch($layout_parts[1]) {
+
+ case 'category':
+ if ( $id == 'category' )
+ return 'Category';
+
+ $term = get_term($id, 'category');
+
+ return $term->name ? stripslashes($term->name) : '(No Title)';
+ break;
+
+ case 'search':
+ return 'Search';
+ break;
+
+ case 'date':
+ return 'Date';
+ break;
+
+ case 'author':
+ if ( $id == 'author' )
+ return 'Author';
+
+ $user_data = get_userdata($id);
+
+ return stripslashes($user_data->display_name);
+ break;
+
+ case 'post_tag':
+ if ( $id == 'post_tag' )
+ return 'Post Tag';
+
+ $term = get_term($id, 'post_tag');
+
+ return $term->name ? stripslashes($term->name) : '(No Title)';
+ break;
+
+ case 'taxonomy':
+ if ( $id == 'taxonomy' )
+ return 'Taxonomy';
+
+ $taxonomy_fragments = explode(self::$sep, str_replace('archive' . self::$sep . 'taxonomy' . self::$sep, '', $layout));
+
+ if ( is_numeric(end($taxonomy_fragments)) ) {
+
+ $term_id = array_pop($taxonomy_fragments);
+
+ $term = get_term($term_id, implode(self::$sep, $taxonomy_fragments));
+
+ return isset($term->name) ? $term->name : '(No Title)';
+
+ } elseif ( $taxonomy = get_taxonomy(implode(self::$sep, $taxonomy_fragments)) ) {
+
+ return $taxonomy->labels->singular_name ? stripslashes($taxonomy->labels->singular_name) : '(No Title)';
+
+ }
+ break;
+
+ case 'post_type':
+ if ( $id == 'post_type' )
+ return 'Post Type';
+
+ //If everything else hasn't triggered, then it's a post type
+ $id = str_replace('archive' . self::$sep . 'post_type' . self::$sep, '', $layout);
+ $post_type = get_post_type_object($id);
+
+ if ( !is_object($post_type) )
+ return null;
+
+ return stripslashes($post_type->labels->singular_name);
+ break;
+
+ case 'post_format':
+ if ( $id == 'post_format' )
+ return 'Post Format';
+
+ $term = get_term($id, 'post_format');
+
+ return stripslashes($term->name);
+ break;
+
+ }
+
+ break;
+
+ case 'four04':
+ return '404 Layout';
+ break;
+
+ }
+
+ /* Template names */
+ if ( strpos($layout_parts[0], 'template-') === 0 ) {
+
+ $templates = self::get_templates();
+ $template_id = str_replace('template-', '', $layout_parts[0]);
+
+ if ( isset($templates[$template_id]) )
+ return stripslashes($templates[$template_id]);
+ else
+ return null;
+
+ }
+
+
+ /* If it's no bueno, give it one more shot by replacing underscores with hyphens */
+ if ( !$retry ) {
+
+ return self::get_name(str_replace('_', '-', $layout), true);
+
+ }
+
+ return false;
+
+ }
+
+
+ /**
+ * Gets the status of the layout. This will tell if it's customized, using a template, or none of the previous mentioned.
+ *
+ * @return string
+ **/
+ public static function get_status($layout, $include_post_status = false) {
+
+ $layout_parts = explode(self::$sep, $layout);
+ $layout_end_part = end($layout_parts);
+
+ /* Get the customized transient */
+ $transient_id_customized_layouts = 'hw_customized_layouts_template_' . HeadwayOption::$current_skin;
+
+ if ( !$customized_layouts = get_transient($transient_id_customized_layouts) ) {
+
+ global $wpdb;
+
+ $customized_layouts = array_unique($wpdb->get_col($wpdb->prepare("SELECT layout FROM $wpdb->hw_blocks WHERE template = '%s'", HeadwayOption::$current_skin)));
+
+ set_transient($transient_id_customized_layouts, $customized_layouts);
+
+ }
+
+ /* Get the templates status transient */
+ $transient_id_layouts_with_templates = 'hw_layouts_with_templates_template_' . HeadwayOption::$current_skin;
+ $layouts_with_templates = get_transient($transient_id_layouts_with_templates);
+
+ if ( !is_array($layouts_with_templates) ) {
+
+ global $wpdb;
+
+ $templated_layouts_hw_meta = $wpdb->get_results($wpdb->prepare("SELECT layout, meta_value FROM $wpdb->hw_layout_meta WHERE meta_key = '%s' AND meta_value <> '' AND template = '%s'", 'template', HeadwayOption::$current_skin));
+ $templated_layouts_wp_meta = $wpdb->get_results($wpdb->prepare("SELECT post_id, meta_value FROM $wpdb->postmeta WHERE meta_key = '%s' AND meta_value <> ''", '_hw_|template=' . HeadwayOption::$current_skin . '|_template'));
+
+ $layouts_with_templates = array();
+
+ foreach ( array_merge($templated_layouts_hw_meta, $templated_layouts_wp_meta) as $templated_layout ) {
+
+ $template_id = isset($templated_layout->layout) ? $templated_layout->layout : $templated_layout->post_id;
+
+ $layouts_with_templates[$template_id] = $templated_layout->meta_value;
+
+ }
+
+ set_transient($transient_id_layouts_with_templates, $layouts_with_templates);
+
+ }
+
+ $customized = ( in_array($layout, $customized_layouts) ) ? true : false;
+
+ $template = false;
+
+ /* Get the template */
+ $possible_template = ( $layout_parts[0] == 'single' && is_numeric($layout_end_part) ) ? headway_get($layout_end_part, $layouts_with_templates) : headway_get($layout, $layouts_with_templates);
+
+ if ( $possible_template && self::template_exists($possible_template) )
+ $template = str_replace('template-', '', $possible_template);
+ /* End getting template */
+
+ $status = array(
+ 'customized' => $customized,
+ 'template' => $template
+ );
+
+ /* If set to include post status and this is a single layout, fetch it */
+ if ( $include_post_status && $layout_parts[0] == 'single' && is_numeric($layout_end_part) ) {
+
+ /* Change status IDs to friendly statuses */
+ $possible_statuses = array('publish', 'pending', 'draft', 'future', 'private');
+ $friendly_status_names = array('Published', 'Pending Review', 'Draft', 'Scheduled', 'Private');
+
+ $status['post_status'] = str_replace($possible_statuses, $friendly_status_names, get_post_status($layout_end_part));
+
+ }
+
+ /* Check if the layout is set to the blog page or the homepage. If so return false on both. */
+ if ( is_numeric($layout_end_part) && $layout_parts[0] == 'single' && $layout_parts[1] == 'page' ) {
+
+ if ( $layout_end_part == get_option('page_on_front') || $layout_end_part == get_option('page_for_posts') ) {
+
+ return array(
+ 'customized' => false,
+ 'template' => false
+ );
+
+ }
+
+ }
+
+ return $status;
+
+ }
+
+
+ public static function is_customized($layout) {
+
+ $layout_status = self::get_status($layout);
+
+ return $layout_status['customized'] && !$layout_status['template'] ? true : false;
+
+ }
+
+
+ /**
+ * Returns all pages and their hierarchy for listing.
+ *
+ * @return array
+ **/
+ public static function get_pages() {
+
+ $layouts = array();
+
+ if ( get_option('show_on_front') == 'page' )
+ $layouts['front_page'] = array();
+
+ $layouts['index'] = array();
+ $layouts['single'] = array();
+ $layouts['archive'] = array();
+ $layouts['four04'] = array();
+
+ //Queries
+ $post_types = get_post_types(array('public' => true), 'objects');
+
+ //Single
+ foreach($post_types as $post_type) {
+
+ $layouts['single']['single' . self::$sep . $post_type->name] = self::get_pages_posts($post_type->name);
+
+ }
+
+ //Archives
+ $layouts['archive'] = array(
+ 'archive' . self::$sep . 'category' => self::get_pages_terms('category'),
+ 'archive' . self::$sep . 'search' => array(),
+ 'archive' . self::$sep . 'date' => array(),
+ 'archive' . self::$sep . 'author' => array(),
+ 'archive' . self::$sep . 'post_tag' => self::get_pages_terms('post_tag'),
+ 'archive' . self::$sep . 'taxonomy' => array(),
+ 'archive' . self::$sep . 'post_type' => array(),
+ 'archive' . self::$sep . 'post_format' => self::get_pages_terms('post_format')
+ );
+
+
+ //Authors
+ if ( !HeadwayOption::get('layout-selector-safe-mode') && !apply_filters('headway_layout_selector_hide_users', false) ) {
+
+ $author_query = get_users(array(
+ 'who' => 'authors',
+ 'fields' => 'ID'
+ ));
+
+ $author_post_counts = count_many_users_posts( $author_query );
+
+ foreach ( $author_query as $author_id ) {
+
+ if ( !headway_get($author_id, $author_post_counts) )
+ continue;
+
+ $layouts['archive']['archive' . self::$sep . 'author']['archive' . self::$sep . 'author' . self::$sep . $author_id] = array();
+
+ }
+
+ }
+
+
+ //Taxonomies and Terms
+ $taxonomies_query = get_taxonomies(array('public' => true, '_builtin' => false), 'objects');
+ $exclude = array('link_category');
+ $taxonomies = array();
+
+ foreach($taxonomies_query as $slug => $taxonomy) {
+
+ $layouts['archive']['archive' . self::$sep . 'taxonomy']['archive' . self::$sep . 'taxonomy' . self::$sep . $slug] = self::get_pages_terms($slug, true);
+
+ }
+
+
+ //Post Types
+ $excluded_post_types = array('post', 'page', 'attachment');
+
+ foreach($post_types as $post_type) {
+
+ //If excluded, skip it
+ if ( in_array($post_type->name, $excluded_post_types) )
+ continue;
+
+ $layouts['archive']['archive' . self::$sep . 'post_type']['archive' . self::$sep . 'post_type' . self::$sep . $post_type->name] = array();
+
+ }
+
+
+ return $layouts;
+
+ }
+
+
+ /**
+ * Recursive function to find terms and their children.
+ *
+ * @see HeadwayLayout::get_pages()
+ *
+ * @return array
+ **/
+ public static function get_pages_terms($taxonomy, $add_taxonomy_to_id = false, $term_parent = 0) {
+
+ if ( HeadwayOption::get('layout-selector-safe-mode') && $taxonomy != 'category' )
+ return null;
+
+ $query = get_terms($taxonomy, array('parent' => $term_parent));
+ $terms = array();
+
+ foreach ($query as $term) {
+
+ //Add taxonomy prefix if set
+ $taxonomy_id = $add_taxonomy_to_id ? 'taxonomy' . self::$sep . $taxonomy : $taxonomy;
+
+ $terms['archive' . self::$sep . $taxonomy_id . self::$sep . $term->term_id] = self::get_pages_terms($taxonomy, $add_taxonomy_to_id, $term->term_id);
+
+ }
+
+ return $terms;
+
+ }
+
+
+ /**
+ * Recursive function to find posts/pages and their children.
+ *
+ * @see HeadwayLayout::get_pages()
+ *
+ * @return array
+ **/
+ public static function get_pages_posts($post_type = 'post', $post_parent = 0) {
+
+ if ( HeadwayOption::get('layout-selector-safe-mode') && $post_type != 'page' )
+ return null;
+
+ $query = get_posts(array(
+ 'post_type' => $post_type,
+ 'post_parent' => $post_parent,
+ 'numberposts' => 99999,
+ 'post_status' => array('publish', 'pending', 'draft', 'future', 'private')
+ ));
+
+ $posts = array();
+
+ foreach ($query as $post)
+ $posts['single' . self::$sep . $post_type . self::$sep . $post->ID] = self::get_pages_posts($post_type, $post->ID);
+
+ return $posts;
+
+ }
+
+
+ /**
+ * Simple function to query for all Headway layout templates from the database.
+ *
+ * @return array
+ **/
+ public static function get_templates() {
+
+ $templates = HeadwaySkinOption::get('list', 'templates', array());
+
+ return $templates;
+
+ }
+
+
+ public static function template_exists($id) {
+
+ $templates = HeadwaySkinOption::get('list', 'templates', array());
+
+ return isset($templates[$id]);
+
+ }
+
+
+ public static function add_template($template_name = null) {
+
+ $templates = HeadwaySkinOption::get('list', 'templates', array());
+ $last_template_id = HeadwaySkinOption::get('last-id', 'templates', 0);
+
+ /* These two variables be used for when a blocks/wrappers imported ID is different than the one that it ends up with... e.g. skin importing to line up instances */
+ $block_id_translations = array();
+ $wrapper_id_translations = array();
+
+ /* Build name */
+ $id = $last_template_id + 1;
+ $template_name = $template_name ? $template_name : 'Template ' . $id;
+
+ /* Add template to templates array so it can be sent to DB */
+ $templates[$id] = $template_name;
+
+ /* Send array to DB */
+ HeadwaySkinOption::set('list', $templates, 'templates');
+ HeadwaySkinOption::set('last-id', $id, 'templates');
+
+ return array(
+ 'id' => $id,
+ 'name' => $template_name
+ );
+
+ }
+
+
+ /**
+ * Deletion method that will handle deleting blocks, wrappers, design editor instances, and removing any rows in wp_options
+ *
+ * @param string ID of layout being deleted
+ * @param bool Whether or not to delete all of the layout options pertaining to this layout or only ones that belong to the active skin
+ **/
+ public static function delete_layout($layout_id, $skin_only = true) {
+
+ //Delete the blocks for the page/post. This will also delete the block instances */
+ HeadwayBlocksData::delete_by_layout($layout_id);
+
+ //Delete wrappers and wrapper instances
+ HeadwayWrappersData::delete_by_layout($layout_id);
+
+ //Delete the layout options for this layout
+ if ( $skin_only ) {
+ HeadwayLayoutOption::delete_all_from_layout($layout_id);
+ } else {
+ HeadwayLayoutOption::delete_all_from_layout($layout_id, true);
+ }
+
+ }
+
+
+ /**
+ * Get the **BEST** URL for a layout ID
+ **/
+ public static function get_url($layout) {
+
+ $layout_fragments = explode(self::$sep, $layout);
+
+ switch ( $layout_fragments[0] ) {
+
+ /* Blog Index */
+ case 'index':
+
+ if ( get_option('show_on_front') == 'page' && get_option('page_for_posts') )
+ return get_permalink(get_option('page_for_posts'));
+
+ return home_url();
+
+ break;
+
+
+ /* Front Page */
+ case 'front_page':
+
+ return home_url();
+
+ break;
+
+
+ /* Singles */
+ case 'single':
+
+ /* If an ID is provided, go straight to it */
+ if ( isset($layout_fragments[2]) && $permalink = get_permalink($layout_fragments[2]) )
+ return $permalink;
+
+ /* Otherwise, go to the post type (force post if post type isn't present... e.g. layout is just "single") */
+ $post_type = isset($layout_fragments[1]) ? $layout_fragments[1] : array(
+ 'post',
+ 'page'
+ );
+
+ $query = get_posts(array(
+ 'numberposts' => 1,
+ 'post_type' => $post_type
+ ));
+
+ if ( !empty($query[0]->ID) && $permalink = get_permalink($query[0]->ID) )
+ return $permalink;
+
+ break;
+
+
+ /* Archives */
+ case 'archive':
+
+ $type = isset($layout_fragments[1]) ? $layout_fragments[1] : 'category';
+
+ switch ( $type ) {
+
+ case 'category':
+
+ /* Category ID provided */
+ if ( isset($layout_fragments[2]) && is_numeric($layout_fragments[2]) ) {
+
+ $cat = $layout_fragments[2];
+
+ /* No category ID provided, get one with posts */
+ } else {
+
+ $categories = get_terms('category', array(
+ 'orderby' => 'count',
+ 'order' => 'desc',
+ 'hide_empty' => true
+ ));
+
+ if ( count($categories) ) {
+ $cat = $categories[0]->term_id;
+ } else {
+ $cat = 0;
+ }
+
+ }
+
+ return home_url('?cat=' . $cat);
+
+ break;
+
+ case 'date':
+
+ return home_url('?m=' . date('Y'));
+
+ break;
+
+ case 'author':
+
+ /* Author ID Provided */
+ if ( isset($layout_fragments[2]) && is_numeric($layout_fragments[2]) ) {
+
+ $author_id = $layout_fragments[2];
+
+ /* Author ID not provided, use logged in user */
+ } else {
+
+ $current_user = wp_get_current_user();
+ $author_id = $current_user->ID;
+
+ }
+
+ return home_url('?author=' . $author_id);
+
+ break;
+
+ case 'search':
+
+ /* Provide a word that will likely pull up some content */
+ return home_url('?s=and');
+
+ break;
+
+ case 'post_type':
+
+ if ( isset($layout_fragments[2]) && $post_type = $layout_fragments[2] )
+ return home_url('?post_type=' . $post_type);
+
+ break;
+
+ case 'taxonomy':
+
+ /* Taxonomy provided */
+ if ( isset($layout_fragments[2]) && $tax = $layout_fragments[2] ) {
+
+ /* Term Provided */
+ if ( isset($layout_fragments[3]) ) {
+
+ $term = get_term($layout_fragments[3], $tax);
+ $term_slug = isset($term->slug) ? $term->slug : null;
+
+ /* No term provided */
+ } else {
+
+ $terms = get_terms($tax, array(
+ 'orderby' => 'count',
+ 'order' => 'desc',
+ 'hide_empty' => true
+ ));
+
+ if ( !empty($terms[0]->slug) )
+ $term_slug = $terms[0]->slug;
+
+ }
+
+ if ( !empty($tax) && !empty($term_slug) )
+ return home_url('?' . $tax . '=' . $term_slug);
+
+ }
+
+ break;
+
+ }
+
+ break;
+
+
+ /* 404 */
+ case 'four04':
+
+ return home_url('404trigger-' . rand(100, 99999));
+
+ break;
+
+ } /* End $layout switch */
+
+ /* Catch All Default */
+ return home_url();
+
+ }
+
+}
\ No newline at end of file
--- /dev/null
+<?php
+class HeadwayResponsiveGrid {
+
+
+ public static function init() {
+
+ /* If responsive grid is not active then we still need viewport correction because anything over 100% width on mobile devices won't work too well. */
+ if ( !self::is_active() )
+ add_action('headway_body_close', array(__CLASS__, 'add_non_responsive_meta_viewport'));
+
+ if ( !self::is_enabled() )
+ return false;
+
+ add_action('headway_head_extras', array(__CLASS__, 'add_meta_viewport'));
+ add_action('init', array(__CLASS__, 'cookie_baker'));
+
+ }
+
+
+ /**
+ * Checks if the responsive grid is active or not.
+ *
+ * Will check against the main option that's set in the Grid mode of the visual editor
+ * and the cookie that disables the responsive grid if the visitor wishes to do so.
+ **/
+ public static function is_active() {
+
+ //If the responsive grid isn't enabled then don't bother.
+ if ( !self::is_enabled() )
+ return false;
+
+ //If the user has clicked on the full site link in the footer block then it'll set this cookie that's being checked.
+ if ( self::is_user_disabled() )
+ return false;
+
+ //If it's the visual editor or the visual editor iframe
+ if ( HeadwayRoute::is_visual_editor() || HeadwayRoute::is_visual_editor_iframe() || headway_get('visual-editor-open') )
+ return false;
+
+ return true;
+
+ }
+
+
+ public static function is_user_disabled() {
+
+ if ( headway_get('full-site') != 'false' )
+ if ( headway_get('headway-full-site', $_COOKIE) == 1 || headway_get('full-site') == 'true' )
+ return true;
+
+ return false;
+
+ }
+
+
+ public static function is_enabled() {
+
+ //If the theme doesn't support the responsive grid, then disable it.
+ if ( !current_theme_supports('headway-grid') || !current_theme_supports('headway-responsive-grid') )
+ return false;
+
+ return HeadwaySkinOption::get('enable-responsive-grid', false, false);
+
+ }
+
+
+ public static function add_meta_viewport() {
+
+ if ( !self::is_active() )
+ return false;
+
+ echo '<meta name="viewport" content="width=device-width, minimum-scale=1.0, maximum-scale=1.0" />' . "\n";
+
+ }
+
+
+ public static function add_non_responsive_meta_viewport() {
+
+ echo '
+ <script type="text/javascript">
+ /* Headway Mobile device 100% width fix */
+ var meta = document.createElement("meta");
+ meta.setAttribute("name", "viewport");
+ meta.setAttribute("content", "width=" + document.body.scrollWidth);
+ document.head.appendChild(meta);
+ </script>
+ ';
+
+ }
+
+
+
+ public static function cookie_baker() {
+
+ /* If headers were already sent, then don't follow through with this function or it will err. */
+ if ( headers_sent() )
+ return false;
+
+ if ( headway_get('full-site') == 'true' )
+ return setcookie('headway-full-site', 1, time() + 60 * 60 * 24 * 7, '/');
+
+ if ( headway_get('full-site') == 'false' )
+ return setcookie('headway-full-site', false, time() - 3600, '/');
+
+ return false;
+
+ }
+
+
+}
\ No newline at end of file
--- /dev/null
+<?php
+class HeadwayRoute {
+
+
+ public static function init() {
+
+ /* For improved compatibility with Shopp and anything that modifies these hooks */
+ add_action('after_setup_theme', array(__CLASS__, 'remove_parsing_hooks'));
+
+ /* Parse request runs before 'wp', but does not have $post or query set up. This speeds things up and keeps 404s from happening */
+ add_action('parse_request', array(__CLASS__, 'maybe_run_trigger'), -1);
+
+ /* We use 'wp' on this so $post is set up so we can query meta */
+ add_action('wp', array(__CLASS__, 'maybe_redirect_301'));
+
+ /* Direct to VE, theme preview warning, or grid */
+ add_action('template_redirect', array(__CLASS__, 'direct'), 1);
+
+ }
+
+
+ /**
+ * To improve compatibility with plugins and prevent interference.
+ **/
+ public static function remove_parsing_hooks() {
+
+ if ( !self::is_visual_editor() && !self::is_visual_editor_iframe() )
+ return;
+
+ remove_all_actions('parse_query');
+ remove_all_actions('parse_request');
+
+ }
+
+
+ /**
+ * Direct index.php to the appropriate function
+ *
+ * @return bool
+ **/
+ public static function direct() {
+
+ //If viewing the visual editor, stop the template loading and show the visual editor.
+ if ( self::is_visual_editor() ) {
+
+ //If user is logged in and can't visually edit, loop them back to normal template.
+ if ( is_user_logged_in() && !HeadwayCapabilities::can_user_visually_edit() ) {
+
+ wp_die('You have insufficient permissions to use the Headway Visual Editor.<br /><br /><a href="' . home_url() . '">Return to Home</a>');
+
+ return false;
+
+ //If the user isn't logged in at all, log 'em in and loop back to visual editor as long as debug mode isn't active
+ } elseif ( !is_user_logged_in() && !HeadwayOption::get('debug-mode') ) {
+
+ return auth_redirect();
+
+ } else if ( defined('FORCE_SSL_ADMIN') && FORCE_SSL_ADMIN && !is_ssl() ) {
+
+ wp_safe_redirect(str_replace('http://', 'https://', headway_get_current_url()));
+ die();
+
+ }
+
+ HeadwayVisualEditor::display();
+ die();
+
+ //Theme Preview
+ } elseif ( self::is_grid() ) {
+
+ Headway::load('visual-editor/iframe-grid');
+
+ HeadwayVisualEditorIframeGrid::show();
+ die();
+
+ }
+
+ }
+
+
+ public static function maybe_run_trigger() {
+
+ if ( !self::is_trigger() )
+ return;
+
+ add_filter('restricted_site_access_is_restricted', '__return_false');
+
+ //Deactivate redirect so the weird 301's don't happen
+ remove_action('template_redirect', 'redirect_canonical');
+ add_filter('wp_redirect', '__return_false', 12);
+
+ //Cycle through
+ switch ( headway_get('headway-trigger') ) {
+
+ case 'compiler':
+ HeadwayCompiler::output_trigger();
+ break;
+
+ case 'layout-redirect':
+ self::redirect_to_layout();
+ break;
+
+ case 'media-uploader':
+ if ( !HeadwayCapabilities::can_user_visually_edit() )
+ die();
+
+ Headway::load('visual-editor/media-uploader');
+ break;
+
+ case 'ace-editor':
+ if ( !HeadwayCapabilities::can_user_visually_edit() )
+ die();
+
+ Headway::load('visual-editor/ace-editor');
+ break;
+
+ }
+
+ exit;
+
+ }
+
+
+ /**
+ * If a post, page, or any other singular item has the 301 Redirect set, then do the redirect.
+ **/
+ public static function maybe_redirect_301() {
+
+ global $post;
+
+ //Don't try redirecting if the headers are already sent. Otherwise, it'll result in an error and no redirect.
+ if ( headers_sent() )
+ return false;
+
+ //Make sure that it's a single post and that $post is a valid object.
+ if ( !is_object($post) || !is_singular() )
+ return false;
+
+ //Do not try redirecting if it's the visual editor or admin
+ if ( is_admin() || self::is_visual_editor() || self::is_visual_editor_iframe() )
+ return false;
+
+ //If the redirect URL isn't set, then don't try anything.
+ if ( !($redirect_url = HeadwayLayoutOption::get($post->ID, 'redirect-301', null, true, 'seo')) )
+ return false;
+
+ //If there is no HTTP or HTTPS in the URL, add it.
+ if ( strpos($redirect_url, 'http://') !== 0 && strpos($redirect_url, 'https://') !== 0 )
+ $redirect_url = 'http://' . $redirect_url;
+
+ wp_redirect($redirect_url, 301);
+ die();
+
+ }
+
+
+ /**
+ * Determine whether or not the site is being viewed in normal display mode.
+ *
+ * @return bool
+ **/
+ public static function is_display() {
+
+ if ( self::is_visual_editor() )
+ return false;
+
+ if ( self::is_trigger() )
+ return false;
+
+ if ( is_admin() )
+ return false;
+
+ return true;
+
+ }
+
+
+ /**
+ * Checks if the visual editor is open.
+ *
+ * @return bool
+ **/
+ public static function is_visual_editor() {
+
+ return headway_get('visual-editor', false);
+
+ }
+
+
+ public static function is_trigger() {
+
+ return ( headway_get('headway-trigger') ) ? true : false;
+
+ }
+
+
+ public static function is_theme_preview() {
+
+ return (headway_get('preview') == 1 && headway_get('preview_iframe') == 1) || headway_post('wp_customize');
+
+ }
+
+
+ public static function is_visual_editor_iframe($mode = null) {
+
+ if ( !headway_get('ve-iframe') || !HeadwayCapabilities::can_user_visually_edit() )
+ return false;
+
+ if ( $mode )
+ return headway_get('ve-iframe-mode') == $mode;
+
+ return true;
+
+ }
+
+
+ public static function is_grid() {
+
+ return self::is_visual_editor_iframe('grid');
+
+ }
+
+
+ /**
+ * Used for when a user clicks View Site in the Visual Editor
+ **/
+ public static function redirect_to_layout() {
+
+ remove_filter('wp_redirect', '__return_false', 12);
+
+ if ( headway_get('debug') && HeadwayCapabilities::can_user_visually_edit() )
+ wp_die(HeadwayLayout::get_url(headway_get('layout')));
+
+ return wp_safe_redirect(HeadwayLayout::get_url(headway_get('layout')));
+
+ }
+
+
+}
\ No newline at end of file
--- /dev/null
+<?php
+class HeadwaySEO {
+
+
+ public static function init() {
+
+ add_filter('get_comment_author_link', array(__CLASS__, 'comment_rel_nofollow'));
+
+ }
+
+
+ public static function is_private() {
+
+ if ( get_option('blog_public') == '0' )
+ return true;
+
+ return false;
+
+ }
+
+
+ public static function plugin_active() {
+
+ if ( defined('WPSEO_VERSION') )
+ return 'wpseo';
+
+ if ( class_exists('All_in_One_SEO_Pack') )
+ return 'aioseop';
+
+ return false;
+
+ }
+
+
+ /**
+ * Displays the title. Parses the variables.
+ **/
+ public static function output_title($title, $forced_title = null) {
+
+ if ( is_feed() )
+ return null;
+
+ if ( self::plugin_active() )
+ return $title;
+
+ $seo_templates_query = HeadwayOption::get('seo-templates', 'general', self::output_layouts_and_defaults());
+ $seo_templates = headway_get(HeadwaySEO::current_seo_layout(), $seo_templates_query, array());
+
+ if ( HeadwayLayoutOption::get(HeadwayLayout::get_current(), 'title', null, true, 'seo') )
+ $title = HeadwayLayoutOption::get(HeadwayLayout::get_current(), 'title', null, true, 'seo');
+
+ elseif ( headway_get('title', $seo_templates) )
+ $title = headway_get('title', $seo_templates);
+
+ /* If the template is %tagline% | %sitename% and there is no tagline, then remove the tagline and pipe character */
+ if ( $title === '%tagline% | %sitename%' && get_bloginfo('description') == false )
+ $title = '%sitename%';
+
+ /* Allow $forced_page_name to change %title%... Useful for plugins like BuddyPress */
+ if ( $forced_title )
+ $title = str_ireplace('%title%', $forced_title, $title);
+
+ return HeadwaySEO::parse_seo_variables($title);
+
+ }
+
+
+ public static function output_meta() {
+
+ if ( self::plugin_active() )
+ return false;
+
+ $meta = '';
+
+ $seo_templates = self::get_seo_templates(self::current_seo_layout());
+
+ //Description
+ if ( HeadwayLayoutOption::get(HeadwayLayout::get_current(), 'seo-description', null, true, 'seo') !== null )
+ $meta .= "\n" . '<meta name="description" content="' . self::parse_seo_variables(HeadwayLayoutOption::get(HeadwayLayout::get_current(), 'seo-description', null, true, 'seo')) . '" />';
+
+ elseif ( headway_get('description', $seo_templates) )
+ $meta .= "\n" . '<meta name="description" content="' . self::parse_seo_variables(headway_get('description', $seo_templates)) . '" />';
+
+ //Robots
+ $robot_settings = array();
+
+ if ( self::is_seo_checkbox_enabled('noindex') )
+ $robot_settings[] = 'noindex';
+
+ if ( self::is_seo_checkbox_enabled('noarchive') )
+ $robot_settings[] = 'noarchive';
+
+ if ( self::is_seo_checkbox_enabled('nosnippet') )
+ $robot_settings[] = 'nosnippet';
+
+ if ( self::is_seo_checkbox_enabled('noodp') )
+ $robot_settings[] = 'noodp';
+
+ if ( self::is_seo_checkbox_enabled('noydir') )
+ $robot_settings[] = 'noydir';
+
+ if ( count($robot_settings) !== 0 )
+ $meta .= "\n" . '<meta name="robots" content="' . implode(',', $robot_settings) . '" />';
+
+ if ( strlen($meta) !== 0 )
+ echo "\n\n" . '<!-- Headway SEO Juice -->' . $meta . "\n";
+
+ do_action('headway_seo_meta');
+
+ }
+
+
+ public static function is_seo_checkbox_enabled($option, $layout = false) {
+
+ if ( !$layout )
+ $layout = HeadwayLayout::get_current();
+
+ $seo_templates = self::get_seo_templates(self::current_seo_layout());
+
+ if ( HeadwayLayoutOption::get($layout, $option, null, true, 'seo') === null && !headway_get($option, $seo_templates) )
+ return false;
+
+ if ( HeadwayLayoutOption::get($layout, $option, null, true, 'seo') === false )
+ return false;
+
+ return true;
+
+ }
+
+
+ /**
+ * Filter that removes nofollow from the comment author URLs.
+ *
+ * @param string $url URL to be filtered.
+ *
+ * @return string $url URL after being filtered.
+ **/
+ public static function comment_rel_nofollow($url) {
+
+ if ( HeadwayOption::get('nofollow-comment-author-url') )
+ return $url;
+
+ return str_replace("rel='external nofollow'", "rel='external'", $url);
+
+ }
+
+
+ public static function current_seo_layout() {
+
+ /* Since the SEO templates are only at a certain level, checking the real layout against the SEO templates would not work. */
+
+ $layout_hierarchy = HeadwayLayout::get_current_hierarchy();
+
+ if ( count($layout_hierarchy) === 1 )
+ return $layout_hierarchy[0];
+ elseif ( count($layout_hierarchy) > 1 )
+ return $layout_hierarchy[1];
+
+ return null;
+
+ }
+
+
+ public static function parse_seo_variables($content) {
+
+ $tagline = get_option('blogdescription');
+ $sitename = get_option('blogname');
+
+ $queried_object = get_queried_object();
+
+ //Figure out the title variable
+ if ( is_front_page() || ( is_home() && get_option('show_on_front') != 'page' ) )
+ $title = 'Home';
+
+ elseif ( is_home() && get_option('show_on_front') == 'page' )
+ $title = 'Blog';
+
+ elseif ( is_singular() )
+ $title = get_the_title();
+
+ elseif ( is_archive() ) {
+
+ if ( is_category() ) {
+
+ $title = single_cat_title('', false);
+
+ } elseif ( is_date() ) {
+
+ if ( is_day() )
+ $title = get_the_time(get_option('date_format'));
+ elseif ( is_month() )
+ $title = get_the_time('F Y');
+ elseif ( is_year() )
+ $title = get_the_time('Y');
+
+ } elseif ( is_author() ) {
+
+ $author = get_queried_object();
+ $title = $author->display_name;
+
+ } elseif ( is_tag() ) {
+
+ $title = single_tag_title('', false);
+
+ } elseif ( is_tax() ) {
+
+ $taxonomy = get_taxonomy($queried_object->taxonomy);
+ $term = get_term($queried_object->term_id, $queried_object->taxonomy);
+
+ $title = $taxonomy->labels->singular_name;
+ $meta = $term->name;
+
+ } elseif ( is_post_type_archive() ) {
+
+ $post_type = get_post_type_object($queried_object->name);
+
+ $title = $post_type->labels->name;
+
+ }
+
+ } elseif ( is_search() )
+ $title = get_search_query();
+
+ elseif ( is_404() )
+ $title = '404';
+
+ elseif ( is_feed() )
+ $title = 'Feed';
+
+
+ if ( isset($title) ) {
+
+ $search = array(
+ '%title%',
+ '%category%',
+ '%archive%',
+ '%search%',
+ '%author%',
+ '%tag%',
+ '%post_type_plural%',
+ '%taxonomy%'
+ );
+
+ //Replace title variables
+ $content = str_ireplace($search, $title, $content);
+
+ }
+
+ if ( isset($meta) ) {
+
+ $search = array(
+ '%meta%'
+ );
+
+ $content = str_ireplace($search, $meta, $content);
+
+ }
+
+ $content = str_ireplace('%sitename%', $sitename, $content);
+ $content = str_ireplace('%tagline%', $tagline, $content);
+
+ return esc_attr(stripslashes(strip_tags($content)));
+
+ }
+
+
+ public static function get_seo_templates($layout = false) {
+
+ $seo_templates_query = HeadwayOption::get('seo-templates', 'general', self::output_layouts_and_defaults());
+
+ if ( $layout )
+ return headway_get(self::current_seo_layout(), $seo_templates_query, array());
+ else
+ return $seo_templates_query;
+
+ }
+
+
+ public static function output_layouts_and_defaults() {
+
+ if ( get_option('show_on_front') == 'page' ) {
+
+ $pages = array(
+ 'front_page' => array(
+ 'title' => '%tagline% | %sitename%'
+ ),
+ 'index' => array(
+ 'title' => '%tagline% | %sitename%'
+ ),
+ );
+
+ } else {
+
+ $pages = array(
+ 'index' => array(
+ 'title' => '%tagline% | %sitename%'
+ )
+ );
+
+ }
+
+ //Custom Post Types
+ $excluded_post_type_archives = array('post', 'page', 'attachment');
+ $post_types = get_post_types(array('public' => true), 'objects');
+
+ foreach($post_types as $post_type) {
+ $pages['single-' . $post_type->name] = array(
+ 'title' => '%title% | %sitename%'
+ );
+
+ //If excluded post type archive, skip it
+ if ( !in_array($post_type->name, $excluded_post_type_archives) )
+ $pages['archive-post_type-' . $post_type->name] = array(
+ 'title' => '%post_type_plural% | %sitename%'
+ );
+ }
+
+ //Archives
+ $pages = array_merge($pages, array(
+ 'archive-category' => array(
+ 'title' => '%title% | %sitename%'
+ ),
+ 'archive-search' => array(
+ 'title' => 'Search: %title% | %sitename%',
+ 'noarchive' => true
+ ),
+ 'archive-date' => array(
+ 'title' => '%title% | %sitename%'
+ ),
+ 'archive-author' => array(
+ 'title' => '%title% | %sitename%'
+ ),
+ 'archive-post_tag' => array(
+ 'title' => 'Tag: %title% | %sitename%'
+ ),
+ 'archive-taxonomy' => array(
+ 'title' => '%title%: %meta% | %sitename%'
+ ),
+ 'archive-post_type' => array(
+ 'title' => '%post_type_plural% | %sitename%'
+ ),
+ 'four04' => array(
+ 'title' => 'Whoops! Page Not Found | %sitename%'
+ )
+ ));
+
+ return $pages;
+
+ }
+
+
+}
\ No newline at end of file
--- /dev/null
+<?php
+class HeadwaySocialOptimization {
+
+
+ public static function init() {
+
+ add_action('wp_loaded', array(__CLASS__, 'allow_rel_attr'));
+
+ add_filter('user_contactmethods', array(__CLASS__, 'add_headway_contact_methods'));
+
+ }
+
+
+ public static function allow_rel_attr() {
+
+ global $allowedtags;
+
+ $allowedtags['a']['rel'] = array();
+
+ }
+
+
+ public static function add_headway_contact_methods($contact_methods) {
+
+ //Add Extra Profile Links
+ $contact_methods['twitter'] = 'Twitter URL';
+ $contact_methods['facebook'] = 'Facebook URL';
+ $contact_methods['google_profile'] = 'Google Profile URL';
+ $contact_methods['about_page_URL'] = 'About Page URL';
+
+ return $contact_methods;
+
+ }
+
+
+}
\ No newline at end of file
--- /dev/null
+<?php
+class HeadwayTemplates {
+
+
+ public static function get($id) {
+
+ $all_skins = self::get_all(true);
+
+ return headway_get($id, $all_skins);
+
+ }
+
+
+ public static function get_all($associative = false, $info_only = true) {
+
+ $skins = array(
+ array(
+ 'id' => 'base',
+ 'name' => 'Base',
+ 'author' => 'Headway Themes',
+ 'version' => HEADWAY_VERSION,
+ 'image-url' => headway_url() . '/screenshot.png',
+ 'description' => null
+ )
+ );
+
+ $installed_skins = HeadwayOption::get_group('skins');
+
+ if ( !$installed_skins ) {
+ $installed_skins = array();
+ }
+
+ if ( !empty($installed_skins) && is_array($installed_skins) ) {
+
+ foreach ( $installed_skins as $installed_skin_id => $installed_skin ) {
+
+ $skin = array_merge(array(
+ 'id' => $installed_skin_id,
+ 'description' => null,
+ 'version' => null,
+ 'author' => null
+ ), $installed_skin);
+
+ if ( $info_only ) {
+
+ foreach ( $skin as $skin_key => $skin_value ) {
+
+ $keys_allowed = array(
+ 'id',
+ 'name',
+ 'author',
+ 'version',
+ 'image-url',
+ 'description'
+ );
+
+ if ( !in_array($skin_key, $keys_allowed) ) {
+ unset($skin[$skin_key]);
+ }
+
+ }
+
+ }
+
+ $skins[] = $skin;
+
+ }
+
+ }
+
+ /* Resize all images */
+ foreach ( $skins as $skin_index => $skin ) {
+
+ $skins[$skin_index]['image-url'] = headway_resize_image(headway_get('image-url', $skin), 220, 190);
+
+ if ( !$skins[$skin_index]['image-url'] || is_wp_error($skins[$skin_index]['image-url']) )
+ $skins[$skin_index]['image-url'] = headway_get('image-url', $skin);
+
+ }
+
+
+ if ( $associative ) {
+
+ $associative_skins = array();
+
+ foreach ( $skins as $skin )
+ $associative_skins[$skin['id']] = $skin;
+
+ return $associative_skins;
+
+ }
+
+ return $skins;
+
+ }
+
+
+ public static function get_active() {
+
+ $current_skin_id = HeadwayOption::get('current-skin', 'general', HEADWAY_DEFAULT_SKIN);
+ $all_skins = self::get_all(true);
+
+ return headway_get($current_skin_id, $all_skins, headway_get(HEADWAY_DEFAULT_SKIN, $all_skins));
+
+ }
+
+
+ public static function get_active_id() {
+
+ $active_skin = self::get_active();
+
+ return $active_skin['id'];
+
+ }
+
+
+ public static function add() {
+
+
+
+ }
+
+
+ public static function delete() {
+
+
+
+ }
+
+
+}
\ No newline at end of file
--- /dev/null
+<?php
+class HeadwayCompatibilityWooCommerce {
+
+
+ public static function init() {
+
+ /* Check requirements */
+ if ( !self::check_requirements() )
+ return;
+
+ /* Load things */
+ require_once HEADWAY_LIBRARY_DIR . '/compatibility/woocommerce/woocommerce-breadcrumbs.php';
+
+ require_once HEADWAY_LIBRARY_DIR . '/compatibility/woocommerce/woocommerce-design-elements.php';
+ require_once HEADWAY_LIBRARY_DIR . '/compatibility/woocommerce/woocommerce-design-defaults.php';
+
+ /* Handle elements */
+ add_action('headway_register_elements', 'headway_storefront_wc_register_elements', 50);
+ add_filter('headway_element_data_defaults', 'headway_storefront_wc_design_defaults', 50);
+
+ /* Remove WooCommerce Breadcrumbs */
+ remove_action( 'woocommerce_before_main_content', 'woocommerce_breadcrumb', 20, 0 );
+
+ /* Setup hooks */
+ add_action('init', array(__CLASS__, 'disallow_edit_of_shop_page'));
+ add_action('wp', array(__CLASS__, 'enqueue_styles'));
+
+ /* Add theme support for WooCommerce */
+ add_theme_support('woocommerce');
+
+ }
+
+
+ public static function check_requirements() {
+
+ if ( !class_exists('WooCommerce') )
+ return false;
+
+ return true;
+
+ }
+
+
+ public static function enqueue_styles() {
+
+ if ( is_admin() )
+ return;
+
+ wp_enqueue_style('headway-storefront-wooc', headway_url() . '/library/compatibility/woocommerce/headway-storefront-wooc.css');
+
+ }
+
+
+
+ public static function disallow_edit_of_shop_page() {
+
+ add_filter('headway_layout_selector_no_edit_item_single-page-' . woocommerce_get_page_id('shop'), '__return_true');
+
+ }
+
+
+}
\ No newline at end of file
--- /dev/null
+/* Resets shadows, etc for more expected results with Headway Design Editor */
+ul.products li.product a img,
+ul.products li.product a:hover img,
+div.product div.images img,
+#content div.product div.images img {
+ box-shadow: none;
+ -moz-box-shadow: none;
+ -webkit-box-shadow: none;
+
+ transition: none;
+ -moz-transition: none;
+ -webkit-transition: none;
+
+ box-sizing: border-box;
+ -moz-box-sizing: border-box;
+}
+
+ul.products li.product .price del,
+ul.products li.product .price .from {
+ font-size: 100%;
+}
+
+.woocommerce-page .products ul li,
+.woocommerce-page ul.products li,
+.woocommerce-page #payment ul.payment_methods li {
+ list-style: none;
+}
+
+button.button,
+input.button {
+ height: 25px;
+ line-height: 100%;
+}
+
+.related ul.products li.product,
+.related ul li.product,
+.upsells.products ul.products li.product,
+.upsells.products ul li.product {
+ width: auto;
+}
+
+ul.products li.product .price .from {
+ text-transform: none;
+}
+
+div.product span.price del, div.product p.price del, #content div.product span.price del, #content div.product p.price del {
+ font-size: inherit;
+}
+
+
+/* Layout */
+body.woocommerce div.block-type-content {
+ overflow: visible;
+}
+
+ul.products li.product {
+ box-sizing: border-box;
+ -moz-box-sizing: border-box;
+ clear: none;
+}
+
+.woocommerce_ordering {
+ width: 50%;
+ float: right;
+ text-align: right;
+}
+
+ul.products li.product .btn,
+ul.products li.product .button {
+ margin-top: 10px;
+ float: left;
+}
+
+div.product div.summary div[itemprop="description"] {
+ margin: 15px 0;
+}
+
+
+/* Product Reviews */
+.woocommerce div.entry-content ol.commentlist {
+ padding: 0;
+}
+
+.woocommerce div.entry-content ol.commentlist li {
+ list-style: none;
+}
+
+div.pp_woocommerce .pp_content {
+ height: auto !important;
+}
+
+div.pp_woocommerce div.pp_content_container {
+ padding: 30px 0 20px;
+}
+
+div.pp_woocommerce .pp_content_container h3#reply-title {
+ font-size: 24px;
+}
+
+div.pp_woocommerce .pp_content_container div#respond label {
+ font-weight: bold;
+ margin: 10px 0;
+ display: block;
+ float: none;
+}
+
+
+/* Widgets */
+.block-type-widget-area li.widget ul.cart_list,
+.block-type-widget-area li.widget ul.product_list_widget,
+.block-type-widget-area li.widget_layered_nav ul {
+ margin: 0;
+ padding: 0;
+ list-style: none;
+}
+
+/* Cart */
+.block-type-widget-area li.widget_shopping_cart a.button {
+ font-size: 80%;
+}
+
+.block-type-widget-area .widget_shopping_cart .total {
+ padding-top: 7px;
+}
+
+.block-type-widget-area .widget_shopping_cart .buttons {
+ margin: 10px 0 0;
+}
+
+/* Layered Nav */
+.block-type-widget-area .widget_layered_nav ul li.chosen a {
+ text-decoration: none;
+}
\ No newline at end of file
--- /dev/null
+<?php
+add_filter('headway_breadcrumbs', 'headway_wc_breadcrumbs');
+function headway_wc_breadcrumbs($breadcrumbs) {
+
+ /* Product Archive Page */
+ if ( is_post_type_archive('product') && get_option('page_on_front') !== woocommerce_get_page_id('shop') ) {
+
+ $shop_page_id = woocommerce_get_page_id('shop');
+
+ $shop_name = $shop_page_id ? get_the_title($shop_page_id) : ucwords(get_option('woocommerce_shop_slug'));
+
+ if ( is_search() ) {
+
+ $breadcrumbs[] = __('Search results for “', 'woocommerce') . get_search_query();
+ $breadcrumbs[get_post_type_archive_link('product')] = $shop_name;
+
+ } else {
+
+ $breadcrumbs[get_post_type_archive_link('product')] = $shop_name;
+
+ }
+
+ }
+ /* End Product Archive Page */
+
+ /* Shop Taxonomy Archives */
+ if ( is_tax('product_cat') || is_tax('product_tag') ) {
+
+ $shop_url = get_option('woocommerce_prepend_shop_page_to_urls');
+ $shop_page_id = woocommerce_get_page_id('shop');
+ $shop_title = get_the_title($shop_page_id);
+
+ if ( 'yes' == $shop_url && $shop_page_id && get_option('page_on_front') !== $shop_page_id )
+ $breadcrumbs[get_permalink($shop_page_id)] = $shop_title;
+
+ }
+
+ /* Shop Categories */
+ if ( is_tax( 'product_cat' ) ) {
+
+ $term = get_term_by('slug', get_query_var('term'), get_query_var('taxonomy'));
+
+ /* Get parent categories */
+ $parents = array();
+ $parent = $term->parent;
+
+ while ( $parent ) {
+
+ $parents[] = $parent;
+
+ $new_parent = get_term_by('id', $parent, get_query_var('taxonomy'));
+ $parent = $new_parent->parent;
+
+ }
+
+ /* Output parent categories */
+ if ( !empty($parents) ) {
+
+ $parents = array_reverse($parents);
+
+ foreach ( $parents as $parent ) {
+
+ $item = get_term_by('id', $parent, get_query_var('taxonomy'));
+
+ $breadcrumbs[get_term_link($item->slug, 'product_cat')] = $item->name;
+
+ }
+
+ }
+
+ /* Add current category */
+ $breadcrumbs[] = single_term_title('', false);
+
+ }
+
+ /* Shop Tags */
+ if ( is_tax('product_tag') ) {
+
+ $breadcrumbs[] = __('Products tagged “', 'hw_sf_wooc') . single_term_title('', false) . _x('”', 'endquote', 'hw_sf_wooc');
+
+ }
+ /* End Shop Taxonomy Archives */
+
+ /* Single Product */
+ if ( is_singular('product') ) {
+
+ /* Remove the current title at end of breadcrumbs. This is easier than trying to put the following items before this item being removed */
+ array_pop($breadcrumbs);
+
+ global $post;
+
+ /* Shop prefix */
+ $shop_url = get_option('woocommerce_prepend_shop_page_to_products');
+ $shop_page_id = woocommerce_get_page_id('shop');
+ $shop_title = get_the_title($shop_page_id);
+
+ if ( 'yes' == $shop_url && $shop_page_id && get_option('page_on_front') !== $shop_page_id )
+ $breadcrumbs[get_permalink($shop_page_id)] = $shop_title;
+
+ /* Product categories */
+ if ( $terms = wp_get_object_terms($post->ID, 'product_cat') ) {
+
+ $term = current($terms);
+ $parents = array();
+ $parent = $term->parent;
+
+ /* Get parent categories */
+ while ( $parent ) {
+
+ $parents[] = $parent;
+
+ $new_parent = get_term_by('id', $parent, 'product_cat');
+ $parent = $new_parent->parent;
+
+ }
+
+ /* Output parent categories */
+ if ( !empty($parents) ) {
+
+ $parents = array_reverse($parents);
+
+ foreach ( $parents as $parent ) {
+
+ $item = get_term_by('id', $parent, 'product_cat');
+ $breadcrumb[get_term_link($item->slug, 'product_cat')] = $item->name;
+
+ }
+
+ }
+
+ /* Output main category */
+ $breadcrumbs[get_term_link($term->slug, 'product_cat')] = $term->name;
+
+ }
+
+ /* Current product */
+ $breadcrumbs[] = get_the_title();
+
+ }
+ /* End Single Product */
+
+ return $breadcrumbs;
+
+}
\ No newline at end of file
--- /dev/null
+<?php
+function headway_storefront_wc_design_defaults($existing_defaults) {
+
+ return array_merge($existing_defaults, array(
+ 'block-content-wc-breadcrumbs' => array(
+ 'properties' => array(
+ 'margin-top' => '10'
+ )
+ ),
+
+ 'block-content-wc-page-title' => array(
+ 'properties' => array(
+ 'font-size' => '24',
+ 'line-height' => '160'
+ )
+ ),
+
+ 'block-content-wc-product-page-short-description' => array(
+ 'properties' => array(
+ 'line-height' => '130'
+ )
+ ),
+
+ 'block-content-wc-related-products-heading' => array(
+ 'properties' => array(
+ 'font-size' => '20',
+ 'line-height' => '150',
+ 'margin-bottom' => '10'
+ )
+ )
+ ));
+
+}
\ No newline at end of file
--- /dev/null
+<?php
+function headway_storefront_wc_register_elements() {
+
+ HeadwayElementAPI::register_element(array(
+ 'group' => 'blocks',
+ 'id' => 'block-content-wc-page-title',
+ 'parent' => 'block-content',
+ 'name' => 'Shop Title',
+ 'description' => 'Storefront: WooCommerce',
+ 'selector' => '.woocommerce .block-type-content h1.page-title'
+ ));
+
+ HeadwayElementAPI::register_element(array(
+ 'group' => 'blocks',
+ 'id' => 'block-content-wc-breadcrumbs',
+ 'parent' => 'block-content',
+ 'name' => 'Breadcrumbs',
+ 'description' => 'Storefront: WooCommerce',
+ 'selector' => '.woocommerce .block-type-content .woocommerce-breadcrumb'
+ ));
+
+
+ /* Product Listings */
+ HeadwayElementAPI::register_element(array(
+ 'group' => 'blocks',
+ 'id' => 'block-content-wc-listings-product-containers',
+ 'parent' => 'block-content',
+ 'name' => 'Product Listings',
+ 'description' => 'Storefront: WooCommerce',
+ 'selector' => '.woocommerce .block-type-content ul.products li.product'
+ ));
+
+ HeadwayElementAPI::register_element(array(
+ 'group' => 'blocks',
+ 'id' => 'block-content-wc-listings-product-names',
+ 'parent' => 'block-content-wc-listings-product-containers',
+ 'name' => 'Product Listings: Names',
+ 'description' => 'Storefront: WooCommerce',
+ 'selector' => '.woocommerce .block-type-content ul.products li.product h3'
+ ));
+
+ HeadwayElementAPI::register_element(array(
+ 'group' => 'blocks',
+ 'id' => 'block-content-wc-listings-product-images',
+ 'parent' => 'block-content-wc-listings-product-containers',
+ 'name' => 'Product Listings: Images',
+ 'description' => 'Storefront: WooCommerce',
+ 'selector' => '.woocommerce .block-type-content ul.products li.product img'
+ ));
+
+ HeadwayElementAPI::register_element(array(
+ 'group' => 'blocks',
+ 'id' => 'block-content-wc-listings-product-prices',
+ 'parent' => 'block-content-wc-listings-product-containers',
+ 'name' => 'Product Listings: Prices',
+ 'description' => 'Storefront: WooCommerce',
+ 'selector' => '.woocommerce .block-type-content ul.products li.product span.amount'
+ ));
+ /* End Product Listings */
+
+
+ /* Product Pages */
+ HeadwayElementAPI::register_element(array(
+ 'group' => 'blocks',
+ 'id' => 'block-content-wc-product-page-name',
+ 'parent' => 'block-content',
+ 'name' => 'Product Page: Name',
+ 'description' => 'Storefront: WooCommerce',
+ 'selector' => '.woocommerce .block-type-content div.product div.summary h1.product_title'
+ ));
+
+ HeadwayElementAPI::register_element(array(
+ 'group' => 'blocks',
+ 'id' => 'block-content-wc-product-page-image',
+ 'parent' => 'block-content',
+ 'name' => 'Product Page: Image',
+ 'indent-in-selector' => true,
+ 'description' => 'Storefront: WooCommerce',
+ 'selector' => '.woocommerce .block-type-content div.product div.images img'
+ ));
+
+ HeadwayElementAPI::register_element(array(
+ 'group' => 'blocks',
+ 'id' => 'block-content-wc-product-page-price',
+ 'parent' => 'block-content',
+ 'name' => 'Product Page: Price',
+ 'indent-in-selector' => true,
+ 'description' => 'Storefront: WooCommerce',
+ 'selector' => '.woocommerce .block-type-content div.product div.summary p.price'
+ ));
+
+ HeadwayElementAPI::register_element(array(
+ 'group' => 'blocks',
+ 'id' => 'block-content-wc-product-page-short-description',
+ 'parent' => 'block-content',
+ 'name' => 'Product Page: Short Description',
+ 'indent-in-selector' => true,
+ 'description' => 'Storefront: WooCommerce',
+ 'selector' => '.woocommerce .block-type-content div.product div.summary div[itemprop="description"]'
+ ));
+ /* End Product Pages */
+
+
+ /* Related Products */
+ HeadwayElementAPI::register_element(array(
+ 'group' => 'blocks',
+ 'id' => 'block-content-wc-related-products',
+ 'parent' => 'block-content',
+ 'name' => 'Related Products Container',
+ 'description' => 'Storefront: WooCommerce',
+ 'selector' => '.woocommerce .block-type-content div.related'
+ ));
+
+ HeadwayElementAPI::register_element(array(
+ 'group' => 'blocks',
+ 'id' => 'block-content-wc-related-products-heading',
+ 'parent' => 'block-content',
+ 'name' => 'Related Products Heading',
+ 'indent-in-selector' => true,
+ 'description' => 'Storefront: WooCommerce',
+ 'selector' => '.woocommerce .block-type-content div.related h2'
+ ));
+
+ HeadwayElementAPI::register_element(array(
+ 'group' => 'blocks',
+ 'id' => 'block-content-wc-related-products-product',
+ 'parent' => 'block-content',
+ 'name' => 'Related Product Container',
+ 'indent-in-selector' => true,
+ 'description' => 'Storefront: WooCommerce',
+ 'selector' => '.woocommerce .block-type-content div.related li.product'
+ ));
+ /* End Related Products */
+
+
+}
\ No newline at end of file
--- /dev/null
+<?php
+class HeadwayBlocksData {
+
+
+ public static function add_block($layout_id, $args) {
+
+ global $wpdb;
+
+ /* Validate input */
+ if ( !$args || !is_array($args) )
+ return false;
+
+ if ( !headway_get('type', $args) )
+ return new WP_Error('hw_add_block_missing_type');
+
+ if ( !is_array($args['dimensions']) && !is_serialized($args['dimensions']) )
+ return new WP_Error('hw_add_block_missing_dimensions');
+
+ if ( !is_array($args['position']) && !is_serialized($args['position']) )
+ return new WP_Error('hw_add_block_missing_position');
+
+ /* Make sure the arrays are all unserialized */
+ $args['position'] = headway_maybe_unserialize($args['position']);
+ $args['dimensions'] = headway_maybe_unserialize($args['dimensions']);
+ $args['settings'] = headway_maybe_unserialize($args['settings']);
+
+ //Figure out mirror ID
+ $mirror_id = headway_get('mirror-block', headway_get('settings', $args, array()));
+
+ //Unset old mirror ID
+ if ( isset($args['settings']['mirror-block']) )
+ unset($args['settings']['mirror-block']);
+
+ //Build insert args
+ $random_prefix = substr(str_shuffle(str_repeat("0123456789abcdefghijklmnopqrstuvwxyz", 2)), 0, 2);
+
+ $insert_args = array(
+ 'id' => uniqid('b' . strtolower(substr($random_prefix, 0, 2))),
+ 'template' => headway_get('template', $args, HeadwayOption::$current_skin),
+ 'layout' => $layout_id,
+ 'type' => $args['type'],
+ 'wrapper_id' => headway_get('wrapper', $args),
+ 'position' => headway_maybe_serialize($args['position']),
+ 'dimensions' => headway_maybe_serialize($args['dimensions']),
+ 'settings' => headway_maybe_serialize(headway_get('settings', $args, array())),
+ 'mirror_id' => $mirror_id
+ );
+
+ //Is a pre-defined ID required?
+ if ( $insert_id = headway_get( 'insert_id', $args ) )
+ $insert_args['id'] = $insert_id;
+
+ if ( $legacy_id = headway_get( 'legacy_id', $args ) )
+ $insert_args['legacy_id'] = $legacy_id;
+
+ //Run the query
+ $wpdb->insert($wpdb->hw_blocks, $insert_args);
+
+ //All done. Spit back ID of newly created block.
+ return $insert_args['id'];
+
+ }
+
+
+ public static function update_block($block_id, $args) {
+
+ global $wpdb;
+
+ $block_to_be_updated = self::get_block($block_id);
+
+ /* Make sure block exists */
+ if ( !$block_to_be_updated )
+ return null;
+
+ /* Map old args */
+ if ( isset($args['wrapper']) ) {
+
+ $args['wrapper_id'] = $args['wrapper'];
+ unset($args['wrapper']);
+
+ }
+
+ /* Map mirror-block setting to mirror_id column */
+ if ( isset($args['settings']) && isset($args['settings']['mirror-block']) ) {
+
+ $args['mirror_id'] = $args['settings']['mirror-block'];
+ unset($args['settings']['mirror-block']);
+
+ }
+
+ /* Handle template argument */
+ $template = headway_get('template', $args, HeadwayOption::$current_skin);
+
+ if ( isset($args['template']) )
+ unset($args['template']);
+
+ /* Query */
+ $query = $wpdb->update($wpdb->hw_blocks, array_map('headway_maybe_serialize', $args), array(
+ 'template' => $template,
+ 'id' => $block_id
+ ));
+
+ return $query;
+
+ }
+
+
+ public static function delete_block($block_id) {
+
+ global $wpdb;
+
+ $block_to_be_deleted = self::get_block($block_id);
+
+ /* Make sure block exists */
+ if ( !$block_to_be_deleted )
+ return null;
+
+ /* Query for deletion */
+ $query = $wpdb->delete( $wpdb->hw_blocks, array(
+ 'template' => HeadwayOption::$current_skin,
+ 'id' => $block_id
+ ));
+
+ /* Unmirror the blocks mirroring this block */
+ $wpdb->update( $wpdb->hw_blocks, array(
+ 'mirror_id' => ''
+ ), array(
+ 'mirror_id' => $block_id
+ ));
+
+ /* Get block type */
+ $block_type = $block_to_be_deleted['type'];
+
+ /* Remove design settings and instances for this block */
+ self::delete_block_design_instances($block_id, $block_type);
+
+ return $query;
+
+ }
+
+
+ public static function delete_block_design_instances($block_id, $block_type) {
+
+ HeadwayElementAPI::register_elements_hook();
+
+ $block_element = HeadwayElementAPI::get_element('block-' . $block_type);
+
+ /* Start by queuing the instance of the block element */
+ $instances_to_delete = array(
+ 'block-' . $block_type => $block_type . '-block-' . $block_id
+ );
+
+ /* Find all block children element instances and queue them to be deleted */
+ foreach ( HeadwayElementAPI::get_block_elements($block_type) as $element_id => $element_info )
+ $instances_to_delete[$element_id] = $element_id . '-block-' . $block_id;
+
+ /* Delete the instances now */
+ foreach ( $instances_to_delete as $element_id => $instance_id )
+ HeadwayElementsData::delete_special_element_properties('blocks', $element_id, 'instance', $instance_id);
+
+ }
+
+
+ public static function delete_by_layout($layout_id) {
+
+ global $wpdb;
+
+ $layout_blocks = self::get_blocks_by_layout($layout_id);
+
+ foreach ( $layout_blocks as $block_id => $options ) {
+
+ //Delete design instances
+ self::delete_block_design_instances($block_id, $options['type']);
+
+ /* Unmirror the blocks mirroring this block */
+ $wpdb->update( $wpdb->hw_blocks, array(
+ 'mirror_id' => ''
+ ), array(
+ 'mirror_id' => $block_id
+ ));
+
+ }
+
+ //Query to delete blocks
+ $query = $wpdb->delete( $wpdb->hw_blocks, array(
+ 'template' => HeadwayOption::$current_skin,
+ 'layout' => $layout_id
+ ));
+
+ return $query;
+
+ }
+
+
+ public static function delete_by_wrapper($layout_id, $wrapper_id) {
+
+ global $wpdb;
+
+ $wrapper_blocks = self::get_blocks_by_layout($layout_id, $wrapper_id);
+
+ foreach ( $wrapper_blocks as $block_id => $options ) {
+
+ //Delete design instances
+ self::delete_block_design_instances($block_id, $options['type']);
+
+ /* Unmirror the blocks mirroring this block */
+ $wpdb->update( $wpdb->hw_blocks, array(
+ 'mirror_id' => ''
+ ), array(
+ 'mirror_id' => $block_id
+ ));
+
+
+ }
+
+ //Query to delete blocks
+ $query = $wpdb->delete( $wpdb->hw_blocks, array(
+ 'template' => HeadwayOption::$current_skin,
+ 'wrapper_id' => $wrapper_id,
+ 'layout' => $layout_id
+ ));
+
+ return $query;
+
+ }
+
+
+ public static function delete_by_template($template) {
+
+ global $wpdb;
+
+ return $wpdb->delete( $wpdb->hw_blocks, array(
+ 'template' => $template
+ ));
+
+ }
+
+
+ public static function get_block($block_id_or_obj, $use_mirrored = false) {
+
+ global $wpdb;
+
+ /* If a block array is supplied, make sure it is legitimate. */
+ if ( is_array( $block_id_or_obj) ) {
+
+ if ( !isset( $block_id_or_obj['id']) && !headway_get('new', $block_id_or_obj, false) )
+ return null;
+
+ $block = $block_id_or_obj;
+
+ /* Fetch the block based off of ID */
+ } elseif ( is_string( $block_id_or_obj) || is_numeric( $block_id_or_obj) ) {
+
+ /* Build cache key */
+ $cache_key = 'hw_block_' . $block_id_or_obj;
+
+ /* Check cache */
+ $block_from_cache = wp_cache_get($cache_key);
+
+ if ( $block_from_cache === false ) {
+
+ $block = $wpdb->get_row($wpdb->prepare("SELECT * FROM $wpdb->hw_blocks WHERE template = '%s' AND id = '%s'", HeadwayOption::$current_skin, $block_id_or_obj), ARRAY_A);
+
+ if ( is_array($block) && !is_wp_error($block) ) {
+
+ $block = array_map('headway_maybe_unserialize', $block);
+
+ } else {
+
+ /* If no block is found, try querying the legacy_id */
+ $block_from_legacy_id = $wpdb->get_row( $wpdb->prepare( "SELECT * FROM $wpdb->hw_blocks WHERE template = '%s' AND legacy_id = '%d'", HeadwayOption::$current_skin, $block_id_or_obj ), ARRAY_A );
+
+ if ( is_array($block_from_legacy_id) && ! is_wp_error( $block_from_legacy_id ) ) {
+ $block = array_map( 'headway_maybe_unserialize', $block_from_legacy_id );
+ } else {
+ $block = null;
+ }
+
+ }
+
+ wp_cache_set($cache_key, $block);
+
+ } else {
+
+ $block = $block_from_cache;
+
+ }
+
+ /* No valid argument provided. */
+ } else {
+
+ return null;
+
+ }
+
+ /* Fetch the mirrored block if $use_mirrored is true */
+ if ( $use_mirrored === true && $mirrored_block = self::get_block_mirror($block) )
+ $block = $mirrored_block;
+
+ return $block;
+
+ }
+
+
+ public static function get_blocks_by_layout($layout_id, $wrapper_id = false, $include_design_editor_instances = false) {
+
+ global $wpdb;
+
+ /* Build cache key */
+ $cache_key = 'hw_blocks_by_layout_' . $layout_id;
+
+ if ( $wrapper_id )
+ $cache_key = $cache_key . '_wrapper_' . $wrapper_id;
+
+ if ( $include_design_editor_instances )
+ $cache_key = $cache_key . '_with_design';
+
+ /* Check cache */
+ $layout_blocks = wp_cache_get($cache_key);
+
+ if ( $layout_blocks === false ) {
+
+ /* Retrieve all blocks from layout */
+ $query_string = $wpdb->prepare("SELECT * FROM $wpdb->hw_blocks WHERE layout = '%s' AND template = '%s'", $layout_id, HeadwayOption::$current_skin);
+
+ if ( $wrapper_id )
+ $query_string .= " AND wrapper_id = '$wrapper_id'";
+
+ $layout_blocks_query = $wpdb->get_results($query_string, ARRAY_A);
+
+ /* Change results array into associative */
+ $layout_blocks = array();
+
+ foreach ( $layout_blocks_query as $layout_block ) {
+
+ $layout_blocks[$layout_block['id']] = array_map('headway_maybe_unserialize', $layout_block);
+
+ /* Add design editor instance in if set to do so */
+ if ( $include_design_editor_instances ) {
+
+ $layout_blocks[$layout_block['id']]['styling'] = self::get_block_styling($layout_block);
+
+ }
+
+ }
+
+ wp_cache_set($cache_key, $layout_blocks);
+
+ }
+
+ return $layout_blocks;
+
+ }
+
+
+ public static function get_block_styling($block) {
+
+ do_action('headway_before_get_block_styling');
+
+ $block_element = HeadwayElementAPI::get_element('block-' . $block['type']);
+
+ /* Set up styling array */
+ $styling = array();
+
+ /* Get block instance styling */
+ $block_instance_properties = HeadwayElementsData::get_special_element_properties(array(
+ 'element' => 'block-' . $block['type'],
+ 'se_type' => 'instance',
+ 'se_meta' => $block['type'] . '-block-' . $block['id']
+ ));
+
+ if ( !empty($block_instance_properties) ) {
+
+ $styling[$block['type'] . '-block-' . $block['id']] = array(
+ 'element' => 'block-' . $block['type'],
+ 'properties' => $block_instance_properties
+ );
+
+ }
+
+ /* Get block children element instances (which could be a LOT) */
+ foreach ( HeadwayElementAPI::get_block_elements($block['type']) as $block_element_sub_element ) {
+
+ /* Make sure that the element supports instances */
+ if ( !headway_get('supports-instances', $block_element_sub_element) )
+ continue;
+
+ $sub_element_instance_id = $block_element_sub_element['id'] . '-block-' . $block['id'];
+
+ $sub_element_instance_properties = HeadwayElementsData::get_special_element_properties(array(
+ 'element' => $block_element_sub_element['id'],
+ 'se_type' => 'instance',
+ 'se_meta' => $sub_element_instance_id
+ ));
+
+ /* Only add sub element instance if there are properties present */
+ if ( !empty($sub_element_instance_properties) ) {
+
+ $styling[$sub_element_instance_id] = array(
+ 'element' => $block_element_sub_element['id'],
+ 'properties' => $sub_element_instance_properties
+ );
+
+ }
+
+ /* Instance states */
+ if ( !empty($block_element_sub_element['states']) && is_array($block_element_sub_element['states']) ) {
+
+ foreach ( $block_element_sub_element['states'] as $instance_state_id => $instance_state_info ) {
+
+ $actual_instance_id = $block_element_sub_element['id'] . '-block-' . $block['id'] . '-state-' . $instance_state_id;
+ $instance_state_properties = HeadwayElementsData::get_special_element_properties(array(
+ 'element' => $block_element_sub_element['id'],
+ 'se_type' => 'instance',
+ 'se_meta' => $actual_instance_id
+ ));
+
+ /* Only add instance state if there are properties present */
+ if ( empty($instance_state_properties) )
+ continue;
+
+ $styling[$actual_instance_id] = array(
+ 'element' => $block_element_sub_element['id'],
+ 'properties' => $instance_state_properties
+ );
+
+ }
+
+ }
+ /* End getting instance states */
+
+ }
+
+ return $styling;
+
+ }
+
+
+ public static function get_blocks_by_wrapper($layout_id, $wrapper_id) {
+
+ $layout_blocks = self::get_blocks_by_layout($layout_id);
+ $layout_wrappers = HeadwayWrappersData::get_wrappers_by_layout($layout_id);
+ $wrapper_blocks = array();
+
+ foreach ( $layout_blocks as $block_id => $block ) {
+
+ if ( headway_get('wrapper_id', $block, HeadwayWrappers::$default_wrapper_id) === $wrapper_id )
+ $wrapper_blocks[$block_id] = $block;
+
+ /* If there's only one wrapper and the block does not have a proper ID or is default, move it to that wrapper */
+ if ( count($layout_wrappers) === 1 && (headway_get('wrapper_id', $block) === null || headway_get('wrapper_id', $block) == 'wrapper-default') )
+ $wrapper_blocks[$block_id] = $block;
+
+ }
+
+ return $wrapper_blocks;
+
+ }
+
+
+ public static function get_blocks_by_type($type) {
+
+ global $wpdb;
+
+ /* Build cache key */
+ $cache_key = 'hw_blocks_by_type_' . $type;
+
+ /* Check cache */
+ $blocks_from_cache = wp_cache_get($cache_key);
+
+ if ( $blocks_from_cache === false ) {
+
+ $blocks_by_type_query = $wpdb->get_results($wpdb->prepare("SELECT * FROM $wpdb->hw_blocks WHERE template = '%s' AND type = '%s'", HeadwayOption::$current_skin, $type), ARRAY_A);
+
+ /* Change results array into associative */
+ $blocks_by_type = array();
+
+ foreach ( $blocks_by_type_query as $block ) {
+
+ $blocks_by_type[$block['id']] = array_map('headway_maybe_unserialize', $block);
+
+ }
+
+ wp_cache_set($cache_key, $blocks_by_type);
+
+ } else {
+
+ $blocks_by_type = $blocks_from_cache;
+
+ }
+
+ return $blocks_by_type;
+
+ }
+
+
+ public static function get_all_blocks() {
+
+ global $wpdb;
+
+ /* Build cache key */
+ $cache_key = 'hw_all_blocks';
+
+ /* Check cache */
+ $blocks_from_cache = wp_cache_get($cache_key);
+
+ if ( $blocks_from_cache === false ) {
+
+ $blocks_query = $wpdb->get_results($wpdb->prepare("SELECT * FROM $wpdb->hw_blocks WHERE template = '%s'", HeadwayOption::$current_skin), ARRAY_A);
+
+ /* Change results array into associative */
+ $all_blocks = array();
+
+ foreach ( $blocks_query as $block ) {
+
+ $all_blocks[$block['id']] = array_map('headway_maybe_unserialize', $block);
+
+ }
+
+ wp_cache_set($cache_key, $all_blocks);
+
+ } else {
+
+ $all_blocks = $blocks_from_cache;
+
+ }
+
+ return $all_blocks;
+
+ }
+
+
+ public static function is_block_mirrored($block) {
+
+ $block = self::get_block($block);
+ $block_settings = headway_get( 'settings', $block, array() );
+
+ /* Use mirror-block setting if present because it means the block is new or the setting has been updated and not saved yet */
+ if ( isset( $block_settings['mirror-block'] ) )
+ return $block_settings['mirror-block'];
+
+ if ( $mirrored_block_id = headway_get('mirror_id', $block) )
+ return $mirrored_block_id;
+
+ return false;
+
+ }
+
+
+ public static function get_block_mirror($block) {
+
+ $block = self::get_block($block);
+
+ if ( $mirrored_block_id = self::is_block_mirrored($block) )
+ return HeadwayBlocksData::get_block($mirrored_block_id);
+
+ return false;
+
+ }
+
+
+ public static function block_exists($id) {
+
+ if ( self::get_block($id) )
+ return true;
+
+ return false;
+
+ }
+
+
+ public static function get_block_name($block) {
+
+ $block = self::get_block($block);
+
+ //Create the default name by using the block type and ID
+ $default_name = HeadwayBlocks::block_type_nice($block['type']);
+
+ return headway_get('alias', headway_get('settings', $block, array()), $default_name);
+
+ }
+
+
+ public static function get_block_width($block) {
+
+ $block = self::get_block($block);
+
+ $block_grid_width = headway_get('width', $block['dimensions'], null);
+
+ if ( $block_grid_width === null )
+ return null;
+
+ /* Fetch the wrapper that way we can get its Grid settings */
+ $wrapper = HeadwayWrappersData::get_wrapper(headway_get('wrapper_id', $block, 'wrapper-default'));
+
+ $column_width = HeadwayWrappers::get_column_width($wrapper);
+ $gutter_width = HeadwayWrappers::get_gutter_width($wrapper);
+
+ return ( $block_grid_width * ($column_width + $gutter_width) ) - $gutter_width;
+
+ }
+
+
+ public static function get_block_height($block) {
+
+ $block = self::get_block($block);
+
+ $block_grid_height = headway_get('height', $block['dimensions'], null);
+
+ if ( $block_grid_height === null )
+ return null;
+
+ return $block_grid_height;
+
+ }
+
+
+ public static function get_block_setting($block, $setting, $default = null) {
+
+ $block = self::get_block($block);
+
+ //No block, no settings
+ if ( !$block )
+ return $default;
+
+ if ( !isset($block['settings'][$setting]) )
+ return $default;
+
+ return headway_fix_data_type($block['settings'][$setting]);
+
+ }
+
+
+ public static function get_legacy_id($block) {
+
+ return is_numeric( headway_get( 'legacy_id', $block ) ) && headway_get( 'legacy_id', $block ) > 0 ? headway_get( 'legacy_id', $block ) : $block['id'];
+
+ }
+
+
+}
\ No newline at end of file
--- /dev/null
+<?php
+class HeadwayElementsData {
+
+
+ public static function init() {
+
+ add_action('headway_visual_editor_save', array(__CLASS__, 'merge_core_default_design_data'));
+
+ }
+
+
+ /* Used to merge in the global defaults for backwards compatibility */
+ public static function get_raw_data($defaults = array()) {
+
+ return headway_array_merge_recursive_simple(self::get_legacy_default_data(), HeadwaySkinOption::get('properties', 'design', $defaults));
+
+ }
+
+
+ /* Mass Get */
+ public static function get_all_elements() {
+
+ $elements = self::get_raw_data();
+
+ //Move default elements to the top
+ foreach ( $elements as $element_id => $element_options ) {
+
+ $element = HeadwayElementAPI::get_element($element_id);
+
+ if ( !isset($element['default-element']) || $element['default-element'] === false )
+ continue;
+
+ $temp_id = $element_id;
+ $temp_options = $element_options;
+
+ unset($elements[$element_id]);
+
+ $elements = array_merge(array($temp_id => $temp_options), $elements);
+
+ }
+
+ return $elements;
+
+ }
+
+
+ public static function get_element_properties($element) {
+
+ //Get element ID
+ $element_id = is_array($element) ? $element['id'] : $element;
+
+ $element = headway_get($element_id, self::get_raw_data());
+
+ if ( !isset($element['properties']) || !is_array($element['properties']) )
+ $element['properties'] = array();
+
+ $properties = $element['properties'];
+
+ //Fetch the property
+ return ( is_array($properties) && count($properties) > 0 ) ? $properties : array();
+
+ }
+
+
+ public static function get_special_element_properties($args) {
+
+ $defaults = array(
+ 'element' => null,
+ 'se_type' => null,
+ 'se_meta' => null
+ );
+
+ extract(array_merge($defaults, $args));
+
+ //Get element ID
+ $element_id = is_array($element) ? $element['id'] : $element;
+
+ $element = headway_get($element_id, self::get_raw_data(), array(
+ 'special-element-' . $se_type => array()
+ ));
+
+ if ( !isset($element['special-element-' . $se_type][$se_meta]) || !is_array($element['special-element-' . $se_type][$se_meta]) )
+ $element['special-element-' . $se_type][$se_meta] = array();
+
+ $properties =& $element['special-element-' . $se_type][$se_meta];
+
+ //Return the data
+ return ( is_array($properties) && count($properties) > 0 ) ? $properties : array();
+
+ }
+
+
+ /* Single Get */
+ public static function get_property($element_id, $property_id, $default = null, $element_group = null) {
+
+ $properties = self::get_element_properties($element_id);
+
+ if ( $properties !== null && !is_wp_error($properties) && isset($properties[$property_id]) && (headway_fix_data_type($properties[$property_id]) || headway_fix_data_type($properties[$property_id]) === 0) )
+ return headway_fix_data_type($properties[$property_id]);
+
+ else
+ return $default;
+
+ }
+
+
+ public static function get_special_element_property($element_id, $se_type, $se_meta, $property_id, $default = null, $element_group = null) {
+
+ $properties = self::get_special_element_properties(array(
+ 'element' => $element_id,
+ 'se_type' => $se_type,
+ 'se_meta' => $se_meta
+ ));
+
+ if ( $properties !== null && !is_wp_error($properties) && isset($properties[$property_id]) && (headway_fix_data_type($properties[$property_id]) || headway_fix_data_type($properties[$property_id]) === 0) )
+ return headway_fix_data_type($properties[$property_id]);
+
+ else
+ return $default;
+
+ }
+
+
+ /* Setting */
+ public static function set_property($element_group = null, $element_id, $property_id, $value) {
+
+ /* Pass the torch onto self::delete_property() if the value is 'delete' */
+ if ( strtolower($value) == 'delete' )
+ return self::delete_property($element_id, $property_id);
+
+ $all_properties = HeadwaySkinOption::get('properties', 'design', array());
+
+ /* Insure array exists for element that property is being set for */
+ if ( !isset($all_properties[$element_id]) || !is_array($all_properties[$element_id]) )
+ $all_properties[$element_id] = array('properties' => array());
+
+ /* Set the property */
+ if ( $value == 'null' )
+ $value = null;
+
+ $all_properties[$element_id]['properties'][$property_id] = $value;
+
+ /* Send it back to DB */
+ return HeadwaySkinOption::set('properties', $all_properties, 'design');
+
+ }
+
+
+ public static function delete_property($element_id, $property_id) {
+
+ $all_properties = HeadwaySkinOption::get('properties', 'design', array());
+
+ /* Delete the property */
+ if ( !empty($all_properties[$element_id]['properties']) && isset($all_properties[$element_id]['properties'][$property_id]) )
+ unset($all_properties[$element_id]['properties'][$property_id]);
+
+ /* Send it back to DB */
+ return HeadwaySkinOption::set('properties', $all_properties, 'design');
+
+ }
+
+
+ public static function set_special_element_property($element_group = null, $element_id, $special_element_type, $special_element_meta, $property_id, $value) {
+
+ /* Pass the torch onto self::delete_special_element_property() if the value is 'delete' */
+ if ( strtolower($value) == 'delete' )
+ return self::delete_special_element_property(null, $element_id, $special_element_type, $special_element_meta, $property_id);
+
+ $all_properties = HeadwaySkinOption::get('properties', 'design', array());
+
+ /* Insure array exists for element that property is being set for */
+ if ( !isset($all_properties[$element_id]) || !is_array($all_properties[$element_id]) )
+ $all_properties[$element_id] = array('special-element-' . $special_element_type => array(
+ $special_element_meta => array()
+ ));
+
+ /* Set the property */
+ if ( $value == 'null' )
+ $value = null;
+
+ $all_properties[$element_id]['special-element-' . $special_element_type][$special_element_meta][$property_id] = $value;
+
+ /* Send it back to DB */
+ return HeadwaySkinOption::set('properties', $all_properties, 'design');
+
+ }
+
+
+ public static function delete_special_element_property($element_group = null, $element_id, $special_element_type, $special_element_meta, $property_id) {
+
+ $all_properties = HeadwaySkinOption::get('properties', 'design', array());
+
+ if ( isset($all_properties[$element_id]['special-element-' . $special_element_type][$special_element_meta][$property_id]) )
+ unset($all_properties[$element_id]['special-element-' . $special_element_type][$special_element_meta][$property_id]);
+
+ /* Send it back to DB */
+ return HeadwaySkinOption::set('properties', $all_properties, 'design');
+
+ }
+
+
+ public static function delete_special_element_properties($element_group = null, $element_id, $special_element_type, $special_element_meta) {
+
+ $all_properties = HeadwaySkinOption::get('properties', 'design', array());
+
+ /* Delete all special elements matching the meta and type */
+ if ( isset($all_properties[$element_id]['special-element-' . $special_element_type][$special_element_meta]) )
+ unset($all_properties[$element_id]['special-element-' . $special_element_type][$special_element_meta]);
+
+ /* Send it back to DB */
+ return HeadwaySkinOption::set('properties', $all_properties, 'design');
+
+ }
+
+
+ /* Defaults */
+ public static function get_default_data() {
+
+ global $headway_core_default_element_data;
+
+ return $headway_core_default_element_data;
+
+ }
+
+
+ public static function get_legacy_default_data() {
+
+ global $headway_default_element_data;
+
+ if ( !isset($headway_default_element_data) || !is_array($headway_default_element_data) )
+ $headway_default_element_data = array();
+
+ return apply_filters('headway_element_data_defaults', $headway_default_element_data);
+
+ }
+
+
+ /**
+ * Merge in default design data. This will be ran upon save and upgrade to Headway 3.6
+ */
+ public static function merge_core_default_design_data() {
+
+ self::merge_default_design_data(HeadwayElementsData::get_default_data(), 'core');
+
+ self::merge_default_design_data( array(
+ 'block-pin-board-pin' => array(
+ 'properties' => array(
+ 'padding-top' => 1,
+ 'padding-right' => 1,
+ 'padding-bottom' => 1,
+ 'padding-left' => 1,
+ 'background-color' => 'ffffff',
+ 'border-color' => 'eeeeee',
+ 'border-style' => 'solid',
+ 'border-top-width' => 1,
+ 'border-right-width' => 1,
+ 'border-bottom-width' => 1,
+ 'border-left-width' => 1,
+ 'box-shadow-color' => 'eee',
+ 'box-shadow-blur' => 3,
+ 'box-shadow-horizontal-offset' => 0,
+ 'box-shadow-vertical-offset' => 2
+ )
+ ),
+ 'block-pin-board-pin-title' => array(
+ 'properties' => array(
+ 'padding-top' => 15,
+ 'padding-right' => 15,
+ 'padding-left' => 15,
+ 'font-size' => 18,
+ 'line-height' => 120,
+ 'text-decoration' => 'none'
+ ),
+ 'special-element-state' => array(
+ 'hover' => array(
+ 'text-decoration' => 'underline'
+ )
+ )
+ ),
+ 'block-pin-board-pin-text' => array(
+ 'properties' => array(
+ 'font-size' => 12,
+ 'line-height' => 150,
+ 'padding-right' => 15,
+ 'padding-left' => 15
+ )
+ ),
+ 'block-pin-board-pin-meta' => array(
+ 'properties' => array(
+ 'font-size' => 12,
+ 'line-height' => 120,
+ 'padding-right' => 15,
+ 'padding-left' => 15,
+ 'color' => '888888'
+ )
+ ),
+ 'block-pin-board-pagination-button' => array(
+ 'properties' => array(
+ 'text-decoration' => 'none',
+ 'background-color' => 'eeeeee',
+ 'border-top-left-radius' => 4,
+ 'border-top-right-radius' => 4,
+ 'border-bottom-right-radius' => 4,
+ 'border-bottom-left-radius' => 4,
+ 'padding-top' => 5,
+ 'padding-right' => 9,
+ 'padding-bottom' => 5,
+ 'padding-left' => 9
+ ),
+ 'special-element-state' => array(
+ 'hover' => array(
+ 'background-color' => 'e7e7e7'
+ )
+ )
+ )
+ ), 'core-37-pin-board' );
+
+ }
+
+
+ /* This function accepts data as well as ID that way it can be used by Headway plugins */
+ public static function merge_default_design_data($default_data, $id) {
+
+ $merge_id = 'merged-default-design-data-' . strtolower(str_replace(array(' ', '-'), '_', $id));
+
+ /* Only merge if it hasn't been merged before. */
+ if ( !HeadwaySkinOption::get($merge_id, 'general', false) ) {
+
+ $design_data = HeadwaySkinOption::get('properties', 'design', array());
+ $design_data_with_defaults = headway_array_merge_recursive_simple($default_data, $design_data);
+
+ HeadwaySkinOption::set($merge_id, true, 'general');
+
+ return HeadwaySkinOption::set('properties', $design_data_with_defaults, 'design');
+
+ }
+
+ /* Already merged, return false */
+ return false;
+
+ }
+
+}
\ No newline at end of file
--- /dev/null
+<?php
+/**
+ * Functions to get, update, and delete data from the database.
+ *
+ * @package Headway
+ * @subpackage Data Handling
+ * @author Clay Griffiths
+ **/
+
+class HeadwayLayoutOption {
+
+
+ /**
+ * Flag for fetching from skin options.
+ **/
+ public static $is_skin_option = false;
+
+ public static $current_skin;
+
+
+ public static function init() {
+
+ self::$current_skin = HeadwayTemplates::get_active_id();
+
+ }
+
+
+ public static function is_post($layout) {
+
+ /* If only number is provided for layout then it's a WP post */
+ if ( is_numeric($layout) )
+ return $layout;
+
+ $layout_fragments = explode(HeadwayLayout::$sep, $layout);
+
+ if ( reset($layout_fragments) == 'single' && is_numeric(end($layout_fragments)) )
+ return end($layout_fragments);
+
+ return false;
+
+ }
+
+
+ public static function postmeta_option($option, $global, $template = false) {
+
+ if ( !$template )
+ $template = self::$current_skin;
+
+ /* Global option */
+ if ( $global ) {
+
+ return '_hw_' . $option;
+
+ /* Template-specific option */
+ } else {
+
+ return '_hw_|template=' . $template . '|_' . $option;
+
+ }
+
+ }
+
+
+ public static function get($layout, $option, $default = null, $global = false, $group_prefix = false) {
+
+ if ( $group_prefix && $group_prefix != 'general' )
+ $option = $group_prefix . '_' . $option;
+
+ /* If it's post meta compatible, then use WP functions */
+ if ( $post_id = self::is_post($layout) ) {
+
+ $options = get_post_custom($post_id);
+ $option = self::postmeta_option($option, $global);
+
+ if ( !$options || !isset($options[$option]) )
+ return $default;
+
+ $return = $options[$option][0];
+
+ /* Otherwise use the Headway layout meta table */
+ } else {
+
+ global $wpdb;
+
+ $template = $global ? '' : self::$current_skin;
+
+ $cache_key = 'hw_layout_options_|template=' . $template . '|_' . $layout;
+ $layout_options = wp_cache_get($cache_key);
+
+ if ( $layout_options === false ) {
+
+ $options = $wpdb->get_results($wpdb->prepare("SELECT * FROM $wpdb->hw_layout_meta WHERE layout = '%s' AND template = '%s'", $layout, $template), ARRAY_A);
+
+ if ( is_wp_error($options) || !is_array($options) || !count($options) ) {
+ wp_cache_set($cache_key, array());
+ return $default;
+ }
+
+ /* Loop through results and make it into an associative array */
+ $layout_options = array();
+
+ foreach ( $options as $option_row ) {
+ $layout_options[$option_row['meta_key']] = $option_row['meta_value'];
+ }
+
+ wp_cache_set($cache_key, $layout_options);
+
+ }
+
+ if ( !isset($layout_options[$option]) )
+ return $default;
+
+ $return = $layout_options[$option];
+
+ }
+
+ return headway_fix_data_type($return);
+
+ }
+
+
+ public static function set($layout, $option, $value, $global = false, $group_prefix = false, $template = null) {
+
+ if ( !$template )
+ $template = self::$current_skin;
+
+ if ( $group_prefix && $group_prefix != 'general' )
+ $option = $group_prefix . '_' . $option;
+
+ /* If it's post meta compatible, then use WP functions */
+ if ( $post_id = self::is_post($layout) ) {
+
+ $option = self::postmeta_option($option, $global, $template);
+
+ return update_post_meta($post_id, $option, $value);
+
+ /* Otherwise use the Headway layout meta table */
+ } else {
+
+ global $wpdb;
+
+ $template = $global ? '' : $template;
+
+ /* Check if option exists. If it does, use $wpdb->update, otherwise use $wpdb->insert */
+ if ( $meta_id = $wpdb->get_var($wpdb->prepare("SELECT meta_id FROM $wpdb->hw_layout_meta WHERE layout = '%s' AND template = '%s' AND meta_key = '%s'", $layout, $template, $option)) ) {
+
+ return $wpdb->update($wpdb->hw_layout_meta, array(
+ 'meta_value' => headway_maybe_serialize($value)
+ ), array(
+ 'meta_id' => $meta_id
+ ));
+
+ } else {
+
+ return $wpdb->insert($wpdb->hw_layout_meta, array(
+ 'meta_key' => $option,
+ 'meta_value' => headway_maybe_serialize($value),
+ 'layout' => $layout,
+ 'template' => $template
+ ));
+
+ }
+
+ }
+
+ }
+
+
+ public static function delete($layout, $option, $global = false) {
+
+ /* If it's post meta compatible, then use WP functions */
+ if ( $post_id = self::is_post($layout) ) {
+
+ $option = self::postmeta_option($option, $global);
+
+ return delete_post_meta($post_id, $option);
+
+ /* Otherwise use the Headway layout meta table */
+ } else {
+
+ global $wpdb;
+
+ $template = $global ? '' : self::$current_skin;
+
+ return $wpdb->delete($wpdb->hw_layout_meta, array(
+ 'layout' => $layout,
+ 'meta_key' => $option,
+ 'template' => $template
+ ));
+
+ }
+
+ }
+
+
+ public static function delete_all_from_layout($layout, $global = false) {
+
+ /* If it's post meta compatible, then use WP functions */
+ if ( $post_id = self::is_post($layout) ) {
+
+ $options = get_post_custom($post_id);
+ $options_deleted = array();
+
+ $key_prefix_to_check = $global ? '_hw_' : '_hw_|template=' . self::$current_skin . '|_';
+
+ foreach ( $options as $meta_key => $meta_id ) {
+
+ if ( strpos($meta_key, $key_prefix_to_check) !== 0 )
+ continue;
+
+ $options_deleted = delete_post_meta($post_id, $meta_key);
+
+ }
+
+ return $options_deleted;
+
+ /* Otherwise use the Headway layout meta table */
+ } else {
+
+ global $wpdb;
+
+ if ( $global ) {
+
+ return $wpdb->delete($wpdb->hw_layout_meta, array(
+ 'layout' => $layout
+ ));
+
+ } else {
+
+ return $wpdb->delete($wpdb->hw_layout_meta, array(
+ 'layout' => $layout,
+ 'template' => self::$current_skin
+ ));
+
+ }
+
+ }
+
+ }
+
+
+ public static function delete_by_template($template) {
+
+ global $wpdb;
+
+ $wpdb->delete($wpdb->hw_layout_meta, array(
+ 'template' => $template
+ ));
+
+ $wpdb->query($wpdb->prepare("DELETE FROM $wpdb->postmeta WHERE meta_key LIKE '%s'", '_hw_|template=' . $template . '|_%'));
+
+ }
+
+
+}
\ No newline at end of file
--- /dev/null
+<?php
+/**
+ * Functions to get, update, and delete data from the database.
+ *
+ * @package Headway
+ * @subpackage Data Handling
+ * @author Clay Griffiths
+ **/
+
+class HeadwayOption {
+
+
+ /**
+ * Set the default group for all of the database functions to get, set, and delete from.
+ **/
+ protected static $default_group = 'general';
+
+
+ /**
+ * Flag for fetching from skin options.
+ **/
+ public static $is_skin_option = false;
+
+ public static $current_skin;
+
+
+ public static function init() {
+
+ self::$current_skin = HeadwayTemplates::get_active_id();
+
+ }
+
+
+ /**
+ * Retrieve a value from the database.
+ *
+ * @param string Option to retrieve
+ * @param string Option group to fetch from
+ * @param mixed Default value to be returned. This will be returned if the requested option does not exist.
+ *
+ * @return mixed
+ **/
+ public static function get($option = null, $group_name = false, $default = null, $main_site = false) {
+
+ if ( $option === null )
+ return false;
+
+ if ( !$group_name )
+ $group_name = self::$default_group;
+
+ $group_data = self::get_group($group_name, $main_site);
+
+ /* If option doesn't exist, return default. */
+ if ( !isset($group_data[$option]) )
+ return $default;
+
+ return headway_fix_data_type($group_data[$option]);
+
+ }
+
+
+ public static function get_group($group_name, $main_site = false) {
+
+ /* Query for the option group */
+ $group_data = self::get_wp_option('headway_option_group_' . $group_name, $main_site);
+
+ return $group_data;
+
+ }
+
+
+ /**
+ * Format option name
+ **/
+ public static function format_wp_option($option) {
+
+ /* Format option name */
+ if ( self::$is_skin_option )
+ $option = str_replace('headway_', 'headway_|template=' . self::$current_skin . '|_', $option);
+
+ return $option;
+
+ }
+
+
+ /**
+ * Function for using get_option() or get_blog_option() depending on second argument
+ **/
+ public static function get_wp_option($option, $main_site = false) {
+
+ global $current_site;
+
+ /* Format option name */
+ $option = self::format_wp_option($option);
+
+ /* Pull option */
+ if ( $main_site && is_multisite() )
+ return get_blog_option($current_site->blog_id, $option);
+
+ return get_option($option);
+
+ }
+
+
+ public static function get_from_main_site($option = null, $group_name = false, $default = null) {
+
+ return self::get($option, $group_name, $default, false, true);
+
+ }
+
+
+ /**
+ * Add or update an option on the database.
+ *
+ * @param string Option to set
+ * @param mixed Value to attach to option
+ * @param string Group to add/update the option to
+ *
+ * @return bool
+ **/
+ public static function set($option = null, $value = null, $group_name = false) {
+
+ if ( $option === null )
+ return false;
+
+ if ( $value === null )
+ return false;
+
+ if ( !$group_name )
+ $group_name = self::$default_group;
+
+ $group_option_name = self::format_wp_option('headway_option_group_' . $group_name);
+
+ /* Pull in existing data so we can add on top of it */
+ $group_data = get_option($group_option_name, array());
+
+ /* Handle boolean values */
+ if ( is_bool($value) )
+ $value = ( $value === true ) ? 'true' : 'false';
+
+ /* Add option */
+ $group_data[$option] = $value;
+
+ /* Send group option to DB */
+ return update_option($group_option_name, $group_data);
+
+ }
+
+
+ public static function set_group($group_name, $group_data) {
+
+ $group_option_name = self::format_wp_option('headway_option_group_' . $group_name);
+
+ return update_option($group_option_name, $group_data);;
+
+ }
+
+
+ /**
+ * Delete option from database.
+ *
+ * @param string Option to delete
+ * @param string Group to delete from
+ *
+ * @return bool
+ **/
+ public static function delete($option = null, $group_name = false) {
+
+ //return wp_die('Deleting some shit right now. Trying: ' . $option);
+
+ if ( $option === null )
+ return false;
+
+ if ( !$group_name )
+ $group_name = self::$default_group;
+
+ $option_name = self::format_wp_option('headway_option_group_' . $group_name);
+ $group_data = get_option($option_name);
+
+ //If the group isn't in the DB or the option doesn't exist
+ if( !is_array($group_data) || !isset($group_data[$option]) )
+ return false;
+
+ //Delete option from group
+ unset($group_data[$option]);
+
+ //If the array is still fine and not empty, just update the group on the DB
+ if ( count($group_data) !== 0 )
+ return update_option($option_name, $group_data);
+
+ //Remove group from DB
+ return delete_option($option_name);
+
+ }
+
+
+}
\ No newline at end of file
--- /dev/null
+<?php
+class HeadwayDataPortability {
+
+
+ public static function export_skin(array $info) {
+
+ global $wpdb;
+
+ do_action('headway_before_export_skin');
+
+ $wp_options_prefix = 'headway_|template=' . HeadwayOption::$current_skin . '|_';
+
+ $skin = array(
+ 'hw-version' => HEADWAY_VERSION,
+ 'name' => headway_get('name', $info, 'Unnamed'),
+ 'author' => headway_get('author', $info),
+ 'image-url' => headway_get('image-url', $info),
+ 'version' => headway_get('version', $info),
+ 'data_wp_options' => $wpdb->get_results($wpdb->prepare("SELECT * FROM $wpdb->options WHERE option_name LIKE '%s'", $wp_options_prefix . '%'), ARRAY_A),
+ 'data_wp_postmeta' => $wpdb->get_results($wpdb->prepare("SELECT * FROM $wpdb->postmeta WHERE meta_key LIKE '%s'", '_hw_|template=' . HeadwayOption::$current_skin . '|_%'), ARRAY_A),
+ 'data_hw_layout_meta' => $wpdb->get_results($wpdb->prepare("SELECT * FROM $wpdb->hw_layout_meta WHERE template = '%s'", HeadwayOption::$current_skin), ARRAY_A),
+ 'data_hw_wrappers' => $wpdb->get_results($wpdb->prepare("SELECT * FROM $wpdb->hw_wrappers WHERE template = '%s'", HeadwayOption::$current_skin), ARRAY_A),
+ 'data_hw_blocks' => $wpdb->get_results($wpdb->prepare("SELECT * FROM $wpdb->hw_blocks WHERE template = '%s'", HeadwayOption::$current_skin), ARRAY_A)
+ );
+
+ /* Spit the file out */
+ $filename = 'Headway Template - ' . headway_get('name', $info, 'Unnamed');
+
+ if ( headway_get('version', $info) ) {
+ $filename .= ' ' . headway_get('version', $info);
+ }
+
+ return self::to_json($filename, 'skin', $skin);
+
+ }
+
+
+ public static function install_skin(array $skin) {
+
+ $skins = HeadwayOption::get_group('skins');
+
+ /* Remove image definitions */
+ if ( isset($skin['image-definitions']) )
+ unset($skin['image-definitions']);
+
+ /* Skin ID ... Truncate the skin ID to 12 characters due to varchar limit in wp_options */
+ $original_skin_id = substr(strtolower(str_replace(' ', '-', $skin['name'])), 0, 12);
+
+ $skin_id = $original_skin_id;
+ $skin_name = $skin['name'];
+
+ $skin_unique_id_counter = 0;
+
+ /* Check if skin already exists. If it does, change ID and skin name */
+ while ( HeadwayOption::get($skin_id, 'skins') || get_option('headway_|template=' . $skin_id . '|_option_group_general') ) {
+
+ $skin_unique_id_counter++;
+ $skin_id = $original_skin_id . '-' . $skin_unique_id_counter;
+
+ $skin_name = $skin['name'] . ' ' . $skin_unique_id_counter;
+
+ }
+
+ /* Send skin to DB */
+ $skin['id'] = $skin_id;
+ $skin['name'] = $skin_name;
+
+ $skin_with_info_only = $skin;
+
+ $data_to_remove_from_saved_skin = array(
+ 'data_wp_options',
+ 'data_wp_postmeta',
+ 'data_hw_layout_meta',
+ 'data_hw_wrappers',
+ 'data_hw_blocks',
+ 'templates',
+ 'layouts',
+ 'element-data'
+ );
+
+ foreach ( $data_to_remove_from_saved_skin as $key_to_remove ) {
+
+ if ( !isset($skin_with_info_only[$key_to_remove]) )
+ continue;
+
+ unset($skin_with_info_only[$key_to_remove]);
+
+ }
+
+ HeadwayOption::set($skin['id'], $skin_with_info_only, 'skins');
+
+ /* Change current skin ID to the newly added skin so we can populate data */
+ HeadwayOption::$current_skin = $skin['id'];
+ HeadwayLayoutOption::$current_skin = $skin['id'];
+
+ /* Process the install */
+ if ( !headway_get('hw-version', $skin) || version_compare(headway_get('hw-version', $skin), '3.7', '<') ) {
+ $skin = self::process_install_skin_pre37($skin);
+ } else {
+ $skin = self::process_install_skin($skin);
+ }
+
+ /* Change $current_skin back just to be safe */
+ HeadwayOption::$current_skin = HeadwayTemplates::get_active_id();
+ HeadwayLayoutOption::$current_skin = HeadwayTemplates::get_active_id();
+
+ return $skin;
+
+ }
+
+
+ public static function process_install_skin_pre37(array $skin) {
+
+ /* Set up skin options that way when it's activated it looks right */
+ /* Install templates */
+ if ( $skin_templates = headway_get('templates', $skin) )
+ HeadwaySkinOption::set_group('templates', $skin_templates);
+
+ /* Assign templates */
+ if ( !empty($skin['templates']['assignments']) ) {
+
+ foreach ( $skin['templates']['assignments'] as $layout_id => $template_id ) {
+
+ /* Change layout ID separators */
+ if ( strpos($layout_id, 'template-') !== 0 )
+ $layout_id = str_replace('-', HeadwayLayout::$sep, $layout_id);
+
+ HeadwayLayoutOption::set($layout_id, 'template', $template_id);
+
+ }
+
+ }
+
+ /* Install layouts (blocks, wrappers, and flags */
+ $wrapper_id_mapping = array();
+ $block_id_mapping = array();
+
+ foreach ( $skin['layouts'] as $layout_id => $layout_data ) {
+
+ /* Change layout ID separators */
+ if ( strpos($layout_id, 'template-') !== 0 )
+ $layout_id = str_replace('-', HeadwayLayout::$sep, $layout_id);
+
+ /* Install Wrappers */
+ foreach ( $layout_data['wrappers'] as $wrapper_id => $wrapper_data ) {
+
+ $wrapper_data['position'] = array_search($wrapper_id, array_keys($layout_data['wrappers']));
+
+ $wrapper_data['settings'] = array(
+ 'fluid' => headway_get('fluid', $wrapper_data),
+ 'fluid-grid' => headway_get('fluid-grid', $wrapper_data),
+ 'columns' => headway_get('columns', $wrapper_data),
+ 'column-width' => headway_get('column-width', $wrapper_data),
+ 'gutter-width' => headway_get('gutter-width', $wrapper_data),
+ 'use-independent-grid' => headway_get('use-independent-grid', $wrapper_data)
+ );
+
+ $new_wrapper = HeadwayWrappersData::add_wrapper($layout_id, $wrapper_data);
+
+ if ( $new_wrapper && !is_wp_error($new_wrapper) ) {
+ $wrapper_id_mapping[HeadwayWrappers::format_wrapper_id($wrapper_id)] = $new_wrapper;
+ }
+
+ }
+
+ /* Install Blocks */
+ foreach ( $layout_data['blocks'] as $block_id => $block_data ) {
+
+ $block_data['wrapper'] = headway_get(HeadwayWrappers::format_wrapper_id(headway_get('wrapper', $block_data)), $wrapper_id_mapping);
+
+ $new_block = HeadwayBlocksData::add_block($layout_id, $block_data);
+
+ if ( $new_block && !is_wp_error($new_block) ) {
+ $block_id_mapping[$block_id] = $new_block;
+ }
+
+ }
+
+ }
+
+ /* Setup mirroring */
+ foreach ( $skin['layouts'] as $layout_id => $layout_data ) {
+
+ /* Change layout ID separators */
+ if (strpos($layout_id, 'template-') !== 0)
+ $layout_id = str_replace('-', HeadwayLayout::$sep, $layout_id);
+
+ foreach ($layout_data['wrappers'] as $wrapper_id => $wrapper_data) {
+
+ $wrapper_to_update = $wrapper_id_mapping[HeadwayWrappers::format_wrapper_id($wrapper_id)];
+
+ if (!$mirror_id = headway_get('mirror-wrapper', $wrapper_data))
+ continue;
+
+ $mirror_id = headway_get(HeadwayWrappers::format_wrapper_id($mirror_id), $wrapper_id_mapping);
+
+ HeadwayWrappersData::update_wrapper($wrapper_to_update, array(
+ 'mirror_id' => $mirror_id
+ ));
+
+ }
+
+ foreach ( $layout_data['blocks'] as $block_id => $block_data ) {
+
+ if ( !isset($block_id_mapping[$block_id]) )
+ continue;
+
+ $block_to_update = $block_id_mapping[$block_id];
+
+ if ( !$mirror_id = headway_get('mirror-block', headway_get('settings', $block_data, array())) )
+ continue;
+
+ $mirror_id = headway_get($mirror_id, $block_id_mapping);
+
+ HeadwayBlocksData::update_block($block_to_update, array(
+ 'mirror_id' => $mirror_id
+ ));
+
+ }
+
+ }
+
+ /* Install design data */
+ /* Sort the block and wrapper mappings by descending number that way when we do a simple recursive find and replace the small block IDs won't mess up the larger block IDs.
+ Example: Replacing block-1 before block-11 is replaced would be bad news */
+ krsort($block_id_mapping);
+ krsort($wrapper_id_mapping);
+
+ foreach ( $block_id_mapping as $old_block_id => $new_block_id ) {
+ $skin['element-data'] = headway_str_replace_json('block-' . $old_block_id, 'block-' . $new_block_id, $skin['element-data']);
+ }
+
+ foreach ( $wrapper_id_mapping as $old_wrapper_id => $new_wrapper_id ) {
+ $skin['element-data'] = headway_str_replace_json('wrapper-' . $old_wrapper_id, 'wrapper-' . $new_wrapper_id, $skin['element-data']);
+ }
+
+ $skin['element-data'] = headway_preg_replace_json( "/-layout-[\w-]*/", '', $skin['element-data'] );
+
+ HeadwaySkinOption::set('properties', $skin['element-data'], 'design');
+ HeadwaySkinOption::set('live-css', stripslashes($skin['live-css']));
+
+ /* Set merge flag that way the next time they save it won't screw up the styling */
+ HeadwaySkinOption::set('merged-default-design-data-core', true, 'general');
+
+ /* Set wrapper defaults */
+ if ( !empty($skin['wrapper-defaults']) && is_array($skin['wrapper-defaults']) ) {
+
+ HeadwaySkinOption::set('columns', headway_get('columns', $skin['wrapper-defaults'], HeadwayWrappers::$default_columns));
+ HeadwaySkinOption::set('columns-width', headway_get('columns', $skin['wrapper-defaults'], HeadwayWrappers::$default_columns));
+ HeadwaySkinOption::set('gutter-width', headway_get('columns', $skin['wrapper-defaults'], HeadwayWrappers::$default_columns));
+
+ }
+
+ return $skin;
+
+ }
+
+
+
+ public static function process_install_skin(array $skin) {
+
+ return HeadwayDataSnapshots::process_rollback($skin, $skin['id']);
+
+ }
+
+
+ public static function export_block_settings($block_id) {
+
+ /* Set up variables */
+ $block = HeadwayBlocksData::get_block($block_id);
+
+ /* Check if block exists */
+ if ( !$block )
+ die('Error: Could not export block settings.');
+
+ /* Spit the file out */
+ return self::to_json('Block Settings - ' . HeadwayBlocksData::get_block_name($block), 'block-settings', array(
+ 'id' => $block_id,
+ 'type' => $block['type'],
+ 'settings' => $block['settings'],
+ 'styling' => HeadwayBlocksData::get_block_styling($block)
+ ));
+
+ }
+
+
+ public static function export_layout($layout_id) {
+
+ /* Set up variables */
+ if ( !$layout_name = HeadwayLayout::get_name($layout_id) )
+ die('Error: Invalid layout.');
+
+ $layout = array(
+ 'name' => $layout_name,
+ 'blocks' => HeadwayBlocksData::get_blocks_by_layout($layout_id)
+ );
+
+ /* Convert all mirrored blocks into original blocks by pulling their mirror target's settings */
+ /* Loop through each block in the template and check if it's mirrored. If it is, replace it with the block that it's mirroring */
+ foreach ( $layout['blocks'] as $layout_block_index => $layout_block ) {
+
+ if ( !$mirrored_block = HeadwayBlocksData::get_block_mirror($layout_block) )
+ continue;
+
+ $layout['blocks'][$layout_block_index] = $mirrored_block;
+
+ }
+
+ /* Spit the file out */
+ return self::to_json('Headway Layout - ' . $layout_name, 'layout', $layout);
+
+ }
+
+
+ /**
+ * Convert array to JSON file and force download.
+ *
+ * Images will be converted to base64 via HeadwayDataPortability::encode_images()
+ **/
+ public static function to_json($filename, $data_type = null, $array) {
+
+ if ( !$array['data-type'] = $data_type )
+ die('Missing data type for HeadwayDataPortability::to_json()');
+
+ $array['image-definitions'] = self::encode_images($array);
+
+ header('Content-Disposition: attachment; filename="' . $filename . '.json"');
+ header('Content-Type: application/json');
+ header('Pragma: no-cache');
+
+ echo json_encode($array);
+
+ return $filename;
+
+ }
+
+
+ /**
+ * Convert all images to base64.
+ *
+ * This method is recursive.
+ **/
+ public static function encode_images(&$array, $images = null) {
+
+ if ( !$images )
+ $images = array();
+
+ foreach ( $array as $key => $value ) {
+
+ $is_serialized = is_serialized($value);
+
+ if ( is_array($value) || $is_serialized ) {
+
+ if ( $is_serialized ) {
+
+ $value = headway_maybe_unserialize($value);
+
+ if ( !is_array($value) ) {
+ continue;
+ }
+
+ $array[$key] = $value;
+
+ }
+
+ $images = array_merge($images, self::encode_images($array[$key], $images));
+
+ continue;
+
+ } else if ( is_string($value) ) {
+
+ $image_matches = array();
+
+ /* PREG_SET_ORDER makes the $image_matches array make more sense */
+ preg_match_all('/([a-z\-_0-9\/\:\.]*\.(jpg|jpeg|png|gif))/i', $value, $image_matches, PREG_SET_ORDER);
+
+ /* Go through each image in the string and download it then base64 encode it and replace the URL with variable */
+ foreach ( $image_matches as $image_match ) {
+
+ if ( !count($image_match) )
+ continue;
+
+ $image_request = wp_remote_get($image_match[0]);
+
+ if ( $image_request && $image_contents = wp_remote_retrieve_body($image_request) ) {
+
+ $image = array(
+ 'base64_contents' => base64_encode($image_contents),
+ 'mime_type' => $image_request['headers']['content-type']
+ );
+
+ /* Add base64 encoded image to image definitions. */
+ /* Make sure that the image isn't already in the definitions. If it is, $possible_duplicate will be the key/ID to the image */
+ if ( !$possible_duplicate = array_search($image, $images) )
+ $images['%%IMAGE_REPLACEMENT_' . (count($images) + 1) . '%%'] = $image;
+
+ /* Replace the URL with variable that way it can be replaced with uploaded image on import. If $possible_duplicate isn't null/false, then use it! */
+ $variable = $possible_duplicate ? $possible_duplicate : '%%IMAGE_REPLACEMENT_' . (count($images)) . '%%';
+ $array[$key] = str_replace($image_match[0], $variable, $array[$key]);
+
+ }
+
+ }
+
+ }
+
+ }
+
+ return $images;
+
+ }
+
+
+ /**
+ * Convert base64 encoded image into a file and move it to proper WP uploads directory.
+ **/
+ public static function decode_image_to_uploads($base64_string) {
+
+ /* Make sure user has permissions to edit in the Visual Editor */
+ if ( !HeadwayCapabilities::can_user_visually_edit() )
+ return;
+
+ /* Create a temporary file and decode the base64 encoded image into it */
+ $temporary_file = wp_tempnam();
+ file_put_contents($temporary_file, base64_decode($base64_string));
+
+ /* Use wp_check_filetype_and_ext() to figure out the real mimetype of the image. Provide a bogus extension and then we'll use the 'proper_filename' later. */
+ $filename = 'headway-imported-image.jpg';
+ $file_information = wp_check_filetype_and_ext($temporary_file, $filename);
+
+ /* Construct $file array which is similar to a PHP $_FILES array. This array must be a variable since wp_handle_sideload() requires a variable reference argument. */
+ if ( headway_get('proper_filename', $file_information) )
+ $filename = $file_information['proper_filename'];
+
+ $file = array(
+ 'name' => $filename,
+ 'tmp_name' => $temporary_file
+ );
+
+ /* Let WordPress move the image and spit out the file path, URL, etc. Set test_form to false that way it doesn't verify $_POST['action'] */
+ $upload = wp_handle_sideload($file, array('test_form' => false));
+
+ /* If there's an error, be sure to unlink/delete the temporary file in case wp_handle_sideload() doesn't. */
+ if ( isset($upload['error']) )
+ @unlink($temporary_file);
+
+ return $upload;
+
+ }
+
+
+}
\ No newline at end of file
--- /dev/null
+<?php
+class HeadwaySkinOption {
+
+
+ private static function pass_method($method, array $args) {
+
+ /* Set skins option flag */
+ HeadwayOption::$is_skin_option = true;
+
+ $result = call_user_func_array(array('HeadwayOption', $method), $args);
+
+ /* Remove skin option flag */
+ HeadwayOption::$is_skin_option = false;
+
+ return $result;
+
+ }
+
+
+ public static function get() {
+
+ $args = func_get_args();
+ return self::pass_method(__FUNCTION__, $args);
+
+ }
+
+
+ public static function get_group() {
+
+ $args = func_get_args();
+ return self::pass_method(__FUNCTION__, $args);
+
+ }
+
+
+ public static function set() {
+
+ $args = func_get_args();
+ return self::pass_method(__FUNCTION__, $args);
+
+ }
+
+
+ public static function set_group() {
+
+ $args = func_get_args();
+ return self::pass_method(__FUNCTION__, $args);
+
+ }
+
+
+ public static function delete() {
+
+ $args = func_get_args();
+ return self::pass_method(__FUNCTION__, $args);
+
+ }
+
+
+}
\ No newline at end of file
--- /dev/null
+<?php
+class HeadwayDataSnapshots {
+
+
+ public static function init() {
+
+
+ }
+
+
+ public static function list_snapshots() {
+
+ global $wpdb;
+
+ return $wpdb->get_results($wpdb->prepare("SELECT id, timestamp, comments FROM $wpdb->hw_snapshots WHERE template = '%s' ORDER BY timestamp DESC", HeadwayOption::$current_skin));
+
+ }
+
+
+ public static function save_snapshot($throttle = false) {
+
+ global $wpdb;
+
+ /* Only allow snapshots to be saved every 15 minutes if $throttle is true */
+ if ( $throttle && $last_snapshot_timestamp = HeadwaySkinOption::get('last-snapshot') ) {
+
+ if ( time() < strtotime('+15 minutes', $last_snapshot_timestamp) )
+ return false;
+
+ }
+
+ $wp_options_prefix = 'headway_|template=' . HeadwayOption::$current_skin . '|_';
+
+ $insert_args = array(
+ 'template' => HeadwayOption::$current_skin,
+ 'comments' => headway_post('snapshot_comments'),
+ 'timestamp' => current_time('mysql', 1), /* GMT */
+ 'data_wp_options' => headway_maybe_serialize($wpdb->get_results($wpdb->prepare("SELECT * FROM $wpdb->options WHERE option_name LIKE '%s'", $wp_options_prefix . '%'))),
+ 'data_wp_postmeta' => headway_maybe_serialize($wpdb->get_results($wpdb->prepare("SELECT * FROM $wpdb->postmeta WHERE meta_key LIKE '%s'", '_hw_|template=' . HeadwayOption::$current_skin . '|_%'))),
+ 'data_hw_layout_meta' => headway_maybe_serialize($wpdb->get_results($wpdb->prepare("SELECT * FROM $wpdb->hw_layout_meta WHERE template = '%s'", HeadwayOption::$current_skin))),
+ 'data_hw_wrappers' => headway_maybe_serialize($wpdb->get_results($wpdb->prepare("SELECT * FROM $wpdb->hw_wrappers WHERE template = '%s'", HeadwayOption::$current_skin))),
+ 'data_hw_blocks' => headway_maybe_serialize($wpdb->get_results($wpdb->prepare("SELECT * FROM $wpdb->hw_blocks WHERE template = '%s'", HeadwayOption::$current_skin)))
+ );
+
+ $snapshotquery = $wpdb->insert($wpdb->hw_snapshots, $insert_args);
+
+ if ( is_wp_error($snapshotquery) ) {
+
+ $output['errors'][] = $snapshotquery->get_error_code() . ($snapshotquery->get_error_message() ? ' - ' . $snapshotquery->get_error_code() : '');
+
+ } else {
+
+ HeadwaySkinOption::set('last-snapshot', time());
+
+ return array(
+ 'id' => $wpdb->insert_id,
+ 'comments' => $insert_args['comments'],
+ 'timestamp' => $insert_args['timestamp']
+ );
+
+ }
+
+ }
+
+
+ public static function rollback($rollback_id) {
+
+ global $wpdb;
+
+ if ( !$rollback = $wpdb->get_row($wpdb->prepare("SELECT * FROM $wpdb->hw_snapshots WHERE id = %d AND template = '%s'", $rollback_id, HeadwayOption::$current_skin), ARRAY_A) )
+ return array('errors' => array('Snapshot does not exist.'));
+
+ $rollback_process = self::process_rollback($rollback);
+
+ return !is_wp_error($rollback_process) ? true : $rollback_process;
+
+ }
+
+
+ public static function process_rollback($data, $template = false) {
+
+ global $wpdb;
+
+ if ( !$template )
+ $template = HeadwayOption::$current_skin;
+
+ $data_arrays = array(
+ 'data_wp_options',
+ 'data_wp_postmeta',
+ 'data_hw_layout_meta',
+ 'data_hw_wrappers',
+ 'data_hw_blocks'
+ );
+
+ /* Go through data and delete and insert */
+ foreach ( $data_arrays as $data_array_id ) {
+
+ $data_set = headway_maybe_unserialize(headway_get($data_array_id, $data));
+ $table_name = str_replace(array('data_', 'wp_'), '', $data_array_id);
+ $wpdb_table_name = $wpdb->{$table_name};
+
+ /* Handle Headway tables */
+ if ( strpos($table_name, 'hw_') === 0 ) {
+
+ $delete_query = $wpdb->query($wpdb->prepare("DELETE FROM $wpdb_table_name WHERE template = '%s'", $template));
+
+ foreach ( $data_set as $data_object ) {
+
+ $insert_data = is_object($data_object) ? get_object_vars($data_object) : $data_object;
+ $insert_data['template'] = $template;
+
+ foreach ( $insert_data as $insert_data_key => $insert_data_value ) {
+
+ if ( is_array($insert_data_value) ) {
+ $insert_data[$insert_data_key] = headway_maybe_serialize($insert_data_value);
+ }
+
+ }
+
+ $insert_query = $wpdb->insert($wpdb_table_name, $insert_data);
+
+ }
+
+ /* Handle WP options/postmeta */
+ } else if ( $table_name == 'options' || $table_name == 'postmeta' ) {
+
+ $prefix = $table_name == 'options' ? 'headway_|template=' . $template . '|_' : '_hw_|template=' . $template . '|_';
+ $key_column = $table_name == 'options' ? 'option_name' : 'meta_key';
+
+ $delete_query = $wpdb->query($wpdb->prepare("DELETE FROM $wpdb_table_name WHERE $key_column LIKE '%s'", $prefix . '%'));
+
+ foreach ( $data_set as $data_object ) {
+
+ $insert_data = is_object($data_object) ? get_object_vars($data_object) : $data_object;
+
+ if ( isset($insert_data['option_id']) )
+ unset($insert_data['option_id']);
+
+ if ( isset($insert_data['meta_id']) )
+ unset($insert_data['meta_id']);
+
+ /* Build the key column ID with the correct template */
+ $key_column_fragments = explode('|_', $insert_data[$key_column]);
+ $key_column_id_without_prefix = $key_column_fragments[1];
+
+ $insert_data[$key_column] = $prefix . $key_column_id_without_prefix;
+
+ /* Fix wrapper IDs */
+ if ( strpos($key_column_id_without_prefix, 'option_group_design') !== false ) {
+ $insert_data['option_value'] = headway_preg_replace_json( "/-layout-[\w-]*/", '', $insert_data['option_value'] );
+ }
+
+ foreach ( $insert_data as $insert_data_key => $insert_data_value ) {
+
+ if ( is_array($insert_data_value) ) {
+ $insert_data[$insert_data_key] = headway_maybe_serialize($insert_data_value);
+ }
+
+ }
+
+ $insert_query = $wpdb->insert($wpdb_table_name, $insert_data);
+
+ }
+
+ }
+
+ }
+
+ do_action('headway_snapshot_rollback');
+
+ return $data;
+
+ }
+
+
+ public static function delete($id) {
+
+ global $wpdb;
+
+ return $wpdb->delete( $wpdb->hw_snapshots, array(
+ 'id' => $id,
+ 'template' => HeadwayOption::$current_skin
+ ) );
+
+ }
+
+
+ public static function delete_by_template($template) {
+
+ global $wpdb;
+
+ return $wpdb->delete($wpdb->hw_snapshots, array(
+ 'template' => $template
+ ));
+
+ }
+
+
+}
\ No newline at end of file
--- /dev/null
+<?php
+class HeadwayWrappersData {
+
+
+ public static function add_wrapper($layout_id, $args) {
+
+ global $wpdb;
+
+ /* Validate input */
+ if ( !$args || !is_array($args) )
+ return false;
+
+ if ( $args['position'] === null || $args['position'] === false || $args['position'] === '' )
+ return new WP_Error('hw_add_wrapper_missing_position');
+
+ //Figure out mirror ID
+ $mirror_id = headway_get('mirror-wrapper', headway_get('settings', $args, array()));
+
+ //Unset old mirror ID
+ if ( isset($args['settings']['mirror-wrapper']) )
+ unset($args['settings']['mirror-wrapper']);
+
+ $random_prefix = substr(str_shuffle(str_repeat("0123456789abcdefghijklmnopqrstuvwxyz", 2)), 0, 2);
+
+ //Build insert args
+ $insert_args = array(
+ 'id' => uniqid('w' . strtolower(substr($random_prefix, 0, 2))),
+ 'template' => headway_get('template', $args, HeadwayOption::$current_skin),
+ 'layout' => $layout_id,
+ 'position' => $args['position'],
+ 'settings' => headway_maybe_serialize(headway_get('settings', $args, array())),
+ 'mirror_id' => $mirror_id
+ );
+
+ if ( $insert_id = headway_get('insert_id', $args) )
+ $insert_args['id'] = $insert_id;
+
+ if ( $legacy_id = headway_get('legacy_id', $args) )
+ $insert_args['legacy_id'] = $legacy_id;
+
+ //Run the query
+ $wpdb->insert($wpdb->hw_wrappers, $insert_args);
+
+ //All done. Spit back ID of newly created wrapper.
+ return $insert_args['id'];
+
+ }
+
+
+ public static function update_wrapper($wrapper_id, $args) {
+
+ global $wpdb;
+
+ $wrapper_to_be_updated = self::get_wrapper($wrapper_id);
+
+ /* Make sure wrapper exists */
+ if ( !$wrapper_to_be_updated )
+ return null;
+
+ /* Map mirror-wrapper setting to mirror_id column */
+ if ( isset($args['settings']) && isset($args['settings']['mirror-wrapper']) ) {
+
+ $args['mirror_id'] = $args['settings']['mirror-wrapper'];
+ unset($args['settings']['mirror-wrapper']);
+
+ }
+
+ /* Handle template argument */
+ $template = headway_get('template', $args, HeadwayOption::$current_skin);
+
+ if ( isset($args['template']) )
+ unset($args['template']);
+
+ /* Query */
+ $query = $wpdb->update($wpdb->hw_wrappers, array_map('headway_maybe_serialize', $args), array(
+ 'template' => $template,
+ 'id' => $wrapper_id
+ ));
+
+ return $query;
+
+ }
+
+
+ /**
+ * @todo remove design instances and remove blocks in that wrapper here
+ * @param $wrapper_id
+ *
+ * @return null
+ */
+ public static function delete_wrapper($layout_id, $wrapper_id) {
+
+ global $wpdb;
+
+ $wrapper_to_be_deleted = self::get_wrapper($wrapper_id);
+
+ /* Make sure wrapper exists */
+ if ( !$wrapper_to_be_deleted )
+ return null;
+
+ /* Query for deletion */
+ $wrapper_delete_query = $wpdb->delete( $wpdb->hw_wrappers, array(
+ 'template' => HeadwayOption::$current_skin,
+ 'id' => $wrapper_id
+ ));
+
+ /* Delete design settings */
+ self::delete_wrapper_design_instances($layout_id, $wrapper_id);
+
+ /* Unmirror the wrappers mirroring this wrappers */
+ $wpdb->update( $wpdb->hw_wrappers, array(
+ 'mirror_id' => ''
+ ), array(
+ 'mirror_id' => $wrapper_id
+ ));
+
+ /* Delete all blocks in that wrapper */
+ $blocks_delete_query = HeadwayBlocksData::delete_by_wrapper($layout_id, $wrapper_id);
+
+ return array($wrapper_delete_query, $blocks_delete_query);
+
+ }
+
+
+ public static function delete_wrapper_design_instances($layout_id, $wrapper_id) {
+
+ return HeadwayElementsData::delete_special_element_properties(null, 'wrapper', 'instance', 'wrapper-' . HeadwayWrappers::format_wrapper_id($wrapper_id));
+
+ }
+
+
+ public static function delete_by_layout($layout_id) {
+
+ global $wpdb;
+
+ $layout_wrappers = self::get_wrappers_by_layout($layout_id);
+ $return = array();
+
+ foreach ( $layout_wrappers as $wrapper_id => $options ) {
+ $return[$wrapper_id] = self::delete_wrapper($layout_id, $wrapper_id);
+ }
+
+ return $return;
+
+ }
+
+
+ public static function delete_by_template($template) {
+
+ global $wpdb;
+
+ return $wpdb->delete( $wpdb->hw_wrappers, array(
+ 'template' => $template
+ ));
+
+ }
+
+
+ public static function get_wrapper($wrapper, $use_mirrored = false) {
+
+ global $wpdb;
+
+ /* If $wrapper is already an array then validate it and return it */
+ if ( is_array($wrapper) ) {
+
+ if ( isset($wrapper['id']) ) {
+ return $wrapper;
+ } else {
+ return null;
+ }
+
+ }
+
+ /* Build cache key */
+ $cache_key = 'hw_wrapper_' . $wrapper;
+
+ if ( $use_mirrored )
+ $cache_key .= '_using_mirrored';
+
+ /* Check cache */
+ $wrapper_from_cache = wp_cache_get($cache_key);
+
+ if ( $wrapper_from_cache !== false )
+ return $wrapper_from_cache;
+
+ /* Not cached... Retrieve wrapper */
+ if ( is_string($wrapper) || is_numeric($wrapper) ) {
+
+ $wrapper_id = HeadwayWrappers::format_wrapper_id($wrapper);
+
+ $wrapper_query = $wpdb->get_row($wpdb->prepare("SELECT * FROM $wpdb->hw_wrappers WHERE template = '%s' AND id = '%s'", HeadwayOption::$current_skin, $wrapper_id), ARRAY_A);
+
+ if ( is_array($wrapper_query) && !is_wp_error($wrapper_query) ) {
+
+ $wrapper = array_map('headway_maybe_unserialize', $wrapper_query);
+
+ } else {
+
+ /* If no wrapper is found, try querying the legacy_id */
+ $wrapper_from_legacy_id = $wpdb->get_row($wpdb->prepare("SELECT * FROM $wpdb->hw_wrappers WHERE template = '%s' AND legacy_id = '%d'", HeadwayOption::$current_skin, $wrapper_id), ARRAY_A);
+
+ if ( is_array($wrapper_from_legacy_id) && ! is_wp_error( $wrapper_from_legacy_id ) ) {
+ $wrapper = array_map( 'headway_maybe_unserialize', $wrapper_from_legacy_id );
+ } else {
+ $wrapper = null;
+ }
+
+ }
+
+ }
+
+ if ( is_array($wrapper) && !isset($wrapper['id']) )
+ return null;
+
+ /* Fetch the mirrored wrapper if $use_mirrored is true */
+ if ( $use_mirrored === true && $mirrored_wrapper = self::get_wrapper_mirror($wrapper) )
+ $wrapper = $mirrored_wrapper;
+
+ wp_cache_set($cache_key, $wrapper);
+
+ return $wrapper;
+
+ }
+
+
+ public static function get_wrappers_by_layout($layout_id, $include_styling = false) {
+
+ global $wpdb;
+
+ /* Build cache key */
+ $cache_key = 'hw_wrappers_by_layout_' . $layout_id;
+
+ if ( $include_styling )
+ $cache_key = $cache_key . '_with_styling';
+
+ /* Check cache */
+ $layout_wrappers = wp_cache_get($cache_key);
+
+ if ( $layout_wrappers === false ) {
+
+ /* Retrieve all wrappers from layout */
+ $layout_wrappers_query = $wpdb->get_results($wpdb->prepare("SELECT * FROM $wpdb->hw_wrappers WHERE template = '%s' AND layout = '%s' ORDER BY position ASC", HeadwayOption::$current_skin, $layout_id), ARRAY_A);
+
+ /* Change results array into associative */
+ $layout_wrappers = array();
+
+ foreach ( $layout_wrappers_query as $layout_wrapper ) {
+ $layout_wrappers[$layout_wrapper['id']] = array_map('headway_maybe_unserialize', $layout_wrapper);
+ }
+
+ /* If wrapper array is empty then load the default wrapper array */
+ if ( !count($layout_wrappers) ) {
+ $layout_wrappers = HeadwayWrappers::$default_wrappers;
+ $layout_wrappers['default']['layout'] = $layout_id;
+ }
+
+ if ( $include_styling ) {
+ $layout_wrappers = self::add_wrapper_styling_to_array($layout_wrappers);
+ }
+
+ wp_cache_set($cache_key, $layout_wrappers);
+
+ }
+
+ return $layout_wrappers;
+
+ }
+
+
+ public static function get_all_wrappers($include_styling = false, $mirrored_only = false) {
+
+ global $wpdb;
+
+ /* Build cache key */
+ $cache_key = 'hw_all_wrappers';
+
+ if ( $include_styling )
+ $cache_key .= '_with_styling';
+
+ if ( $mirrored_only )
+ $cache_key .= '_mirrored_only';
+
+ /* Check cache */
+ $wrappers_from_cache = wp_cache_get($cache_key);
+
+ if ( $wrappers_from_cache !== false )
+ return $wrappers_from_cache;
+
+ /* Not cached... Retrieve all wrappers */
+ $query = "SELECT * FROM $wpdb->hw_wrappers WHERE template = '%s'";
+
+ if ( $mirrored_only )
+ $query .= " AND mirror_id <> ''";
+
+ $wrapper_query = $wpdb->get_results($wpdb->prepare($query, HeadwayOption::$current_skin), ARRAY_A);
+
+ /* Change results array into associative */
+ $wrappers = array();
+
+ foreach ( $wrapper_query as $wrapper ) {
+ $wrappers[$wrapper['id']] = array_map('headway_maybe_unserialize', $wrapper);
+ }
+
+ if ( $include_styling ) {
+ $wrappers = self::add_wrapper_styling_to_array($wrappers);
+ }
+
+ wp_cache_set($cache_key, $wrappers);
+
+ return $wrappers;
+
+ }
+
+
+ public static function add_wrapper_styling_to_array($wrappers) {
+
+ if ( !is_array($wrappers) )
+ return false;
+
+ /* If the array provided is just one wrapper, then put it into an array */
+ if ( isset($wrappers['id']) && isset($wrappers['position']) ) {
+ $wrappers = array($wrappers);
+ }
+
+ foreach ( $wrappers as $wrapper_id => $wrapper ) {
+
+ $wrappers[$wrapper_id]['styling'] = HeadwayElementsData::get_special_element_properties(array(
+ 'element' => 'wrapper',
+ 'se_type' => 'instance',
+ 'se_meta' => 'wrapper-' . HeadwayWrappers::format_wrapper_id($wrapper_id)
+ ));
+
+ }
+
+ return $wrappers;
+
+ }
+
+
+ public static function is_wrapper_mirrored($wrapper) {
+
+ $wrapper = self::get_wrapper($wrapper);
+
+ if ( $mirrored_wrapper_id = headway_get('mirror_id', $wrapper) )
+ return $mirrored_wrapper_id;
+
+ return false;
+
+ }
+
+
+ public static function get_wrapper_mirror($wrapper) {
+
+ $wrapper = self::get_wrapper($wrapper);
+
+ if ( $mirrored_wrapper_id = headway_get('mirror_id', $wrapper) )
+ return self::get_wrapper($mirrored_wrapper_id);
+
+ return false;
+
+ }
+
+
+ public static function wrapper_exists($id) {
+
+ if ( self::get_wrapper($id) )
+ return true;
+
+ return false;
+
+ }
+
+ public static function get_wrapper_setting($wrapper, $option_name, $default_value = null) {
+
+ if (!is_array($wrapper))
+ $wrapper = HeadwayWrappersData::get_wrapper($wrapper);
+
+ return headway_get($option_name, headway_get('settings', $wrapper, array()), $default_value);
+
+ }
+
+
+ public static function get_legacy_id( $wrapper ) {
+
+ return is_numeric( headway_get( 'legacy_id', $wrapper ) ) && headway_get( 'legacy_id', $wrapper ) > 0 ? headway_get( 'legacy_id', $wrapper ) : $wrapper['id'];
+
+ }
+
+
+}
\ No newline at end of file
--- /dev/null
+<?php
+global $headway_core_default_element_data;
+
+$headway_core_default_element_data = array(
+ /* Defaults */
+ 'default-text' => array(
+ 'properties' => array(
+ 'font-size' => '14',
+ 'font-family' => 'palatino',
+ 'line-height' => '100',
+ 'color' => '555555'
+ )
+ ),
+
+ 'default-hyperlink' => array(
+ 'properties' => array(
+ 'color' => '555555'
+ )
+ ),
+
+ 'default-blockquote' => array(
+ 'properties' => array(
+ 'color' => '666666',
+ 'padding-top' => '5',
+ 'padding-right' => '0',
+ 'padding-bottom' => '5',
+ 'padding-left' => '25',
+ 'border-left-width' => '2',
+ 'border-style' => 'solid',
+ 'border-color' => '666666',
+ 'margin-top' => '15',
+ 'margin-right' => '0',
+ 'margin-bottom' => '15',
+ 'margin-left' => '20'
+
+ )
+ ),
+
+ 'default-block' => array(
+ 'properties' => array(
+ 'overflow' => 'hidden',
+ 'margin-bottom' => '10'
+ )
+ ),
+
+ 'block-title' => array(
+ 'properties' => array(
+ 'font-size' => '22',
+ 'line-height' => '150'
+ )
+ ),
+
+ 'block-subtitle' => array(
+ 'properties' => array(
+ 'font-size' => '14',
+ 'font-styling' => 'italic',
+ 'color' => '999999'
+ )
+ ),
+
+ /* Structure */
+ 'body' => array(
+ 'properties' => array(
+ 'background-color' => 'dddddd'
+ )
+ ),
+
+ 'wrapper' => array(
+ 'properties' => array(
+ 'background-color' => 'ffffff',
+ 'padding-top' => '15',
+ 'padding-right' => '15',
+ 'padding-bottom' => '15',
+ 'padding-left' => '15',
+ 'box-shadow-color' => 'c7c7c7',
+ 'box-shadow-blur' => '8',
+ 'box-shadow-horizontal-offset' => '1',
+ 'box-shadow-vertical-offset' => '1',
+ 'margin-top' => '30',
+ 'margin-bottom' => '30'
+ )
+ ),
+
+ /* Header Block */
+ 'block-header-site-title' => array(
+ 'properties' => array(
+ 'color' => '222222',
+ 'font-size' => '34',
+ 'line-height' => '100',
+ 'text-decoration' => 'none',
+ 'margin-top' => '20',
+ 'margin-right' => '10',
+ 'margin-bottom' => '0',
+ 'margin-left' => '10'
+ )
+ ),
+
+ 'block-header-site-tagline' => array(
+ 'properties' => array(
+ 'color' => '999999',
+ 'font-size' => '15',
+ 'line-height' => '120',
+ 'font-styling' => 'italic',
+ 'margin-top' => '10',
+ 'margin-right' => '10',
+ 'margin-bottom' => '20',
+ 'margin-left' => '10'
+ )
+ ),
+
+ /* Navigation Block */
+ 'block-navigation' => array(
+ 'properties' => array(
+ 'border-top-width' => '1',
+ 'border-bottom-width' => '1',
+ 'border-left-width' => '0',
+ 'border-right-width' => '0',
+ 'border-color' => 'eeeeee',
+ 'border-style' => 'solid',
+ 'overflow' => 'visible'
+ )
+ ),
+
+ 'block-navigation-menu-item' => array(
+ 'properties' => array(
+ 'text-decoration' => 'none',
+ 'color' => '888888',
+ 'capitalization' => 'uppercase',
+ 'padding-right' => '15',
+ 'padding-left' => '15'
+ ),
+ 'special-element-state' => array(
+ 'selected' => array(
+ 'color' => '222222'
+ ),
+ 'hover' => array(
+ 'color' => '555555'
+ )
+ )
+ ),
+
+ 'block-navigation-sub-nav-menu' => array(
+ 'properties' => array(
+ 'background-color' => 'eeeeee'
+ )
+ ),
+
+ /* Widget Block */
+ 'block-widget-area-widget' => array(
+ 'properties' => array(
+ 'line-height' => '150',
+ 'padding-top' => '5',
+ 'padding-right' => '10',
+ 'padding-bottom' => '5',
+ 'padding-left' => '10',
+ 'margin-top' => '15'
+ )
+ ),
+
+ 'block-widget-area-widget-title' => array(
+ 'properties' => array(
+ 'font-size' => '13',
+ 'border-style' => 'solid',
+ 'border-top-width' => '1',
+ 'border-bottom-width' => '1',
+ 'border-left-width' => '0',
+ 'border-right-width' => '0',
+ 'border-color' => 'eeeeee',
+ 'letter-spacing' => '1',
+ 'capitalization' => 'uppercase',
+ 'line-height' => '250',
+ 'color' => '111111',
+ 'margin-bottom' => '10'
+ )
+ ),
+
+ 'block-widget-area-widget-links' => array(
+ 'properties' => array(
+ 'color' => '333333'
+ )
+ ),
+
+ /* Content Block */
+ 'block-content-entry-container' => array(
+ 'properties' => array(
+ 'border-style' => 'solid',
+ 'border-top-width' => '0',
+ 'border-bottom-width' => '1',
+ 'border-left-width' => '0',
+ 'border-right-width' => '0',
+ 'border-color' => 'efefef',
+ 'padding-bottom' => '30'
+ )
+ ),
+
+ 'block-content-title' => array(
+ 'properties' => array(
+ 'font-size' => '24',
+ 'color' => '333333',
+ 'line-height' => '130'
+ )
+ ),
+
+ 'block-content-archive-title' => array(
+ 'properties' => array(
+ 'font-size' => '24',
+ 'color' => '555555',
+ 'line-height' => '110',
+ 'border-bottom-width' => '1',
+ 'border-color' => 'eeeeee',
+ 'border-style' => 'solid',
+ 'padding-bottom' => '15'
+ )
+ ),
+
+ 'block-content-entry-meta' => array(
+ 'properties' => array(
+ 'line-height' => '120',
+ 'color' => '818181'
+ )
+ ),
+
+ 'block-content-entry-content' => array(
+ 'properties' => array(
+ 'color' => '555555',
+ 'font-size' => '14',
+ 'line-height' => '180'
+ )
+ ),
+
+ 'block-content-heading' => array(
+ 'properties' => array(
+ 'font-size' => '20',
+ 'line-height' => '180'
+ )
+ ),
+
+ 'block-content-sub-heading' => array(
+ 'properties' => array(
+ 'font-size' => '16',
+ 'line-height' => '180'
+ )
+ ),
+
+ 'block-content-more-link' => array(
+ 'properties' => array(
+ 'background-color' => 'eeeeee',
+ 'text-decoration' => 'none',
+ 'border-top-left-radius' => '4',
+ 'border-top-right-radius' => '4',
+ 'border-bottom-right-radius' => '4',
+ 'border-bottom-left-radius' => '4',
+ 'padding-top' => '2',
+ 'padding-right' => '6',
+ 'padding-bottom' => '2',
+ 'padding-left' => '6'
+ ),
+ 'special-element-state' => array(
+ 'hover' => array(
+ 'background-color' => 'e7e7e7'
+ )
+ )
+ ),
+
+ 'block-content-loop-navigation-link' => array(
+ 'properties' => array(
+ 'background-color' => 'e1e1e1',
+ 'text-decoration' => 'none',
+ 'border-top-left-radius' => '4',
+ 'border-top-right-radius' => '4',
+ 'border-bottom-right-radius' => '4',
+ 'border-bottom-left-radius' => '4',
+ 'padding-top' => '4',
+ 'padding-right' => '8',
+ 'padding-bottom' => '4',
+ 'padding-left' => '8',
+ 'line-height' => '130'
+ ),
+ 'special-element-state' => array(
+ 'hover' => array(
+ 'background-color' => 'd5d5d5'
+ )
+ )
+ ),
+
+ 'block-content-post-thumbnail' => array(
+ 'properties' => array(
+ 'border-top-width' => '1',
+ 'border-right-width' => '1',
+ 'border-bottom-width' => '1',
+ 'border-left-width' => '1',
+ 'border-color' => 'eeeeee',
+ 'border-style' => 'solid',
+ 'padding-top' => '3',
+ 'padding-right' => '3',
+ 'padding-bottom' => '3',
+ 'padding-left' => '3'
+ )
+ ),
+
+ 'block-content-comments-area-headings' => array(
+ 'properties' => array(
+ 'color' => '333333',
+ 'font-size' => '18',
+ 'line-height' => '130'
+ )
+ ),
+
+ 'block-content-comment-container' => array(
+ 'properties' => array(
+ 'padding-left' => '64'
+ )
+ ),
+
+ 'block-content-comment-author' => array(
+ 'properties' => array(
+ 'font-size' => '18',
+ 'line-height' => '120'
+ )
+ ),
+
+ 'block-content-comment-meta' => array(
+ 'properties' => array(
+ 'color' => '888888',
+ 'font-size' => '14'
+ )
+ ),
+
+ 'block-content-comment-body' => array(
+ 'properties' => array(
+ 'font-size' => '14',
+ 'line-height' => '170'
+ )
+ ),
+
+ 'block-content-comment-reply-link' => array(
+ 'properties' => array(
+ 'font-size' => '12',
+ 'background-color' => 'eeeeee',
+ 'text-decoration' => 'none',
+ 'border-top-left-radius' => '4',
+ 'border-top-right-radius' => '4',
+ 'border-bottom-right-radius' => '4',
+ 'border-bottom-left-radius' => '4',
+ 'padding-top' => '3',
+ 'padding-right' => '6',
+ 'padding-bottom' => '3',
+ 'padding-left' => '6'
+ ),
+ 'special-element-state' => array(
+ 'hover' => array(
+ 'background-color' => 'e7e7e7'
+ )
+ )
+ ),
+
+ 'block-content-comment-form-input-label' => array(
+ 'properties' => array(
+ 'font-size' => '14',
+ 'line-height' => '220',
+ 'color' => '888888'
+ )
+ ),
+
+
+ /* Slider */
+ 'block-slider-slider-container' => array(
+ 'properties' => array(
+ 'overflow' => 'visible',
+ 'margin-bottom' => '30'
+ )
+ ),
+
+ 'block-slider-slider-viewport' => array(
+ 'properties' => array(
+ 'overflow' => 'hidden'
+ )
+ ),
+
+ 'block-slider-slider-caption' => array(
+ 'properties' => array(
+ 'background-color' => 'rgba(0, 0, 0, 0.6)',
+ 'color' => 'ffffff',
+ 'font-size' => '14',
+ 'line-height' => '150',
+ 'padding-top' => '20',
+ 'padding-right' => '20',
+ 'padding-bottom' => '20',
+ 'padding-left' => '20',
+ 'position' => 'absolute',
+ 'text-align' =>'center'
+ )
+ ),
+
+ 'block-slider-slider-paging' => array(
+ 'properties' => array(
+ 'position' => 'absolute',
+ 'text-align' => 'center'
+ )
+ ),
+
+ 'block-slider-slider-direction-nav-link' => array(
+ 'properties' => array(
+ 'margin-top' => '-20',
+ 'position' => 'absolute',
+ 'background-image' => headway_url() . '/library/blocks/slider/assets/bg_direction_nav.png',
+ 'background-repeat' => 'no-repeat',
+ 'background-position' => 'left top'
+ )
+ ),
+
+ 'block-slider-slider-direction-nav-next' => array(
+ 'properties' => array(
+ 'background-position' => 'right top'
+ )
+ ),
+
+ 'block-slider-slider-paging-link' => array(
+ 'properties' => array(
+ 'background-color' => 'rgba(0,0,0,0.5)',
+ 'border-top-left-radius' => '20',
+ 'border-top-right-radius' => '20',
+ 'border-bottom-right-radius' => '20',
+ 'border-bottom-left-radius' => '20',
+ 'margin-left' => '2',
+ 'margin-right' => '2'
+ ),
+ 'special-element-state' => array(
+ 'hover' => array(
+ 'background-color' => 'rgba(0,0,0,0.7)'
+ ),
+ 'active' => array(
+ 'background-color' => 'rgba(0,0,0,0.9)'
+ )
+ )
+ ),
+
+
+ /* Text Block */
+ 'block-text-heading' => array(
+ 'properties' => array(
+ 'font-size' => '20',
+ 'line-height' => '180'
+ )
+ ),
+
+ 'block-text-sub-heading' => array(
+ 'properties' => array(
+ 'font-size' => '16',
+ 'line-height' => '180'
+ )
+ ),
+ /* End Text Block */
+
+
+ /* Pin Board */
+ 'block-pin-board-pin' => array(
+ 'properties' => array(
+ 'padding-top' => 1,
+ 'padding-right' => 1,
+ 'padding-bottom' => 1,
+ 'padding-left' => 1,
+
+ 'background-color' => 'ffffff',
+
+ 'border-color' => 'eeeeee',
+ 'border-style' => 'solid',
+ 'border-top-width' => 1,
+ 'border-right-width' => 1,
+ 'border-bottom-width' => 1,
+ 'border-left-width' => 1,
+
+ 'box-shadow-color' => 'eee',
+ 'box-shadow-blur' => 3,
+ 'box-shadow-horizontal-offset' => 0,
+ 'box-shadow-vertical-offset' => 2
+ )
+ ),
+
+ 'block-pin-board-pin-title' => array(
+ 'properties' => array(
+ 'padding-top' => 15,
+ 'padding-right' => 15,
+ 'padding-left' => 15,
+
+ 'font-size' => 18,
+ 'line-height' => 120,
+
+ 'text-decoration' => 'none'
+ ),
+ 'special-element-state' => array(
+ 'hover' => array(
+ 'text-decoration' => 'underline'
+ )
+ )
+ ),
+
+ 'block-pin-board-pin-text' => array(
+ 'properties' => array(
+ 'font-size' => 12,
+ 'line-height' => 150,
+
+ 'padding-right' => 15,
+ 'padding-left' => 15
+ )
+ ),
+
+ 'block-pin-board-pin-meta' => array(
+ 'properties' => array(
+ 'font-size' => 12,
+ 'line-height' => 120,
+
+ 'padding-right' => 15,
+ 'padding-left' => 15,
+
+ 'color' => '888888'
+ )
+ ),
+
+ 'block-pin-board-pagination-button' => array(
+ 'properties' => array(
+ 'text-decoration' => 'none',
+ 'background-color' => 'eeeeee',
+
+ 'border-top-left-radius' => 4,
+ 'border-top-right-radius' => 4,
+ 'border-bottom-right-radius' => 4,
+ 'border-bottom-left-radius' => 4,
+
+ 'padding-top' => 5,
+ 'padding-right' => 9,
+ 'padding-bottom' => 5,
+ 'padding-left' => 9
+ ),
+ 'special-element-state' => array(
+ 'hover' => array(
+ 'background-color' => 'e7e7e7'
+ )
+ )
+ ),
+ /* End Pin Board */
+
+
+ /* Footer */
+ 'block-footer' => array(
+ 'properties' => array(
+ 'border-top-width' => '1',
+ 'border-right-width' => '0',
+ 'border-bottom-width' => '0',
+ 'border-left-width' => '0',
+ 'border-color' => 'eeeeee',
+ 'border-style' => 'solid'
+ )
+ ),
+
+ 'block-footer-copyright' => array(
+ 'properties' => array(
+ 'color' => '666666'
+ )
+ ),
+
+ 'block-footer-headway-attribution' => array(
+ 'properties' => array(
+ 'color' => '666666'
+ )
+ ),
+
+ 'block-footer-administration-panel' => array(
+ 'properties' => array(
+ 'color' => '666666'
+ )
+ ),
+
+ 'block-footer-go-to-top' => array(
+ 'properties' => array(
+ 'color' => '666666'
+ )
+ ),
+
+ 'block-footer-responsive-grid-link' => array(
+ 'properties' => array(
+ 'color' => '666666'
+ )
+ )
+);
\ No newline at end of file
--- /dev/null
+<?php
+class HeadwayDisplay {
+
+
+ public static $plugin_template_generic_content = null;
+
+
+ public static function init() {
+
+ if ( is_admin() )
+ return;
+
+ Headway::load(array(
+ 'display/head' => true,
+ 'display/grid-renderer',
+ 'display/layout-renderer'
+ ));
+
+ add_filter('body_class', array(__CLASS__, 'body_class'));
+
+ if ( HeadwayRoute::is_visual_editor_iframe() ) {
+
+ Headway::load('visual-editor', 'VisualEditor');
+
+ HeadwayAdminBar::remove_admin_bar();
+
+ }
+
+ /* If it's a plugin template, then route all of the content to the content block */
+ add_action('get_header', array(__CLASS__, 'handle_plugin_template'), 1);
+
+ }
+
+
+ public static function layout() {
+
+ get_header();
+
+ self::grid();
+
+ get_footer();
+
+ }
+
+
+ public static function grid() {
+
+ echo "\n\n";
+
+ if ( current_theme_supports('headway-grid') ) {
+
+ $layout = new HeadwayLayoutRenderer;
+ $layout->display();
+
+ } else {
+
+ echo '<div class="alert alert-yellow"><p>The Headway Grid is not supported in this Child Theme.</p></div>';
+
+ }
+
+ echo "\n\n";
+
+ }
+
+ /**
+ * Plugin Templateh andling sstem.
+ *
+ * If the template file isn't Headway's index.php, then fetch the contents and put them into the Content Block
+ **/
+ public static function handle_plugin_template() {
+
+ if ( !self::is_plugin_template() )
+ return false;
+
+ add_action('headway_whitewrap_open', array(__CLASS__, 'headway_whitewrap_open_ob_start'));
+ add_action('headway_whitewrap_close', array(__CLASS__, 'headway_whitewrap_close_ob_get_clean'));
+
+ }
+
+
+ public static function is_plugin_template() {
+
+ global $template;
+
+ /* Replace backslashes with forward slashes for Windows compatibility */
+ if ( strpos(str_replace('\\', '/', $template), '/wp-content/plugins/') !== false || !$template )
+ return true;
+
+ return false;
+
+ }
+
+
+ public static function headway_whitewrap_open_ob_start() {
+
+ ob_start();
+
+ }
+
+
+ public static function headway_whitewrap_close_ob_get_clean() {
+
+ self::$plugin_template_generic_content = ob_get_clean();
+
+ /* Hook generic content */
+ add_action('generic_content', array(__CLASS__, 'display_generic_content'));
+
+ /* Display grid in between header and footer */
+ self::grid();
+
+ }
+
+
+ public static function display_generic_content() {
+
+ echo self::$plugin_template_generic_content;
+
+ }
+ /* End Plugin Template Handling System */
+
+
+
+ /**
+ * Assembles the classes for the body element.
+ **/
+ public static function body_class($c) {
+
+ global $wp_query, $authordata;
+
+ $c[] = 'custom';
+
+ /* User Agents */
+ if ( !HeadwayCompiler::is_plugin_caching() ) {
+
+ $user_agent = $_SERVER['HTTP_USER_AGENT'];
+
+ /* IE */
+ if ( $ie_version = headway_is_ie() ) {
+
+ $c[] = 'ie';
+ $c[] = 'ie' . $ie_version;
+
+ }
+
+ /* Modern Browsers */
+ if ( stripos($user_agent, 'Safari') !== false )
+ $c[] = 'safari';
+
+ elseif ( stripos($user_agent, 'Firefox') !== false )
+ $c[] = 'firefox';
+
+ elseif ( stripos($user_agent, 'Chrome') !== false )
+ $c[] = 'chrome';
+
+ elseif ( stripos($user_agent, 'Opera') !== false )
+ $c[] = 'opera';
+
+ /* Rendering Engines */
+ if ( stripos($user_agent, 'WebKit') !== false )
+ $c[] = 'webkit';
+
+ elseif ( stripos($user_agent, 'Gecko') !== false )
+ $c[] = 'gecko';
+
+ /* Mobile */
+ if ( stripos($user_agent, 'iPhone') !== false )
+ $c[] = 'iphone';
+
+ elseif ( stripos($user_agent, 'iPod') !== false )
+ $c[] = 'ipod';
+
+ elseif ( stripos($user_agent, 'iPad') !== false )
+ $c[] = 'ipad';
+
+ elseif ( stripos($user_agent, 'Android') !== false )
+ $c[] = 'android';
+
+ }
+ /* End User Agents */
+
+ /* Responsive Grid */
+ if ( HeadwayResponsiveGrid::is_enabled() )
+ $c[] = 'responsive-grid-enabled';
+
+ if ( HeadwayResponsiveGrid::is_active() )
+ $c[] = 'responsive-grid-active';
+
+ /* Pages */
+ if ( is_page() && isset($wp_query->post) && isset($wp_query->post->ID) ) {
+
+ $c[] = 'pageid-' . $wp_query->post->ID;
+ $c[] = 'page-slug-' . $wp_query->post->post_name;
+
+ }
+
+ /* Posts & Pages */
+ if ( is_singular() && isset($wp_query->post) && isset($wp_query->post->ID) ) {
+
+ //Add the custom classes from the meta box
+ if ( $custom_css_class = HeadwayLayoutOption::get($wp_query->post->ID, 'css-class', null, true) ) {
+
+ $custom_css_classes = str_replace(' ', ' ', str_replace(',', ' ', esc_attr(strip_tags($custom_css_class))));
+
+ $c = array_merge($c, array_filter(explode(' ', $custom_css_classes)));
+
+ }
+
+ }
+
+ /* Layout IDs, etc */
+ $c[] = 'layout-' . str_replace(HeadwayLayout::$sep, '-', HeadwayLayout::get_current());
+ $c[] = 'layout-using-' . str_replace( HeadwayLayout::$sep, '-', HeadwayLayout::get_current_in_use());
+
+ if ( HeadwayRoute::is_visual_editor_iframe() )
+ $c[] = 've-iframe';
+
+ if ( headway_get('ve-iframe-mode') && HeadwayRoute::is_visual_editor_iframe() )
+ $c[] = 'visual-editor-mode-' . headway_get('ve-iframe-mode');
+
+ if ( !current_theme_supports('headway-design-editor') )
+ $c[] = 'design-editor-disabled';
+
+ $c = array_unique(array_filter($c));
+
+ return $c;
+
+ }
+
+
+ public static function html_open() {
+
+ echo apply_filters('headway_doctype', '<!DOCTYPE HTML>');
+ echo '<html '; language_attributes(); echo '>' . "\n";
+
+ do_action('headway_html_open');
+
+ echo "\n" . '<head>' . "\n";
+
+ echo '<meta charset="' . get_bloginfo('charset') . '" />' . "\n";
+ echo '<link rel="profile" href="http://gmpg.org/xfn/11" />' . "\n";
+
+ }
+
+
+ public static function html_close() {
+
+ echo "\n\n";
+
+ do_action('headway_html_close');
+
+ echo "\n" . '</html>';
+
+ }
+
+
+ public static function body_open() {
+
+ echo "\n" . '</head><!-- End <head> -->' . "\n\n";
+
+ echo '<body '; body_class(); echo ' itemscope itemtype="http://schema.org/WebPage">' . "\n\n";
+
+ do_action('headway_body_open');
+
+ echo "\n" . '<div id="whitewrap">' . "\n";
+
+ do_action('headway_whitewrap_open');
+
+ do_action('headway_page_start');
+
+ }
+
+
+ public static function body_close() {
+
+ echo "\n\n";
+
+ do_action('headway_whitewrap_close');
+
+ echo '</div><!-- #whitewrap -->' . "\n";
+
+ do_action('headway_body_close');
+
+ echo "\n" . '</body>';
+
+ }
+
+
+}
\ No newline at end of file
--- /dev/null
+<?php
+
+class HeadwayGridRenderer {
+ private $wrapper;
+ public $blocks = array();
+ private $layout = array();
+ private $rows = array();
+ private $columns = array();
+ private $column_positions = array();
+ private $section_classes = array();
+ private $column_top_tolerance = 30;
+ private $row_top_tolerance = 20;
+
+ public function __construct( $blocks, $wrapper ) {
+ $this->blocks = $blocks;
+ $this->wrapper = $wrapper;
+ }
+
+ private function step_1_sort_blocks_by_position() {
+ uasort( $this->blocks, array( __CLASS__, 'uasort_blocks_by_top_to_left' ) );
+ }
+
+ private function uasort_blocks_by_top_to_left( $a, $b ) {
+ if ( is_array( $a ) && is_string( reset( $a ) ) )
+ $a = reset( $a );
+ if ( is_array( $b ) && is_string( reset( $b ) ) )
+ $b = reset( $b );
+ if ( is_string( $a ) )
+ $a = $this->blocks[ $a ];
+ if ( is_string( $b ) )
+ $b = $this->blocks[ $b ];
+ $a_top = $a['position']['top'];
+ $a_left = $a['position']['left'];
+ $b_top = $b['position']['top'];
+ $b_left = $b['position']['left'];
+ if ( $a_top === $b_top && $a_left === $b_left )
+ return 0;
+ if ( $a_top === $b_top )
+ return ( $a_left < $b_left ) ? - 1 : 1;
+
+ return ( $a_top < $b_top ) ? - 1 : 1;
+ }
+
+ private function step_2_build_rows() {
+ $prev_block = null;
+ $row_count = 0;
+ foreach ( $this->blocks as $block_id => $block ) {
+ $range_beginning = is_array( $prev_block ) ? $prev_block['position']['top'] - $this->row_top_tolerance : null;
+ $range_end = is_array( $prev_block ) ? $prev_block['position']['top'] + $this->row_top_tolerance : null;
+ if ( $range_beginning && headway_in_numeric_range( $block['position']['top'], $range_beginning, $range_end ) ) {
+ $this->rows[ $row_count ][] = $block['id'];
+ } else {
+ $row_count ++;
+ $this->rows[ $row_count ] = array( $block['id'] );
+ }
+ $prev_block = $block;
+ }
+ }
+
+ private function step_3_construct_columns() {
+ $column_id = 0;
+ foreach ( $this->blocks as $block_id => $block ) {
+ if ( isset( $this->blocks_in_sub_columns ) && in_array( $block['id'], $this->blocks_in_sub_columns ) )
+ continue;
+ $column_id ++;
+ $this->columns[ $column_id ] = array( $block_id );
+ $sub_column_blocks = $this->step_3a_extract_sub_columns( $block['id'] );
+ if ( ! is_array( $sub_column_blocks ) )
+ continue;
+ $sub_column_row_id = 1;
+ $prev_sub_column_offset = 0;
+ $existing_sub_columns = array();
+ foreach ( $sub_column_blocks as $sub_column_block_id ) {
+ $sub_column_block = $this->blocks[ $sub_column_block_id ];
+ $sub_column = $sub_column_block['dimensions']['width'] == $block['dimensions']['width'] ? false : true;
+ $this->step_3b_remove_block_from_columns( $sub_column_block_id );
+ if ( isset( $prev_sub_column_top ) && $prev_sub_column_top + $prev_sub_column_height < $block['position']['top'] )
+ if ( $sub_column_block['position']['top'] > $block['position']['top'] + $block['dimensions']['height'] )
+ $sub_column_row_id ++;
+ $sub_column_original = 'sub-column-' . $sub_column_block['dimensions']['width'] . ':' . $sub_column_block['position']['left'];
+ $sub_column_id = $sub_column_original . '-' . $sub_column_row_id;
+ $origin_width = (int) $block['dimensions']['width'];
+ $origin_left = (int) $block['position']['left'];
+ if ( $prev_sub_column_offset + $sub_column_block['dimensions']['width'] - $origin_left > $origin_width ) {
+ $prev_sub_column_offset = 0;
+ if ( ! in_array( $sub_column_original, $existing_sub_columns ) )
+ $sub_column_row_id ++;
+ }
+ if ( $sub_column ) {
+ $existing_sub_columns[] = $sub_column_original;
+ if ( ! isset( $this->columns[ $column_id ][ $sub_column_id ] ) )
+ $this->columns[ $column_id ][ $sub_column_id ] = array();
+ $this->columns[ $column_id ][ $sub_column_id ][] = $sub_column_block_id;
+ } else {
+ $this->columns[ $column_id ][] = $sub_column_block_id;
+ }
+ $prev_sub_column_offset = (int) $sub_column_block['dimensions']['width'] + (int) $sub_column_block['position']['left'];
+ $prev_sub_column_top = (int) $sub_column_block['position']['top'];
+ $prev_sub_column_height = (int) $sub_column_block['dimensions']['height'];
+ }
+ $sub_columns = false;
+ foreach ( $this->columns[ $column_id ] as $block_or_sub_column )
+ if ( is_array( $block_or_sub_column ) )
+ $sub_columns = true;
+ if ( $sub_columns ) {
+ $this->step_3c_modify_rows_for_sub_column_above_origin( $block, $this->blocks[ reset( $sub_column_blocks ) ], $sub_column_blocks );
+ } elseif ( ! $sub_columns && isset( $this->blocks_in_sub_columns ) ) {
+ foreach ( $this->columns[ $column_id ] as $block_or_sub_column )
+ headway_remove_from_array( $this->blocks_in_sub_columns, $block_or_sub_column );
+ foreach ( $this->columns as $test_column_id => $blocks_or_sub_columns ) {
+ if ( $column_id == $test_column_id )
+ continue;
+ foreach ( $blocks_or_sub_columns as $index => $block_id_or_sub_column ) {
+ if ( $block_id_or_sub_column == $block['id'] )
+ unset( $this->columns[ $test_column_id ][ $index ] );
+ if ( count( $this->columns[ $test_column_id ] ) === 0 )
+ unset( $this->columns[ $test_column_id ] );
+ }
+ }
+ }
+ uasort( $this->columns[ $column_id ], array( __CLASS__, 'uasort_blocks_by_top_to_left' ) );
+ if ( isset( $this->columns[ $column_id ] ) )
+ $this->columns[ $column_id ] = array_values( $this->columns[ $column_id ] );
+ }
+ $this->columns = array_values( $this->columns );
+ }
+
+ private function step_3a_extract_sub_columns( $origin_block_id ) {
+ if ( isset( $this->blocks_in_sub_columns ) && in_array( $origin_block_id, $this->blocks_in_sub_columns ) )
+ return false;
+ $matches = array();
+ $origin = $this->blocks[ $origin_block_id ];
+ foreach ( $this->blocks as $check ) {
+ if ( $origin['id'] == $check['id'] )
+ continue;
+ if ( isset( $this->blocks_in_sub_columns ) && in_array( $check['id'], $this->blocks_in_sub_columns ) )
+ continue;
+ if ( $check['position']['left'] > $origin['position']['left'] + $origin['dimensions']['width'] )
+ continue;
+ if ( $check['position']['left'] < $origin['position']['left'] )
+ continue;
+ if ( $check['position']['left'] + $check['dimensions']['width'] > $origin['position']['left'] + $origin['dimensions']['width'] )
+ continue;
+ $matches[] = $check['id'];
+ }
+ if ( count( $matches ) === 0 )
+ return null;
+ $bad_matches = array();
+ $match_row_ids = array();
+ foreach ( $matches as $match_id )
+ $match_row_ids[ $match_id ] = $this->get_block_row( $match_id );
+ foreach ( $match_row_ids as $match_block_id => $match_row_id ) {
+ reset( $this->rows[ $match_row_id ] );
+ while ( $current_match = current( $this->rows[ $match_row_id ] ) ) {
+ if ( $current_match == $match_block_id ) {
+ $neighbors = headway_array_key_neighbors( $this->rows[ $match_row_id ], key( $this->rows[ $match_row_id ] ) );
+ $left_block = ( is_string( $neighbors['prev'] ) && isset( $this->blocks[ $neighbors['prev'] ] ) ) ? $this->blocks[ $neighbors['prev'] ] : null;
+ $right_block = ( is_string( $neighbors['next'] ) && isset( $this->blocks[ $neighbors['next'] ] ) ) ? $this->blocks[ $neighbors['next'] ] : null;
+ $origin_block_left = $origin['position']['left'];
+ $origin_block_width = $origin['dimensions']['width'];
+ if ( $left_block ) {
+ $left_block_left = $left_block['position']['left'];
+ $left_block_width = $left_block['dimensions']['width'];
+ }
+ if ( $right_block ) {
+ $right_block_left = $right_block['position']['left'];
+ $right_block_width = $right_block['dimensions']['width'];
+ }
+ if ( $left_block && $left_block_left + $left_block_width > $origin_block_left && $left_block_left < $origin_block_left )
+ $bad_matches[ $match_block_id ] = 'left-block-outside-origin';
+ if ( $right_block && $right_block_left < $origin_block_left + $origin_block_width )
+ if ( $right_block_left + $right_block_width > $origin_block_left + $origin_block_width )
+ $bad_matches[ $match_block_id ] = 'right-block-outside-origin';
+ if ( isset( $bad_matches[ $match_block_id ] ) )
+ headway_remove_from_array( $matches, $match_block_id );
+ break;
+ }
+ next( $this->rows[ $match_row_id ] );
+ }
+ }
+ $bad_matches = array();
+ $prev_row_block_id = $origin['id'];
+ foreach ( $matches as $match_id ) {
+ $match_block = $this->blocks[ $match_id ];
+ $prev_row_block = $this->blocks[ $prev_row_block_id ];
+ $is_first_match = $match_id == reset( $matches );
+ if ( $match_block['position']['top'] < $origin['position']['top'] )
+ continue;
+ if ( ! ( $prev_row_block['position']['top'] === $match_block['position']['top'] ) || $is_first_match ) {
+ if ( $match_block['position']['top'] <= $prev_row_block['dimensions']['height'] + $prev_row_block['position']['top'] )
+ $bad_matches[ $match_id ] = 'not below previous';
+ if ( $match_block['position']['top'] > $prev_row_block['dimensions']['height'] + $prev_row_block['position']['top'] + $this->column_top_tolerance )
+ $bad_matches[ $match_id ] = 'below previous block and tolerance';
+ }
+ if ( isset( $bad_matches[ $match_id ] ) )
+ headway_remove_from_array( $matches, $match_id ); elseif ( $match_block['position']['top'] > $prev_row_block['position']['top'] )
+ $prev_row_block_id = $match_id;
+ }
+ $reversed_matches = array_reverse( $matches );
+ $prev_row_block_id = $origin['id'];
+ foreach ( $reversed_matches as $match_id ) {
+ $match_block = $this->blocks[ $match_id ];
+ $prev_row_block = $this->blocks[ $prev_row_block_id ];
+ $is_first_match = $match_id == reset( $reversed_matches );
+ if ( $match_block['position']['top'] > $origin['position']['top'] )
+ continue;
+ if ( ! ( $prev_row_block['position']['top'] === $match_block['position']['top'] ) || $is_first_match ) {
+ if ( $match_block['position']['top'] + $match_block['dimensions']['height'] > $prev_row_block['position']['top'] )
+ $bad_matches[ $match_id ] = 'not above previous';
+ if ( $match_block['position']['top'] + $match_block['dimensions']['height'] < $prev_row_block['position']['top'] - $this->column_top_tolerance )
+ $bad_matches[ $match_id ] = 'above previous block and tolerance';
+ }
+ if ( isset( $bad_matches[ $match_id ] ) )
+ headway_remove_from_array( $matches, $match_id ); elseif ( $match_block['position']['top'] < $prev_row_block['position']['top'] )
+ $prev_row_block_id = $match_id;
+ }
+ if ( count( $matches ) === 0 )
+ return null;
+ $check_1 = false;
+ $check_2 = false;
+ foreach ( $this->blocks as $block ) {
+ if ( in_array( $block['id'], $matches ) || $block['id'] == $origin_block_id )
+ continue;
+ $check_left = $block['position']['left'];
+ $check_top = $block['position']['top'];
+ $check_width = $block['dimensions']['width'];
+ $check_height = $block['dimensions']['height'];
+ $origin_width = $origin['dimensions']['width'];
+ $origin_left = $origin['position']['left'];
+ $origin_height = $origin['dimensions']['height'];
+ $origin_top = $origin['position']['top'];
+ $top_block_top = $this->blocks[ reset( $matches ) ]['position']['top'];
+ $top_block_height = $this->blocks[ reset( $matches ) ]['dimensions']['height'];
+ $height_check_block = ( $top_block_top < $origin_top ) ? $top_block_height : $origin_height;
+ $top_check_block = ( $top_block_top < $origin_top ) ? $top_block_top : $origin_top;
+ if ( $check_left < $origin_left || $check_left >= $origin_left + $origin_width )
+ $check_1 = true;
+ if ( $check_top >= $top_check_block && $check_top < $top_check_block + $height_check_block )
+ $check_2 = true;
+ }
+ if ( ! ( $check_1 && $check_2 ) )
+ return false;
+ $this->blocks_in_sub_columns = isset( $this->blocks_in_sub_columns ) ? array_merge( $this->blocks_in_sub_columns, $matches ) : $matches;
+
+ return count( $matches ) > 0 ? $matches : null;
+ }
+
+ private function step_3b_remove_block_from_columns( $block_id_to_remove ) {
+ foreach ( $this->columns as $column_id => $column_blocks ) {
+ if ( in_array( $block_id_to_remove, $column_blocks ) ) {
+ headway_remove_from_array( $this->columns[ $column_id ], $block_id_to_remove );
+ if ( empty( $this->columns[ $column_id ] ) )
+ unset( $this->columns[ $column_id ] );
+
+ return true;
+ }
+ }
+
+ return false;
+ }
+
+ private function step_3c_modify_rows_for_sub_column_above_origin( $origin_block, $first_block, array $sub_column_blocks ) {
+ if ( $origin_block['position']['top'] < $first_block['position']['top'] )
+ return false;
+ foreach ( $this->rows as $row_id => $row_blocks ) {
+ foreach ( $row_blocks as $row_block_id ) {
+ if ( $row_block_id === $origin_block['id'] )
+ $origin_block_row_id = $row_id; elseif ( $row_block_id === $first_block['id'] )
+ $first_block_row_id = $row_id;
+ }
+ }
+ $sub_column_blocks_above_origin = array();
+ foreach ( $sub_column_blocks as $sub_column_block_id ) {
+ $test_block = $this->blocks[ $sub_column_block_id ];
+ if ( $test_block['position']['top'] + $test_block['dimensions']['height'] >= $origin_block['position']['top'] )
+ continue;
+ $sub_column_blocks_above_origin[] = $sub_column_block_id;
+ }
+ $first_block_position_in_row = array_search( $first_block['id'], $this->rows[ $first_block_row_id ] );
+ headway_array_insert( $this->rows[ $first_block_row_id ], array( $origin_block['id'] ), $first_block_position_in_row );
+ foreach ( $sub_column_blocks_above_origin as $block_id )
+ $this->step_3d_remove_block_from_rows( $block_id );
+ headway_remove_from_array( $this->rows[ $origin_block_row_id ], $origin_block['id'] );
+ if ( count( $this->rows[ $first_block_row_id ] ) === 0 )
+ unset( $this->rows[ $first_block_row_id ] );
+ if ( count( $this->rows[ $origin_block_row_id ] ) === 0 )
+ unset( $this->rows[ $origin_block_row_id ] );
+ }
+
+ private function step_3d_remove_block_from_rows( $block_id_to_remove ) {
+ foreach ( $this->rows as $row_id => $row_blocks ) {
+ if ( in_array( $block_id_to_remove, $row_blocks ) ) {
+ headway_remove_from_array( $this->rows[ $row_id ], $block_id_to_remove );
+ if ( empty( $this->rows[ $row_id ] ) )
+ unset( $this->rows[ $row_id ] );
+
+ return true;
+ }
+ }
+
+ return false;
+ }
+
+ private function step_4_fetch_column_row_positions() {
+ foreach ( $this->columns as $column => $blocks ) {
+ foreach ( $blocks as $block_id ) {
+ foreach ( $this->rows as $row => $blocks ) {
+ if ( in_array( $block_id, $blocks ) ) {
+ $this->column_positions[ $column ] = $row;
+ break;
+ }
+ }
+ if ( isset( $this->column_positions[ $column ] ) )
+ break;
+ }
+ }
+ }
+
+ private function step_5_add_columns_to_rows() {
+ foreach ( $this->column_positions as $column => $row ) {
+ if ( ! isset( $this->columns[ $column ] ) )
+ continue;
+ $this->layout[ $row ][ $column ] = $this->columns[ $column ];
+ }
+ foreach ( $this->layout as $row => $row_columns )
+ uasort( $this->layout[ $row ], array( __CLASS__, 'uasort_columns_by_left' ) );
+ ksort( $this->layout, SORT_NUMERIC );
+ }
+
+ private function uasort_columns_by_left( $a, $b ) {
+ foreach ( $a as $block_or_sub_column_a )
+ if ( is_string( $block_or_sub_column_a ) && $a = $block_or_sub_column_a )
+ break;
+ foreach ( $b as $block_or_sub_column_b )
+ if ( is_string( $block_or_sub_column_b ) && $b = $block_or_sub_column_b )
+ break;
+ $a = $this->blocks[ $a ];
+ $b = $this->blocks[ $b ];
+ $a_left = $a['position']['left'];
+ $b_left = $b['position']['left'];
+ if ( $a_left === $b_left )
+ return 0;
+
+ return ( $a_left < $b_left ) ? - 1 : 1;
+ }
+
+ private function step_6_add_section_classes() {
+ $row_count = 1;
+ foreach ( $this->layout as $row_index => $columns ) {
+ $this->section_classes[ $row_index ] = array();
+ $this->section_classes[ $row_index ]['classes'][] = 'row';
+ $this->section_classes[ $row_index ]['classes'][] = 'row-' . $row_count;
+ $row_count ++;
+ $previous_column_offset = 0;
+ $column_count = 1;
+ foreach ( $columns as $column_index => $column_contents ) {
+ $this->section_classes[ $row_index ][ $column_index ] = array();
+ foreach ( $column_contents as $block_index_or_sub_index => $block_id_or_sub_contents ) {
+ if ( is_string( $block_id_or_sub_contents ) && isset( $this->blocks[ $block_id_or_sub_contents ] ) ) {
+ $first_block_in_column = $this->blocks[ $block_id_or_sub_contents ];
+ break;
+ } else continue;
+ }
+ $this->section_classes[ $row_index ][ $column_index ]['classes'][] = 'column';
+ $this->section_classes[ $row_index ][ $column_index ]['classes'][] = 'column-' . $column_count;
+ $this->section_classes[ $row_index ][ $column_index ]['classes'][] = 'grid-left-' . ( (int) $first_block_in_column['position']['left'] - (int) $previous_column_offset );
+ $this->section_classes[ $row_index ][ $column_index ]['classes'][] = 'grid-width-' . ( (int) $first_block_in_column['dimensions']['width'] );
+ $this->section_classes[ $row_index ][ $column_index ]['width'] = ( (int) $first_block_in_column['dimensions']['width'] );
+ $this->section_classes[ $row_index ][ $column_index ]['absolute-left'] = (int) $first_block_in_column['position']['left'];
+ $previous_column_offset = (int) $first_block_in_column['dimensions']['width'] + (int) $first_block_in_column['position']['left'];
+ $column_count ++;
+ $sub_column_count = 1;
+ $prev_sub_column_offset = 0;
+ $this->section_classes[ $row_index ][ $column_index ]['sub-columns'] = array();
+ foreach ( $column_contents as $sub_index => $sub_contents ) {
+ if ( is_string( $sub_contents ) )
+ continue;
+ $sub_column_block = $this->blocks[ reset( $sub_contents ) ];
+ $main_column_absolute_left = $this->section_classes[ $row_index ][ $column_index ]['absolute-left'];
+ $main_column_width = $this->section_classes[ $row_index ][ $column_index ]['width'];
+ if ( $prev_sub_column_offset + (int) $sub_column_block['dimensions']['width'] - $main_column_absolute_left > $main_column_width ) {
+ $sub_column_count = 1;
+ $prev_sub_column_offset = 0;
+ }
+ $main_column_left_offset = $sub_column_count === 1 ? $main_column_absolute_left : 0;
+ $this->section_classes[ $row_index ][ $column_index ]['sub-columns'][ $sub_index ]['classes'] = array(
+ 'sub-column',
+ 'sub-column-' . $sub_column_count,
+ 'column',
+ 'column-' . $sub_column_count,
+ 'grid-width-' . $sub_column_block['dimensions']['width'],
+ 'grid-left-' . ( $sub_column_block['position']['left'] - $prev_sub_column_offset - $main_column_left_offset )
+ );
+ $prev_sub_column_offset = (int) $sub_column_block['dimensions']['width'] + (int) $sub_column_block['position']['left'];
+ $sub_column_count ++;
+ }
+ if ( count( $this->section_classes[ $row_index ][ $column_index ]['sub-columns'] ) === 0 )
+ unset( $this->section_classes[ $row_index ][ $column_index ]['sub-columns'] );
+ }
+ }
+ }
+
+ private function get_block_row( $block_id ) {
+ foreach ( $this->rows as $row_id => $row_blocks )
+ foreach ( $row_blocks as $row_block_id )
+ if ( $row_block_id == $block_id )
+ return $row_id;
+
+ return null;
+ }
+
+ private function step_7_finalize() {
+ $this->finalized_layout = array();
+ foreach ( $this->layout as $row_index => $row_columns ) {
+ $this->finalized_layout[ $row_index ] = array(
+ 'type' => 'row',
+ 'classes' => $this->section_classes[ $row_index ]['classes'],
+ 'columns' => array()
+ );
+ $current_row =& $this->finalized_layout[ $row_index ];
+ foreach ( $row_columns as $column_index => $column_content ) {
+ $current_row['columns'][ $column_index ] = array(
+ 'type' => 'column',
+ 'width' => $this->section_classes[ $row_index ][ $column_index ]['width'],
+ 'classes' => $this->section_classes[ $row_index ][ $column_index ]['classes'],
+ 'contents' => array()
+ );
+ $current_column =& $current_row['columns'][ $column_index ];
+ foreach ( $column_content as $block_or_sub_index => $block_id_or_sub_content ) {
+ if ( ! is_array( $block_id_or_sub_content ) ) {
+ $block = $this->blocks[ $block_id_or_sub_content ];
+ $current_column['contents'][ $block_or_sub_index ] = array(
+ 'type' => 'block',
+ 'block' => $block
+ );
+ $block_settings = headway_get( 'settings', $block );
+ if ( headway_get( 'css-classes-bubble', $block_settings, false, true ) === true && headway_get( 'css-classes', $block_settings ) ) {
+ $current_row['classes'] = array_merge( $current_row['classes'], explode( ' ', headway_get( 'css-classes', $block_settings ) ) );
+ $current_column['classes'] = array_merge( $current_column['classes'], explode( ' ', headway_get( 'css-classes', $block_settings ) ) );
+ }
+ } else {
+ $current_column['contents'][ $block_or_sub_index ] = array(
+ 'type' => 'sub-column',
+ 'classes' => $this->section_classes[ $row_index ][ $column_index ]['sub-columns'][ $block_or_sub_index ]['classes'],
+ 'blocks' => array()
+ );
+ $current_sub_column =& $current_column['contents'][ $block_or_sub_index ];
+ foreach ( $block_id_or_sub_content as $sub_block_id ) {
+ $this->blocks[ $sub_block_id ]['parent-column-width'] = $current_column['width'];
+ $current_sub_column['blocks'][] = $this->blocks[ $sub_block_id ];
+ $block_settings = headway_get( 'settings', $this->blocks[ $sub_block_id ] );
+ if ( headway_get( 'css-classes-bubble', $block_settings, false, true ) === true && headway_get( 'css-classes', $block_settings ) ) {
+ $current_row['classes'] = array_merge( $current_row['classes'], explode( ' ', headway_get( 'css-classes', $block_settings ) ) );
+ $current_column['classes'] = array_merge( $current_column['classes'], explode( ' ', headway_get( 'css-classes', $block_settings ) ) );
+ $current_sub_column['classes'] = array_merge( $current_sub_column['classes'], explode( ' ', headway_get( 'css-classes', $block_settings ) ) );
+ }
+ }
+ }
+ }
+ }
+ }
+
+ return $this->finalized_layout;
+ }
+
+ public function process() {
+ $this->step_1_sort_blocks_by_position();
+ $this->step_2_build_rows();
+ $this->step_3_construct_columns();
+ $this->step_4_fetch_column_row_positions();
+ $this->step_5_add_columns_to_rows();
+ $this->step_6_add_section_classes();
+ $this->step_7_finalize();
+ }
+
+ public function render_grid() {
+ $this->process();
+ echo '<div class="grid-container clearfix">' . "\n";
+ do_action( 'headway_grid_container_open', $this->wrapper );
+ foreach ( $this->finalized_layout as $row_index => $row ) {
+ echo "\n" . '<section class="' . implode( ' ', array_unique( array_filter( $row['classes'] ) ) ) . '">' . "\n";
+ do_action( 'headway_block_row_open', $this->wrapper );
+ foreach ( $row['columns'] as $column_index => $column ) {
+ echo "\n" . '<section class="' . implode( ' ', array_unique( array_filter( $column['classes'] ) ) ) . '">' . "\n";
+ do_action( 'headway_block_column_open', $this->wrapper );
+ foreach ( $column['contents'] as $index => $block_or_sub_column ) {
+ if ( headway_get( 'type', $block_or_sub_column ) == 'block' ) {
+ HeadwayBlocks::display_block( headway_get( 'block', $block_or_sub_column ), 'grid-renderer' );
+ } elseif ( headway_get( 'type', $block_or_sub_column ) == 'sub-column' ) {
+ echo "\n" . '<section class="' . implode( ' ', array_unique( array_filter( $block_or_sub_column['classes'] ) ) ) . '">' . "\n";
+ do_action( 'headway_block_sub_column_open', $this->wrapper );
+ foreach ( $block_or_sub_column['blocks'] as $sub_block )
+ HeadwayBlocks::display_block( $sub_block, 'grid-renderer' );
+ do_action( 'headway_block_sub_column_column', $this->wrapper );
+ echo "\n" . '</section><!-- .sub-column -->' . "\n";
+ }
+ }
+ do_action( 'headway_block_column_close', $this->wrapper );
+ echo "\n" . '</section><!-- .column -->' . "\n";
+ }
+ do_action( 'headway_block_row_close', $this->wrapper );
+ echo "\n" . '</section><!-- .row -->' . "\n\n";
+ }
+ do_action( 'headway_grid_container_close', $this->wrapper );
+ echo "\n" . '</div><!-- .grid-container -->' . "\n\n";
+ }
+}
\ No newline at end of file
--- /dev/null
+<?php
+class HeadwayHead {
+
+ /**
+ * Set up hooks for <head>
+ **/
+ public static function init() {
+
+ if ( !HeadwayRoute::is_display() )
+ return false;
+
+ add_filter('wp_title', array('HeadwaySEO', 'output_title'), 9);
+
+ //Remove actions
+ remove_action('wp_head', 'wp_print_styles', 8);
+ remove_action('wp_head', 'wp_print_head_scripts', 9);
+ remove_action('wp_head', 'rel_canonical');
+ remove_action('wp_head', 'feed_links', 2);
+ remove_action('wp_head', 'feed_links_extra', 3);
+
+ //Set Up Actions
+ add_action('wp_head', array(__CLASS__, 'print_title'), 1);
+
+ add_action('wp_enqueue_scripts', array(__CLASS__, 'register_files'), 1);
+ add_action('wp_enqueue_scripts', array(__CLASS__, 'enqueue_scripts'), 1);
+
+ add_action('wp_head', array('HeadwaySEO', 'output_meta'), 2);
+ add_action('wp_head', array(__CLASS__, 'print_stylesheets'), 7);
+ add_action('wp_head', array(__CLASS__, 'print_scripts'), 8);
+ add_action('wp_head', array(__CLASS__, 'extras'), 9);
+
+ add_action('headway_stylesheets', 'wp_print_styles');
+ add_action('headway_stylesheets', array(__CLASS__, 'child_theme_stylesheet'), 11);
+ add_action('headway_stylesheets', array(__CLASS__, 'visual_editor_live_css'), 12);
+
+ add_action('headway_scripts', 'wp_print_head_scripts');
+ add_action('headway_scripts', array(__CLASS__, 'add_standards_compliance_js'));
+ add_action('headway_scripts', array(__CLASS__, 'header_scripts'));
+
+ add_action('headway_seo_meta', 'rel_canonical');
+
+ add_action('headway_head_extras', 'feed_links');
+ add_action('headway_head_extras', 'feed_links_extra');
+
+ add_action('headway_body_close', array(__CLASS__, 'footer_scripts'), 15);
+
+ add_action('wp_head', array(__CLASS__, 'favicon'), 9);
+
+ add_filter('style_loader_src', array(__CLASS__, 'remove_dependency_query_vars'));
+ add_filter('script_loader_src', array(__CLASS__, 'remove_dependency_query_vars'));
+
+ }
+
+
+ public static function print_title() {
+
+ echo "\n<!-- Title -->\n<title>" . wp_title(false, false) . '</title>';
+
+ }
+
+
+ /**
+ * All general CSS and JS used across the site will be registered and/or enqueued here.
+ *
+ * @return void
+ **/
+ public static function register_files() {
+
+ self::register_general_css();
+
+ self::register_layout_css();
+
+ self::register_responsive_css();
+
+ self::register_visual_editor_css();
+
+ }
+
+
+ public static function register_general_css() {
+
+ $general_css_fragments = array();
+
+ /* Basic CSS */
+ if ( current_theme_supports('headway-reset-css') )
+ $general_css_fragments['reset.css'] = HEADWAY_LIBRARY_DIR . '/media/css/reset.css';
+
+ if ( current_theme_supports('headway-grid') )
+ $general_css_fragments['grid.css'] = HEADWAY_LIBRARY_DIR . '/media/css/grid.css';
+
+ if ( current_theme_supports('headway-block-basics-css') )
+ $general_css_fragments['block-basics.css'] = HEADWAY_LIBRARY_DIR . '/media/css/block-basics.css';
+
+ if ( current_theme_supports('headway-content-styling-css') ) {
+
+ $general_css_fragments['content-styling.css'] = HEADWAY_LIBRARY_DIR . '/media/css/content-styling.css';
+ $general_css_fragments['alerts.css'] = HEADWAY_LIBRARY_DIR . '/media/css/alerts.css';
+
+ }
+
+ /* Block heights */
+ $general_css_fragments['dynamic-block-heights'] = array('HeadwayDynamicStyle', 'block_heights');
+
+ /* Design Editor CSS */
+ if ( current_theme_supports('headway-design-editor') )
+ $general_css_fragments['dynamic-design-editor'] = array('HeadwayDynamicStyle', 'design_editor');
+
+ /* Allow filters to be applied to the general CSS fragments/dependencies before the count is made */
+ $general_css_fragments = apply_filters('headway_general_css', $general_css_fragments);
+
+ /* Live CSS */
+ if ( current_theme_supports('headway-live-css') && HeadwaySkinOption::get('live-css') )
+ $general_css_fragments['dynamic-live-css'] = array('HeadwayDynamicStyle', 'live_css');
+
+ /* Have a separate filter after Live CSS is applied that way injecting into the 'headway_general_css' filter will insert stuff before Live CSS */
+ $general_css_fragments = apply_filters('headway_general_css_live_css_applied', $general_css_fragments);
+
+ $general_css_dependencies = array_unique(apply_filters('headway_general_css_dependencies', array(
+ HEADWAY_LIBRARY_DIR . '/media/dynamic/style.php'
+ )));
+
+ /* Handle regular requests. */
+ if ( !HeadwayRoute::is_visual_editor_iframe('design') || !current_theme_supports('headway-design-editor') ) {
+
+ HeadwayCompiler::register_file(array(
+ 'name' => 'general',
+ 'format' => 'css',
+ 'fragments' => $general_css_fragments,
+ 'dependencies' => $general_css_dependencies
+ ));
+
+ /* Handle design editor requests by stripping out the design editor fragment and separating it for better skin importing */
+ } else {
+
+ $general_fragments_excluding_design_editor = $general_css_fragments;
+ unset($general_fragments_excluding_design_editor['dynamic-design-editor']);
+ unset($general_fragments_excluding_design_editor['dynamic-live-css']);
+
+ HeadwayCompiler::register_file(array(
+ 'name' => 'general-excluding-design-editor',
+ 'format' => 'css',
+ 'iframe-cache' => true,
+ 'fragments' => $general_fragments_excluding_design_editor,
+ 'dependencies' => $general_css_dependencies
+ ));
+
+ HeadwayCompiler::register_file(array(
+ 'name' => 'general-design-editor',
+ 'format' => 'css',
+ 'fragments' => array(
+ array('HeadwayDynamicStyle', 'design_editor')
+ ),
+ 'dependencies' => $general_css_dependencies
+ ));
+
+ }
+
+
+ }
+
+
+ public static function register_layout_css() {
+
+ $current_layout_in_use = HeadwayLayout::get_current_in_use();
+ $css_name = str_replace(HeadwayLayout::$sep, '-', 'layout-' . HeadwayLayout::get_current_in_use());
+
+ $fragments = array();
+
+ /* If the grid is supported, then include the wrapper, grid, and block heights */
+ if ( current_theme_supports('headway-grid') ) {
+
+ $fragments['dynamic-wrapper'] = array('HeadwayDynamicStyle', 'wrapper');
+
+ }
+
+ /* Include dynamic CSS from blocks such as navigation block or any block that has per-block CSS */
+ $fragments['dynamic-block-css'] = array('HeadwayBlocks', 'output_block_dynamic_css');
+
+ return HeadwayCompiler::register_file(array(
+ 'name' => $css_name,
+ 'format' => 'css',
+ 'fragments' => $fragments,
+ 'dependencies' => array(
+ HEADWAY_LIBRARY_DIR . '/media/dynamic/style.php'
+ )
+ ));
+
+ }
+
+
+ public static function register_responsive_css() {
+
+ if ( !HeadwayResponsiveGrid::is_enabled() )
+ return;
+
+ /* CSS */
+ HeadwayCompiler::register_file(array(
+ 'name' => 'responsive-grid',
+ 'format' => 'css',
+ 'fragments' => array(
+ array('HeadwayResponsiveGridDynamicMedia', 'content')
+ ),
+ 'dependencies' => array(
+ HEADWAY_LIBRARY_DIR . '/media/dynamic/responsive-grid.php'
+ )
+ ));
+
+ /* JS */
+ if ( HeadwayResponsiveGrid::is_active() && apply_filters('headway_responsive_fitvids', HeadwayOption::get('responsive-video-resizing', false, true)) ) {
+
+ wp_enqueue_script('fitvids', headway_url() . '/library/media/js/jquery.fitvids.js', array('jquery'));
+
+ HeadwayCompiler::register_file(array(
+ 'name' => 'responsive-grid-js',
+ 'format' => 'js',
+ 'fragments' => array(
+ array('HeadwayResponsiveGridDynamicMedia', 'fitvids')
+ ),
+ 'dependencies' => array(
+ HEADWAY_LIBRARY_DIR . '/media/dynamic/responsive-grid.php'
+ )
+ ));
+
+ }
+
+ }
+
+
+ public static function register_visual_editor_css() {
+
+ if ( !HeadwayRoute::is_visual_editor_iframe() )
+ return;
+
+ HeadwayCompiler::register_file(array(
+ 'name' => 've-iframe',
+ 'format' => 'less',
+ 'fragments' => array(
+ HEADWAY_LIBRARY_DIR . '/visual-editor/css/editor-loading.css',
+ HEADWAY_LIBRARY_DIR . '/visual-editor/css/editor-mixins.less',
+ HEADWAY_LIBRARY_DIR . '/visual-editor/css/editor-iframe.less',
+ HEADWAY_LIBRARY_DIR . '/visual-editor/css/editor-tooltips.less'
+ ),
+ 'require-hard-flush' => true,
+ 'iframe-cache' => true
+ ));
+
+ }
+
+
+ /**
+ * Add extra junk into <head>.
+ **/
+ public static function extras() {
+ ?>
+
+<!-- Extras -->
+<link rel="alternate" type="application/rss+xml" href="<?php echo get_bloginfo('rss2_url'); ?>" title="<?php echo get_bloginfo('name')?>" />
+<link rel="pingback" href="<?php bloginfo('pingback_url') ?>" />
+ <?php
+ do_action('headway_head_extras');
+ }
+
+
+ /**
+ * Enqueues the Headway JS for blocks.
+ *
+ * @uses wp_enqueue_script()
+ **/
+ public static function enqueue_scripts() {
+
+ if (
+ is_singular()
+ && comments_open(get_the_id())
+ && !(get_post_type() == 'page' && !HeadwayOption::get('allow-page-comments'))
+ )
+ wp_enqueue_script('comment-reply');
+
+ }
+
+
+ public static function print_scripts() {
+ echo "\n<!-- Scripts -->\n";
+
+ do_action('headway_scripts');
+ }
+
+
+ public static function add_standards_compliance_js() {
+
+ $standards_compliance_js = apply_filters('headway_standards_compliance_js', '
+<!--[if lt IE 9]>
+<script src="' . headway_url() . '/library/media/js/html5shiv.js"></script>
+<![endif]-->
+
+<!--[if lt IE 8]>
+<script src="' . headway_url() . '/library/media/js/ie8.js"></script>
+<![endif]-->
+');
+
+ echo $standards_compliance_js;
+
+ }
+
+
+ /**
+ * Adds all of the links for the Headway stylesheets.
+ **/
+ public static function print_stylesheets() {
+
+ echo "\n\n" . '<!-- Stylesheets -->' . "\n";
+
+ do_action('headway_stylesheets');
+
+ echo "\n";
+
+ }
+
+
+ public static function child_theme_stylesheet() {
+
+ /* If no child theme is active, then we won't use the style.css file. */
+ if ( HEADWAY_CHILD_THEME_ACTIVE === false )
+ return false;
+
+ echo '<link rel="stylesheet" type="text/css" media="all" href="' . get_stylesheet_uri() . '" />';
+
+
+ }
+
+
+ public static function visual_editor_live_css() {
+
+ if ( HeadwayRoute::is_visual_editor_iframe() )
+ echo '<style id="live-css-holder">' . HeadwaySkinOption::get('live-css') . '</style>';
+
+ }
+
+
+ /**
+ * Adds the link to the favicon to the <head>.
+ **/
+ public static function favicon() {
+
+ if ( !$favicon_url = HeadwayOption::get('favicon') )
+ return null;
+
+ if ( is_ssl() )
+ $favicon_url = str_replace('http:', 'https:', $favicon_url);
+
+ echo "\n\n<!-- Favicon -->\n" . '<link rel="shortcut icon" type="image/ico" href="' . $favicon_url . '" />' . "\n\n\n";
+
+ }
+
+
+ /**
+ * Callback function to be used for displaying the header scripts.
+ *
+ * @uses headway_parse_php()
+ **/
+ public static function header_scripts() {
+
+ echo "\n" . headway_parse_php(HeadwayOption::get('header-scripts')) . "\n";
+
+ }
+
+
+ /**
+ * Callback function to be used for displaying the footer scripts.
+ *
+ * @uses headway_parse_php()
+ **/
+ public static function footer_scripts() {
+ echo "\n" . headway_parse_php(HeadwayOption::get('footer-scripts')) . "\n";
+ }
+
+
+ /**
+ * To promote caching on browsers, Headway can tell WordPress to not put in the query variables on the style and script URLs.
+ **/
+ public static function remove_dependency_query_vars($query) {
+
+ if ( !HeadwayOption::get('remove-dependency-query-vars', 'general', false) && !HeadwayRoute::is_visual_editor_iframe() )
+ return $query;
+
+ return remove_query_arg('ver', $query);
+
+ }
+
+
+}
\ No newline at end of file
--- /dev/null
+<?php
+class HeadwayLayoutRenderer {
+
+
+ private $id;
+
+
+ private $blocks;
+
+
+ private $wrappers;
+
+
+ public function __construct() {
+
+ $this->id = HeadwayLayout::get_current_in_use();
+ $this->blocks = HeadwayBlocksData::get_blocks_by_layout($this->id);
+
+ $this->wrappers = HeadwayWrappersData::get_wrappers_by_layout($this->id);
+
+ }
+
+
+ public function display() {
+
+ if ( !$this->blocks )
+ return $this->display_no_blocks_message();
+
+ foreach ( $this->wrappers as $wrapper_id => $wrapper ) {
+
+ $wrapper_id_for_blocks = $wrapper_id;
+ $wrapper_settings = headway_get('settings', $wrapper, array());
+
+ /* Check if mirroring. If mirroring, change wrapper ID to the wrapper being mirrored and preserve original ID for a later class */
+ if ( $wrapper_being_mirrored = HeadwayWrappersData::get_wrapper_mirror($wrapper) ) {
+
+ $mirrored_wrapper_id = $wrapper_being_mirrored['id'];
+ $wrapper_id_for_blocks = $mirrored_wrapper_id;
+
+ foreach ( HeadwayBlocksData::get_blocks_by_wrapper($wrapper_being_mirrored['layout'], $mirrored_wrapper_id) as $block_from_mirrored_wrapper )
+ $this->blocks[$block_from_mirrored_wrapper['id']] = $block_from_mirrored_wrapper;
+
+ }
+
+ /* Grab blocks belonging to this wrapper */
+ $wrapper_blocks = array();
+
+ foreach ( $this->blocks as $block_id => $block ) {
+
+ if ( headway_get('wrapper_id', $block, HeadwayWrappers::$default_wrapper_id) == $wrapper_id_for_blocks )
+ $wrapper_blocks[$block_id] = $block;
+
+ /* If there's only one wrapper and the block does not have a proper ID or is default, move it to that wrapper */
+ if ( count($this->wrappers) === 1 && (headway_get('wrapper_id', $block) === null || headway_get('wrapper_id', $block) == 'wrapper-default' || !isset($this->wrappers[headway_get('wrapper_id', $block)])) )
+ $wrapper_blocks[$block_id] = $block;
+
+ }
+
+ /* Setup wrapper classes */
+ $wrapper_id = HeadwayWrappersData::get_legacy_id( $wrapper );
+ $wrapper['original-id'] = $wrapper['id'];
+ $wrapper['id'] = HeadwayWrappersData::get_legacy_id( $wrapper );
+
+
+ $wrapper_columns = HeadwayWrappers::get_columns($wrapper);
+ $wrapper_column_width = HeadwayWrappers::get_column_width($wrapper);
+ $wrapper_gutter_width = HeadwayWrappers::get_gutter_width($wrapper);
+
+ $wrapper_classes = array('wrapper');
+
+ $wrapper_classes[] = HeadwayWrappers::is_independent_grid($wrapper) ? 'independent-grid' : null;
+ $wrapper_classes[] = HeadwayWrappers::is_fluid($wrapper) ? 'wrapper-fluid' : 'wrapper-fixed';
+ $wrapper_classes[] = HeadwayWrappers::is_grid_fluid($wrapper) ? 'wrapper-fluid-grid' : 'wrapper-fixed-grid';
+ $wrapper_classes[] = 'grid-' . (HeadwayWrappers::is_grid_fluid($wrapper) || HeadwayResponsiveGrid::is_enabled() ? 'fluid' : 'fixed') . '-' . $wrapper_columns . '-' . $wrapper_column_width . '-' . $wrapper_gutter_width;
+
+ $wrapper_classes[] = HeadwayResponsiveGrid::is_active() ? 'responsive-grid' : null;
+ $wrapper_classes[] = $wrapper_being_mirrored ? 'wrapper-mirroring-' . HeadwayWrappersData::get_legacy_id($wrapper_being_mirrored) : null;
+
+ $last_wrapper_id = array_slice(array_keys($this->wrappers), -1, 1);
+ $last_wrapper_id = $last_wrapper_id[0];
+
+ $first_wrapper_id = array_keys($this->wrappers);
+ $first_wrapper_id = $first_wrapper_id[0];
+
+ if ( $last_wrapper_id == $wrapper['original-id'] )
+ $wrapper_classes[] = 'wrapper-last';
+ else if ( $first_wrapper_id == $wrapper['original-id'] )
+ $wrapper_classes[] = 'wrapper-first';
+
+ /* Custom wrapper classes */
+ $custom_css_classes = explode(' ', str_replace(' ', ' ', str_replace(',', ' ', esc_attr(strip_tags(headway_get('css-classes', $wrapper_settings, ''))))));
+ $wrapper_classes = array_merge($wrapper_classes, $custom_css_classes);
+
+ /* Display the wrapper */
+ do_action('headway_before_wrapper');
+
+ echo '<div id="wrapper-' . $wrapper_id . '" class="' . implode(' ', array_unique(array_filter($wrapper_classes))) . '" data-alias="' . esc_attr( headway_get( 'alias', headway_get( 'settings', $wrapper, array() )) ) . '">' . "\n\n";
+
+ do_action('headway_wrapper_open');
+
+ $wrapper = new HeadwayGridRenderer($wrapper_blocks, $wrapper_settings);
+ $wrapper->render_grid();
+
+ do_action('headway_wrapper_close');
+
+ echo '</div><!-- .wrapper -->' . "\n\n";
+
+ do_action('headway_after_wrapper');
+ /* End displaying wrapper */
+
+ }
+
+ }
+
+
+ private function display_no_blocks_message() {
+
+ echo '<div class="wrapper wrapper-no-blocks wrapper-fixed" id="wrapper-default">' . "\n\n";
+
+ echo '<div class="block-type-content">';
+
+ echo '<div class="entry-content">';
+
+ echo '<h1 class="entry-title">' . __('No Content to Display', 'headway') . '</h1>';
+
+ $visual_editor_url = add_query_arg(array('visual-editor' => 'true', 'visual-editor-mode' => 'grid', 've-layout' => HeadwayLayout::get_current()), home_url());
+
+ if ( HeadwayCapabilities::can_user_visually_edit() ) {
+
+ echo sprintf(__('<p>There are no blocks to display. Add some by going to the <a href="%s">Headway Grid</a>!</p>', 'headway'), $visual_editor_url);
+
+ } else {
+
+ echo sprintf(__('<p>There is no content to display. Please notify the site administrator or <a href="%s">login</a>.</p>', 'headway'), $visual_editor_url);
+
+ }
+
+ echo '</div><!-- .entry-content -->';
+
+ echo '</div><!-- .block-type-content -->';
+
+ echo '</div><!-- .wrapper -->';
+
+ return false;
+
+ }
+
+
+}
\ No newline at end of file
--- /dev/null
+<?php
+add_action('headway_register_elements', 'headway_register_default_elements');
+function headway_register_default_elements() {
+
+ HeadwayElementAPI::register_group('default-elements', 'Global Styling');
+
+ HeadwayElementAPI::register_element(array(
+ 'id' => 'default-text',
+ 'name' => 'Text',
+ 'description' => '<body>',
+ 'properties' => array('fonts'),
+ 'default-element' => true,
+ 'selector' => 'body'
+ ));
+
+ HeadwayElementAPI::register_element(array(
+ 'id' => 'default-paragraph',
+ 'name' => 'Paragraph',
+ 'description' => 'All <p> elements',
+ 'properties' => array('margins'),
+ 'default-element' => true,
+ 'selector' => 'body p'
+ ));
+
+ HeadwayElementAPI::register_element(array(
+ 'id' => 'default-hyperlink',
+ 'name' => 'Hyperlink',
+ 'default-element' => true,
+ 'selector' => 'a'
+ ));
+
+ HeadwayElementAPI::register_element(array(
+ 'id' => 'default-headings',
+ 'name' => 'Headings',
+ 'description' => '<H3>, <H2>, <H1>',
+ 'default-element' => true,
+ 'selector' => 'h1, h2, h3'
+ ));
+
+ HeadwayElementAPI::register_element(array(
+ 'id' => 'default-heading-h1',
+ 'name' => 'Heading 1',
+ 'description' => '<H1>',
+ 'default-element' => true,
+ 'selector' => 'h1',
+ 'parent' => 'default-headings'
+ ));
+
+ HeadwayElementAPI::register_element(array(
+ 'id' => 'default-heading-h2',
+ 'name' => 'Heading 2',
+ 'description' => '<H2>',
+ 'default-element' => true,
+ 'selector' => 'h2',
+ 'parent' => 'default-headings'
+ ));
+
+ HeadwayElementAPI::register_element(array(
+ 'id' => 'default-heading-h3',
+ 'name' => 'Heading 3',
+ 'description' => '<H3>',
+ 'default-element' => true,
+ 'selector' => 'h3',
+ 'parent' => 'default-headings'
+ ));
+
+ HeadwayElementAPI::register_element(array(
+ 'id' => 'default-heading-h4',
+ 'name' => 'Heading 4',
+ 'description' => '<H4>',
+ 'default-element' => true,
+ 'selector' => 'h4',
+ 'parent' => 'default-headings'
+ ));
+
+ HeadwayElementAPI::register_element(array(
+ 'id' => 'default-form',
+ 'name' => 'Form',
+ 'description' => '<form>',
+ 'default-element' => true,
+ 'selector' => 'form'
+ ));
+
+ HeadwayElementAPI::register_element(array(
+ 'id' => 'default-form-input',
+ 'name' => 'Input',
+ 'description' => 'Inputs & Textareas',
+ 'default-element' => true,
+ 'selector' => 'input[type="text"], input[type="password"], input[type="email"], textarea, select',
+ 'states' => array(
+ 'Focus' => 'input[type="text"]:focus, input[type="password"]:focus, input[type="email"]:focus, textarea:focus'
+ ),
+ 'parent' => 'default-form'
+ ));
+
+ HeadwayElementAPI::register_element(array(
+ 'id' => 'default-form-button',
+ 'name' => 'Button',
+ 'description' => 'Buttons & Submit Inputs',
+ 'default-element' => true,
+ 'selector' => 'input[type="submit"], input[type="button"], button, .button',
+ 'states' => array(
+ 'Hover' => 'input[type="submit"]:hover, input[type="button"]:hover, button:hover',
+ 'Active' => 'input[type="submit"]:active, input[type="button"]:active, button:active'
+ ),
+ 'parent' => 'default-form'
+ ));
+
+ HeadwayElementAPI::register_element(array(
+ 'id' => 'default-blockquote',
+ 'name' => 'Blockquote',
+ 'properties' => array('background', 'borders', 'fonts', 'padding', 'corners', 'box-shadow', 'overflow'),
+ 'default-element' => true,
+ 'selector' => 'blockquote'
+ ));
+
+ HeadwayElementAPI::register_element(array(
+ 'id' => 'default-block',
+ 'name' => 'Block',
+ 'properties' => array('background', 'borders', 'fonts', 'padding', 'corners', 'box-shadow', 'overflow'),
+ 'default-element' => true,
+ 'selector' => '.block'
+ ));
+
+ HeadwayElementAPI::register_element(array(
+ 'id' => 'block-title',
+ 'name' => 'Block Title',
+ 'selector' => '.block-title',
+ 'default-element' => true
+ ));
+
+ HeadwayElementAPI::register_element(array(
+ 'id' => 'block-title-inner',
+ 'name' => 'Block Title Inner',
+ 'selector' => '.block-title span',
+ 'default-element' => true,
+ 'parent' => 'block-title'
+ ));
+
+ HeadwayElementAPI::register_element(array(
+ 'id' => 'block-subtitle',
+ 'name' => 'Block Subtitle',
+ 'selector' => '.block-subtitle',
+ 'default-element' => true
+ ));
+
+}
\ No newline at end of file
--- /dev/null
+<?php
+class HeadwayElements {
+
+
+ public static function init() {
+
+ Headway::load(array(
+ 'elements/properties',
+ 'data/data-elements' => 'ElementsData',
+ 'api/api-element' => 'ElementAPI'
+ ));
+
+ add_action('headway_elements_init', array(__CLASS__, 'load_elements'));
+
+ do_action('headway_elements_init');
+
+ }
+
+
+ public static function load_elements() {
+
+ include_once 'default-elements.php';
+ include_once 'structural-elements.php';
+
+ }
+
+
+}
\ No newline at end of file
--- /dev/null
+<?php
+class HeadwayElementProperties {
+
+
+ protected static $properties = array(
+
+ /* Fonts */
+ 'font-family' => array(
+ 'group' => 'Fonts',
+ 'name' => 'Font Family',
+ 'type' => 'font-family-select',
+ 'js-callback' => 'propertyInputCallbackFontFamily(params);',
+ 'complex-property' => 'HeadwayElementProperties::complex_property_font_family'
+ ),
+
+ 'font-size' => array(
+ 'group' => 'Fonts',
+ 'name' => 'Font Size',
+ 'type' => 'integer',
+ 'default' => '12',
+ 'js-callback' => 'stylesheet.update_rule(params.selector, {"font-size": params.value + params.unit});',
+ 'unit' => array(),
+ ),
+
+ 'color' => array(
+ 'group' => 'Fonts',
+ 'name' => 'Font Color',
+ 'type' => 'color',
+ 'js-callback' => 'stylesheet.update_rule(params.selector, {"color": params.value});',
+ 'default' => '000000'
+ ),
+
+ 'line-height' => array(
+ 'group' => 'Fonts',
+ 'name' => 'Line Height',
+ 'type' => 'integer',
+ 'default' => 100,
+ 'js-callback' => 'stylesheet.update_rule(params.selector, {"line-height": params.value + params.unit});',
+ 'unit' => array('default' => '%')
+ ),
+
+ 'font-styling' => array(
+ 'group' => 'Fonts',
+ 'name' => 'Font Styling',
+ 'type' => 'select',
+ 'options' => array(
+ 'normal' => 'Normal',
+ 'light' => 'Light',
+ 'bold' => 'Bold',
+ 'italic' => 'Italic',
+ 'bold-italic' => 'Bold Italic'
+ ),
+ 'js-callback' => 'propertyInputCallbackFontStyling(params);',
+ 'complex-property' => 'HeadwayElementProperties::complex_property_font_styling'
+ ),
+
+ 'text-align' => array(
+ 'group' => 'Fonts',
+ 'name' => 'Text Alignment',
+ 'type' => 'select',
+ 'options' => array(
+ 'left' => 'Left',
+ 'center' => 'Center',
+ 'right' => 'Right'
+ ),
+ 'js-callback' => 'stylesheet.update_rule(params.selector, {"text-align": params.value});'
+ ),
+
+ 'capitalization' => array(
+ 'group' => 'Fonts',
+ 'name' => 'Capitalization',
+ 'type' => 'select',
+ 'options' => array(
+ 'none' => 'Normal',
+ 'uppercase' => 'Uppercase',
+ 'lowercase' => 'Lowercase',
+ 'small-caps' => 'Small Caps',
+ ),
+ 'js-callback' => 'propertyInputCallbackCapitalization(params);',
+ 'complex-property' => 'HeadwayElementProperties::complex_property_capitalization'
+ ),
+
+ 'letter-spacing' => array(
+ 'group' => 'Fonts',
+ 'name' => 'Letter Spacing',
+ 'type' => 'select',
+ 'js-callback' => 'stylesheet.update_rule(params.selector, {"letter-spacing": params.value + "px"});',
+ 'unit' => 'px',
+ 'options' => array(
+ '0' => '0',
+ '1' => '1px',
+ '2' => '2px',
+ '3' => '3px',
+ '-1' => '-1px',
+ '-2' => '-2px',
+ '-3' => '-3px'
+ )
+ ),
+
+ 'text-decoration' => array(
+ 'group' => 'Fonts',
+ 'name' => 'Text Underline',
+ 'type' => 'select',
+ 'js-callback' => 'stylesheet.update_rule(params.selector, {"text-decoration": params.value});',
+ 'options' => array(
+ 'none' => 'No Underline',
+ 'underline' => 'Underline',
+ )
+ ),
+
+ /* Fonts/Text Shadow */
+ 'text-shadow-horizontal-offset' => array(
+ 'group' => 'Fonts',
+ 'name' => 'Shadow: Horizontal Offset',
+ 'type' => 'integer',
+ 'unit' => 'px',
+ 'js-callback' => 'propertyInputCallbackShadow(params);',
+ 'complex-property' => 'HeadwayElementProperties::complex_property_shadow',
+ 'default' => 0
+ ),
+
+ 'text-shadow-vertical-offset' => array(
+ 'group' => 'Fonts',
+ 'name' => 'Shadow: Vertical Offset',
+ 'type' => 'integer',
+ 'unit' => 'px',
+ 'js-callback' => 'propertyInputCallbackShadow(params);',
+ 'complex-property' => 'HeadwayElementProperties::complex_property_shadow',
+ 'default' => 0
+ ),
+
+ 'text-shadow-blur' => array(
+ 'group' => 'Fonts',
+ 'name' => 'Shadow: Blur',
+ 'type' => 'integer',
+ 'unit' => 'px',
+ 'js-callback' => 'propertyInputCallbackShadow(params);',
+ 'complex-property' => 'HeadwayElementProperties::complex_property_shadow',
+ 'default' => 0
+ ),
+
+ 'text-shadow-color' => array(
+ 'group' => 'Fonts',
+ 'name' => 'Shadow: Color',
+ 'type' => 'color',
+ 'js-callback' => 'propertyInputCallbackShadow(params);',
+ 'complex-property' => 'HeadwayElementProperties::complex_property_shadow',
+ 'default' => '000000'
+ ),
+
+ /* Background */
+ 'background-color' => array(
+ 'group' => 'Background',
+ 'name' => 'Color',
+ 'type' => 'color',
+ 'js-callback' => 'stylesheet.update_rule(params.selector, {"background-color": params.value});',
+ 'default' => 'ffffff'
+ ),
+
+ 'background-image' => array(
+ 'group' => 'Background',
+ 'name' => 'Image',
+ 'type' => 'image',
+ 'js-callback' => 'propertyInputCallbackBackgroundImage(params);'
+ ),
+
+ 'background-repeat' => array(
+ 'group' => 'Background',
+ 'name' => ' – Repeat',
+ 'type' => 'select',
+ 'js-callback' => 'stylesheet.update_rule(params.selector, {"background-repeat": params.value});',
+ 'options' => array(
+ 'repeat' => 'Tile',
+ 'no-repeat' => 'No Tiling',
+ 'repeat-x' => 'Tile Horizontally',
+ 'repeat-y' => 'Tile Vertically'
+ )
+ ),
+
+ 'background-position' => array(
+ 'group' => 'Background',
+ 'name' => ' – Position',
+ 'type' => 'select',
+ 'js-callback' => 'stylesheet.update_rule(params.selector, {"background-position": params.value});',
+ 'options' => array(
+ 'left top' => 'Left Top',
+ 'left center' => 'Left Center',
+ 'left bottom' => 'Left Bottom',
+ 'right top' => 'Right Top',
+ 'right center' => 'Right Center',
+ 'right bottom' => 'Right Bottom',
+ 'center top' => 'Center Top',
+ 'center center' => 'Center Center',
+ 'center bottom' => 'Center Bottom'
+ )
+ ),
+
+ 'background-attachment' => array(
+ 'group' => 'Background',
+ 'name' => ' – Behavior',
+ 'type' => 'select',
+ 'js-callback' => 'stylesheet.update_rule(params.selector, {"background-attachment": params.value});',
+ 'options' => array(
+ 'scroll' => 'Stay at top of document (Scroll)',
+ 'fixed' => 'Stay in same position as you scroll (Fixed)'
+ )
+ ),
+
+ 'background-size' => array(
+ 'group' => 'Background',
+ 'name' => ' – Size',
+ 'type' => 'select',
+ 'js-callback' => 'stylesheet.update_rule(params.selector, {"background-size": params.value});',
+ 'options' => array(
+ 'auto' => 'Default',
+ 'cover' => 'Cover – Scales the background image so that the smallest dimension reaches the maximum width/height of the element.',
+ 'contain' => 'Contain – Ensures that the entire background-image will display by showing the image at a scaled size.'
+ )
+ ),
+
+ /* Borders */
+ 'border-color' => array(
+ 'group' => 'Borders',
+ 'name' => 'Border Color',
+ 'type' => 'color',
+ 'js-callback' => 'stylesheet.update_rule(params.selector, {"border-color": params.value});',
+ 'default' => '000000'
+ ),
+
+ 'border-style' => array(
+ 'group' => 'Borders',
+ 'name' => 'Border Style',
+ 'type' => 'select',
+ 'js-callback' => 'stylesheet.update_rule(params.selector, {"border-style": params.value});',
+ 'options' => array(
+ 'none' => 'Hidden',
+ 'solid' => 'Solid',
+ 'dashed' => 'Dashed',
+ 'dotted' => 'Dotted',
+ 'double' => 'Double',
+ 'groove' => 'Grooved',
+ 'inset' => 'Inset',
+ 'outset' => 'Outset',
+ 'ridge' => 'Ridged'
+ )
+ ),
+
+ 'border-width' => array(
+ 'group' => 'Borders',
+ 'name' => 'Border Width',
+ 'type' => 'box-model',
+ 'position' => 'sides',
+ 'lockable' => true,
+
+ 'box-model-inputs' => array(
+ 'border-top-width',
+ 'border-right-width',
+ 'border-bottom-width',
+ 'border-left-width'
+ )
+ ),
+
+ 'border-top-width' => array(
+ 'group' => 'Borders',
+ 'name' => 'Top Border Width',
+ 'type' => 'integer',
+ 'js-callback' => 'stylesheet.update_rule(params.selector, {"border-top-width": params.value + params.unit});',
+ 'unit' => array(),
+ 'display' => false,
+ 'lockable' => true,
+ 'default' => 0
+ ),
+
+ 'border-right-width' => array(
+ 'group' => 'Borders',
+ 'name' => 'Right Border Width',
+ 'type' => 'integer',
+ 'js-callback' => 'stylesheet.update_rule(params.selector, {"border-right-width": params.value + params.unit});',
+ 'unit' => array(),
+ 'display' => false,
+ 'lockable' => true,
+ 'default' => 0
+ ),
+
+ 'border-bottom-width' => array(
+ 'group' => 'Borders',
+ 'name' => 'Bottom Border Width',
+ 'type' => 'integer',
+ 'js-callback' => 'stylesheet.update_rule(params.selector, {"border-bottom-width": params.value + params.unit});',
+ 'unit' => array(),
+ 'display' => false,
+ 'lockable' => true,
+ 'default' => 0
+ ),
+
+ 'border-left-width' => array(
+ 'group' => 'Borders',
+ 'name' => 'Left Border Width',
+ 'type' => 'integer',
+ 'js-callback' => 'stylesheet.update_rule(params.selector, {"border-left-width": params.value + params.unit});',
+ 'unit' => array(),
+ 'display' => false,
+ 'lockable' => true,
+ 'default' => 0
+ ),
+
+ /* Padding */
+ 'padding' => array(
+ 'group' => 'Padding',
+ 'type' => 'box-model',
+ 'position' => 'sides',
+ 'lockable' => true,
+
+ 'box-model-inputs' => array(
+ 'padding-top',
+ 'padding-right',
+ 'padding-bottom',
+ 'padding-left'
+ )
+ ),
+
+ 'padding-top' => array(
+ 'group' => 'Padding',
+ 'name' => 'Top',
+ 'type' => 'integer',
+ 'js-callback' => 'stylesheet.update_rule(params.selector, {"padding-top": params.value + params.unit});updateInspectorVisibleBoxModal();',
+ 'unit' => array(),
+ 'display' => false,
+ 'lockable' => true,
+ 'default' => 0
+ ),
+
+ 'padding-right' => array(
+ 'group' => 'Padding',
+ 'name' => 'Right',
+ 'type' => 'integer',
+ 'js-callback' => 'stylesheet.update_rule(params.selector, {"padding-right": params.value + params.unit});updateInspectorVisibleBoxModal();',
+ 'unit' => array(),
+ 'display' => false,
+ 'lockable' => true,
+ 'default' => 0
+ ),
+
+ 'padding-bottom' => array(
+ 'group' => 'Padding',
+ 'name' => 'Bottom',
+ 'type' => 'integer',
+ 'js-callback' => 'stylesheet.update_rule(params.selector, {"padding-bottom": params.value + params.unit});updateInspectorVisibleBoxModal();',
+ 'unit' => array(),
+ 'display' => false,
+ 'lockable' => true,
+ 'default' => 0
+ ),
+
+ 'padding-left' => array(
+ 'group' => 'Padding',
+ 'name' => 'Left',
+ 'type' => 'integer',
+ 'js-callback' => 'stylesheet.update_rule(params.selector, {"padding-left": params.value + params.unit});updateInspectorVisibleBoxModal();',
+ 'unit' => array(),
+ 'display' => false,
+ 'lockable' => true,
+ 'default' => 0
+ ),
+
+ /* Margin */
+ 'margins' => array(
+ 'group' => 'Margins',
+ 'type' => 'box-model',
+ 'position' => 'sides',
+ 'lockable' => true,
+
+ 'box-model-inputs' => array(
+ 'margin-top',
+ 'margin-right',
+ 'margin-bottom',
+ 'margin-left'
+ )
+ ),
+
+ 'margin-top' => array(
+ 'group' => 'Margins',
+ 'name' => 'Top',
+ 'type' => 'integer',
+ 'js-callback' => 'stylesheet.update_rule(params.selector, {"margin-top": params.value + params.unit});updateInspectorVisibleBoxModal();',
+ 'unit' => array(),
+ 'display' => false,
+ 'lockable' => true,
+ 'default' => 0
+ ),
+
+ 'margin-right' => array(
+ 'group' => 'Margins',
+ 'name' => 'Right',
+ 'type' => 'integer',
+ 'js-callback' => 'stylesheet.update_rule(params.selector, {"margin-right": params.value + params.unit});updateInspectorVisibleBoxModal();',
+ 'unit' => array(),
+ 'display' => false,
+ 'lockable' => true,
+ 'default' => 0
+ ),
+
+ 'margin-bottom' => array(
+ 'group' => 'Margins',
+ 'name' => 'Bottom',
+ 'type' => 'integer',
+ 'js-callback' => 'stylesheet.update_rule(params.selector, {"margin-bottom": params.value + params.unit});updateInspectorVisibleBoxModal();',
+ 'unit' => array(),
+ 'display' => false,
+ 'lockable' => true,
+ 'default' => 0
+ ),
+
+ 'margin-left' => array(
+ 'group' => 'Margins',
+ 'name' => 'Left',
+ 'type' => 'integer',
+ 'js-callback' => 'stylesheet.update_rule(params.selector, {"margin-left": params.value + params.unit});updateInspectorVisibleBoxModal();',
+ 'unit' => array(),
+ 'display' => false,
+ 'lockable' => true,
+ 'default' => 0
+ ),
+
+ /* Corners (Border Radius) */
+ 'border-radius' => array(
+ 'group' => 'Corners',
+ 'type' => 'box-model',
+ 'position' => 'corners',
+ 'lockable' => true,
+
+ 'box-model-inputs' => array(
+ 'border-top-left-radius',
+ 'border-top-right-radius',
+ 'border-bottom-left-radius',
+ 'border-bottom-right-radius'
+ )
+ ),
+
+ 'border-top-left-radius' => array(
+ 'group' => 'Corners',
+ 'name' => 'Top Left',
+ 'type' => 'integer',
+ 'js-callback' => 'stylesheet.update_rule(params.selector, {"border-top-left-radius": params.value + params.unit});',
+ 'unit' => array(),
+ 'display' => false,
+ 'lockable' => true,
+ 'default' => 0
+ ),
+
+ 'border-top-right-radius' => array(
+ 'group' => 'Corners',
+ 'name' => 'Top Right',
+ 'type' => 'integer',
+ 'js-callback' => 'stylesheet.update_rule(params.selector, {"border-top-right-radius": params.value + params.unit});',
+ 'unit' => array(),
+ 'display' => false,
+ 'lockable' => true,
+ 'default' => 0
+ ),
+
+ 'border-bottom-left-radius' => array(
+ 'group' => 'Corners',
+ 'name' => 'Bottom Left',
+ 'type' => 'integer',
+ 'js-callback' => 'stylesheet.update_rule(params.selector, {"border-bottom-left-radius": params.value + params.unit});',
+ 'unit' => array(),
+ 'display' => false,
+ 'lockable' => true,
+ 'default' => 0
+ ),
+
+ 'border-bottom-right-radius' => array(
+ 'group' => 'Corners',
+ 'name' => 'Bottom Right',
+ 'type' => 'integer',
+ 'js-callback' => 'stylesheet.update_rule(params.selector, {"border-bottom-right-radius": params.value + params.unit});',
+ 'unit' => array(),
+ 'display' => false,
+ 'lockable' => true,
+ 'default' => 0
+ ),
+
+ /* Box Shadow */
+ 'box-shadow-horizontal-offset' => array(
+ 'group' => 'Box Shadow',
+ 'name' => 'Horizontal Offset',
+ 'type' => 'integer',
+ 'unit' => 'px',
+ 'js-callback' => 'propertyInputCallbackShadow(params);',
+ 'complex-property' => 'HeadwayElementProperties::complex_property_shadow',
+ 'default' => 0
+ ),
+
+ 'box-shadow-vertical-offset' => array(
+ 'group' => 'Box Shadow',
+ 'name' => 'Vertical Offset',
+ 'type' => 'integer',
+ 'unit' => 'px',
+ 'js-callback' => 'propertyInputCallbackShadow(params);',
+ 'complex-property' => 'HeadwayElementProperties::complex_property_shadow',
+ 'default' => 0
+ ),
+
+ 'box-shadow-blur' => array(
+ 'group' => 'Box Shadow',
+ 'name' => 'Blur',
+ 'type' => 'integer',
+ 'unit' => 'px',
+ 'js-callback' => 'propertyInputCallbackShadow(params);',
+ 'complex-property' => 'HeadwayElementProperties::complex_property_shadow',
+ 'default' => 0
+ ),
+
+ 'box-shadow-color' => array(
+ 'group' => 'Box Shadow',
+ 'name' => 'Color',
+ 'type' => 'color',
+ 'js-callback' => 'propertyInputCallbackShadow(params);',
+ 'complex-property' => 'HeadwayElementProperties::complex_property_shadow',
+ 'default' => '000000'
+ ),
+
+ 'box-shadow-position' => array(
+ 'group' => 'Box Shadow',
+ 'name' => 'Position',
+ 'type' => 'select',
+ 'js-callback' => 'propertyInputCallbackShadow(params);',
+ 'complex-property' => 'HeadwayElementProperties::complex_property_shadow',
+ 'options' => array(
+ 'outside' => 'Outside',
+ 'inset' => 'Inset'
+ )
+ ),
+
+ /* List Styling */
+ 'list-style' => array(
+ 'group' => 'Lists',
+ 'name' => 'List Style',
+ 'type' => 'select',
+ 'js-callback' => 'stylesheet.update_rule(params.selector, {"list-style": params.value});',
+ 'options' => array(
+ 'none' => 'No Bullet/Style',
+ 'disc' => 'Bullet',
+ 'circle' => 'Circle',
+ 'square' => 'Square',
+ 'decimal' => 'Decimal Numbers (1., 2., etc)',
+ 'lower-alpha' => 'Alphabetical (Lowercase)',
+ 'upper-alpha' => 'Alphabetical (Uppercase)',
+ 'lower-roman' => 'Roman Numerals (Lowercase)',
+ 'upper-roman' => 'Roman Numerals (Uppercase)',
+ ),
+ 'default' => 'disc'
+ ),
+
+ /* Nudging */
+ 'top' => array(
+ 'group' => 'Nudging',
+ 'name' => 'Vertical Offset',
+ 'type' => 'integer',
+ 'unit' => 'px',
+ 'js-callback' => 'stylesheet.update_rule(params.selector, {"top": params.value + "px"});',
+ 'default' => 0
+ ),
+
+ 'left' => array(
+ 'group' => 'Nudging',
+ 'name' => 'Horizontal Offset',
+ 'type' => 'integer',
+ 'unit' => 'px',
+ 'js-callback' => 'stylesheet.update_rule(params.selector, {"left": params.value + "px"});',
+ 'default' => 0
+ ),
+
+ 'position' => array(
+ 'group' => 'Nudging',
+ 'name' => 'Method',
+ 'type' => 'select',
+ 'default' => 'static',
+ 'options' => array(
+ 'static' => 'Static',
+ 'relative' => 'Relative',
+ 'absolute' => 'Absolute',
+ 'fixed' => 'Floating (Fixed)'
+ ),
+ 'js-callback' => 'stylesheet.update_rule(params.selector, {"position": params.value});',
+ ),
+
+ 'z-index' => array(
+ 'group' => 'Nudging',
+ 'name' => 'Layer Index (z-index)',
+ 'type' => 'integer',
+ 'js-callback' => 'stylesheet.update_rule(params.selector, {"z-index": params.value});',
+ 'default' => 1
+ ),
+
+ /* Overflow */
+ 'overflow' => array(
+ 'group' => 'Overflow',
+ 'name' => 'Visibility',
+ 'type' => 'select',
+ 'options' => array(
+ 'visible' => 'Visible',
+ 'hidden' => 'Hidden',
+ 'scroll' => 'Scroll',
+ ),
+ 'js-callback' => 'stylesheet.update_rule(params.selector, {"overflow": params.value});',
+ )
+
+ );
+
+
+ public static function get_property($property) {
+
+ return isset(self::$properties[$property]) ? self::$properties[$property] : null;
+
+ }
+
+
+ public static function get_properties_by_group($group) {
+
+ //Filter though all of the properties to make sure they are in the selected group
+ $filtered_properties = array_filter(self::$properties, create_function('$property', 'return ($property[\'group\'] === \'' . $group . '\');'));
+
+ if ( !is_array($filtered_properties) || count($filtered_properties) === 0 )
+ return null;
+ else
+ return $filtered_properties;
+
+ }
+
+
+ public static function get_properties() {
+
+ return self::$properties;
+
+ }
+
+
+ public static function output_css($selector, $properties = array()) {
+
+ if ( !isset($selector) || $selector == false )
+ return null;
+
+ if ( !is_array($properties) || count($properties) === 0 )
+ return null;
+
+ $output = '';
+
+ //Loop through properties
+ foreach ( $properties as $property_id => $value ) {
+
+ //If the value is an empty string, false, or null, don't attempt to put anything.
+ if ( (!isset($value) || $value === '' || $value === false || $value === null || $value === 'null') && ($value !== '0' && $value !== 0) )
+ continue;
+
+ //Look up the property to figure out how to handle it
+ $property = self::get_property($property_id);
+
+ //If the property does not exist, skip it.
+ if ( !$property )
+ continue;
+
+ /* Everything's good, inject the selector in if it hasn't already been that way the selector isn't added when an element doesn't have any properties */
+ if ( empty($output) )
+ $output .= $selector . ' {' . "\n";
+
+ //If it's a complex property, pass everything through it.
+ if ( headway_get('complex-property', $property) && is_callable(headway_get('complex-property', $property)) ) {
+ $output .= call_user_func(headway_get('complex-property', $property), array(
+ 'selector' => $selector,
+ 'property_id' => $property_id,
+ 'value' => $value,
+ 'properties' => $properties,
+ 'property' => $property
+ ));
+
+ continue;
+ }
+
+ //Format the $value by adding the unit or hex indicator if it's a color
+ if ( headway_get('unit', $property) !== null ) {
+
+ /* we get the unit property value if the unit is customizable */
+ if ( is_array(headway_get('unit', $property)) ) {
+
+ $unit = trim( str_replace( array_merge(range( 0, 9 ), array('.', '-')), '', $value ) );
+ $unit_settings = headway_get( 'unit', $property );
+
+ /* If there's no unit in the string then pull the default */
+ if ( !$unit ) {
+ $value = $value . headway_get('default', $unit_settings, 'px');
+ }
+
+ } else {
+ $value = $value . $property['unit'];
+ }
+
+ }
+
+ if ( headway_get('type', $property) === 'color' )
+ $value = headway_format_color($value);
+
+ if ( headway_get('type', $property) === 'image' && $value != 'none' )
+ $value = 'url(' . $value . ')';
+
+ $output .= $property_id . ': ' . $value . ';' . "\n";
+
+ } //foreach: Regular Properties
+
+ /* Only close if there's actual output */
+ if ( !empty($output) )
+ $output .= '}' . "\n";
+
+ return $output;
+
+ }
+
+
+ public static function complex_property_font_family($args) {
+
+ extract($args);
+
+ $font_fragments = explode('|', $value);
+
+ /* Web Font */
+ if ( count($font_fragments) >= 2 )
+ $stack = $font_fragments[1];
+
+ /* Traditional Font */
+ else
+ $stack = HeadwayFonts::get_stack($value);
+
+ return 'font-family: ' . $stack . ';';
+
+ }
+
+
+ public static function complex_property_shadow($args) {
+
+ extract($args);
+
+ $shadow_type = (strpos($property_id, 'box-shadow') !== false) ? 'box-shadow' : 'text-shadow';
+
+ global $headway_complex_property_check;
+
+ //If the complex property check isn't even set, make it an empty array.
+ if ( !is_array($headway_complex_property_check) )
+ $headway_complex_property_check = array($shadow_type => array());
+
+ //Since the complex property is a combination of a bunch of properties, we only want it to output once.
+ if ( isset($headway_complex_property_check[$shadow_type][$selector]) && $headway_complex_property_check[$shadow_type][$selector] == true )
+ return;
+
+ $headway_complex_property_check[$shadow_type][$selector] = true;
+
+ if ( !isset($properties[$shadow_type . '-color']) )
+ return null;
+
+ $shadow_color = headway_format_color($properties[$shadow_type . '-color']);
+
+ if ( $shadow_color == 'transparent' )
+ return null;
+
+ $shadow_hoffset = isset($properties[$shadow_type . '-horizontal-offset']) ? $properties[$shadow_type . '-horizontal-offset'] : '0';
+ $shadow_voffset = isset($properties[$shadow_type . '-vertical-offset']) ? $properties[$shadow_type . '-vertical-offset'] : '0';
+ $shadow_blur = isset($properties[$shadow_type . '-blur']) ? $properties[$shadow_type . '-blur'] : '0';
+ $shadow_inset = (headway_get($shadow_type . '-position', $properties, 'outside') == 'inset') ? ' inset' : null;
+
+ return $shadow_type . ': ' . $shadow_color . ' ' . $shadow_hoffset . 'px ' . $shadow_voffset . 'px ' . $shadow_blur . 'px' . $shadow_inset . ';';
+
+ }
+
+
+ public static function complex_property_capitalization($args) {
+
+ extract($args);
+
+ $data = '';
+
+ if ( $value == 'none' ) {
+
+ $data .= 'text-transform: none;';
+ $data .= 'font-variant: normal;';
+
+ } elseif ( $value == 'small-caps' ) {
+
+ $data .= 'text-transform: none;';
+ $data .= 'font-variant: small-caps;';
+
+ } else {
+
+ $data .= 'text-transform: ' . $value . ';';
+ $data .= 'font-variant: normal;';
+
+ }
+
+ return $data;
+
+ }
+
+
+ public static function complex_property_font_styling($args) {
+
+ extract($args);
+
+ $data = '';
+
+ if ( $value == 'normal' ) {
+
+ $data .= 'font-style: normal;';
+ $data .= 'font-weight: normal;';
+
+ } elseif ( $value == 'bold' ) {
+
+ $data .= 'font-style: normal;';
+ $data .= 'font-weight: bold;';
+
+ } elseif ( $value == 'light' ) {
+
+ $data .= 'font-style: normal;';
+ $data .= 'font-weight: lighter;';
+
+ } elseif ( $value == 'italic' ) {
+
+ $data .= 'font-style: italic;';
+ $data .= 'font-weight: normal;';
+
+ } elseif ( $value == 'bold-italic' ) {
+
+ $data .= 'font-style: italic;';
+ $data .= 'font-weight: bold;';
+
+ }
+
+ return $data;
+
+ }
+
+
+}
\ No newline at end of file
--- /dev/null
+<?php
+add_action('headway_register_elements', 'headway_register_structural_elements');
+function headway_register_structural_elements() {
+
+ //Structure
+ HeadwayElementAPI::register_group('structure', array(
+ 'name' => 'Structure'
+ ));
+
+ HeadwayElementAPI::register_element( array(
+ 'group' => 'structure',
+ 'id' => 'html',
+ 'name' => 'HTML Document',
+ 'selector' => 'html',
+ 'disallow-nudging' => true
+ ) );
+
+ HeadwayElementAPI::register_element(array(
+ 'group' => 'structure',
+ 'id' => 'body',
+ 'name' => 'Body',
+ 'selector' => 'body',
+ 'properties' => array('background', 'borders', 'padding'),
+ 'disallow-nudging' => true
+ ));
+
+ HeadwayElementAPI::register_element(array(
+ 'group' => 'structure',
+ 'id' => 'wrapper',
+ 'name' => 'Wrapper',
+ 'selector' => 'div.wrapper',
+ 'properties' => array('fonts', 'background', 'borders', 'padding', 'corners', 'box-shadow')
+ ));
+
+ //Blocks
+ HeadwayElementAPI::register_group('blocks', array(
+ 'name' => 'Blocks',
+ 'description' => 'Individual block types and block elements'
+ ));
+
+}
\ No newline at end of file
--- /dev/null
+<?php
+class HeadwayGoogleFonts extends HeadwayWebFontProvider {
+
+
+ public $id = 'google';
+
+ public $name = 'Google Web Fonts';
+
+ public $webfont_provider = 'google';
+
+ public $load_with_ajax = true;
+
+
+ public $sorting_options = array(
+ 'popularity' => 'Popularity',
+ 'trending' => 'Trending',
+ 'alpha' => 'Alphabetically',
+ 'date' => 'Date Added',
+ 'style' => 'Style'
+ );
+
+
+ protected $api_url = 'http://headwaythemes.com/api/google-fonts';
+
+ protected $backup_api_url = 'http://cdn.headwaythemes.com/api/google-fonts';
+
+
+ public function query_fonts($sortby = 'date', $retry = false) {
+
+ $fonts_query = wp_remote_get(add_query_arg(array(
+ 'license' => 'legacy',
+ 'sortby' => $sortby,
+ ), trailingslashit($this->api_url)), array(
+ 'timeout' => 20
+ ));
+
+ /* If the original query to Headway cannot connect, find a way to proxy to Headway's CDN */
+ if ( is_wp_error($fonts_query) ) {
+
+ $fonts_query = wp_remote_get($this->backup_api_url . '/legacy/' . $sortby, array(
+ 'timeout' => 20
+ ));
+
+ }
+
+ return json_decode(wp_remote_retrieve_body($fonts_query), true);
+
+ }
+
+
+}
+headway_register_web_font_provider('HeadwayGoogleFonts');
\ No newline at end of file
--- /dev/null
+<?php
+class HeadwayTraditionalFonts extends HeadwayWebFontProvider {
+
+ public $id = 'traditional';
+
+ public $name = 'Traditional Fonts';
+
+ public $webfont_provider = false;
+
+ public $search = false;
+
+
+
+ public function retrieve_fonts($sortby = false) {
+
+ return $this->query_fonts($sortby);
+
+ }
+
+
+ public function query_fonts($sortby) {
+
+ $fonts = array();
+
+ foreach ( HeadwayFonts::get_fonts() as $font_id => $font_name )
+ $fonts[] = array(
+ 'id' => $font_id,
+ 'name' => $font_name,
+ 'stack' => HeadwayFonts::get_stack($font_id)
+ );
+
+ return $fonts;
+
+ }
+
+
+ public function content_fonts_list() {
+
+ echo '<div class="fonts-list">';
+
+ echo '<ul>';
+ $this->list_fonts('traditional');
+ echo '</ul>';
+
+ echo '</div><!-- .fonts-list -->';
+
+ }
+
+
+}
+
+
+class HeadwayFonts {
+
+
+ public static $fonts = array(
+ 'georgia' => 'Georgia',
+ 'cambria' => 'Cambria',
+ 'palatino' => 'Palatino',
+ 'times' => 'Times',
+ 'times new roman' => 'Times New Roman',
+
+ 'arial' => 'Arial',
+ 'arial black' => 'Arial Black',
+ 'arial narrow' => 'Arial Narrow',
+ 'century gothic' => 'Century Gothic',
+ 'gill sans' => 'Gill Sans',
+ 'helvetica' => 'Helvetica',
+ 'impact' => 'Impact',
+ 'lucida grande' => 'Lucida Grande',
+ 'tahoma' => 'Tahoma',
+ 'trebuchet ms' => 'Trebuchet MS',
+ 'verdana' => 'Verdana',
+
+ 'courier' => 'Courier',
+ 'courier new' => 'Courier New',
+
+ 'papyrus' => 'Papyrus',
+ 'copperplate' => 'Copperplate'
+ );
+
+
+ public static $font_stacks = array(
+ 'georgia' => 'georgia, serif',
+ 'cambria' => 'cambria, georgia, serif',
+ 'palatino' => 'palatino linotype, palatino, serif',
+ 'times' => 'times, serif',
+ 'times new roman' => 'times new roman, serif',
+ 'arial' => 'arial, sans-serif',
+ 'arial black' => 'arial black, sans-serif',
+ 'arial narrow' => 'arial narrow, sans-serif',
+ 'century gothic' => '\'Century Gothic\', CenturyGothic, AppleGothic, sans-serif',
+ 'gill sans' => 'gill sans, sans-serif',
+ 'helvetica' => 'helvetica, sans-serif',
+ 'impact' => 'impact, sans-serif',
+ 'lucida grande' => 'lucida grande, sans-serif',
+ 'tahoma' => 'tahoma, sans-serif',
+ 'trebuchet ms' => 'trebuchet ms, sans-serif',
+ 'verdana' => 'verdana, sans-serif',
+ 'courier' => 'courier, monospace',
+ 'courier new' => 'courier new, monospace',
+ 'papyrus' => 'papyrus, fantasy',
+ 'copperplate' => 'copperplate, copperplate gothic bold, fantasy'
+ );
+
+
+ public static function get_fonts() {
+
+ return apply_filters('headway_fonts', self::$fonts);
+
+ }
+
+
+ public static function get_stack($font_id) {
+
+ return headway_get($font_id, apply_filters('headway_fonts_stacks', self::$font_stacks));
+
+ }
+
+
+ public static function register_font(array $args) {
+
+ extract($args);
+
+ /* Check args */
+ if ( !isset($id) || !isset($stack) || !isset($name) )
+ return new WP_Error('hw_fonts_register_font_invalid_args', __('To register a font, the argument array must include an "id", "stack", and "name".', 'headway'), $args);
+
+ /* Add the font to the stacks first */
+ self::$font_stacks[$id] = $stack;
+
+ /* Add the font */
+ self::$fonts[$id] = $name;
+
+ return true;
+
+ }
+
+
+}
+
+headway_register_web_font_provider('HeadwayTraditionalFonts');
\ No newline at end of file
--- /dev/null
+<?php
+function headway_register_web_font_provider($class) {
+
+ return new $class;
+
+}
+
+
+abstract class HeadwayWebFontProvider {
+
+
+ public $id = null;
+
+ public $name = null;
+
+
+ public $search = true;
+
+ public $sorting_options = array();
+
+
+ public $webfont_provider = false;
+
+ public $load_with_ajax = false;
+
+
+ protected $transient_id;
+
+
+ /* Initiate the web font provider... Add hooks, etc */
+ public function __construct() {
+
+ if ( !$this->id || !$this->name )
+ return;
+
+ $this->transient_id = 'headway_webfonts_' . $this->id;
+
+ add_action('headway_fonts_browser_tabs', array($this, 'tab'));
+ add_action('headway_fonts_browser_content', array($this, 'content'));
+
+ if ( $this->load_with_ajax )
+ add_action('headway_fonts_ajax_list_fonts_' . $this->id, array($this, 'list_fonts'));
+
+ }
+
+
+ public function tab() {
+
+ echo '<li><a href="#' . $this->id . '-fonts">' . $this->name . '</a></li>';
+
+ }
+
+
+ public function content() {
+
+ $attrs = array(
+ 'search' => $this->search ? 'true' : 'false',
+ 'sorting' => (is_array($this->sorting_options) && !empty($this->sorting_options)) ? 'true' : 'false',
+ 'provider' => $this->webfont_provider ? $this->webfont_provider : 'false',
+ 'ajax' => $this->load_with_ajax ? 'true' : 'false'
+ );
+
+ echo '<div id="' . $this->id . '-fonts" class="tab-content font-provider-tab-content" data-font-allow-search="' . $attrs['search'] . '" data-font-allow-sorting="' . $attrs['sorting'] . '" data-font-webfont-provider="' . $attrs['provider'] . '" data-font-load-with-ajax="' . $attrs['ajax'] . '">';
+
+ if ( $this->search )
+ $this->content_search();
+
+ $this->content_fonts_list();
+
+ echo '</div><!-- #-fonts -->';
+
+ }
+
+
+ public function content_search() {
+
+ echo '<form class="fonts-search">';
+
+ echo '<input class="fonts-filter" type="text" placeholder="Search ' . $this->name . '" name="search-input">';
+
+ if ( is_array($this->sorting_options) && !empty($this->sorting_options) ) {
+
+ echo '<div class="select-container"><select name="choices">';
+ echo '<option value="" disabled="disabled">– Sort By –</option>';
+
+ foreach ( $this->sorting_options as $sorting_option_value => $sorting_option_text )
+ echo '<option value="' . $sorting_option_value . '">' . $sorting_option_text . '</option>';
+
+ echo '</select></div><!-- .select-container -->';
+
+ }
+
+ echo '</form>';
+
+ }
+
+
+ public function content_fonts_list() {
+
+ echo '
+ <div class="fonts-list webfonts-list">
+ <ul></ul>
+
+ <div class="loading fonts-loading"><p>Loading Fonts...</p></div>
+ <div class="fonts-noresults" style="display:none;">No Results</div>
+ </div><!-- .fonts-list -->
+ ';
+
+ }
+
+
+ /* Retrieves the fonts from the provider */
+ public function query_fonts($sortby) {
+
+ return array(
+ array(
+ 'id' => 'font-family',
+ 'name' => 'Font Family',
+ 'stack' => 'font family'
+ )
+ );
+
+ }
+
+
+ /* Gets the fonts using the transient if possible. Otherwise it'll query the fonts and set the transient */
+ public function retrieve_fonts($sortby = false) {
+
+ $fonts = get_transient($this->transient_id, array());
+
+ if ( !$fonts || !is_array($fonts) || empty($fonts) ) {
+
+ $fonts[$sortby] = $this->query_fonts($sortby);
+
+ /* Only set the transient if the fonts are returned properly and there's no error */
+ if ( !empty($fonts) && empty($fonts[$sortby]['error']) )
+ set_transient($this->transient_id, $fonts, 60 * 60 * 24);
+
+ }
+
+ /* If there's an error, delete the transient */
+ if ( !empty($fonts[$sortby]['error']) || empty($fonts[$sortby]) || is_wp_error($fonts[$sortby]) )
+ $this->reset_transients();
+
+ return isset($fonts[$sortby]) ? $fonts[$sortby] : null;
+
+ }
+
+
+ /* Resets font provider transient */
+ public function reset_transients() {
+
+ return delete_transient($this->transient_id);
+
+ }
+
+
+ /* Outputs HTML for fonts list */
+ public function list_fonts($sortby = false) {
+
+ if ( headway_post('sortby') )
+ $sortby = headway_post('sortby');
+
+ if ( !($fonts = $this->retrieve_fonts($sortby)) ) {
+ echo '<p class="error">Unable to retrieve fonts at this time.</p>';
+ return;
+ }
+
+ /* Display possible error */
+ if ( isset($fonts['error']) ) {
+
+ echo '<p class="error">' . $fonts['error'] . '</p>';
+ return;
+
+ }
+
+ /* Output the fonts */
+ foreach ( $fonts as $font ) {
+
+ echo '
+ <li data-value="' . $font['id'] . '" style="font-family:' . $font['stack'] . ';" data-variants="' . esc_attr(json_encode(headway_get('variants', $font, array()))) . '">
+ <span class="font-family">' . $font['name'] . '</span>
+ <span class="font-preview-text">The quick brown fox jumps over the lazy dog.</span>
+
+ <span title="Use Font" class="use-font action"></span>
+ <span title="Preview Font" class="preview-font action"></span>
+ </li>
+ ';
+
+ }
+
+ return true;
+
+ }
+
+
+}
\ No newline at end of file
--- /dev/null
+<?php
+class HeadwayWebFontsLoader {
+
+
+ public static function init() {
+
+ add_action( 'wp', array( __CLASS__, 'enqueue_webfont_api_for_design_editor' ) );
+ add_action( 'headway_stylesheets', array( __CLASS__, 'google_fonts_stylesheet' ), 1 );
+
+ add_action( 'headway_visual_editor_save', array( __CLASS__, 'flush_cache' ) );
+ add_action( 'headway_switch_skin', array( __CLASS__, 'flush_cache' ) );
+ add_action( 'headway_db_upgrade', array( __CLASS__, 'flush_cache' ) );
+
+ }
+
+
+ /* Google Web Fonts */
+ public static function enqueue_webfont_api_for_design_editor() {
+
+ if ( ! HeadwayRoute::is_visual_editor_iframe( 'design' ) )
+ return;
+
+ wp_enqueue_script( 'webfont', headway_format_url_ssl( 'http:///ajax.googleapis.com/ajax/libs/webfont/1.4.7/webfont.js' ) );
+
+ }
+
+
+ public static function google_check_if_should_load() {
+
+ $webfonts_in_use = self::get_fonts_in_use();
+
+ if ( !is_array($webfonts_in_use) || count($webfonts_in_use) == 0 || !isset($webfonts_in_use['google']) )
+ return false;
+
+ return $webfonts_in_use;
+
+ }
+
+
+ public static function google_fonts_stylesheet() {
+
+ $webfonts_in_use = self::google_check_if_should_load();
+
+ if ( ! $webfonts_in_use || !is_array(headway_get('google', $webfonts_in_use)) )
+ return;
+
+ foreach ( $webfonts_in_use['google'] as $key => $font )
+ $webfonts_in_use['google'][ $key ] = urlencode( $font );
+
+ $stylesheet_url = '//fonts.googleapis.com/css?family=' . implode( '|', $webfonts_in_use['google'] );
+
+ echo "<link rel='stylesheet' id='headway-google-fonts' href='$stylesheet_url' type='text/css' media='all' />\n";
+
+ }
+ /* End Google Web Fonts */
+
+
+ public static function get_fonts_in_use() {
+
+ /* If cache exists then use it */
+ $cache = get_transient( 'hw_webfont_cache_template_' . HeadwayOption::$current_skin );
+
+ if ( is_array($cache) )
+ return $cache;
+
+ /* Build cache otherwise */
+ self::cache();
+
+ return get_transient( 'hw_webfont_cache_template_' . HeadwayOption::$current_skin );
+
+ }
+
+
+ public static function cache() {
+
+ $raw_webfonts = self::pluck_webfonts(HeadwayElementsData::get_all_elements());
+ $sorted_webfonts = array();
+
+ foreach ( $raw_webfonts as $webfont ) {
+
+ $fragments = explode('|', $webfont);
+
+ $sorted_webfonts[$fragments[0]][] = !empty($fragments[2]) ? $fragments[1] . ':' . $fragments[2] : $fragments[1]; /* $fragments[2] are the variants */
+ $sorted_webfonts[$fragments[0]] = array_unique($sorted_webfonts[$fragments[0]]);
+
+ }
+
+ return set_transient( 'hw_webfont_cache_template_' . HeadwayOption::$current_skin, $sorted_webfonts );
+
+ }
+
+
+ public static function pluck_webfonts($array) {
+
+ $web_fonts = array();
+
+ foreach ( $array as $key => $value ) {
+
+ /* If the value is an array, then loop this function to pluck the font values out of instances, states, etc */
+ if ( is_array($value) ) {
+
+ $web_fonts = array_merge($web_fonts, self::pluck_webfonts($value));
+
+ /* We've found a font family property. Now make sure that the font is a web font by checking for the | delimiter */
+ } else if ( $key === 'font-family' && strpos($value, '|') ) {
+
+ $web_fonts[] = $value;
+
+ }
+
+ }
+
+ return array_unique($web_fonts);
+
+ }
+
+
+ public static function flush_cache() {
+
+ return delete_transient( 'hw_webfont_cache_template_' . HeadwayOption::$current_skin );
+
+ }
+
+
+}
\ No newline at end of file
--- /dev/null
+msgid ""
+msgstr ""
+"Project-Id-Version: Headway Base v3.4.4\n"
+"Report-Msgid-Bugs-To: \n"
+"POT-Creation-Date: \n"
+"PO-Revision-Date: 2013-04-04 11:42+0100\n"
+"Last-Translator: Mikkel Breum <mikkel@wpkitchen.com>\n"
+"Language-Team: \n"
+"MIME-Version: 1.0\n"
+"Content-Type: text/plain; charset=UTF-8\n"
+"Content-Transfer-Encoding: 8bit\n"
+"Plural-Forms: nplurals=2; plural=n != 1;\n"
+"X-Generator: CSL v1.x\n"
+"X-Poedit-SourceCharset: utf-8\n"
+"X-Poedit-KeywordsList: __;_e;__ngettext:1,2;_n:1,2;__ngettext_noop:1,2;"
+"_n_noop:1,2;_c,_nc:4c,1,2;_x:1,2c;_ex:1,2c;_nx:4c,1,2;_nx_noop:4c,1,2\n"
+"X-Poedit-Basepath: ../../\n"
+"X-Textdomain-Support: yes\n"
+"Language: da_DK\n"
+"X-Poedit-SearchPath-0: .\n"
+
+# @ headway
+#: library/admin/admin.php:353
+#, php-format
+msgid ""
+"<div class=\"headway-update-backup-reminder alert-red alert\"><h3>Remember!</"
+"h3><p>Please backup before updating. Headway Themes recommends <a href=\"%s"
+"\" target=\"_blank\"><strong>BackupBuddy</strong></a> for all backup and "
+"migration needs.</div>"
+msgstr ""
+"<div class=\"headway-update-backup-reminder alert-red alert\"><h3>Husk!</"
+"h3><p>Tag en backup før du opdaterer. Headway Themes anbefaler <a href=\"%s"
+"\" target=\"_blank\"><strong>BackupBuddy</strong></a> når du skal tage "
+"backup eller flytte server.</div>"
+
+# @ headway
+#: library/api/api-admin-meta-box.php:12
+msgid "Error: The meta box class being registered does not exist."
+msgstr "Fejl: Meta box klassen kan ikke registreres, da den ikke findes."
+
+# @ headway
+#: library/api/api-block.php:127
+msgid "Error: The block options class being registered does not exist."
+msgstr "Fejl: Block options klassen kan ikke registreres, da den ikke findes."
+
+# @ headway
+#: library/api/api-box.php:12
+msgid "Error: The box class being registered does not exist."
+msgstr "Fejl: Box klassen kan ikke registreres, da den ikke findes."
+
+# @ headway
+#: library/api/api-element.php:125
+msgid "Error: Arguments must be an array for this element."
+msgstr "Fejl: Argumenterne for dette element skal være et Array."
+
+# @ headway
+#: library/api/api-element.php:150
+msgid "Error: An ID is required for this element."
+msgstr "Fejl: Et ID er krævet for dette element."
+
+# @ headway
+#: library/api/api-element.php:153
+msgid "Error: A name is required for this element."
+msgstr "Fejl: Et navn er krævet for dette element."
+
+# @ headway
+#: library/api/api-element.php:156
+msgid "Error: A group is required for this element."
+msgstr "Fejl: En gruppe er krævet for dette element."
+
+# @ headway
+#: library/api/api-element.php:159
+msgid "Error: A CSS selector is required for this element."
+msgstr "Fejl: En CSS selector er krævet for dette element."
+
+# @ headway
+#: library/api/api-element.php:162
+msgid "Error: Properties are required for this element."
+msgstr "Fejl: Egenskaber er krævet for dette element."
+
+# @ headway
+#: library/api/api-element.php:201
+msgid "Error: Arguments must be an array for this element instance."
+msgstr "Fejl: Argumenterne for dette element skal være et Array."
+
+# @ headway
+#: library/api/api-element.php:217
+msgid "Error: An ID is required for this element instance."
+msgstr "Fejl: Et ID er krævet for dette element."
+
+# @ headway
+#: library/api/api-element.php:220
+msgid "Error: A name is required for this element instance."
+msgstr "Fejl: Et navn er krævet for dette element."
+
+# @ headway
+#: library/api/api-element.php:223
+msgid "Error: A group is required for this element instance."
+msgstr "Fejl: En gruppe er krævet for dette element."
+
+# @ headway
+#: library/api/api-element.php:226
+msgid "Error: A parent element is required for this element instance."
+msgstr "Fejl: Et forældre-element er krævet for dette element."
+
+# @ headway
+#: library/api/api-element.php:229
+msgid "Error: A CSS selector is required for this element instance."
+msgstr "Fejl: En CSS selector er krævet for dette element."
+
+# @ headway
+#: library/api/api-element.php:239
+msgid "Error: The element specified does not support instances."
+msgstr "Fejl: Det specificerede element understøtter ikke instantiering."
+
+# @ headway
+#: library/api/api-element.php:265
+msgid "Error: The group being registered already exists."
+msgstr "Fejl: Gruppen findes allerede."
+
+# @ headway
+#: library/api/api-element.php:281
+msgid "Error: Arguments must be an array for deregistering this element."
+msgstr ""
+"Fejl: Argumenterne for afregistrering af dette element skal være et array."
+
+# @ headway
+#: library/api/api-element.php:293
+msgid "Error: A group is required for deregistering this element."
+msgstr "Fejl: En gruppe er krævet for afregistrering af dette element."
+
+# @ headway
+#: library/api/api-element.php:296
+msgid "Error: An ID is required for deregistering this element."
+msgstr "Fejl: Et ID er krævet for afregistrering af dette element."
+
+# @ headway
+#: library/api/api-element.php:318
+msgid ""
+"Error: Arguments must be an array for deregistering this element instance."
+msgstr ""
+"Fejl: Argumenterne for afregistrering af dette element skal være et array."
+
+# @ headway
+#: library/api/api-element.php:331
+msgid "Error: A group is required for deregistering this element instance."
+msgstr "Fejl: En gruppe er krævet for afregistrering af dette element."
+
+# @ headway
+#: library/api/api-element.php:334
+msgid ""
+"Error: An instance ID is required for deregistering this element instance."
+msgstr "Fejl: Et ID er krævet for afregistrering af dette element."
+
+# @ headway
+#: library/api/api-element.php:337
+msgid "Error: An element is required for deregistering this element instance."
+msgstr "Fejl: Et element er krævet for afregistrering af dette element."
+
+# @ headway
+#: library/api/api-element.php:357
+msgid "Error: The group being deregistered does not exist."
+msgstr "Fejl: Gruppen kan ikke afregistreres, da den ikke findes."
+
+# @ headway
+#: library/api/api-panel.php:12
+msgid "Error: The panel class being registered does not exist."
+msgstr "Fejl: Panel klassen kan ikke registreres, da den ikke findes."
+
+# @ headway
+#: library/api/api-updater.php:168
+#, php-format
+msgid ""
+"<div id=\"update-nag\">%s %s is now available, you're running %s! <a href="
+"\"%s\">Click here to update</a> or <a href=\"%s\" target=\"_blank\">learn "
+"more</a> about the update.</div>"
+msgstr ""
+"<div id=\"update-nag\">%s %s er nu tilgængelig, du kører %s! <a href=\"%s"
+"\">Klik her for at opdatere</a> eller <a href=\"%s\" target=\"_blank\">find "
+"ud af mere</a> om opdateringen.</div>"
+
+# @ headway
+#: library/api/api-updater.php:173
+#, php-format
+msgid ""
+"<div id=\"update-nag\">%s %s is now available, you're running %s! Go to the "
+"<a href=\"%s\" target=\"_blank\">Headway Dashboard</a> to download the "
+"latest version or <a href=\"%s\" target=\"_blank\">learn more</a> about the "
+"update.</div>"
+msgstr ""
+"<div id=\"update-nag\">%s %s er nu tilgængelig, du kører %s! Gå til <a href="
+"\"%s\" target=\"_blank\">Headway Dashboard'et</a> for at downloade den "
+"seneste versioneller <a href=\"%s\" target=\"_blank\">find ud af mere</a> om "
+"opdateringen.</div>"
+
+# @ headway
+#: library/api/api-updater.php:185
+#, php-format
+msgid ""
+"<div id=\"update-nag\">%s %s is now available, you're running %s! Your "
+"Headway license has expired. Please visit the <a href=\"%s\">Headway "
+"Dashboard</a> to renew your license so you can continue to receive updates.</"
+"div>"
+msgstr ""
+"<div id=\"update-nag\">%s %s er nu tilgængelig, du kører %s! Din Headway "
+"licens er udløbet. Gå venligst til <a href=\"%s\">Headway Dashboard'et</a> "
+"for at forny din licens så du fortsat kan modtage opdateringer.</div>"
+
+# @ headway
+#: library/api/api-updater.php:190
+#, php-format
+msgid ""
+"<div id=\"update-nag\">%s %s is now available, you're running %s! You will "
+"not be able to update until you enter a valid license key on the <a href=\"%s"
+"\">Headway Options</a> panel.</div>"
+msgstr ""
+"<div id=\"update-nag\">%s %s er nu tilgængelig, du kører %s! Du kan ikke "
+"opdaterer før du indtaster en godkendt licenskode under <a href=\"%s"
+"\">Headway Indstillingspanelet</a>.</div>"
+
+# @ headway
+#: library/blocks/blocks.php:80
+msgid "The block class being registered does not exist."
+msgstr "Block klassen kan ikke registreres, da den ikke findes."
+
+# @ headway
+#: library/blocks/blocks.php:636
+msgid "The Headway blocks array does not exist."
+msgstr "Headway blocks array'et eksisterer ikke."
+
+# @ headway
+#: library/blocks/breadcrumbs/breadcrumbs.php:51
+msgid "Home"
+msgstr "Hjem"
+
+# @ headway
+#: library/blocks/breadcrumbs/breadcrumbs.php:94
+msgid "Search Results For:"
+msgstr "Søgeresutat for:"
+
+# @ headway
+#: library/blocks/breadcrumbs/breadcrumbs.php:103
+msgid "Author Archives:"
+msgstr "Forfatterarkiv:"
+
+# @ headway
+#: library/blocks/breadcrumbs/breadcrumbs.php:110
+msgid "Tag Archives:"
+msgstr "Emnearkiv:"
+
+# @ headway
+#: library/blocks/breadcrumbs/breadcrumbs.php:117
+msgid "Archives:"
+msgstr "Arkiv:"
+
+# @ headway
+#: library/blocks/breadcrumbs/breadcrumbs.php:124
+msgid "Whoops! Page Not Found..."
+msgstr "Siden findes ikke."
+
+# @ headway
+#: library/blocks/breadcrumbs/breadcrumbs.php:132
+msgid "You Are Here:"
+msgstr "Du er her:"
+
+# @ headway
+#: library/blocks/content/comments.php:28
+msgid ""
+"This post is password protected. Please enter the password to view the "
+"comments."
+msgstr ""
+"Dette indlæg er kodeordsbeskyttet. Indtast venligst koden for at se "
+"kommentarene."
+
+# @ headway
+#: library/blocks/content/comments.php:44
+msgid "No Responses"
+msgstr "Ingen svar"
+
+# @ headway
+#: library/blocks/content/comments.php:44
+msgid "One Response"
+msgstr "Et svar"
+
+# @ headway
+#: library/blocks/content/comments.php:44
+msgid "% Responses"
+msgstr "%s svar"
+
+# @ headway
+#: library/blocks/content/comments.php:45
+msgid "to"
+msgstr "til"
+
+# @ headway
+#: library/blocks/content/comments.php:68
+msgid "Sorry, comments are closed for this post."
+msgstr "Der kan ikke kommenteres på dette indlæg."
+
+# @ headway
+#: library/blocks/content/content-display.php:159
+#, php-format
+msgid "Daily Archives: %s"
+msgstr "dagsarkiv: %s"
+
+# @ headway
+#: library/blocks/content/content-display.php:162
+#, php-format
+msgid "Monthly Archives: %s"
+msgstr "Månedsarkiv: %s"
+
+# @ headway
+#: library/blocks/content/content-display.php:165
+#, php-format
+msgid "Yearly Archives: %s"
+msgstr "Årsarkiv: %s"
+
+# @ headway
+#: library/blocks/content/content-display.php:168
+msgid "Blog Archives"
+msgstr "Blogarkiv:"
+
+# @ headway
+#: library/blocks/content/content-display.php:178
+#, php-format
+msgid "Category Archives: %s"
+msgstr "Kategoriarkiv: %s"
+
+# @ headway
+#: library/blocks/content/content-display.php:196
+#: library/blocks/content/content-display.php:199
+#, php-format
+msgid "Author Archives: %s"
+msgstr "Forfatterarkiv: %s"
+
+# @ headway
+#: library/blocks/content/content-display.php:209
+#, php-format
+msgid "Search Results for: %s"
+msgstr "Søgeresultat for: %s"
+
+# @ headway
+#: library/blocks/content/content-display.php:218
+#, php-format
+msgid "Tag Archives: %s"
+msgstr "Emnearkiv: %s"
+
+# @ headway
+#: library/blocks/content/content-display.php:383
+#, php-format
+msgid "%s"
+msgstr "%s"
+
+# @ headway
+#: library/blocks/content/content-display.php:509
+msgid "Pages:"
+msgstr "Sider:"
+
+# @ headway
+#: library/blocks/content/content-display.php:545
+msgid "Whoops! Page Not Found"
+msgstr "Siden blev ikke fundet"
+
+# @ headway
+#: library/blocks/content/content-display.php:553
+msgid ""
+"<p>Don't fret, you didn't do anything wrong. It appears that the page you "
+"are looking for does not exist or has been moved elsewhere.</p>"
+msgstr ""
+"<p>Det ser ud til, at siden du leder efter ikke findes, eller er blevet "
+"flyttet.</p>"
+
+# @ headway
+#: library/blocks/content/content-display.php:555
+#, php-format
+msgid ""
+"<p>If you keep ending up here, please head back to our <a href=\"%s"
+"\">homepage</a> or try the search form below.</p>"
+msgstr ""
+"<p>Hvis du hele tiden ender her, kan du gå tilbahe til <a href=\"%s"
+"\">forsiden</a> eller benytte søgefeltet nedenfor.</p>"
+
+# @ headway
+#: library/blocks/content/content-display.php:621
+msgid "Discard Reply"
+msgstr "Slet svar"
+
+# @ headway
+#: library/blocks/content/content-display.php:647
+msgid "<span class=\"meta-nav\">←</span> Older posts"
+msgstr "<span class=\"meta-nav\">←</span> Ældre indlæg"
+
+# @ headway
+#: library/blocks/content/content-display.php:648
+msgid "Newer posts <span class=\"meta-nav\">→</span>"
+msgstr "Nyere indlæg <span class=\"meta-nav\">→</span>"
+
+# @ headway
+#: library/blocks/content/content-display.php:800
+#, php-format
+msgid "%s – Comments"
+msgstr "%s – Kommentarer"
+
+# @ headway
+#: library/blocks/content/content-display.php:809
+#, php-format
+msgid "Respond to %s"
+msgstr "Svar til %s"
+
+# @ headway
+#: library/blocks/content/content-display.php:816
+#, php-format
+msgid "View all posts by %s"
+msgstr "Se alle indlæg af %s"
+
+# @ headway
+#: library/blocks/content/content-display.php:826
+msgid "<span class=\"tag-links\"><span>Tags:</span> "
+msgstr "<span class=\"tag-links\"><span>Emner:</span> "
+
+# @ headway
+#: library/blocks/footer/footer.php:118
+msgid "Administration Panel"
+msgstr "Administrationspanel"
+
+# @ headway
+#: library/blocks/footer/footer.php:120
+msgid "Administration Login"
+msgstr "Administrationslogin"
+
+# @ headway
+#: library/blocks/footer/footer.php:141
+msgid "Powered by Headway, the "
+msgstr "Powered by Headway, the "
+
+# @ headway
+#: library/blocks/footer/footer.php:153
+msgid "Copyright"
+msgstr "Copyright"
+
+# @ headway
+#: library/blocks/footer/footer.php:169
+msgid "Go To Top"
+msgstr "Gå til toppen"
+
+# @ headway
+#: library/blocks/footer/footer.php:191
+msgid "View Full Site"
+msgstr "Se desktop version"
+
+# @ headway
+#: library/blocks/footer/footer.php:198
+msgid "View Mobile Site"
+msgstr "Se mobil version"
+
+# @ headway
+#: library/common/compiler.php:336
+msgid ""
+"There was an error while Headway tried to compile the LESS CSS. Full Error: "
+msgstr ""
+"Der skete en fejl når HEadWay forsøgte at kompilere LESS CSS'en. Fejlen var:"
+
+# @ headway
+#: library/common/functions.php:756
+msgid "Type to search, then press enter"
+msgstr "Skriv og tryk retur for at søge"
+
+# @ headway
+#: library/common/functions.php:784 library/common/functions.php:786
+msgid "Search"
+msgstr "Søg"
+
+# @ headway
+#: library/data/data-elements.php:65 library/data/data-elements.php:92
+#: library/data/data-elements.php:173 library/data/data-elements.php:204
+#: library/data/data-elements.php:233 library/data/data-elements.php:257
+msgid "The element ID is not registered."
+msgstr "Dette element ID er ikke registreret."
+
+# @ headway
+#: library/display/grid-renderer.php:2
+msgid "No Content to Display"
+msgstr "Der er intet indhold at vise"
+
+# @ headway
+#: library/display/grid-renderer.php:2
+#, php-format
+msgid ""
+"<p>There are no blocks to display. Add some by going to the <a href=\"%s"
+"\">Headway Grid</a>!</p>"
+msgstr ""
+"<p>Der er ingen blokke at vise. Tilføj nogle ved at gå til <a href=\"%s"
+"\">Headway Grid'et</a>!</p>"
+
+# @ headway
+#: library/display/grid-renderer.php:2
+#, php-format
+msgid ""
+"<p>There is no content to display. Please notify the site administrator or "
+"<a href=\"%s\">login</a>.</p>"
+msgstr "<p>Der er intet indhold at vise. <a href=\"%s\">Login</a>.</p>"
+
+# @ headway
+#: library/fonts/traditional-fonts.php:127
+msgid ""
+"To register a font, the argument array must include an \"id\", \"stack\", "
+"and \"name\"."
+msgstr ""
+"For at registrere en font, skal argument array'et indeholde \"id\", \"stack"
+"\", og \"name\"."
+
+# @ headway
+#: library/visual-editor/panels/design/panel-default-elements.php:32
+msgid "Please select a default element to the left."
+msgstr "Vælg venligst et standard element til venstre."
+
+# @ headway
+#: library/visual-editor/panels/design/panel-editor.php:115
+msgid "Please select an element to the left."
+msgstr "Vælg venligst et element til venstre."
--- /dev/null
+msgid ""
+msgstr ""
+"Project-Id-Version: Headway Base v3.7.6\n"
+"Report-Msgid-Bugs-To: \n"
+"POT-Creation-Date: \n"
+"PO-Revision-Date: 2014-07-13 00:14+0100\n"
+"Last-Translator: Carsten Dohmann <info@headway-support-deutsch.de>\n"
+"Language-Team: www.headway-support-deutsch.de <info@headway-support-deutsch."
+"de>\n"
+"MIME-Version: 1.0\n"
+"Content-Type: text/plain; charset=UTF-8\n"
+"Content-Transfer-Encoding: 8bit\n"
+"Plural-Forms: nplurals=2; plural=n != 1;\n"
+"X-Generator: Poedit 1.6.6\n"
+"X-Poedit-SourceCharset: UTF-8\n"
+"X-Poedit-KeywordsList: __;_e;__ngettext:1,2;_n:1,2;__ngettext_noop:1,2;"
+"_n_noop:1,2;_c,_nc:4c,1,2;_x:1,2c;_ex:1,2c;_nx:4c,1,2;_nx_noop:4c,1,2\n"
+"X-Poedit-Basepath: ../../\n"
+"X-Textdomain-Support: yes\n"
+"Language: de_DE\n"
+"X-Poedit-SearchPath-0: .\n"
+
+# @ headway
+#: library/admin/admin.php:145 library/admin/admin.php:182
+msgid "Please contact Headway Support if this error persists."
+msgstr ""
+"Bitte melden Sie sich beim Headway Support, falls der Fehler weiterhin "
+"erscheint."
+
+# @ headway
+#: library/admin/admin.php:169
+msgid "License saved and activated."
+msgstr "Lizenz gespeichert und aktiviert."
+
+# @ headway
+#: library/admin/admin.php:173
+msgid ""
+"\n"
+"\t\t\t\t\t<strong>Whoops!</strong> Could not activate license. Please check "
+"that you have entered your license correctly and that it has not expired."
+"<br /><br />\n"
+"\t\t\t\t\tMake sure you copied your license correctly from the <a href="
+"\"http://headwaythemes.com/dashboard\" target=\"_blank\">Headway Dashboard</"
+"a>.\n"
+"\t\t\t\t"
+msgstr ""
+"\n"
+"\n"
+"\\\t\\\t\\\t\\\t\\\t<strong>Uuups!</strong> Lizenz konnte nicht aktiviert "
+"werden. Bitte prüfen Sie, ob Sie ihre Lizenz richtig eingegeben haben und "
+"diese nicht abgelaufen ist.<br /><br />\n"
+"\n"
+"\\\t\\\t\\\t\\\t\\\tPrüfen Sie ob Sie Ihre Lizenz richtig kopiert haben vom "
+"<a href=\"http://headwaythemes.com/dashboard\" target=\"_blank\">Headway "
+"Dashboard</a>.\n"
+"\n"
+"\\\t\\\t\\\t\\\t"
+
+# @ default
+#: library/admin/pages/options.php:49
+msgid "Deactivate License"
+msgstr "Lizenz deaktivieren."
+
+# @ default
+#: library/admin/pages/options.php:50
+msgid "Active"
+msgstr "Aktiv"
+
+# @ default
+#: library/admin/pages/options.php:52 library/admin/pages/options.php:55
+msgid "Save & Activate License"
+msgstr "Speichern & Lizenz aktivieren."
+
+# @ headway
+#: library/admin/pages/whats-new.php:2
+#, php-format
+msgid "Welcome to Headway %s"
+msgstr "Willkommen zu Headway %s"
+
+# @ headway
+#: library/admin/pages/whats-new.php:4
+msgid ""
+"Thank you for updating! Headway 3.7 has many improvements we think you'll "
+"enjoy."
+msgstr ""
+"Vielen Dank fürs aktualisieren! Headway 3.7 beinhaltet viele Verbesserungen, "
+"die Sie lieben werden."
+
+# @ headway
+#: library/api/api-admin-meta-box.php:12
+msgid "Error: The meta box class being registered does not exist."
+msgstr "Fehler: Die zu registrierende Meta Box Klasse existiert nicht."
+
+# @ headway
+#: library/api/api-block.php:134
+msgid "Error: The block options class being registered does not exist."
+msgstr "Fehler: Die zu registrierende Block Optionen Klasse existiert nicht."
+
+# @ headway
+#: library/api/api-box.php:12
+msgid "Error: The box class being registered does not exist."
+msgstr "Fehler: Die zu registrierende Box Klasse existiert nicht."
+
+# @ headway
+#: library/api/api-element.php:110
+msgid "Error: Arguments must be an array for this element."
+msgstr "Fehler: Argumente müssen in einem Array für dieses Element vorliegen."
+
+# @ headway
+#: library/api/api-element.php:134
+msgid "Error: An ID is required for this element."
+msgstr "Fehler: Eine ID muss für dieses Element vergeben werden."
+
+# @ headway
+#: library/api/api-element.php:137
+msgid "Error: A name is required for this element."
+msgstr "Fehler: Ein Name muss für dieses Element vergeben werden."
+
+# @ headway
+#: library/api/api-element.php:140
+msgid "Error: A group is required for this element."
+msgstr "Fehler: Eine Gruppe ist für dieses Element notwendig."
+
+# @ headway
+#: library/api/api-element.php:143
+msgid "Error: A CSS selector is required for this element."
+msgstr "Fehler: Eine CSS Auswahl (Selektor) ist für dieses Element notwendig."
+
+# @ headway
+#: library/api/api-element.php:146
+msgid "Error: Properties are required for this element."
+msgstr "Fehler: Einstellungen sind für dieses Element notwendig."
+
+# @ headway
+#: library/api/api-element.php:189
+msgid "Error: Arguments must be an array for this element instance."
+msgstr ""
+"Fehler: Argumente müssen in einem Array für diese Element-Instanz vorliegen."
+
+# @ headway
+#: library/api/api-element.php:205
+msgid "Error: An ID is required for this element instance."
+msgstr "Fehler: Eine ID muss für diese Element Instanz vorliegen."
+
+# @ headway
+#: library/api/api-element.php:208
+msgid "Error: A name is required for this element instance."
+msgstr "Fehler: Eine Name muss für diese Element Instanz vorliegen."
+
+# @ headway
+#: library/api/api-element.php:211
+msgid "Error: A group is required for this element instance."
+msgstr "Fehler: Eine Gruppe muss für diese Element Instanz vorliegen."
+
+# @ headway
+#: library/api/api-element.php:214
+msgid "Error: A parent element is required for this element instance."
+msgstr "Fehler: Ein Eltern-Element muss für diese Element Instanz vorliegen."
+
+# @ headway
+#: library/api/api-element.php:217
+msgid "Error: A CSS selector is required for this element instance."
+msgstr ""
+"Fehler: Eine CSS Auswahl (Selektor) muss für diese Element Instanz vorliegen."
+
+# @ headway
+#: library/api/api-element.php:252
+msgid "Error: The group being registered already exists."
+msgstr "Fehler: Die zu registrierende Gruppe existiert bereits."
+
+# @ headway
+#: library/api/api-panel.php:12
+msgid "Error: The panel class being registered does not exist."
+msgstr "Fehler: Die zu registrierende Panel Klasse existiert nicht."
+
+# @ headway
+#: library/blocks/blocks.php:87
+msgid "The block class being registered does not exist."
+msgstr "Die zu registrierende Block Klasse existiert nicht."
+
+# @ headway
+#: library/blocks/blocks.php:782
+msgid "The Headway blocks array does not exist."
+msgstr "Der Headway Blocks Array existiert nicht."
+
+# @ headway
+#: library/blocks/breadcrumbs/breadcrumbs.php:61
+msgid "Home"
+msgstr "Start"
+
+# @ headway
+#: library/blocks/breadcrumbs/breadcrumbs.php:104
+msgid "Search Results For:"
+msgstr "Suchergebnisse für:"
+
+# @ headway
+#: library/blocks/breadcrumbs/breadcrumbs.php:113
+msgid "Author Archives:"
+msgstr "Autoren-Archiv:"
+
+# @ headway
+#: library/blocks/breadcrumbs/breadcrumbs.php:120
+msgid "Tag Archives:"
+msgstr "Tag-Archiv:"
+
+# @ headway
+#: library/blocks/breadcrumbs/breadcrumbs.php:127
+msgid "Archives:"
+msgstr "Archiv:"
+
+# @ headway
+#: library/blocks/breadcrumbs/breadcrumbs.php:134
+msgid "Whoops! Page Not Found..."
+msgstr "Uuups! Die Seite wurde nicht gefunden..."
+
+# @ headway
+#: library/blocks/breadcrumbs/breadcrumbs.php:142
+msgid "You Are Here:"
+msgstr "Sie befinden sich hier:"
+
+# @ headway
+#: library/blocks/content/comments-template.php:54
+msgid "Sorry, comments are closed for this post."
+msgstr "Entschuldigung, Kommentare zu diesem Artikel sind nicht möglich."
+
+# @ headway
+#: library/blocks/content/comments-template.php:68
+msgid ""
+"This post is password protected. Please enter the password to view the "
+"comments."
+msgstr ""
+"Dieser Artikel ist passwortgeschützt. Bitte geben Sie das Passwort ein, um "
+"die Kommentare sehen zu können."
+
+# @ headway
+#: library/blocks/content/content-display.php:123
+#: library/blocks/listings/content-display.php:69
+msgid "<p>Sorry, there was no content that matched your search.</p>"
+msgstr ""
+"<p>Entschuldigung, es wurde kein Inhalt gefunden, der mit Ihrer Suchanfrage "
+"übereinstimmt.</p>"
+
+# @ headway
+#: library/blocks/content/content-display.php:209
+#, php-format
+msgid "Daily Archives: %s"
+msgstr "Tages-Archive: %s"
+
+# @ headway
+#: library/blocks/content/content-display.php:212
+#, php-format
+msgid "Monthly Archives: %s"
+msgstr "Monats-Archive: %s"
+
+# @ headway
+#: library/blocks/content/content-display.php:215
+#, php-format
+msgid "Yearly Archives: %s"
+msgstr "Jahres-Archive: %s"
+
+# @ headway
+#: library/blocks/content/content-display.php:218
+msgid "Blog Archives"
+msgstr "Blog-Archive"
+
+# @ headway
+#: library/blocks/content/content-display.php:228
+#, php-format
+msgid "Category Archives: %s"
+msgstr "Kategorie-Archive: %s"
+
+# @ headway
+#: library/blocks/content/content-display.php:246
+#: library/blocks/content/content-display.php:249
+#, php-format
+msgid "Author Archives: %s"
+msgstr "Autoren-Archive: %s"
+
+# @ headway
+#: library/blocks/content/content-display.php:259
+#, php-format
+msgid "Search Results for: %s"
+msgstr "Suchergebnisse zu: %s"
+
+# @ headway
+#: library/blocks/content/content-display.php:268
+#, php-format
+msgid "Tag Archives: %s"
+msgstr "Schlagworte-Archive: %s"
+
+# @ headway
+#: library/blocks/content/content-display.php:436
+#: library/blocks/listings/content-display.php:197
+#, php-format
+msgid "%s"
+msgstr "%s"
+
+# @ headway
+#: library/blocks/content/content-display.php:565
+msgid "Pages:"
+msgstr "Seiten:"
+
+# @ headway
+#: library/blocks/content/content-display.php:600
+msgid "Whoops! Page Not Found"
+msgstr "Uuups! Die Seite wurde nicht gefunden."
+
+# @ headway
+#: library/blocks/content/content-display.php:608
+msgid ""
+"<p>Don't fret, you didn't do anything wrong. It appears that the page you "
+"are looking for does not exist or has been moved elsewhere.</p>"
+msgstr ""
+"<p>Nicht verzweifeln, Sie haben nichts falsch gemacht. Es scheint, als würde "
+"die Seite, die Sie suchen, nicht existieren oder als wäre Sie woanders hin "
+"verschoben worden.</p>"
+
+# @ headway
+#: library/blocks/content/content-display.php:610
+#, php-format
+msgid ""
+"<p>If you keep ending up here, please head back to our <a href=\"%s"
+"\">homepage</a> or try the search form below.</p>"
+msgstr ""
+"<p>Wenn Sie immer wieder hier landen, gehen Sie bitte zurück zu unserer <a "
+"href=\"%s\">Homepage</a> oder versuchen Sie es mit dem Suchformular unten.</"
+"p>"
+
+# @ headway
+#: library/blocks/content/content-display.php:685
+msgid "Discard Reply"
+msgstr "Antwort verwerfen"
+
+# @ headway
+#: library/blocks/content/content-display.php:711
+msgid "<span class=\"meta-nav\">←</span> Older posts"
+msgstr "<span class=\"meta-nav\">←</span> Ältere Artikel"
+
+# @ headway
+#: library/blocks/content/content-display.php:712
+msgid "Newer posts <span class=\"meta-nav\">→</span>"
+msgstr "Neuere Artikel <span class=\"meta-nav\">→</span>"
+
+# @ headway
+#: library/blocks/content/content-display.php:866
+#, php-format
+msgid "%s – Comments"
+msgstr "%s – Kommentare"
+
+# @ headway
+#: library/blocks/content/content-display.php:875
+#, php-format
+msgid "Respond to %s"
+msgstr "Antworten zu %s"
+
+# @ headway
+#: library/blocks/content/content-display.php:882
+#, php-format
+msgid "View all posts by %s"
+msgstr "Anzeigen aller Artikel von %s"
+
+# @ headway
+#: library/blocks/footer/footer.php:120
+msgid "Administration Panel"
+msgstr "Administrations Bereich"
+
+# @ headway
+#: library/blocks/footer/footer.php:122
+msgid "Administration Login"
+msgstr "Administrator Anmeldung"
+
+# @ headway
+#: library/blocks/footer/footer.php:143
+msgid "Powered by Headway, the "
+msgstr "Erstellt mit Headway, dem"
+
+# @ headway
+#: library/blocks/footer/footer.php:155
+msgid "Copyright"
+msgstr "Copyright"
+
+# @ headway
+#: library/blocks/footer/footer.php:171
+msgid "Go To Top"
+msgstr "Nach oben"
+
+# @ headway
+#: library/blocks/footer/footer.php:193
+msgid "View Full Site"
+msgstr "Zur Desktop-Ansicht wechseln"
+
+# @ headway
+#: library/blocks/footer/footer.php:200
+msgid "View Mobile Site"
+msgstr "Zur mobilen Seite wechseln"
+
+# @ headway
+#: library/blocks/navigation/navigation.php:228
+msgid "Navigation"
+msgstr "Navigation"
+
+# @ default
+#: library/blocks/pin-board/pin-board.php:554
+msgid "« Previous Page"
+msgstr "« Vorherige Seite"
+
+# @ headway
+#: library/common/compiler.php:358
+msgid ""
+"There was an error while Headway tried to compile the LESS CSS. Full Error: "
+msgstr ""
+"Es ist ein Fehler aufgetreten, während Headway versucht hat, das LESS CSS zu "
+"kompilieren. Vollständiger Fehler: "
+
+# @ headway
+#: library/common/functions.php:721
+msgid "Type to search, then press enter"
+msgstr "Suchbegriff eingeben, danach Enter drücken"
+
+# @ headway
+#: library/common/functions.php:749 library/common/functions.php:751
+msgid "Search"
+msgstr "Suche"
+
+# @ headway
+#: library/common/image-resizer.php:57
+msgid "Error: Invalid image URL or size inputs"
+msgstr "Fehler: Falsche Bild-URL oder Größen Eingabe"
+
+# @ headway
+#: library/common/image-resizer.php:81
+msgid "Error: Image not local"
+msgstr "Fehler: Kein lokales Bild"
+
+# @ headway
+#: library/common/image-resizer.php:88
+msgid "Error: Image does not exist or not accessible"
+msgstr "Fehler: Bild ist nicht vorhanden oder nicht erreichbar"
+
+# @ headway
+#: library/common/image-resizer.php:113
+msgid "Error: Cannot resize, check if $upscale is enabled"
+msgstr ""
+"Fehler: Größe kann nicht geändert werden, prüfen Sie ob $upscale aktiviert "
+"ist"
+
+# @ headway
+#: library/common/image-resizer.php:125
+msgid "Error: Cannot resize image with WP_Image_Editor class"
+msgstr "Fehler: Größe kann nicht geändert werden mit WP_Image_Editor class"
+
+# @ headway
+#: library/common/image-resizer.php:133
+msgid "Error: Unable to save image with WP_Image_Editor class"
+msgstr "Fehler: Bild konnte nicht gespeichert werden mit WP_Image_Editor class"
+
+# @ woocommerce
+#: library/compatibility/woocommerce/woocommerce-breadcrumbs.php:14
+msgid "Search results for “"
+msgstr "Suchergebnisse für “"
+
+# @ hw_sf_wooc
+#: library/compatibility/woocommerce/woocommerce-breadcrumbs.php:79
+msgid "Products tagged “"
+msgstr "Produkte getagged “"
+
+# @ hw_sf_wooc
+#: library/compatibility/woocommerce/woocommerce-breadcrumbs.php:79
+msgctxt "endquote"
+msgid "”"
+msgstr "”"
+
+# @ headway
+#: library/display/layout-renderer.php:124
+msgid "No Content to Display"
+msgstr "Kein Inhalt zum Anzeigen"
+
+# @ headway
+#: library/display/layout-renderer.php:130
+#, php-format
+msgid ""
+"<p>There are no blocks to display. Add some by going to the <a href=\"%s"
+"\">Headway Grid</a>!</p>"
+msgstr ""
+"<p>Keine Blocks zum Anzeigen. Fügen Sie welche hinzu, indem Sie den <a href="
+"\"%s\">Headway Grid Mode</a> aufrufen!</p>"
+
+# @ headway
+#: library/display/layout-renderer.php:134
+#, php-format
+msgid ""
+"<p>There is no content to display. Please notify the site administrator or "
+"<a href=\"%s\">login</a>.</p>"
+msgstr ""
+"<p>Kein Inhalt zum Anzeigen. Bitte informieren Sie den Seiten-Administrator "
+"oder <a href=\"%s\">melden Sie sich an</a>.</p>"
+
+# @ headway
+#: library/fonts/traditional-fonts.php:127
+msgid ""
+"To register a font, the argument array must include an \"id\", \"stack\", "
+"and \"name\"."
+msgstr ""
+"Um eine Schrift zu registrieren, muss das Argument Array eine \"id\", \"stack"
+"\", und \"name\". enthalten."
+
+# @ default
+#: library/updater/theme-updater.php:66
+msgid ""
+"Before clicking OK to update, be sure that you have a backup of your website."
+msgstr ""
+"Bitte stellen Sie sicher, dass Sie ein Backup Ihrer Seite erstellt haben, "
+"bevor Sie auf OK zum aktualisieren klicken."
+
+# @ headway
+#: library/visual-editor/panels/design/property-inputs.php:151
+msgid "You have customized a property in this property group."
+msgstr "Sie haben eine Eigenschaft in dieser Eigenschafts-Gruppe angepasst."
+
+# @ headway
+#: library/visual-editor/panels/design/property-inputs.php:275
+msgid "You have customized this property."
+msgstr "Sie haben diese Eigenschaft angepasst."
--- /dev/null
+msgid ""
+msgstr ""
+"Project-Id-Version: Headway 3.6.x\n"
+"POT-Creation-Date: 2014-01-23 14:10-0600\n"
+"PO-Revision-Date: 2014-01-23 14:10-0600\n"
+"Last-Translator: Clay Griffiths <clay@headwaythemes.com>\n"
+"Language-Team: Headway Themes <hello@headwaythemes.com>\n"
+"Language: English\n"
+"MIME-Version: 1.0\n"
+"Content-Type: text/plain; charset=UTF-8\n"
+"Content-Transfer-Encoding: 8bit\n"
+"X-Generator: Poedit 1.5.4\n"
+"X-Poedit-KeywordsList: _;gettext;gettext_noop;__;_e\n"
+"X-Poedit-Basepath: .\n"
+"X-Poedit-SearchPath-0: /Users/clay/Dropbox/Web/dev/wp-content/themes/"
+"headway\n"
+
+#: /Users/clay/Dropbox/Web/dev/wp-content/themes/headway/library/admin/admin.php:146
+#: /Users/clay/Dropbox/Web/dev/wp-content/themes/headway/library/admin/admin.php:183
+msgid "Please contact Headway Support if this error persists."
+msgstr ""
+
+#: /Users/clay/Dropbox/Web/dev/wp-content/themes/headway/library/admin/admin.php:170
+msgid "License saved and activated."
+msgstr ""
+
+#: /Users/clay/Dropbox/Web/dev/wp-content/themes/headway/library/admin/admin.php:174
+msgid ""
+"\n"
+"\t\t\t\t\t<strong>Whoops!</strong> Could not activate license. Please check "
+"that you have entered your license correctly and that it has not expired."
+"<br /><br />\n"
+"\t\t\t\t\tMake sure you copied your license correctly from the <a href="
+"\"http://headwaythemes.com/dashboard\" target=\"_blank\">Headway Dashboard</"
+"a>.\n"
+"\t\t\t\t"
+msgstr ""
+
+#: /Users/clay/Dropbox/Web/dev/wp-content/themes/headway/library/admin/pages/options.php:49
+msgid "Deactivate License"
+msgstr ""
+
+#: /Users/clay/Dropbox/Web/dev/wp-content/themes/headway/library/admin/pages/options.php:50
+msgid "Active"
+msgstr ""
+
+#: /Users/clay/Dropbox/Web/dev/wp-content/themes/headway/library/admin/pages/options.php:52
+msgid "Activate License"
+msgstr ""
+
+#: /Users/clay/Dropbox/Web/dev/wp-content/themes/headway/library/admin/pages/options.php:55
+msgid "Save & Activate License"
+msgstr ""
+
+#: /Users/clay/Dropbox/Web/dev/wp-content/themes/headway/library/api/api-admin-meta-box.php:12
+msgid "Error: The meta box class being registered does not exist."
+msgstr ""
+
+#: /Users/clay/Dropbox/Web/dev/wp-content/themes/headway/library/api/api-block.php:135
+msgid "Error: The block options class being registered does not exist."
+msgstr ""
+
+#: /Users/clay/Dropbox/Web/dev/wp-content/themes/headway/library/api/api-box.php:12
+msgid "Error: The box class being registered does not exist."
+msgstr ""
+
+#: /Users/clay/Dropbox/Web/dev/wp-content/themes/headway/library/api/api-element.php:128
+msgid "Error: Arguments must be an array for this element."
+msgstr ""
+
+#: /Users/clay/Dropbox/Web/dev/wp-content/themes/headway/library/api/api-element.php:153
+msgid "Error: An ID is required for this element."
+msgstr ""
+
+#: /Users/clay/Dropbox/Web/dev/wp-content/themes/headway/library/api/api-element.php:156
+msgid "Error: A name is required for this element."
+msgstr ""
+
+#: /Users/clay/Dropbox/Web/dev/wp-content/themes/headway/library/api/api-element.php:159
+msgid "Error: A group is required for this element."
+msgstr ""
+
+#: /Users/clay/Dropbox/Web/dev/wp-content/themes/headway/library/api/api-element.php:162
+msgid "Error: A CSS selector is required for this element."
+msgstr ""
+
+#: /Users/clay/Dropbox/Web/dev/wp-content/themes/headway/library/api/api-element.php:165
+msgid "Error: Properties are required for this element."
+msgstr ""
+
+#: /Users/clay/Dropbox/Web/dev/wp-content/themes/headway/library/api/api-element.php:208
+msgid "Error: Arguments must be an array for this element instance."
+msgstr ""
+
+#: /Users/clay/Dropbox/Web/dev/wp-content/themes/headway/library/api/api-element.php:224
+msgid "Error: An ID is required for this element instance."
+msgstr ""
+
+#: /Users/clay/Dropbox/Web/dev/wp-content/themes/headway/library/api/api-element.php:227
+msgid "Error: A name is required for this element instance."
+msgstr ""
+
+#: /Users/clay/Dropbox/Web/dev/wp-content/themes/headway/library/api/api-element.php:230
+msgid "Error: A group is required for this element instance."
+msgstr ""
+
+#: /Users/clay/Dropbox/Web/dev/wp-content/themes/headway/library/api/api-element.php:233
+msgid "Error: A parent element is required for this element instance."
+msgstr ""
+
+#: /Users/clay/Dropbox/Web/dev/wp-content/themes/headway/library/api/api-element.php:236
+msgid "Error: A CSS selector is required for this element instance."
+msgstr ""
+
+#: /Users/clay/Dropbox/Web/dev/wp-content/themes/headway/library/api/api-element.php:271
+msgid "Error: The group being registered already exists."
+msgstr ""
+
+#: /Users/clay/Dropbox/Web/dev/wp-content/themes/headway/library/api/api-panel.php:12
+msgid "Error: The panel class being registered does not exist."
+msgstr ""
+
+#: /Users/clay/Dropbox/Web/dev/wp-content/themes/headway/library/blocks/blocks.php:85
+msgid "The block class being registered does not exist."
+msgstr ""
+
+#: /Users/clay/Dropbox/Web/dev/wp-content/themes/headway/library/blocks/blocks.php:759
+msgid "The Headway blocks array does not exist."
+msgstr ""
+
+#: /Users/clay/Dropbox/Web/dev/wp-content/themes/headway/library/blocks/breadcrumbs/breadcrumbs.php:55
+msgid "Home"
+msgstr ""
+
+#: /Users/clay/Dropbox/Web/dev/wp-content/themes/headway/library/blocks/breadcrumbs/breadcrumbs.php:98
+msgid "Search Results For:"
+msgstr ""
+
+#: /Users/clay/Dropbox/Web/dev/wp-content/themes/headway/library/blocks/breadcrumbs/breadcrumbs.php:107
+msgid "Author Archives:"
+msgstr ""
+
+#: /Users/clay/Dropbox/Web/dev/wp-content/themes/headway/library/blocks/breadcrumbs/breadcrumbs.php:114
+msgid "Tag Archives:"
+msgstr ""
+
+#: /Users/clay/Dropbox/Web/dev/wp-content/themes/headway/library/blocks/breadcrumbs/breadcrumbs.php:121
+msgid "Archives:"
+msgstr ""
+
+#: /Users/clay/Dropbox/Web/dev/wp-content/themes/headway/library/blocks/breadcrumbs/breadcrumbs.php:128
+msgid "Whoops! Page Not Found..."
+msgstr ""
+
+#: /Users/clay/Dropbox/Web/dev/wp-content/themes/headway/library/blocks/breadcrumbs/breadcrumbs.php:136
+msgid "You Are Here:"
+msgstr ""
+
+#: /Users/clay/Dropbox/Web/dev/wp-content/themes/headway/library/blocks/content/comments-template.php:53
+msgid "Sorry, comments are closed for this post."
+msgstr ""
+
+#: /Users/clay/Dropbox/Web/dev/wp-content/themes/headway/library/blocks/content/comments-template.php:67
+msgid ""
+"This post is password protected. Please enter the password to view the "
+"comments."
+msgstr ""
+
+#: /Users/clay/Dropbox/Web/dev/wp-content/themes/headway/library/blocks/content/content-display.php:123
+#: /Users/clay/Dropbox/Web/dev/wp-content/themes/headway/library/blocks/listings/content-display.php:69
+msgid "<p>Sorry, there was no content that matched your search.</p>"
+msgstr ""
+
+#: /Users/clay/Dropbox/Web/dev/wp-content/themes/headway/library/blocks/content/content-display.php:209
+#, php-format
+msgid "Daily Archives: %s"
+msgstr ""
+
+#: /Users/clay/Dropbox/Web/dev/wp-content/themes/headway/library/blocks/content/content-display.php:212
+#, php-format
+msgid "Monthly Archives: %s"
+msgstr ""
+
+#: /Users/clay/Dropbox/Web/dev/wp-content/themes/headway/library/blocks/content/content-display.php:215
+#, php-format
+msgid "Yearly Archives: %s"
+msgstr ""
+
+#: /Users/clay/Dropbox/Web/dev/wp-content/themes/headway/library/blocks/content/content-display.php:218
+msgid "Blog Archives"
+msgstr ""
+
+#: /Users/clay/Dropbox/Web/dev/wp-content/themes/headway/library/blocks/content/content-display.php:228
+#, php-format
+msgid "Category Archives: %s"
+msgstr ""
+
+#: /Users/clay/Dropbox/Web/dev/wp-content/themes/headway/library/blocks/content/content-display.php:246
+#: /Users/clay/Dropbox/Web/dev/wp-content/themes/headway/library/blocks/content/content-display.php:249
+#, php-format
+msgid "Author Archives: %s"
+msgstr ""
+
+#: /Users/clay/Dropbox/Web/dev/wp-content/themes/headway/library/blocks/content/content-display.php:259
+#, php-format
+msgid "Search Results for: %s"
+msgstr ""
+
+#: /Users/clay/Dropbox/Web/dev/wp-content/themes/headway/library/blocks/content/content-display.php:268
+#, php-format
+msgid "Tag Archives: %s"
+msgstr ""
+
+#: /Users/clay/Dropbox/Web/dev/wp-content/themes/headway/library/blocks/content/content-display.php:558
+msgid "Pages:"
+msgstr ""
+
+#: /Users/clay/Dropbox/Web/dev/wp-content/themes/headway/library/blocks/content/content-display.php:593
+msgid "Whoops! Page Not Found"
+msgstr ""
+
+#: /Users/clay/Dropbox/Web/dev/wp-content/themes/headway/library/blocks/content/content-display.php:601
+msgid ""
+"<p>Don't fret, you didn't do anything wrong. It appears that the page you "
+"are looking for does not exist or has been moved elsewhere.</p>"
+msgstr ""
+
+#: /Users/clay/Dropbox/Web/dev/wp-content/themes/headway/library/blocks/content/content-display.php:603
+#, php-format
+msgid ""
+"<p>If you keep ending up here, please head back to our <a href=\"%s"
+"\">homepage</a> or try the search form below.</p>"
+msgstr ""
+
+#: /Users/clay/Dropbox/Web/dev/wp-content/themes/headway/library/blocks/content/content-display.php:678
+msgid "Discard Reply"
+msgstr ""
+
+#: /Users/clay/Dropbox/Web/dev/wp-content/themes/headway/library/blocks/content/content-display.php:704
+msgid "<span class=\"meta-nav\">←</span> Older posts"
+msgstr ""
+
+#: /Users/clay/Dropbox/Web/dev/wp-content/themes/headway/library/blocks/content/content-display.php:705
+msgid "Newer posts <span class=\"meta-nav\">→</span>"
+msgstr ""
+
+#: /Users/clay/Dropbox/Web/dev/wp-content/themes/headway/library/blocks/content/content-display.php:859
+#, php-format
+msgid "%s – Comments"
+msgstr ""
+
+#: /Users/clay/Dropbox/Web/dev/wp-content/themes/headway/library/blocks/content/content-display.php:868
+#, php-format
+msgid "Respond to %s"
+msgstr ""
+
+#: /Users/clay/Dropbox/Web/dev/wp-content/themes/headway/library/blocks/content/content-display.php:875
+#, php-format
+msgid "View all posts by %s"
+msgstr ""
+
+#: /Users/clay/Dropbox/Web/dev/wp-content/themes/headway/library/blocks/footer/footer.php:120
+msgid "Administration Panel"
+msgstr ""
+
+#: /Users/clay/Dropbox/Web/dev/wp-content/themes/headway/library/blocks/footer/footer.php:122
+msgid "Administration Login"
+msgstr ""
+
+#: /Users/clay/Dropbox/Web/dev/wp-content/themes/headway/library/blocks/footer/footer.php:143
+msgid "Powered by Headway, the "
+msgstr ""
+
+#: /Users/clay/Dropbox/Web/dev/wp-content/themes/headway/library/blocks/footer/footer.php:155
+msgid "Copyright"
+msgstr ""
+
+#: /Users/clay/Dropbox/Web/dev/wp-content/themes/headway/library/blocks/footer/footer.php:171
+msgid "Go To Top"
+msgstr ""
+
+#: /Users/clay/Dropbox/Web/dev/wp-content/themes/headway/library/blocks/footer/footer.php:193
+msgid "View Full Site"
+msgstr ""
+
+#: /Users/clay/Dropbox/Web/dev/wp-content/themes/headway/library/blocks/footer/footer.php:200
+msgid "View Mobile Site"
+msgstr ""
+
+#: /Users/clay/Dropbox/Web/dev/wp-content/themes/headway/library/blocks/navigation/navigation.php:219
+msgid "Navigation"
+msgstr ""
+
+#: /Users/clay/Dropbox/Web/dev/wp-content/themes/headway/library/common/compiler.php:354
+msgid ""
+"There was an error while Headway tried to compile the LESS CSS. Full Error: "
+msgstr ""
+
+#: /Users/clay/Dropbox/Web/dev/wp-content/themes/headway/library/common/functions.php:666
+msgid "Type to search, then press enter"
+msgstr ""
+
+#: /Users/clay/Dropbox/Web/dev/wp-content/themes/headway/library/common/functions.php:694
+msgid "Search"
+msgstr ""
+
+#: /Users/clay/Dropbox/Web/dev/wp-content/themes/headway/library/common/image-resizer.php:57
+msgid "Error: Invalid image URL or size inputs"
+msgstr ""
+
+#: /Users/clay/Dropbox/Web/dev/wp-content/themes/headway/library/common/image-resizer.php:81
+msgid "Error: Image not local"
+msgstr ""
+
+#: /Users/clay/Dropbox/Web/dev/wp-content/themes/headway/library/common/image-resizer.php:88
+msgid "Error: Image does not exist or not accessible"
+msgstr ""
+
+#: /Users/clay/Dropbox/Web/dev/wp-content/themes/headway/library/common/image-resizer.php:113
+msgid "Error: Cannot resize, check if $upscale is enabled"
+msgstr ""
+
+#: /Users/clay/Dropbox/Web/dev/wp-content/themes/headway/library/common/image-resizer.php:125
+msgid "Error: Cannot resize image with WP_Image_Editor class"
+msgstr ""
+
+#: /Users/clay/Dropbox/Web/dev/wp-content/themes/headway/library/common/image-resizer.php:133
+msgid "Error: Unable to save image with WP_Image_Editor class"
+msgstr ""
+
+#: /Users/clay/Dropbox/Web/dev/wp-content/themes/headway/library/display/layout-renderer.php:115
+msgid "No Content to Display"
+msgstr ""
+
+#: /Users/clay/Dropbox/Web/dev/wp-content/themes/headway/library/display/layout-renderer.php:121
+#, php-format
+msgid ""
+"<p>There are no blocks to display. Add some by going to the <a href=\"%s"
+"\">Headway Grid</a>!</p>"
+msgstr ""
+
+#: /Users/clay/Dropbox/Web/dev/wp-content/themes/headway/library/display/layout-renderer.php:125
+#, php-format
+msgid ""
+"<p>There is no content to display. Please notify the site administrator or "
+"<a href=\"%s\">login</a>.</p>"
+msgstr ""
+
+#: /Users/clay/Dropbox/Web/dev/wp-content/themes/headway/library/fonts/traditional-fonts.php:127
+msgid ""
+"To register a font, the argument array must include an \"id\", \"stack\", "
+"and \"name\"."
+msgstr ""
+
+#: /Users/clay/Dropbox/Web/dev/wp-content/themes/headway/library/updater/theme-updater.php:68
+msgid ""
+"Before clicking OK to update, be sure that you have a backup of your website."
+msgstr ""
+
+#: /Users/clay/Dropbox/Web/dev/wp-content/themes/headway/library/visual-editor/panels/design/property-inputs.php:151
+msgid "You have customized a property in this property group."
+msgstr ""
+
+#: /Users/clay/Dropbox/Web/dev/wp-content/themes/headway/library/visual-editor/panels/design/property-inputs.php:274
+msgid "You have customized this property."
+msgstr ""
--- /dev/null
+msgid ""
+msgstr ""
+"Project-Id-Version: Headway Base v3.2.3\n"
+"Report-Msgid-Bugs-To: \n"
+"POT-Creation-Date: \n"
+"PO-Revision-Date: 2012-07-15 13:48:36+0000\n"
+"Last-Translator: admin <cinquequarti@gmail.com>\n"
+"Language-Team: \n"
+"MIME-Version: 1.0\n"
+"Content-Type: text/plain; charset=UTF-8\n"
+"Content-Transfer-Encoding: 8bit\n"
+"Plural-Forms: nplurals=2; plural=n != 1;\n"
+"X-Poedit-Language: Italian\n"
+"X-Poedit-Country: ITALY\n"
+"X-Poedit-SourceCharset: utf-8\n"
+"X-Poedit-KeywordsList: __;_e;__ngettext:1,2;_n:1,2;__ngettext_noop:1,2;_n_noop:1,2;_c,_nc:4c,1,2;_x:1,2c;_ex:1,2c;_nx:4c,1,2;_nx_noop:4c,1,2;\n"
+"X-Poedit-Basepath: ../../\n"
+"X-Poedit-Bookmarks: \n"
+"X-Poedit-SearchPath-0: .\n"
+"X-Textdomain-Support: yes"
+
+#: library/admin/admin.php:358
+#, php-format
+#@ default
+msgid "<div class=\"headway-update-backup-reminder alert-red alert\"><h3>Remember!</h3><p>Please backup before updating. Headway Themes recommends <a href=\"%s\" target=\"_blank\"><strong>BackupBuddy</strong></a> for all backup and migration needs.</div>"
+msgstr ""
+
+#: library/api/api-admin-meta-box.php:12
+#@ headway
+msgid "The meta box class being registered does not exist."
+msgstr "La classe meta box che stai registrando non esiste."
+
+#: library/api/api-block.php:128
+#@ headway
+msgid "The block options class being registered does not exist."
+msgstr "La classe di opzioni per i blocchi che stai registrando non esiste."
+
+#: library/api/api-box.php:12
+#@ headway
+msgid "The box class being registered does not exist."
+msgstr "La classe di box che stai registrando non esiste."
+
+#: library/api/api-element.php:125
+#@ default
+msgid "Arguments must be an array for this element."
+msgstr ""
+
+#: library/api/api-element.php:150
+#@ default
+msgid "An ID is required for this element."
+msgstr ""
+
+#: library/api/api-element.php:153
+#@ default
+msgid "A name is required for this element."
+msgstr ""
+
+#: library/api/api-element.php:156
+#@ default
+msgid "A group is required for this element."
+msgstr ""
+
+#: library/api/api-element.php:159
+#@ default
+msgid "A CSS selector is required for this element."
+msgstr ""
+
+#: library/api/api-element.php:162
+#@ default
+msgid "Properties are required for this element."
+msgstr ""
+
+#: library/api/api-element.php:201
+#@ default
+msgid "Arguments must be an array for this element instance."
+msgstr ""
+
+#: library/api/api-element.php:217
+#@ default
+msgid "An ID is required for this element instance."
+msgstr ""
+
+#: library/api/api-element.php:220
+#@ default
+msgid "A name is required for this element instance."
+msgstr ""
+
+#: library/api/api-element.php:223
+#@ default
+msgid "A group is required for this element instance."
+msgstr ""
+
+#: library/api/api-element.php:226
+#@ default
+msgid "A parent element is required for this element instance."
+msgstr ""
+
+#: library/api/api-element.php:229
+#@ default
+msgid "A CSS selector is required for this element instance."
+msgstr ""
+
+#: library/api/api-element.php:239
+#@ default
+msgid "The element specified does not support instances."
+msgstr ""
+
+#: library/api/api-element.php:265
+#@ default
+msgid "The group being registered already exists."
+msgstr ""
+
+#: library/api/api-element.php:281
+#@ default
+msgid "Arguments must be an array for deregistering this element."
+msgstr ""
+
+#: library/api/api-element.php:293
+#@ default
+msgid "A group is required for deregistering this element."
+msgstr ""
+
+#: library/api/api-element.php:296
+#@ default
+msgid "An ID is required for deregistering this element."
+msgstr ""
+
+#: library/api/api-element.php:318
+#@ default
+msgid "Arguments must be an array for deregistering this element instance."
+msgstr ""
+
+#: library/api/api-element.php:331
+#@ default
+msgid "A group is required for deregistering this element instance."
+msgstr ""
+
+#: library/api/api-element.php:334
+#@ default
+msgid "An instance ID is required for deregistering this element instance."
+msgstr ""
+
+#: library/api/api-element.php:337
+#@ default
+msgid "An element is required for deregistering this element instance."
+msgstr ""
+
+#: library/api/api-element.php:357
+#@ default
+msgid "The group being deregistered does not exist."
+msgstr ""
+
+#: library/api/api-panel.php:12
+#@ headway
+msgid "The panel class being registered does not exist."
+msgstr "La classe di pannelli che stai registrando non esiste."
+
+#: library/api/api-panel.php:205
+#@ headway
+msgid "There are no inputs registered for this tab."
+msgstr "Non ci sono input registrati per questo tab."
+
+#: library/api/api-updater.php:168
+#, php-format
+#@ default
+msgid "<div id=\"update-nag\">%s %s is now available, you're running %s! <a href=\"%s\">Click here to update</a> or <a href=\"%s\" target=\"_blank\">learn more</a> about the update.</div>"
+msgstr ""
+
+#: library/api/api-updater.php:173
+#, php-format
+#@ default
+msgid "<div id=\"update-nag\">%s %s is now available, you're running %s! Go to the <a href=\"%s\" target=\"_blank\">Headway Dashboard</a> to download the latest version or <a href=\"%s\" target=\"_blank\">learn more</a> about the update.</div>"
+msgstr ""
+
+#: library/api/api-updater.php:185
+#, php-format
+#@ default
+msgid "<div id=\"update-nag\">%s %s is now available, you're running %s! Your Headway license has expired. Please visit the <a href=\"%s\">Headway Dashboard</a> to renew your license so you can continue to receive updates.</div>"
+msgstr ""
+
+#: library/api/api-updater.php:190
+#, php-format
+#@ default
+msgid "<div id=\"update-nag\">%s %s is now available, you're running %s! You will not be able to update until you enter a valid license key on the <a href=\"%s\">Headway Options</a> panel.</div>"
+msgstr ""
+
+#: library/blocks/blocks.php:64
+#@ headway
+msgid "The block class being registered does not exist."
+msgstr "La classe di blocchi che stai registrando non esiste."
+
+#: library/blocks/blocks.php:538
+#@ headway
+msgid "The Headway blocks array does not exist."
+msgstr "L'array dei blocchi di Headway non esiste."
+
+#: library/blocks/core/breadcrumbs/breadcrumbs.php:64
+#@ headway
+msgid "You Are Here"
+msgstr "Sei Qui"
+
+#: library/blocks/core/breadcrumbs/breadcrumbs.php:68
+#: library/blocks/core/breadcrumbs/breadcrumbs.php:70
+#@ headway
+msgid "Home"
+msgstr ""
+
+#: library/blocks/core/breadcrumbs/breadcrumbs.php:122
+#@ headway
+msgid "Search Results For:"
+msgstr "Risultati della Ricerca per:"
+
+#: library/blocks/core/breadcrumbs/breadcrumbs.php:129
+#@ headway
+msgid "Author Archives:"
+msgstr "Archivi dell'Autore:"
+
+#: library/blocks/core/breadcrumbs/breadcrumbs.php:135
+#@ headway
+msgid "404 Error!"
+msgstr "Errore 404!"
+
+#: library/blocks/core/breadcrumbs/breadcrumbs.php:139
+#@ headway
+msgid "Tag Archives:"
+msgstr "Archivi per il Tag:"
+
+#: library/blocks/core/breadcrumbs/breadcrumbs.php:143
+#@ headway
+msgid "Archives:"
+msgstr "Archivi:"
+
+#: library/blocks/core/content/comments-template.php:12
+#@ headway
+msgid "Discard Reply"
+msgstr "Scarta Risposta"
+
+#: library/blocks/core/content/comments.php:28
+#@ headway
+msgid "This post is password protected. Please enter the password to view the comments."
+msgstr "Questo articolo è protetto da password. Per favore, inserisci la password per vedere i commenti."
+
+#: library/blocks/core/content/comments.php:44
+#@ headway
+msgid "No Responses"
+msgstr "Nessuna Risposta"
+
+#: library/blocks/core/content/comments.php:44
+#@ headway
+msgid "One Response"
+msgstr "Una Risposta"
+
+#: library/blocks/core/content/comments.php:44
+#@ headway
+msgid "% Responses"
+msgstr "% Risposte"
+
+#: library/blocks/core/content/comments.php:45
+#@ headway
+msgid "to"
+msgstr "a"
+
+#: library/blocks/core/content/comments.php:68
+#@ headway
+msgid "Sorry, comments are closed for this post."
+msgstr "Ci dispiace, i commenti sono chiusi per questo articolo."
+
+#: library/blocks/core/content/content-display.php:149
+#, php-format
+#@ headway
+msgid "Daily Archives: %s"
+msgstr "Archivi per il Giorno: %s"
+
+#: library/blocks/core/content/content-display.php:152
+#, php-format
+#@ headway
+msgid "Monthly Archives: %s"
+msgstr "Archivi per il Mese: %s"
+
+#: library/blocks/core/content/content-display.php:155
+#, php-format
+#@ headway
+msgid "Yearly Archives: %s"
+msgstr "Archivi per l'Anno: %s"
+
+#: library/blocks/core/content/content-display.php:158
+#@ headway
+msgid "Blog Archives"
+msgstr "Archivi del Blog"
+
+#: library/blocks/core/content/content-display.php:168
+#, php-format
+#@ headway
+msgid "Category Archives: %s"
+msgstr "Archivi per la Categoria: %s"
+
+#: library/blocks/core/content/content-display.php:186
+#: library/blocks/core/content/content-display.php:189
+#, php-format
+#@ headway
+msgid "Author Archives: %s"
+msgstr "Archivi per l'Autore: %s"
+
+#: library/blocks/core/content/content-display.php:199
+#, php-format
+#@ headway
+msgid "Search Results for: %s"
+msgstr "Risultati della Ricerca per: %"
+
+#: library/blocks/core/content/content-display.php:208
+#, php-format, php-format
+#@ headway
+#@ headway
+msgid "Tag Archives: %s"
+msgstr "Archivi per il Tag: %s"
+
+#: library/blocks/core/content/content-display.php:345
+#, php-format
+#@ headway
+msgid "Permalink to %s"
+msgstr "Link a %s"
+
+#: library/blocks/core/content/content-display.php:356
+#, php-format
+#@ headway
+msgid "View all posts by %s"
+msgstr "Guarda tutti gli articoli di %s"
+
+#: library/blocks/core/content/content-display.php:506
+#@ headway
+msgid "Pages:"
+msgstr "Pagine:"
+
+#: library/blocks/core/content/content-display.php:542
+#@ headway
+msgid "Whoops! Page Not Found"
+msgstr "Ooops! Pagina non trovata"
+
+#: library/blocks/core/content/content-display.php:550
+#@ headway
+msgid "<p>Don't fret, you didn't do anything wrong. It appears that the page you are looking for does not exist or has been moved elsewhere.</p>"
+msgstr "<p>Non preoccuparti, non hai fatto niente di sbagliato. Sembra che la pagina che stai cercando non esista più o sia stata sposta da qualche altra parte.</p>"
+
+#: library/blocks/core/content/content-display.php:552
+#, php-format
+#@ headway
+msgid "<p>If you keep ending up here, please head back to our <a href=\"%s\">homepage</a> or try the search form below.</p>"
+msgstr "<p>Se continui a finire qui, per favore torna alla nostra <a href=\"%s\">homepage</a> o prova una ricerca attraverso il modulo qui sotto.</p>"
+
+#: library/blocks/core/content/content-display.php:620
+#@ headway
+msgid "<span class=\"meta-nav\">←</span> Older posts"
+msgstr "<span class=\"meta-nav\">←</span> Articoli meno recenti"
+
+#: library/blocks/core/content/content-display.php:621
+#@ headway
+msgid "Newer posts <span class=\"meta-nav\">→</span>"
+msgstr "Articoli più recenti <span class=\"meta-nav\">→</span>"
+
+#: library/blocks/core/content/content-display.php:701
+#@ headway
+msgid "<span class=\"tag-links\"><span>Tags:</span> "
+msgstr "<span class=\"tag-links\"><span>Tag:</span> "
+
+#: library/blocks/core/footer/footer.php:116
+#@ headway
+msgid "Administration Panel"
+msgstr "Pannello di Amministrazione"
+
+#: library/blocks/core/footer/footer.php:118
+#@ headway
+msgid "Administration Login"
+msgstr "Login Amministratore"
+
+#: library/blocks/core/footer/footer.php:136
+#@ headway
+msgid "Powered by Headway, the "
+msgstr "Basato su Headway, il"
+
+#: library/blocks/core/footer/footer.php:148
+#@ headway
+msgid "Copyright"
+msgstr ""
+
+#: library/blocks/core/footer/footer.php:164
+#@ headway
+msgid "Go To Top"
+msgstr "Torna in Cima"
+
+#: library/blocks/core/footer/footer.php:186
+#@ headway
+msgid "View Full Site"
+msgstr "Vai al Sito Completo"
+
+#: library/blocks/core/footer/footer.php:193
+#@ headway
+msgid "View Mobile Site"
+msgstr "Vai al Sito Mobile"
+
+#: library/common/fonts.php:84
+#@ default
+msgid "To register a font, the argument array must include an \"id\", \"stack\", and \"name\"."
+msgstr ""
+
+#: library/data/data-elements.php:64
+#: library/data/data-elements.php:92
+#: library/data/data-elements.php:170
+#: library/data/data-elements.php:198
+#: library/data/data-elements.php:224
+#@ default
+msgid "The element ID is not registered."
+msgstr ""
+
+#: library/display/grid-renderer.php:2
+#@ headway
+msgid "No Content to Display"
+msgstr "Nessun Contenuto da Mostrare"
+
+#: library/display/grid-renderer.php:2
+#, php-format
+#@ headway
+msgid "<p>There are no blocks to display. Add some by going to the <a href=\"%s\">Headway Grid</a>!</p>"
+msgstr "<p>Non ci sono blocchi da mostrare. Aggiungine qualcuno andando alla <a href=\"%s\">Headway Grid</a>!</p>"
+
+#: library/display/grid-renderer.php:2
+#, php-format
+#@ headway
+msgid "<p>There is no content to display. Please notify the site administrator or <a href=\"%s\">login</a>.</p>"
+msgstr "<p>Nessun contenuto da mostrare. Per favore avvisa l'amministratore del sito o <a href=\"%s\">fai login</a>.</p>"
+
+#: library/visual-editor/display.php:213
+#@ headway
+msgid "Toggle Options"
+msgstr "Attiva le Opzioni"
+
+#: library/visual-editor/panels/design/panel-default-elements.php:32
+#@ default
+msgid "Please select a default element to the left."
+msgstr ""
+
+#: library/visual-editor/panels/design/panel-editor.php:109
+#@ default
+msgid "Please select an element to the left."
+msgstr ""
+
+#: library/widgets/widgets.php:49
+#: library/widgets/widgets.php:51
+#@ headway
+msgid "Search"
+msgstr "Cerca"
+
--- /dev/null
+<?php
+/**
+ * Pre-3.6
+ *
+ * - Merge all design settings into the one option
+ **/
+add_action('headway_do_upgrade_36', 'headway_do_upgrade_36');
+function headway_do_upgrade_36() {
+
+ global $wpdb;
+
+ $combined_design_settings = array();
+ $existing_design_settings = get_option('headway_option_group_design', array());
+
+ foreach ( $wpdb->get_results("SELECT * FROM $wpdb->options") as $option ) {
+
+ if ( strpos($option->option_name, 'headway_option_group_design-editor-group') !== 0 )
+ continue;
+
+ $combined_design_settings = array_merge($combined_design_settings, maybe_unserialize($option->option_value));
+
+ }
+
+ $existing_design_settings['properties'] = $combined_design_settings;
+
+ update_option('headway_option_group_design', $existing_design_settings);
+
+ HeadwayMaintenance::output_status('Successfully Upgraded Design Editor Data');
+
+ return true;
+
+}
\ No newline at end of file
--- /dev/null
+<?php
+/**
+ * 3.6.1
+ *
+ * Do 3.6 design conversion if the Headway 3.6 design options is the same as the default. This is to fix the bad 3.6 upgrade bug
+ **/
+add_action('headway_do_upgrade_361', 'headway_do_upgrade_361');
+function headway_do_upgrade_361() {
+
+ global $wpdb;
+
+ $existing_design_settings = get_option('headway_option_group_design', array());
+
+ if ( HeadwayOption::$current_skin == HEADWAY_DEFAULT_SKIN && $existing_design_settings == HeadwayElementsData::get_default_data() ) {
+
+ $combined_design_settings = array();
+
+ foreach ( $wpdb->get_results("SELECT * FROM $wpdb->options") as $option ) {
+
+ if ( strpos($option->option_name, 'headway_option_group_design-editor-group') !== 0 )
+ continue;
+
+ $combined_design_settings = array_merge($combined_design_settings, maybe_unserialize($option->option_value));
+
+ }
+
+ $existing_design_settings['properties'] = $combined_design_settings;
+
+ update_option('headway_option_group_design', $existing_design_settings);
+
+ }
+
+ HeadwayMaintenance::output_status('Successfully Upgraded Design Editor Data');
+
+}
\ No newline at end of file
--- /dev/null
+<?php
+/**
+ * 3.7
+ *
+ * Add new custom MySQL table for blocks and transfer blocks in wp_options over to it
+ */
+add_action('headway_do_upgrade_37', 'headway_do_upgrade_37');
+function headway_do_upgrade_37($current_step = false) {
+
+ global $wpdb;
+
+ $available_steps = array(
+ 'step_1',
+ 'step_2',
+ 'step_3',
+ 'step_4',
+ 'step_5',
+ 'finish'
+ );
+
+ /* If first run of upgrade, start on first step */
+ if ( ! $current_step && ! get_option( 'hw_37_upgrade_current_step' ) ) {
+
+ $current_step = $available_steps[0];
+
+ /* If currently in middle of upgrade, set the current step to whatever the DB says */
+ } else if ( ! $current_step && get_option( 'hw_37_upgrade_current_step' ) ) {
+
+ $current_step = get_option( 'hw_37_upgrade_current_step' );
+
+ }
+
+ switch ( $current_step ) {
+
+ case 'step_1':
+
+ /* Create a backup of all Headway MySQL rows in wp_options */
+ HeadwayMaintenance::output_status( 'Backing up current Headway settings...' );
+
+ $wp_options_backup = headway_upgrade_37_backup_wp_options();
+
+ if ( ! $wp_options_backup ) {
+ HeadwayMaintenance::output_status( 'Headway Error: Unable to back up current Headway settings. Unable to proceed with upgrade. Please contact Headway support at support@headwaythemes.com' );
+ wp_die('<strong>Error: Unable to back up current Headway settings. Unable to proceed with upgrade. Please contact Headway support at support@headwaythemes.com');
+ }
+
+ break;
+
+ case 'step_2':
+
+ /* Setup MySQL Tables */
+ HeadwayMaintenance::output_status( 'Setting up new data structure...' );
+ headway_upgrade_37_setup_mysql();
+
+ /* Fix template IDs and names */
+ HeadwayMaintenance::output_status( 'Fixing template names...' );
+ headway_upgrade_37_fix_templates();
+
+ /* Upgrade wrappers */
+ HeadwayMaintenance::output_status( 'Transferring wrappers to new data location...' );
+ headway_upgrade_37_upgrade_wrappers();
+
+ break;
+
+
+ case 'step_3':
+
+ /* Upgrade blocks and layout options */
+ HeadwayMaintenance::output_status( 'Transferring blocks to new data location...' );
+ headway_upgrade_37_upgrade_blocks_and_layout_options();
+
+ break;
+
+ case 'step_4':
+
+ /* Setup mirroring */
+ HeadwayMaintenance::output_status( 'Setting up mirroring of blocks and wrappers...' );
+ headway_upgrade_37_setup_mirroring();
+
+ /* Setup and copy options */
+ HeadwayMaintenance::output_status( 'Renaming old options...' );
+ headway_upgrade_37_setup_options();
+
+
+ break;
+
+ case 'step_5':
+
+ /* Fix design settings and instance IDs */
+ HeadwayMaintenance::output_status( 'Verifying Design Editor settings...' );
+ headway_upgrade_37_fix_design_data();
+
+ break;
+
+ case 'finish':
+
+ /* Rename and delete old options */
+ HeadwayMaintenance::output_status( 'Deleting old options...' );
+ headway_upgrade_37_rename_and_delete_old_options();
+
+ /* Clean up upgrade */
+ HeadwayMaintenance::output_status( 'Cleaning up...' );
+ headway_upgrade_37_cleanup();
+
+ break;
+
+
+ }
+
+ /* Go to next step */
+ $index_of_current_step = array_search($current_step, $available_steps);
+
+ if ( isset($available_steps[$index_of_current_step + 1]) ) {
+
+ $next_step = $available_steps[$index_of_current_step + 1];
+
+ update_option( 'hw_37_upgrade_current_step', $next_step );
+
+ headway_do_upgrade_37($next_step);
+
+ }
+
+}
+
+
+
+function headway_upgrade_37_backup_wp_options() {
+
+ global $wpdb;
+
+ $wp_options_prefix = 'headway';
+
+ $ignored_wp_option_value_1 = 'a:1:{s:7:"general";a:1:{s:6:"blocks";a:0:{}}}';
+ $ignored_wp_option_value_2 = 'a:3:{s:7:"general";a:4:{s:8:"template";s:0:"";s:10:"hide-title";s:0:"";s:15:"alternate-title";s:0:"";s:9:"css-class";s:0:"";}s:14:"post-thumbnail";a:1:{s:8:"position";s:0:"";}s:3:"seo";a:9:{s:5:"title";s:0:"";s:11:"description";s:0:"";s:7:"noindex";s:5:"false";s:8:"nofollow";s:5:"false";s:9:"noarchive";s:5:"false";s:9:"nosnippet";s:5:"false";s:5:"noodp";s:5:"false";s:6:"noydir";s:5:"false";s:12:"redirect-301";s:0:"";}}';
+ $ignored_wp_option_value_3 = 'a:2:{s:7:"general";a:4:{s:8:"template";s:0:"";s:10:"hide-title";s:0:"";s:15:"alternate-title";s:0:"";s:9:"css-class";s:0:"";}s:14:"post-thumbnail";a:1:{s:8:"position";s:0:"";}}';
+ $ignored_wp_option_value_4 = 'a:2:{s:7:"general";a:4:{s:9:"css-class";s:0:"";s:8:"template";s:0:"";s:10:"hide-title";s:0:"";s:15:"alternate-title";s:0:"";}s:14:"post-thumbnail";a:1:{s:8:"position";s:4:"left";}}';
+ $ignored_wp_option_value_5 = 'a:2:{s:7:"general";a:6:{s:8:"template";s:0:"";s:10:"hide-title";s:0:"";s:15:"alternate-title";s:0:"";s:9:"css-class";s:0:"";s:16:"page_title_alias";s:0:"";s:20:"page_sub_title_alias";s:0:"";}s:14:"post-thumbnail";a:1:{s:8:"position";s:0:"";}}';
+ $ignored_wp_option_value_6 = 'a:2:{s:7:"general";a:4:{s:8:"template";s:0:"";s:10:"hide-title";s:0:"";s:15:"alternate-title";s:0:"";s:9:"css-class";s:0:"";}s:14:"post-thumbnail";a:1:{s:8:"position";s:4:"left";}}';
+
+ $query = $wpdb->prepare("SELECT * FROM $wpdb->options WHERE option_name LIKE '%s' AND option_name NOT LIKE '%s' AND option_name != 'headway_option_group_block-actions-cache' AND option_value != '%s' AND option_value != '%s' AND option_value != '%s' AND option_value != '%s' AND option_value != '%s' AND option_value != '%s'", $wp_options_prefix . '%', 'headway_option_group_design-editor-group%', $ignored_wp_option_value_1, $ignored_wp_option_value_2, $ignored_wp_option_value_3, $ignored_wp_option_value_4, $ignored_wp_option_value_5, $ignored_wp_option_value_6);
+
+ $wp_options_backup_data = $wpdb->get_results($query);
+
+ $file_content = '
+<?php
+/* Protect the backup contents */
+die();
+
+/* BACKUP CONTENTS
+
+' . json_encode($wp_options_backup_data) . '
+
+END BACKUP CONTENTS */
+';
+
+ /* Write the backup to a text file */
+ $file_handle = @fopen(HEADWAY_UPLOADS_DIR . '/' . 'headway_37_upgrade_backup_' . mktime() . '.php', 'w');
+
+ if ( !@fwrite($file_handle, $file_content) )
+ return false;
+
+ return true;
+
+}
+
+
+function headway_upgrade_37_setup_mysql() {
+
+ Headway::mysql_drop_tables();
+ Headway::mysql_dbdelta();
+
+}
+
+
+function headway_upgrade_37_fix_templates() {
+
+ global $wpdb;
+
+ /* Shorten template IDs */
+ $templates = HeadwayOption::get_group('skins');
+
+ /* If $templates turns up false then we need to repair it using the name of options */
+ if ( !$templates || !is_array($templates) ) {
+
+ $query_for_template_ids = $wpdb->get_results( "SELECT option_name FROM $wpdb->options WHERE option_name LIKE 'headway_%skin=%'" );
+ $templates_repaired = array();
+
+ foreach ( $query_for_template_ids as $query_for_template_ids_obj ) {
+
+ $option_name_fragments = explode('|_', str_replace('headway_|skin=', '', $query_for_template_ids_obj->option_name));
+ $template_id = $option_name_fragments[0];
+
+ $templates_repaired[$template_id] = array(
+ 'name' => $template_id,
+ 'id' => $template_id
+ );
+
+ }
+
+ if ( count($templates_repaired) ) {
+ $templates = $templates_repaired;
+ }
+
+ }
+
+ foreach ( $templates as $template_id => $template ) {
+
+ /* Truncate the template ID to 12 characters due to varchar limit in wp_options */
+ $new_template_id = substr(strtolower(str_replace(' ', '-', $template['id'])), 0, 12);
+ $original_template_id = $template['id'];
+
+ /* If the new template ID is the same as the current ID then don't do anything with this template */
+ if ( $new_template_id == $original_template_id )
+ continue;
+
+ $template_unique_id_counter = 0;
+
+ /* Check if template ID already exists. If it does, change ID */
+ while ( headway_get($new_template_id, $templates) || get_option('headway_|skin=' . $new_template_id . '|_option_group_general') ) {
+
+ $template_unique_id_counter++;
+ $new_template_id = $new_template_id . '-' . $template_unique_id_counter;
+
+ }
+
+ /* Update WP option names */
+ $wpdb->query( "UPDATE $wpdb->options SET option_name = replace(option_name, 'headway_|skin=$original_template_id', 'headway_|skin=$new_template_id') WHERE option_name LIKE 'headway_|skin=$original_template_id%'" );
+
+ /* If the current skin is the one with the name change then change that */
+ if ( HeadwayOption::get('current-skin', 'general', HEADWAY_DEFAULT_SKIN) == $original_template_id ) {
+ HeadwayOption::set('current-skin', $new_template_id);
+ HeadwayOption::$current_skin = $new_template_id;
+ }
+
+ $templates[$new_template_id] = $templates[$original_template_id];
+ unset($templates[$original_template_id]);
+
+ $templates[$new_template_id]['id'] = $new_template_id;
+
+ }
+
+ /* Save templates */
+ HeadwayOption::set_group('skins', $templates);
+
+}
+
+
+function headway_upgrade_37_upgrade_wrappers() {
+
+ global $wpdb;
+
+ /* Make sure wrappers table is empty in case this step was interrupted */
+ $wpdb->query( "TRUNCATE TABLE $wpdb->hw_wrappers" );
+
+ $upgraded_wrappers = array();
+
+ $wrappers_by_template = $wpdb->get_results("SELECT * FROM $wpdb->options WHERE option_name LIKE 'headway%option_group_wrappers'");
+
+ foreach ( $wrappers_by_template as $template_wrappers ) {
+
+ if ( strpos($template_wrappers->option_name, 'headway_|skin=') !== 0 ) {
+ $template = 'base';
+ } else {
+ $option_name_fragments = explode('|_', str_replace('headway_|skin=', '', $template_wrappers->option_name));
+ $template = $option_name_fragments[0];
+ }
+
+ foreach ( headway_maybe_unserialize($template_wrappers->option_value) as $layout_id => $layout_wrappers ) {
+
+ if ( !is_array($layout_wrappers) )
+ continue;
+
+ $layout_id = HeadwayLayout::format_old_id($layout_id);
+
+ foreach ( $layout_wrappers as $layout_wrapper_id => $layout_wrapper ) {
+
+ $layout_wrapper['template'] = $template;
+ $layout_wrapper['position'] = array_search($layout_wrapper_id, array_keys($layout_wrappers));
+ $layout_wrapper['legacy_id'] = HeadwayWrappers::format_wrapper_id($layout_wrapper_id);
+
+ $layout_wrapper['settings'] = array(
+ 'fluid' => headway_get( 'fluid', $layout_wrapper ),
+ 'fluid-grid' => headway_get( 'fluid-grid', $layout_wrapper ),
+ 'columns' => headway_get( 'columns', $layout_wrapper ),
+ 'column-width' => headway_get( 'column-width', $layout_wrapper ),
+ 'gutter-width' => headway_get( 'gutter-width', $layout_wrapper ),
+ 'use-independent-grid' => headway_get( 'use-independent-grid', $layout_wrapper ),
+ 'alias' => headway_get( 'alias', $layout_wrapper ),
+ 'css-classes' => headway_get( 'css-classes', $layout_wrapper ),
+ 'responsive-wrapper-options' => headway_get( 'responsive-wrapper-options', $layout_wrapper, array() )
+ );
+
+ $new_wrapper = HeadwayWrappersData::add_wrapper($layout_id, $layout_wrapper);
+
+ if ( $new_wrapper && !is_wp_error($new_wrapper) ) {
+
+ if ( !isset( $upgraded_wrappers[ $template ]) )
+ $upgraded_wrappers[ $template ] = array();
+
+ /* Gracefully handle duplicate IDs */
+ if ( !isset($upgraded_wrappers[$template][HeadwayWrappers::format_wrapper_id($layout_wrapper_id)]) ) {
+
+ $upgraded_wrappers[$template][HeadwayWrappers::format_wrapper_id($layout_wrapper_id)] = array(
+ 'id' => $new_wrapper,
+ 'mirror-wrapper' => headway_get('mirror-wrapper', $layout_wrapper)
+ );
+
+ } else if ( isset($upgraded_wrappers[$template][HeadwayWrappers::format_wrapper_id($layout_wrapper_id)]['id']) ) {
+
+ $upgraded_wrappers[$template][HeadwayWrappers::format_wrapper_id($layout_wrapper_id)] = array(
+ $upgraded_wrappers[$template][HeadwayWrappers::format_wrapper_id($layout_wrapper_id)],
+ array(
+ 'id' => $new_wrapper,
+ 'mirror-wrapper' => headway_get('mirror-wrapper', $layout_wrapper)
+ )
+ );
+
+ } else {
+
+ $upgraded_wrappers[$template][HeadwayWrappers::format_wrapper_id($layout_wrapper_id)][] = array(
+ 'id' => $new_wrapper,
+ 'mirror-wrapper' => headway_get('mirror-wrapper', $layout_wrapper)
+ );
+
+ }
+
+ }
+
+ }
+
+ }
+
+ }
+
+
+ delete_option('hw_37_upgrade_wrappers');
+
+ return add_option('hw_37_upgrade_wrappers', $upgraded_wrappers, false, 'no');
+
+}
+
+
+function headway_upgrade_37_upgrade_blocks_and_layout_options() {
+
+ global $wpdb;
+
+ /* Make sure blocks and layout options tables are empty in case this step is interrupted */
+ $wpdb->query( "TRUNCATE TABLE $wpdb->hw_blocks" );
+ $wpdb->query( "TRUNCATE TABLE $wpdb->hw_layout_meta" );
+
+ $upgraded_blocks = array();
+ $upgraded_wrappers = get_option('hw_37_upgrade_wrappers');
+
+ $all_layout_options = headway_upgrade_37_extract_layout_options();
+
+ foreach ( $all_layout_options as $template => $template_layouts ) {
+
+ foreach ( $template_layouts as $template_layout_id => $template_layout_options ) {
+
+ /* Move blocks to hw_blocks table */
+ foreach ( headway_get('blocks', headway_get('general', $template_layout_options), array()) as $block_id => $block ) {
+
+ $block['template'] = $template;
+
+ $wrapper = headway_get( HeadwayWrappers::format_wrapper_id( headway_get('wrapper', $block) ), headway_get($template, $upgraded_wrappers, array()) );
+
+ if ( !isset($wrapper['id']) )
+ $wrapper = $wrapper[0];
+
+ $block['wrapper'] = $wrapper['id'];
+ $block['legacy_id'] = $block_id;
+
+ $new_block_mirror_id = headway_get( 'mirror-block', headway_get( 'settings', $block ) );
+
+ if ( isset($block['settings']) && isset($block['settings']['mirror-block']) ) {
+ unset($block['settings']['mirror-block']);
+ }
+
+ $new_block = HeadwayBlocksData::add_block( HeadwayLayout::format_old_id( $template_layout_id ), $block );
+
+ if ( $new_block && !is_wp_error($new_block) ) {
+
+ if ( ! isset( $upgraded_blocks[ $template ] ) )
+ $upgraded_blocks[ $template ] = array();
+
+ /* Gracefully handle duplicate IDs */
+ if ( ! isset( $upgraded_blocks[$template][$block_id] ) ) {
+
+ $upgraded_blocks[$template][$block_id] = array(
+ 'id' => $new_block,
+ 'type' => $block['type'],
+ 'mirror-block' => $new_block_mirror_id
+ );
+
+ } else if ( isset( $upgraded_blocks[$template][$block_id]['id'] ) ) {
+
+ $upgraded_blocks[$template][$block_id] = array(
+ $upgraded_blocks[$template][$block_id],
+ array(
+ 'id' => $new_block,
+ 'type' => $block['type'],
+ 'mirror-block' => $new_block_mirror_id
+ )
+ );
+
+ } else {
+
+ $upgraded_blocks[$template][$block_id][] = array(
+ 'id' => $new_block,
+ 'type' => $block['type'],
+ 'mirror-block' => $new_block_mirror_id
+ );
+
+ }
+
+ }
+
+ }
+
+ /* Move layout meta from postmeta capable layouts to the wp_postmeta table */
+ if ( is_array($template_layout_options) ) {
+
+ foreach ( $template_layout_options as $template_layout_options_group => $template_layout_options_group_options ) {
+
+ foreach ( $template_layout_options_group_options as $option => $option_value ) {
+
+ if ( in_array($option, array('customized', 'blocks')) )
+ continue;
+
+ $global = $option == 'template' ? false : true;
+
+ HeadwayLayoutOption::set( HeadwayLayout::format_old_id( $template_layout_id ), $option, $option_value, $global, $template_layout_options_group, $template );
+
+
+ }
+
+ }
+
+ }
+
+ }
+
+
+ }
+
+
+ delete_option('hw_37_upgrade_blocks');
+
+ return add_option('hw_37_upgrade_blocks', $upgraded_blocks, false, 'no');
+
+}
+
+
+function headway_upgrade_37_extract_layout_options() {
+
+ global $wpdb;
+
+ $all_layout_options = array();
+
+ $post_query = $wpdb->get_col( "SELECT ID FROM $wpdb->posts" );
+ $revisions_query = $wpdb->get_col( "SELECT ID FROM $wpdb->posts WHERE post_status = 'inherit' AND post_type != 'attachment'" );
+
+ /* Build layout options catalog */
+ foreach ( $wpdb->get_results( "SELECT option_name, option_value FROM $wpdb->options WHERE option_name LIKE 'headway_%'" ) as $option_obj ) {
+
+ if ( $option_obj->option_name == 'headway_layout_options_catalog' || (strpos( $option_obj->option_name, 'headway_') === 0 && substr( $option_obj->option_name, -8) == '_preview') )
+ continue;
+
+ if ( strpos( $option_obj->option_name, 'headway_') !== 0 || strpos( $option_obj->option_name, 'layout_options') === false )
+ continue;
+
+ /* Check against bad option values */
+ $bad_option_values = array(
+ 'a:1:{s:7:"general";a:1:{s:6:"blocks";a:0:{}}}',
+ 'a:3:{s:7:"general";a:4:{s:8:"template";s:0:"";s:10:"hide-title";s:0:"";s:15:"alternate-title";s:0:"";s:9:"css-class";s:0:"";}s:14:"post-thumbnail";a:1:{s:8:"position";s:0:"";}s:3:"seo";a:9:{s:5:"title";s:0:"";s:11:"description";s:0:"";s:7:"noindex";s:5:"false";s:8:"nofollow";s:5:"false";s:9:"noarchive";s:5:"false";s:9:"nosnippet";s:5:"false";s:5:"noodp";s:5:"false";s:6:"noydir";s:5:"false";s:12:"redirect-301";s:0:"";}}',
+ 'a:2:{s:7:"general";a:4:{s:8:"template";s:0:"";s:10:"hide-title";s:0:"";s:15:"alternate-title";s:0:"";s:9:"css-class";s:0:"";}s:14:"post-thumbnail";a:1:{s:8:"position";s:0:"";}}',
+ 'a:2:{s:7:"general";a:4:{s:9:"css-class";s:0:"";s:8:"template";s:0:"";s:10:"hide-title";s:0:"";s:15:"alternate-title";s:0:"";}s:14:"post-thumbnail";a:1:{s:8:"position";s:4:"left";}}',
+ 'a:2:{s:7:"general";a:6:{s:8:"template";s:0:"";s:10:"hide-title";s:0:"";s:15:"alternate-title";s:0:"";s:9:"css-class";s:0:"";s:16:"page_title_alias";s:0:"";s:20:"page_sub_title_alias";s:0:"";}s:14:"post-thumbnail";a:1:{s:8:"position";s:0:"";}}',
+ 'a:2:{s:7:"general";a:4:{s:8:"template";s:0:"";s:10:"hide-title";s:0:"";s:15:"alternate-title";s:0:"";s:9:"css-class";s:0:"";}s:14:"post-thumbnail";a:1:{s:8:"position";s:4:"left";}}'
+ );
+
+ if ( in_array($option_obj->option_value, $bad_option_values) )
+ continue;
+
+ $option = $option_obj->option_name;
+ $option_value = $option_obj->option_value;
+
+ /* Figure out template ID and layout */
+ if ( strpos($option, 'headway_|skin=') !== 0 ) {
+
+ $template = 'base';
+ $layout = str_replace('headway_layout_options_', '', $option);
+
+ } else {
+
+ $option_name_fragments = explode('|_', str_replace('headway_|skin=', '', $option));
+
+ $template = $option_name_fragments[0];
+ $layout = str_replace('layout_options_', '', $option_name_fragments[1]);
+
+ }
+
+ /* If the layout ID is template then change the underscore to a hyphen */
+ if ( strpos($layout, 'template_') === 0 )
+ $layout = str_replace('template_', 'template-', $layout);
+
+ /* If the layout is numeric, then check if the post even exists and isn't a revision. If it does not exist or is a revision, delete it! */
+ if ( is_numeric($layout) ) {
+
+ /* If the post row is false (doesn't exist) don't process layout */
+ if ( !in_array($layout, $post_query) ) {
+ continue;
+ }
+
+ /* If the post row is post revision then don't process it */
+ if ( in_array( $layout, $revisions_query ) ) {
+ continue;
+ }
+
+
+ }
+
+ /* Add to return array */
+ if ( !isset($all_layout_options[$template]) )
+ $all_layout_options[$template] = array();
+
+ $all_layout_options[$template][$layout] = headway_maybe_unserialize($option_value);
+
+ }
+
+ return $all_layout_options;
+
+}
+
+
+function headway_upgrade_37_setup_mirroring() {
+
+ $upgraded_blocks = get_option('hw_37_upgrade_blocks');
+ $upgraded_wrappers = get_option('hw_37_upgrade_wrappers');
+
+ foreach ( $upgraded_blocks as $template => $template_blocks ) {
+
+ foreach ( $template_blocks as $old_block_id => $new_blocks_info ) {
+
+ if ( isset($new_blocks_info['id']) ) {
+ $new_blocks_info = array($new_blocks_info);
+ }
+
+ foreach ( $new_blocks_info as $new_block_info ) {
+
+ if ( ! $mirror_block = headway_get( headway_get( 'mirror-block', $new_block_info ), $template_blocks ) )
+ continue;
+
+ if ( headway_get( 'type', $new_block_info ) != headway_get( 'type', $mirror_block ) )
+ continue;
+
+ if ( headway_get( 'id', $new_block_info ) == headway_get( 'id', $mirror_block ) )
+ continue;
+
+ $mirror_id = headway_get( 'id', $mirror_block );
+
+ HeadwayBlocksData::update_block( $new_block_info['id'], array(
+ 'mirror_id' => $mirror_id,
+ 'template' => $template
+ ) );
+
+ }
+
+ }
+
+ }
+
+
+ foreach ( $upgraded_wrappers as $template => $template_wrappers ) {
+
+ foreach ( $template_wrappers as $old_wrapper_id => $new_wrappers_info ) {
+
+ if ( isset($new_wrappers_info['id']) ) {
+ $new_wrappers_info = array($new_wrappers_info);
+ }
+
+ foreach ( $new_wrappers_info as $new_wrapper_info ) {
+
+ if ( ! $mirror_wrapper = headway_get( HeadwayWrappers::format_wrapper_id(headway_get( 'mirror-wrapper', $new_wrapper_info )), $template_wrappers ) )
+ continue;
+
+ $mirror_id = headway_get( 'id', $mirror_wrapper );
+
+ HeadwayWrappersData::update_wrapper( $new_wrapper_info['id'], array(
+ 'mirror_id' => $mirror_id,
+ 'template' => $template
+ ) );
+
+ }
+
+ }
+
+ }
+
+}
+
+
+function headway_upgrade_37_setup_options() {
+
+ global $wpdb;
+
+ $wpdb->query( "DELETE FROM $wpdb->options WHERE option_name LIKE 'headway_|template=%'" );
+
+ update_option( 'headway_|skin=base|_option_group_design', get_option( 'headway_option_group_design', array() ) );
+ update_option( 'headway_|skin=base|_option_group_general', get_option( 'headway_option_group_general', array() ) );
+ update_option( 'headway_|skin=base|_option_group_templates', get_option( 'headway_option_group_templates', array() ) );
+
+ wp_cache_flush();
+
+ /* Pull settings from headway_option_group_general and headway_|skin=base|_option_group_general */
+ $option_group_general = get_option('headway_option_group_general');
+
+ foreach ( $option_group_general as $option => $option_value ) {
+
+ $options_to_remove = array(
+ 'cache',
+ 'colorpicker-swatches',
+ 'webfont-cache'
+ );
+
+ if ( in_array($option, $options_to_remove) || strpos( $option, 'merged-default-design-data-' ) === 0 ) {
+ unset( $option_group_general[ $option ] );
+ }
+
+ }
+
+ update_option('headway_option_group_general', $option_group_general);
+
+}
+
+
+function headway_upgrade_37_fix_design_data() {
+
+ $upgraded_blocks = get_option('hw_37_upgrade_blocks');
+ $upgraded_wrappers = get_option('hw_37_upgrade_wrappers');
+
+ /* Sort the block and wrapper mappings by descending number that way when we do a simple recursive find and replace the small block IDs won't mess up the larger block IDs.
+ Example: Replacing block-1 before block-11 is replaced would be bad news */
+ /* Pull settings from headway_option_group_general and headway_|skin=base|_option_group_general */
+ foreach ( $upgraded_blocks as $template => $template_blocks ) {
+
+ $template_design_settings = get_option( 'headway_|skin=' . $template . '|_option_group_design', array() );
+
+ if ( !is_array($template_design_settings) )
+ continue;
+
+ $template_design_settings_json = json_encode($template_design_settings);
+
+ krsort( $template_blocks );
+
+ foreach ( $template_blocks as $old_block_id => $new_block_info ) {
+
+ if ( !isset($new_block_info['id']) ) {
+ $new_block_info = $new_block_info[0];
+ }
+
+ $template_design_settings_json = str_replace( 'block-' . $old_block_id, 'block-' . $new_block_info['id'], $template_design_settings_json );
+
+ }
+
+ update_option( 'headway_|skin=' . $template . '|_option_group_design', json_decode($template_design_settings_json, true) );
+
+ }
+
+
+ foreach ( $upgraded_wrappers as $template => $template_wrappers ) {
+
+ $template_design_settings = get_option( 'headway_|skin=' . $template . '|_option_group_design', array() );
+
+ if ( !is_array($template_design_settings) )
+ continue;
+
+ $template_design_settings_json = json_encode($template_design_settings);
+
+ krsort( $template_wrappers );
+
+ foreach ( $template_wrappers as $old_wrapper_id => $new_wrapper_info ) {
+
+ if ( !isset($new_wrapper_info['id']) ) {
+ $new_wrapper_info = $new_wrapper_info[0];
+ }
+
+ $template_design_settings_json = str_replace( 'wrapper-' . $old_wrapper_id, 'wrapper-' . $new_wrapper_info['id'], $template_design_settings_json );
+
+ }
+
+ update_option( 'headway_|skin=' . $template . '|_option_group_design', json_decode($template_design_settings_json, true) );
+
+ }
+
+}
+
+
+function headway_upgrade_37_rename_and_delete_old_options() {
+
+ global $wpdb;
+
+ /* Change option names */
+ $wpdb->query( "UPDATE $wpdb->options SET option_name = replace(option_name, 'headway_|skin=', 'headway_|template=') WHERE option_name LIKE 'headway_|skin=%'" );
+
+ $wpdb->query( "DELETE FROM $wpdb->options WHERE option_name LIKE 'headway_%layout_options_%'" );
+
+ /* Delete old options */
+ $wpdb->query( "DELETE FROM $wpdb->options WHERE option_name = 'headway_option_group_design'" );
+ $wpdb->query( "DELETE FROM $wpdb->options WHERE option_name = 'headway_option_group_templates'" );
+
+ $wpdb->query( "DELETE FROM $wpdb->options WHERE option_name LIKE 'headway%option_group_wrappers'" );
+ $wpdb->query( "DELETE FROM $wpdb->options WHERE option_name LIKE 'headway%option_group_blocks'" );
+ $wpdb->query( "DELETE FROM $wpdb->options WHERE option_name LIKE 'headway%option_group_block-actions'" );
+
+}
+
+
+function headway_upgrade_37_cleanup() {
+
+ global $wpdb;
+
+ $wpdb->query("UPDATE $wpdb->options SET autoload = 'no' WHERE option_name LIKE 'headway_%'");
+
+ $wpdb->update($wpdb->options, array(
+ 'autoload' => 'yes'
+ ), array(
+ 'option_name' => 'headway_option_group_general'
+ ));
+
+ $wpdb->query("UPDATE $wpdb->options SET autoload = 'yes' WHERE option_name LIKE 'headway_|template=" . HeadwayOption::$current_skin . "|%'");
+
+}
--- /dev/null
+<?php
+/**
+ * 3.7.1
+ *
+ * Change wrapper instance IDs and change MySQL collate and charset
+ */
+add_action('headway_do_upgrade_371', 'headway_do_upgrade_371');
+function headway_do_upgrade_371() {
+
+ global $wpdb;
+
+ /* Alter MySQL schema */
+ Headway::mysql_dbdelta();
+
+ /* Loop through installed Templates and fix wrapper instance IDs */
+ $templates = HeadwayTemplates::get_all(true, true);
+
+ foreach ( $templates as $template_id => $template ) {
+
+ $template_design_settings = get_option( 'headway_|template=' . $template_id . '|_option_group_design', array() );
+
+ if ( !empty($template_design_settings) ) {
+
+ $template_design_settings = headway_preg_replace_json( "/-layout-[\w-]*/", '', $template_design_settings );
+ update_option( 'headway_|template=' . $template_id . '|_option_group_design', $template_design_settings );
+
+ }
+
+ }
+
+ /* Alter MySQL charset and collate */
+ $charset = 'utf8';
+
+ if ( ! empty($wpdb->collate ) ) {
+ $collate = $wpdb->collate;
+ } else {
+ $collate = 'utf8_general_ci';
+ }
+
+ $wpdb->query("ALTER TABLE $wpdb->hw_blocks CONVERT TO CHARACTER SET $charset COLLATE $collate;");
+ $wpdb->query("ALTER TABLE $wpdb->hw_wrappers CONVERT TO CHARACTER SET $charset COLLATE $collate;");
+ $wpdb->query("ALTER TABLE $wpdb->hw_layout_meta CONVERT TO CHARACTER SET $charset COLLATE $collate;");
+ $wpdb->query("ALTER TABLE $wpdb->hw_snapshots CONVERT TO CHARACTER SET $charset COLLATE $collate;");
+
+}
\ No newline at end of file
--- /dev/null
+<?php
+class HeadwayMaintenance {
+
+ public static $available_upgrades = array(
+ '3.6',
+ '3.6.1',
+ '3.7',
+ '3.7.1'
+ );
+
+ /**
+ * Over time, there may be issues to be corrected between updates or naming conventions to be changed between updates.
+ * All of that will be processed here.
+ **/
+ static function do_upgrades($version_to_upgrade = false) {
+
+ $headway_settings = get_option('headway', array('version' => 0));
+ $db_version = $headway_settings['version'];
+
+ if ( get_transient('headway_upgrading') == 'upgrading' ) {
+ return false;
+ }
+
+ self::setup_upgrade_environment();
+
+ if ( $db_version == HEADWAY_VERSION ) {
+ return false;
+ }
+
+ /* Add current version to upgrades if it's not there so the basic upgrade routine is still ran */
+ if ( !in_array(HEADWAY_VERSION, self::$available_upgrades) ) {
+ self::$available_upgrades[] = HEADWAY_VERSION;
+ }
+
+
+ if ( !$version_to_upgrade ) {
+
+ foreach ( self::$available_upgrades as $possible_upgrade ) {
+
+ if ( version_compare( $db_version, $possible_upgrade, '<' ) ) {
+
+ $version_to_upgrade = $possible_upgrade;
+ break;
+
+ }
+
+ }
+
+ }
+
+ /* Do specified upgrade routine */
+ if ( $upgrade_in_progress = $version_to_upgrade ) {
+
+ $version_filename = str_replace( '.', '', $upgrade_in_progress );
+
+ if ( version_compare( $db_version, $upgrade_in_progress, '<' ) ) {
+
+ self::start_upgrade($upgrade_in_progress);
+
+ if ( file_exists(HEADWAY_LIBRARY_DIR . '/maintenance/upgrade-' . $version_filename . '.php') ) {
+ require_once HEADWAY_LIBRARY_DIR . '/maintenance/upgrade-' . $version_filename . '.php';
+ }
+
+ do_action('headway_do_upgrade_' . $version_filename);
+
+ self::after_upgrade($upgrade_in_progress);
+
+ }
+
+ }
+
+ return true;
+
+ }
+
+
+ public static function setup_upgrade_environment() {
+
+ @ignore_user_abort( true );
+ @set_time_limit( 0 );
+
+ /* Attempt to raise memory limit to max */
+ @ini_set( 'memory_limit', apply_filters( 'headway_memory_limit', WP_MAX_MEMORY_LIMIT ) );
+
+ }
+
+
+ public static function output_status( $text ) {
+
+ error_log('Headway Upgrade Status: ' . $text);
+
+ return true;
+
+ }
+
+
+ public static function start_upgrade($version) {
+
+ set_transient( 'headway_upgrading', 'upgrading', 15 );
+
+ self::output_status('Currently Upgrading to ' . $version );
+
+ }
+
+
+ public static function after_upgrade($version) {
+
+ /* Update the version here. */
+ $headway_settings = get_option( 'headway', array( 'version' => 0 ) );
+ $headway_settings['version'] = $version;
+
+ update_option( 'headway', $headway_settings );
+ delete_transient( 'headway_upgrading' );
+
+ /* Flush caches */
+ do_action( 'headway_db_upgrade' );
+
+ /* Run next upgrade if available */
+ $index_of_current_version = array_search($version, self::$available_upgrades);
+
+ if ( isset(self::$available_upgrades[$index_of_current_version + 1]) ) {
+
+ $next_upgrade = self::$available_upgrades[$index_of_current_version + 1];
+
+ return self::do_upgrades($next_upgrade);
+
+ } else {
+
+ if ( current_user_can('manage_options') ) {
+ wp_safe_redirect( admin_url('admin.php?page=headway-whats-new') );
+ } else {
+ wp_safe_redirect( home_url() );
+ }
+
+ die();
+
+ }
+
+ }
+
+}
\ No newline at end of file
--- /dev/null
+.alert {
+ -webkit-border-radius: 3px;
+ -moz-border-radius: 3px;
+ border-radius: 3px;
+ box-shadow: 0 1px 0 #fff inset;
+ padding: 5px 20px;
+ margin: 20px 0;
+ display: block;
+}
+
+ .alert p {
+ margin: 10px 0;
+ line-height: 160%;
+ }
+
+.alert-green {
+ border: 1px solid #97B48A;
+ background-color: #CBECA0;
+}
+
+.alert-red {
+ border: 1px solid #CFADB3;
+ color: #832525;
+ background-color: #FAF2F5;
+}
+
+.alert-yellow {
+ border: 1px solid #E6DB55;
+ background-color: #FFFBCC;
+ color: #424242;
+}
+
+.alert-gray, .alert-grey {
+ border: 1px solid #CCC;
+ color: #424242;
+ background-color: #EEE;
+}
+
+.alert-blue {
+ border: 1px solid #92CAE4;
+ color: #205791;
+ background-color: #D5EDF8;
+}
+
+.alert a {
+ color: inherit;
+}
\ No newline at end of file
--- /dev/null
+/* Blocks */
+ /* Header */
+ .block-type-header .banner {
+ display: block;
+ }
+
+ .block-type-header .banner a {
+ display: block;
+ }
+
+ .block-type-header a.banner-image {
+ display: block;
+ width: 100%;
+ height: 100%;
+ }
+
+ .block-type-header .tagline {
+ display: block;
+ }
+
+
+ /* Navigation */
+ .block-type-navigation ul {
+ width: 100%;
+ display: inline-block;
+
+ /* display: inline-block; gap workaround */
+ letter-spacing: -4px;
+ word-spacing: -4px;
+ }
+
+ .block-type-navigation ul li {
+ display: inline-block;
+
+ /* display: inline-block; gap workaround */
+ letter-spacing: normal;
+ word-spacing: normal;
+ }
+
+ .block-type-navigation ul li a {
+ display: block;
+ width: auto;
+ padding: 0 15px;
+ box-sizing: border-box;
+ -moz-box-sizing: border-box;
+ white-space: nowrap;
+ }
+
+ /* Navigation Alignment */
+ .block-type-navigation .nav-align-left ul { text-align: left; }
+ .block-type-navigation .nav-align-right ul { text-align: right; }
+ .block-type-navigation .nav-align-center ul { text-align: center; }
+
+ /* Vertical Orientation */
+ .block-type-navigation .nav-vertical {
+ position: relative;
+ }
+
+ .block-type-navigation .nav-vertical ul li {
+ width: 100%;
+ }
+
+ .block-type-navigation .nav-vertical ul li a {
+ height: auto;
+ line-height: 40px;
+ }
+
+ /* Navigation Search */
+ .block-type-navigation .nav-search-active ul {
+ width: 75%;
+ }
+
+ .block-type-navigation .nav-search-active .nav-search {
+ float: right;
+ width: 22.5%;
+ padding: 0 10px;
+ box-sizing: border-box;
+ -moz-box-sizing: border-box;
+ display: table;
+ }
+
+ .block-type-navigation .nav-search-active.nav-search-position-left .nav-search {
+ float: left;
+ }
+
+ .block-type-navigation .nav-search-active #searchform {
+ height: 100%;
+ display: table-cell;
+ vertical-align: middle;
+ }
+
+ .block-type-navigation .nav-search-active #searchform label,
+ .block-type-navigation .nav-search-active #searchform input#searchsubmit {
+ display: none;
+ }
+
+ .block-type-navigation .nav-search-active #searchform input#s {
+ width: 100%;
+ }
+
+ /* SUB MENUS */
+ .block-type-navigation a span.sf-sub-indicator {
+ display: none;
+ }
+
+ .block-type-navigation ul.sub-menu {
+ position: absolute;
+ z-index: 150;
+ left: -9999px; /* Hide the dropdowns */
+ width: auto;
+ }
+
+ .block-type-navigation ul.sub-menu li {
+ display: block;
+ height: auto;
+ width: 100%;
+ }
+
+ .block-type-navigation ul.sub-menu li a {
+ min-width: 175px;
+ max-width: 500px;
+ width: auto;
+
+ height: auto;
+ line-height: 40px;
+
+ box-sizing: border-box;
+ -moz-box-sizing: border-box;
+ }
+
+ /* Show the drop downs on hover */
+ .block-type-navigation ul.menu li:hover > ul.sub-menu,
+ .block-type-navigation ul.menu li.sfHover > ul.sub-menu {
+ left: auto;
+ }
+ /* END SUB MENUS */
+
+ /* Responsive Select */
+ .block-type-navigation .selectnav {
+ display: none;
+ margin: 10px 2%;
+ width: 96%;
+ font-size: 16px;
+ }
+
+ /* Search */
+ .block-type-search input.field {
+ width: 100%;
+ }
+
+ /* Search button visible */
+ .block-type-search form.search-button-visible div {
+ overflow: hidden;
+ padding-right: 5px;
+ }
+
+ .block-type-search form.search-button-visible input.submit {
+ min-width: 60px;
+ float: right;
+ }
+
+
+
+/* Breadcrumbs */
+ .block-type-breadcrumbs p.breadcrumbs {
+ margin: 13px 10px;
+ }
+
+ /* Widget Area */
+ .block-type-widget-area ul.widget-area {
+ padding: 0;
+ margin: 0;
+ }
+
+ .block-type-widget-area li.widget {
+ margin: 15px 0 0;
+ padding: 5px 10px;
+ list-style: none;
+ }
+
+ .block-type-widget-area li.widget ul {
+ padding: 0 0 0 25px;
+ margin: 5px 0;
+ list-style: disc;
+ }
+
+ .block-type-widget-area li.widget span.widget-title {
+ margin: 0 0 10px;
+ display: block;
+ }
+
+ .block-type-widget-area li.widget span.widget-title:empty {
+ display: none;
+ }
+
+ /* Horizontal Widget Area */
+ .block-type-widget-area .horizontal-sidebar li.widget {
+ float: left;
+ margin: 0 15px 0 15px;
+ width: 20%;
+ }
+
+ /* Widgets */
+ li.widget table#wp-calendar th, li.widget table#wp-calendar td {
+ color: #444;
+ text-align: center; }
+
+ li.widget table#wp-calendar a { color: #444; }
+
+ li.widget table#wp-calendar caption {
+ font-weight: bold;
+ font-size: 14px;
+ line-height: 100%; }
+
+ li.widget table#wp-calendar td#today {
+ color: #111; }
+
+ li.widget table#wp-calendar tfoot .pad { background: none; }
+
+
+ /* Content */
+ .block-type-content div.loop {
+ width: 100%;
+ float: left;
+ clear: both;
+ box-sizing: border-box;
+ -moz-box-sizing: border-box;
+ }
+
+ .block-type-content .entry-title, .block-type-content .archive-title {
+ margin: 0 0 5px;
+ max-width: 100%;
+ word-wrap: break-word;
+ }
+
+ .block-type-content .entry-title .post-edit-link {
+ display: inline-block;
+ font-size: 12px;
+ margin: 10px 0 0 15px;
+ background: rgba(0, 0, 0, .6);
+ color: rgba(255, 255, 255, .8) !important;
+ padding: 0 10px;
+ line-height: 100%;
+ vertical-align: middle;
+ height: 20px;
+ line-height: 20px;
+ border-radius: 10px;
+ text-shadow: 0 0 1px rgba(0, 0, 0, .8);
+ box-shadow: -1px -1px 0 rgba(255, 255, 255, .15);
+ opacity: 0;
+ text-transform: none;
+ letter-spacing: 0;
+ font-weight: normal;
+ position: absolute;
+ font-family: helvetica, sans-serif;
+ -webkit-font-smoothing: antialiased;
+ -moz-transition: opacity 250ms linear;
+ -webkit-transition: opacity 250ms linear;
+ transition: opacity 250ms linear;
+ }
+
+ .block-type-content .post:hover .post-edit-link {
+ opacity: .6;
+ }
+
+ .block-type-content .entry-title .post-edit-link:hover {
+ opacity: 1;
+ }
+
+ .block-type-content .archive-title {
+ padding: 15px 0 15px;
+ border-width: 0;
+ }
+
+ .block-type-content .entry-title a, .block-type-content .archive-title a {
+ color: inherit;
+ font-size: inherit;
+ text-decoration: inherit;
+ }
+
+ .block-type-content div.entry-content {
+ width: 100%;
+ margin: 20px 0;
+ box-sizing: border-box;
+ -moz-box-sizing: border-box;
+ -webkit-box-sizing: border-box;
+ }
+
+ .block-type-content div.entry-content:first-child {
+ margin-top: 0;
+ }
+
+ .block-type-content .entry-row {
+ float: left;
+ width: 100%;
+ }
+
+ .block-type-content .entry-row .hentry {
+ clear: none;
+ }
+
+ .block-type-content .entry-row .hentry:first-child {
+ margin-left: 0 !important;
+ }
+
+ .block-type-content .hentry {
+ clear: both;
+ padding: 15px 0 30px;
+ margin: 0 0 10px;
+ float: left;
+ width: 100%;
+ box-sizing: border-box;
+ -moz-box-sizing: border-box;
+ -webkit-box-sizing: border-box;
+ }
+
+ .block-type-content a.post-thumbnail {
+ display: block;
+ }
+
+ .block-type-content a.post-thumbnail img {
+ max-width: 100%;
+ box-sizing: border-box;
+ -moz-box-sizing: border-box;
+ -webkit-box-sizing: border-box;
+ }
+
+ .block-type-content a.post-thumbnail-left {
+ float: left;
+ margin: 2px 15px 0 0;
+ }
+
+ .block-type-content a.post-thumbnail-right {
+ float: right;
+ margin: 2px 0 0 15px;
+ }
+
+ .block-type-content a.post-thumbnail-above-content {
+ margin: 15px 0 -5px;
+ }
+
+ .block-type-content a.post-thumbnail-above-title {
+ margin: 0 0 15px;
+ }
+
+ /* Specific tag formatting */
+ address {
+ margin: 0 0 20px;
+ font-style: italic;
+ }
+
+ dl {
+ margin: 0 20px;
+ }
+
+ dt {
+ font-weight: bold;
+ }
+
+ dd {
+ margin: 0 0 20px;
+ }
+
+ abbr[title] {
+ border-bottom: 1px dotted;
+ cursor: help;
+ }
+
+ pre {
+ background: #F5F5F5;
+ color: #666;
+ font-family: monospace;
+ font-size: 14px;
+ line-height: 20px;
+ margin: 20px 0;
+ overflow: auto;
+ padding: 20px;
+ white-space: pre-wrap;
+ word-wrap: break-word;
+ }
+ /* End specific tag formatting */
+
+ .block-type-content .entry-meta {}
+
+ .block-type-content .entry-utility {
+ clear: both;
+ }
+
+ /* REVIEW TEXT DECORATION */
+ .block-type-content div.entry-meta a, .block-type-content div.entry-utility a {
+ color: inherit;
+ text-decoration: none;
+ }
+
+ /* REVIEW */
+ .block-type-content div.entry-meta a:hover, .block-type-content div.entry-utility a:hover {
+ text-decoration: underline;
+ }
+
+ /* Loop Navigation */
+ .loop-navigation {
+ margin: 15px 0 30px;
+ float: left;
+ clear: both;
+ width: 100%;
+ box-sizing: border-box;
+ -moz-box-sizing: border-box;
+ -webkit-box-sizing: border-box;
+ }
+
+ .loop-navigation .nav-previous, .loop-navigation .nav-next {
+ display: inline-block;
+ max-width: 48%;
+ }
+
+ .loop-navigation .nav-previous a, .loop-navigation .nav-next a {
+ display: inline-block;
+ width: 100%;
+ -moz-box-sizing: border-box;
+ -webkit-box-sizing: border-box;
+ box-sizing: border-box;
+ }
+
+ .loop-navigation .nav-previous {
+ float: left;
+ }
+
+ .loop-navigation .nav-next {
+ float: right;
+ }
+
+ /* 404 Search Form */
+ div.system-404 form#searchform {
+ margin: 10px 0 0 0;
+ float: left;
+ clear: both;
+ }
+
+ div.system-404 form#searchform label {
+ display: none;
+ }
+
+ div.system-404 form#searchform input#s {
+ width: 200px;
+ float: left;
+ }
+
+ div.system-404 form#searchform input#searchsubmit {
+ float: left;
+ margin: 2px 0 0 5px;
+ }
+
+ /* Comments Styling */
+ div#comments {
+ float: left;
+ clear: both;
+ margin: 0 0 50px;
+ width: 100%;
+ box-sizing: border-box;
+ -moz-box-sizing: border-box;
+ -webkit-box-sizing: border-box;
+ }
+
+ div#comments h3#comments {
+ margin: 15px 0 0 0;
+ display: block;
+ }
+
+ ol.commentlist {
+ margin: 30px 0 0;
+ float: left;
+ width: 100%;
+ box-sizing: border-box;
+ -moz-box-sizing: border-box;
+ -webkit-box-sizing: border-box;
+ }
+
+ li.comment {
+ position: relative;
+ padding: 0 0 0 64px;
+ clear: both;
+ }
+
+ li.comment div.comment-body {
+ margin: 0 0 30px;
+ }
+
+ li.comment ul.children {
+ clear: both;
+ }
+
+ li.comment .comment-author {
+ margin: 0;
+ padding: 0;
+ }
+
+ li.comment img.avatar {
+ position: absolute;
+ left: 0;
+ top: 0;
+ }
+
+ li.comment .comment-author cite {
+ font-weight: bold;
+ }
+
+ li.comment .comment-author span.says { }
+
+ li.pingback .comment-author span.says {
+ display: none;
+ }
+
+ li.comment .comment-meta {
+ margin: 5px 0 20px 0;
+ }
+
+ li.comment .comment-meta a {
+ text-decoration: none;
+ color: inherit;
+ }
+
+ li.comment .comment-body p {
+ margin: 0 0 10px 0;
+ }
+
+ li.comment div.reply {
+ margin: 20px 0 0;
+ }
+
+ li.comment a.comment-reply-link {
+ margin: 10px 0 0 -6px;
+ padding: 3px 6px;
+ }
+
+ /* Comment Form */
+ div#respond {
+ padding: 0;
+ margin: 0;
+ float: left;
+ width: 100%;
+ }
+
+ ol.commentlist div#respond {
+ padding: 5px 0 20px;
+ margin: -20px 0 30px;
+ }
+
+ h3#reply-title {
+ margin: 15px 0;
+ }
+
+ h3#reply-title small {
+ font-size: 75%;
+ margin: 0 0 0 5px;
+ }
+
+ div#respond p.logged-in-as {
+ margin: 10px 0 20px;
+ }
+
+ div#respond label {
+ display: inline-block;
+ margin: 0;
+ float: left;
+ }
+
+ div#respond p {
+ clear: both;
+ float: left;
+ width: 100%;
+ }
+
+ div#respond span.required {
+ display: inline;
+ color: #c00;
+ line-height: 25px;
+ margin: 0 0 0 3px;
+ }
+
+ div#respond input[type='text'] {
+ width: 50%;
+ }
+
+ div#respond textarea {
+ width: 85%;
+ height: 150px;
+ }
+
+ div#respond input[type='text'], div#respond textarea {
+ clear: both;
+ float: left;
+ margin: 0 0 10px;
+ }
+
+ /* Footer */
+ .block-type-footer .footer-left {
+ margin-top: 10px;
+ margin-left: 10px;
+ float: left;
+ }
+
+ .block-type-footer .footer-right {
+ margin-top: 10px;
+ margin-right: 10px;
+ float: right;
+ }
+
+ .block-type-footer .footer-link {
+ margin-bottom: 10px;
+ }
+
+ .block-type-footer .copyright {
+ float: left;
+ width: 100%;
+ clear: both;
+ text-align: center;
+ margin: 10px 0;
+ }
+
+ .block-type-footer a {
+ color: inherit;
+ }
+
+ .block-type-footer p.footer-responsive-grid-link-container {
+ float: left;
+ width: 100%;
+ clear: both;
+ text-align: center;
+ margin: 10px 0;
+ display: none;
+ }
+
+ .block-type-footer p.footer-responsive-grid-link-enable-container {
+ display: block;
+ }
+
+ /* Image */
+ .block-type-header img {
+ max-width: 100%;
+ }
+/* END BLOCKS */
+
+/* WIDGETS */
+ /* Calendar Widget */
+ li.widget table#wp-calendar {
+ width: 100%;
+ }
+
+ li.widget table#wp-calendar th, li.widget table#wp-calendar td {
+ padding: 5px 0;
+ }
+
+ li.widget table#wp-calendar caption {
+ margin: 0 0 8px 0;
+ }
+
+ /* Search Widget */
+ li.widget_search label, li.widget_search input#searchsubmit {
+ display: none;
+ }
+
+ li.widget_search input#s {
+ width: 100%;
+ }
\ No newline at end of file
--- /dev/null
+/* Content Block Elements */
+ /* More Link and Loop Navigation */
+ a.more-link {
+ padding: 2px 6px;
+ white-space: nowrap;
+ }
+
+ div.loop-navigation div.nav-previous a, div.loop-navigation div.nav-next a {
+ padding: 4px 8px;
+ }
+
+
+ /* Headings */
+ div.entry-content h1, div.entry-content h2 {
+ margin: 0 0 20px;
+ }
+
+ div.entry-content h3, div.entry-content h4, div.entry-content h5, div.entry-content h6 {
+ margin: 0 0 15px;
+ }
+
+ /* Paragraphs */
+ div.entry-content p {
+ margin: 0 0 15px;
+ }
+
+ /* Horizontal rules */
+ div.entry-content hr {
+ background-color: #ccc;
+ border: 0;
+ height: 1px;
+ margin: 0 0 15px;
+ }
+
+ /* Lists */
+ div.entry-content ul, div.entry-content ol {
+ padding: 0 0 0 40px;
+ margin: 15px 0;
+ }
+
+ div.entry-content ul ul, div.entry-content ol ol { margin: 0; } /* Lists inside lists should not have the margin on them. */
+
+ div.entry-content ul li { list-style: disc; }
+ div.entry-content ul ul li { list-style: circle; }
+ div.entry-content ul ul ul li { list-style: square; }
+
+ div.entry-content ol li { list-style: decimal; }
+ div.entry-content ol ol li { list-style: lower-alpha; }
+ div.entry-content ol ol ol li { list-style: lower-roman; }
+
+ /* Images */
+ .align-left,.alignleft {
+ float: left;
+ margin: 0 7px 0 0; }
+
+ .align-right,.alignright {
+ float: right;
+ margin: 0 0 0 7px; }
+
+ .aligncenter {
+ display: block;
+ margin-left: auto;
+ margin-right: auto;
+ clear: both; }
+
+ img.border {
+ padding: 1px;
+ border: 1px solid #ddd; }
+
+ img.no-border {
+ padding: 0;
+ border: none; }
+
+ img.wp-smiley { border: none; }
+
+ .wp-caption {
+ padding: 5px;
+ border: 1px solid #eee;
+ background: #fcfcfc;
+ margin-top: 15px;
+ max-width: 100%;
+ box-sizing: border-box;
+ -webkit-box-sizing: border-box;
+ -moz-box-sizing: border-box;
+ margin-bottom: 15px; }
+
+ .wp-caption img {
+ border: 1px solid #ddd;
+ margin: 0 auto;
+ display: block;
+ box-sizing: border-box;
+ -webkit-box-sizing: border-box;
+ -moz-box-sizing: border-box;
+ width: 100%;
+ height: auto;
+ padding: 0; }
+
+ .wp-caption img.wp-smiley { border: none; }
+
+ .wp-caption .wp-caption-text {
+ text-align: center;
+ color: #555;
+ margin: 5px 0 0 !important;
+ font-style: italic; }
+
+ /* Blockquotes */
+ blockquote {
+ color: #666;
+ padding: 5px 0 5px 25px;
+ border-top: 0 dotted;
+ border-bottom: 0 dotted;
+ border-left: 2px solid #f6f6f6;
+ margin: 15px 0 15px 20px; }
+
+ /* Drop Caps */
+ .drop-cap {
+ font-size: 310%;
+ line-height: 120%;
+ margin-bottom: -0.25em;
+ color: #888;
+ float: left;
+ padding: 0 6px 0 0; }
+
+ /* Code */
+ code {
+ background: #eaeaea;
+ font-family: Consolas,Monaco,Courier,monospace;
+ font-size: 0.9em;
+ margin: 0 1px;
+ padding: 1px 3px;
+ color: #555; }
+
+ pre code {
+ display: block;
+ border: 1px solid #ddd;
+ padding: 4px 7px;
+ }
+
+ .code-block {
+ display: block;
+ background: #eaeaea;
+ border: 1px solid #ddd;
+ color: #555;
+ font-family: Consolas,Monaco,Courier,monospace;
+ padding: 10px;
+ overflow: auto;
+ white-space: pre;
+ font-size: 12.5px;
+ line-height: 18px;
+ margin: 5px 0; }
+
+ /* Tables */
+ table {
+ width: 100%;
+ background-color: transparent;
+ border-collapse: collapse;
+ border-spacing: 0;
+ margin-bottom: 20px;
+ }
+
+ table th,
+ table td {
+ padding: 8px;
+ line-height: 18px;
+ text-align: left;
+ vertical-align: top;
+ border-top: 1px solid #ddd;
+ }
+
+ table th {
+ font-weight: bold;
+ }
+
+ table thead th {
+ vertical-align: bottom;
+ }
+
+ thead tr:first-child th, table tr:first-child th {
+ border-top: none;
+ }
+
+ /* Superscripts and Subscripts */
+ sup,
+ sub {
+ height: 0;
+ line-height: 1;
+ vertical-align: baseline;
+ _vertical-align: bottom;
+ position: relative;
+
+ }
+
+ sup {
+ bottom: 1ex;
+ }
+
+ sub {
+ top: .5ex;
+ }
+/* End Content Block Elements */
+
+
+/* Global Content Styles */
+strong { font-weight: bold; }
+
+em { font-style: italic; }
+
+
+/* Miscellaneous (to silence Theme Check) */
+.sticky {}
+.wp-caption-text {}
+.gallery-caption {}
+.bypostauthor {}
+
+
+/* FORM STYLING */
+input[type="text"], input[type="password"], input[type="email"], textarea, select {
+ border: 1px solid #ccc;
+ padding: 6px 4px;
+ outline: none;
+ -moz-border-radius: 2px;
+ -webkit-border-radius: 2px;
+ border-radius: 2px;
+ color: #777;
+ display: inline-block;
+ background: #fff;
+ box-sizing: border-box;
+ -moz-box-sizing: border-box;
+}
+
+select {
+ padding: 0;
+}
+
+input[type="text"]:focus, input[type="password"]:focus, input[type="email"]:focus, textarea:focus {
+ border: 1px solid #aaa;
+ color: #444;
+ -moz-box-shadow: 0 0 3px rgba(0,0,0,.2);
+ -webkit-box-shadow: 0 0 3px rgba(0,0,0,.2);
+ box-shadow: 0 0 3px rgba(0,0,0,.2);
+}
+
+input[type="submit"], input[type="button"], button {
+ background: #ddd;
+ padding: 0 12px;
+ -moz-border-radius: 3px;
+ -webkit-border-radius: 3px;
+ border-radius: 3px;
+ color: #444;
+ display: inline-block;
+ font-size: 11px;
+ font-weight: bold;
+ text-decoration: none;
+ cursor: pointer;
+ line-height: 27px;
+ border: none;
+}
+
+input[type="submit"]:hover, input[type="button"]:hover, button:hover {
+ color: #222;
+ background: #d1d1d1;
+}
+
+input[type="submit"]:active, input[type="button"]:active, button:active {
+ background: #c8c8c8;
+}
\ No newline at end of file
--- /dev/null
+/* Wrapper */
+ div.wrapper {
+ margin: 0 auto;
+ clear: both;
+ }
+
+ div.wrapper.wrapper-fluid {
+ width: 100%;
+ -moz-box-sizing: border-box;
+ -webkit-box-sizing: border-box;
+ box-sizing: border-box;
+ }
+
+ div.wrapper.wrapper-fluid.wrapper-first {
+ margin-top: 0;
+ }
+
+ div.wrapper.wrapper-fluid.wrapper-last {
+ margin-bottom: 0;
+ }
+
+ div.grid-container {
+ width: 100%;
+ height: auto;
+ margin: 0;
+ }
+
+ div.wrapper-fluid div.grid-container {
+ margin: 0 auto;
+ }
+
+ div.wrapper-fluid.wrapper-fluid-grid div.grid-container {
+ width: 100%;
+ }
+
+ div#whitewrap {
+ width: 100%;
+ float: left;
+ }
+/* End Wrapper */
+
+/* Structural stuff */
+ .clear {
+ clear: both;
+ }
+
+ .block {
+ box-shadow: none;
+ background: none;
+ margin: 0 0 10px;
+ border: none;
+ float: left;
+ -moz-box-sizing: border-box;
+ -webkit-box-sizing: border-box;
+ box-sizing: border-box;
+ width: 100%;
+ overflow: hidden;
+ }
+
+ div.block-content {
+ display: block;
+ float: left;
+ width: 100%;
+ height: auto;
+ }
+
+ .block-fixed-height div.block-content, body.visual-editor-iframe-grid div.block-content {
+ height: 100%;
+ }
+
+ .row {
+ float: left;
+ width: 100%;
+ }
+
+ .column {
+ float: left;
+ }
+
+ .column-1.grid-left-0 {
+ margin-left: 0 !important;
+ }
+
+ .sub-column-1 {
+ clear: both;
+ }
+/* End structural stuff */
+
+
+/* No Blocks Notice */
+ div.wrapper-no-blocks div.entry-content {
+ margin: 40px 0 !important;
+ text-align: center;
+ }
\ No newline at end of file
--- /dev/null
+html, body, div, span, applet, object, iframe,
+h1, h2, h3, h4, h5, h6, p, blockquote, pre,
+a, abbr, acronym, address, big, cite, code,
+del, dfn, em, img, ins, kbd, q, s, samp,
+small, strike, strong, sub, sup, tt, var,
+b, u, i, center,
+dl, dt, dd, ol, ul, li,
+fieldset, form, label, legend,
+table, caption, tbody, tfoot, thead, tr, th, td,
+article, aside, canvas, details, embed,
+figure, figcaption, footer, header, hgroup,
+menu, nav, output, ruby, section, summary,
+time, mark, audio, video {
+ margin: 0;
+ padding: 0;
+ border: 0;
+ font: inherit;
+ vertical-align: baseline;
+}
+
+/* HTML5 display-role reset for older browsers */
+article, aside, details, figcaption, figure,
+footer, header, hgroup, menu, nav, section {
+ display: block;
+}
+body {
+ line-height: 1;
+ margin: 0;
+ background-color: #fff;
+}
+ol, ul {
+ list-style: none;
+}
+blockquote, q {
+ quotes: none;
+}
+blockquote:before, blockquote:after,
+q:before, q:after {
+ content: '';
+ content: none;
+}
+table {
+ border-collapse: collapse;
+ border-spacing: 0;
+}
+
+/* Remove outline from images and links */
+a {
+ outline: none;
+}
+
+img {
+ outline: none;
+}
+
+/* Clearfix */
+.clearfix:before,
+.clearfix:after {
+ content: "";
+ display: table;
+}
+
+.clearfix:after {
+ clear: both;
+}
+
+.clearfix {
+ zoom: 1; /* For IE 6/7 (trigger hasLayout) */
+}
\ No newline at end of file
--- /dev/null
+<?php
+class HeadwayResponsiveGridDynamicMedia {
+
+
+ static function content() {
+
+ $content = self::computers();
+ $content .= self::generic_mobile();
+ $content .= self::ipad_landscape();
+ $content .= self::ipad_portrait();
+ $content .= self::smartphones();
+
+ return apply_filters('headway_responsive_grid_css', $content);
+
+ }
+
+
+ static function computers() {
+
+ return '
+ /* --- Computers (Laptops/Desktops) --- */
+ @media only screen and (min-width: 1024px) {
+
+ /* Responsive Block Hiding */
+ .responsive-block-hiding-device-computers {
+ display: none !important;
+ }
+
+ }
+ ';
+
+ }
+
+
+ static function generic_mobile() {
+
+ return '
+ /* --- Generic Mobile --- */
+ @media only screen and (max-width: 1024px) {
+
+ .responsive-grid-active .block img,
+ .responsive-grid-active .block .wp-caption {
+ max-width: 100%;
+ height: auto;
+ }
+
+ .responsive-grid-active .block-type-footer p.footer-responsive-grid-link-container {
+ display: block;
+ }
+
+ }
+ ';
+
+ }
+
+
+ static function ipad_landscape() {
+
+ return '
+ /* --- iPad Landscape --- */
+ @media only screen and (min-width : 600px) and (max-width: 1024px) and (orientation : landscape) {
+
+ /* Responsive Block Hiding */
+ .responsive-block-hiding-device-tablets-landscape {
+ display: none !important;
+ }
+
+ }
+ ';
+
+ }
+
+
+ static function ipad_portrait() {
+
+ return '
+ /* --- iPad Portrait --- */
+ @media only screen and (min-width : 600px) and (max-width : 1024px) and (orientation : portrait) {
+
+ /* Responsive Block Hiding */
+ .responsive-block-hiding-device-tablets-portrait {
+ display: none !important;
+ }
+
+ }
+ ';
+
+ }
+
+
+ static function smartphones() {
+
+ return '
+ /* --- Smartphones and small Tablet PCs --- */
+ @media only screen and (max-width : 600px) {
+
+ /* Remove wrapper margins where necessary. Remove top margin from top wrapper as well as side margins */
+ .responsive-grid-active div.wrapper:first-child {
+ margin-top: 0 !important;
+ }
+
+ .responsive-grid-active div.wrapper {
+ margin-left: 0 !important;
+ margin-right: 0 !important;
+ }
+
+ /* Set all blocks/columns to be 100% width */
+ .responsive-grid-active .block, .responsive-grid-active .row, .responsive-grid-active .column {
+ width: 100% !important;
+ margin-left: 0 !important;
+ margin-right: 0 !important;
+ }
+
+ /* Take the minimum height off of fluid blocks. */
+ .responsive-grid-active .block {
+ min-height: inherit !important;
+ height: auto !important;
+ }
+
+ /* Responsive Block Hiding */
+ .responsive-block-hiding-device-smartphones {
+ display: none !important;
+ }
+
+ /* Navigation Block */
+ .responsive-grid-active .block-type-navigation {
+ height: auto;
+ }
+
+ .responsive-grid-active .block-type-navigation .selectnav { display: block; }
+ .responsive-grid-active .block-type-navigation ul.menu.selectnav-active { display: none; }
+ /* End Navigation Block */
+
+ /* Content Block */
+ .responsive-grid-active .block-type-content a.post-thumbnail {
+ width: 100%;
+ margin: 20px 0;
+ text-align: center;
+ }
+
+ .responsive-grid-active .block-type-content a.post-thumbnail img {
+ max-width: 100%;
+ height: auto;
+ }
+
+ .responsive-grid-active .block-type-content .loop-navigation {
+ text-align: center;
+ }
+
+ .responsive-grid-active .block-type-content .loop-navigation .nav-previous,
+ .responsive-grid-active .block-type-content .loop-navigation .nav-next {
+ float: none;
+ margin: 0 10px;
+ }
+
+ .responsive-grid-active .block-type-content .loop-navigation .nav-next {
+ margin-top: 20px;
+ }
+ /* End Content Block */
+
+ /* Footer Block */
+ .responsive-grid-active .block-type-footer div.footer > * {
+ clear: both;
+ float: none;
+ display: block;
+ margin: 15px 0;
+ text-align: center;
+ }
+ /* End Footer Block */
+
+ }
+ ';
+
+ }
+
+
+ static function fitvids() {
+
+ return 'jQuery(document).ready(function() { jQuery(document).fitVids(); });';
+
+ }
+
+
+}
\ No newline at end of file
--- /dev/null
+<?php
+class HeadwayDynamicStyle {
+
+
+ static function design_editor() {
+
+ /* Action used for registering elements */
+ do_action('headway_dynamic_style_design_editor_init');
+
+ $elements = HeadwayElementsData::get_all_elements();
+
+ $return = "/* DESIGN EDITOR STYLING */\n";
+
+ foreach ( $elements as $element_id => $element_options ) {
+
+ $element = HeadwayElementAPI::get_element($element_id);
+ $selector = $element['selector'];
+ $nudging_properties = array('top', 'left', 'position', 'z-index');
+
+ //Continue to next element if the element/selector does not exist
+ if ( !isset($selector) || $selector == false )
+ continue;
+
+ /* Regular Element */
+ if ( isset($element_options['properties']) )
+ $return .= HeadwayElementProperties::output_css($selector, self::filter_nudging_properties($element_options['properties'], $element));
+
+ /* Layout-specific elements */
+ if ( isset($element_options['special-element-layout']) && is_array($element_options['special-element-layout']) ) {
+
+ //Handle every layout
+ foreach ( $element_options['special-element-layout'] as $layout => $layout_properties ) {
+
+ if ( HeadwayLayout::is_customized($layout) ) {
+ $selector_prefix = 'body.layout-using-' . str_replace( HeadwayLayout::$sep, '-', $layout ) . ' ';
+ } else {
+ $selector_prefix = 'body.layout-' . str_replace( HeadwayLayout::$sep, '-', $layout ) . ' ';
+ }
+
+ $selector_array = explode(',', $selector);
+
+ foreach ( $selector_array as $selector_index => $selector )
+ $selector_array[$selector_index] = $selector_prefix . trim($selector);
+
+ $layout_element_selector = implode(',', $selector_array);
+
+ //Since the layout selectors are targeted by the body element, we can't do anything body to style the actual body element. Let's fix that.
+ if ( $selector == 'body' )
+ $layout_element_selector = str_replace(' body', '', $layout_element_selector); //The space inside str_replace is completely intentional.
+
+ $return .= HeadwayElementProperties::output_css($layout_element_selector, self::filter_nudging_properties($layout_properties, $element));
+
+ }
+
+ }
+
+ /* Instances */
+ if ( isset($element_options['special-element-instance']) && is_array($element_options['special-element-instance']) ) {
+
+ //Handle every instance
+ foreach ( $element_options['special-element-instance'] as $instance => $instance_properties ) {
+
+ //Make sure the instance exists
+ if ( !isset($element['instances'][$instance]) )
+ continue;
+
+ //Get the selector for the instance
+ $instance_selector = $element['instances'][$instance]['selector'];
+
+ $return .= HeadwayElementProperties::output_css($instance_selector, self::filter_nudging_properties($instance_properties, $element));
+
+ }
+
+ }
+
+ /* States */
+ if ( isset($element_options['special-element-state']) && is_array($element_options['special-element-state']) ) {
+
+ //Handle every instance
+ foreach ( $element_options['special-element-state'] as $state => $state_properties ) {
+
+ //Make sure the state exists
+ if ( !isset($element['states'][$state]) )
+ continue;
+
+ //Get the selector for the layout
+ $state_info = $element['states'][$state];
+
+ $return .= HeadwayElementProperties::output_css($state_info['selector'], self::filter_nudging_properties($state_properties, $element));
+
+ }
+
+ }
+
+ } //End main $elements foreach
+
+ return $return;
+
+ }
+
+
+
+ private static function filter_nudging_properties($properties, $element) {
+
+ if ( !isset($element['disallow-nudging']) || !$element['disallow-nudging'] )
+ return $properties;
+
+ /* If nudging is disallowed (e.g. sub menu element or body element), then do not even output the CSS */
+ foreach ( array('top', 'left', 'position', 'z-index') as $blocked_nudging_property )
+ unset($properties[$blocked_nudging_property]);
+
+ return $properties;
+
+ }
+
+
+ static function wrapper() {
+
+ $layout_id = headway_get('layout-in-use');
+ $wrappers = HeadwayWrappersData::get_wrappers_by_layout($layout_id);
+
+ $return = '';
+
+ /* Default Wrapper Margins */
+ if ( headway_get('file') == 've-iframe-grid-dynamic' && headway_get('visual-editor-open') ) {
+
+ $return .= HeadwayElementProperties::output_css('div.wrapper', array(
+ 'margin-top' => HeadwayElementsData::get_property('wrapper', 'margin-top', HeadwayWrappers::$default_wrapper_margin_top, 'structure'),
+ 'margin-bottom' => HeadwayElementsData::get_property('wrapper', 'margin-bottom', HeadwayWrappers::$default_wrapper_margin_bottom, 'structure'),
+ 'padding-top' => HeadwayElementsData::get_property('wrapper', 'padding-top', null, 'structure'),
+ 'padding-right' => HeadwayElementsData::get_property('wrapper', 'padding-right', null, 'structure'),
+ 'padding-bottom' => HeadwayElementsData::get_property('wrapper', 'padding-bottom', null, 'structure'),
+ 'padding-left' => HeadwayElementsData::get_property('wrapper', 'padding-left', null, 'structure')
+ ));
+
+ }
+
+ /* Wrappers for Layout */
+ foreach ( $wrappers as $wrapper_id => $wrapper ) {
+
+ $wrapper_settings = headway_get('settings', $wrapper, array());
+ $wrapper_grid_width = HeadwayWrappers::get_grid_width($wrapper);
+
+ $wrapper_id = HeadwayWrappersData::get_legacy_id( $wrapper );
+ $wrapper['original-id'] = $wrapper['id'];
+ $wrapper['id'] = HeadwayWrappersData::get_legacy_id( $wrapper );
+
+ /* Set up variables for wrapper */
+ if ( headway_get('file') == 've-iframe-grid-dynamic' && headway_get('visual-editor-open') ) {
+ $wrapper_selector = 'div#wrapper-' . HeadwayWrappers::format_wrapper_id($wrapper['original-id']);
+ } else {
+ $wrapper_selector = 'div#wrapper-' . HeadwayWrappers::format_wrapper_id($wrapper_id);
+ }
+
+ /* Fixed Wrapper */
+ if ( !headway_get('fluid', $wrapper_settings, false, true) ) {
+
+ /* Wrapper */
+ $return .= $wrapper_selector . ' {
+ width: ' . $wrapper_grid_width . 'px;
+ }';
+
+ if ( HeadwayResponsiveGrid::is_enabled() ) {
+
+ $return .= $wrapper_selector . '.responsive-grid {
+ width: auto !important;
+ max-width: ' . $wrapper_grid_width . 'px;
+ }';
+
+ }
+
+ /* Grid */
+ if ( headway_get('file') != 've-iframe-grid-dynamic' || !headway_get('visual-editor-open') )
+ $return .= HeadwayResponsiveGrid::is_enabled() ? self::responsive_grid($wrapper) : self::fixed_grid($wrapper);
+
+ /* Fluid Wrapper */
+ } else {
+
+ /* Grid Container */
+ /* Fixed Grid */
+ if ( !(headway_get('fluid', $wrapper_settings, false, true) && headway_get('fluid-grid', $wrapper_settings, false, true)) ) {
+
+ $return .= $wrapper_selector . ' div.grid-container {
+ width: ' . $wrapper_grid_width . 'px;
+ }';
+
+ if ( HeadwayResponsiveGrid::is_enabled() ) {
+
+ $return .= $wrapper_selector . '.responsive-grid div.grid-container {
+ width: auto !important;
+ max-width: ' . $wrapper_grid_width . 'px;
+ }';
+
+ }
+
+ }
+
+ /* Grid */
+ if ( headway_get('file') != 've-iframe-grid-dynamic' || !headway_get('visual-editor-open') )
+ $return .= (HeadwayResponsiveGrid::is_enabled() || (headway_get('fluid', $wrapper_settings, false, true) && headway_get('fluid-grid', $wrapper_settings, false, true))) ? self::responsive_grid($wrapper) : self::fixed_grid($wrapper);
+
+ }
+
+ /* Both Fixed and Fluid: Margin in Grid Mode */
+ if ( headway_get('file') == 've-iframe-grid-dynamic' && headway_get('visual-editor-open') ) {
+
+ $wrapper_instance_id = 'wrapper-' . HeadwayWrappers::format_wrapper_id($wrapper['original-id']);
+
+ $return .= HeadwayElementProperties::output_css($wrapper_selector, array(
+ 'margin-top' => HeadwayElementsData::get_special_element_property('wrapper', 'instance', $wrapper_instance_id, 'margin-top', null, 'structure'),
+ 'margin-bottom' => HeadwayElementsData::get_special_element_property('wrapper', 'instance', $wrapper_instance_id, 'margin-bottom', null, 'structure'),
+ 'padding-top' => HeadwayElementsData::get_special_element_property('wrapper', 'instance', $wrapper_instance_id, 'padding-top', null, 'structure'),
+ 'padding-right' => HeadwayElementsData::get_special_element_property('wrapper', 'instance', $wrapper_instance_id, 'padding-right', null, 'structure'),
+ 'padding-bottom' => HeadwayElementsData::get_special_element_property('wrapper', 'instance', $wrapper_instance_id, 'padding-bottom', null, 'structure'),
+ 'padding-left' => HeadwayElementsData::get_special_element_property('wrapper', 'instance', $wrapper_instance_id, 'padding-left', null, 'structure')
+ ));
+
+ }
+
+ /* Responsive Break Points */
+ if ( !HeadwayRoute::is_visual_editor_iframe('grid') && !(headway_get( 'file' ) == 've-iframe-grid-dynamic') ) {
+
+ $responsive_options = headway_get( 'responsive-wrapper-options', $wrapper_settings, array() );
+
+ $options = self::get_repeater_options( $responsive_options, 'breakpoint' );
+
+ if ( $options ) {
+
+ foreach ( $options as $option ) {
+
+ /* Responsive CSS - some magic to make the columns work with the smartphone setting */
+ $breakpoint = headway_fix_data_type( headway_get( 'breakpoint', $option, 'off' ) );
+ $max_width = headway_fix_data_type( headway_get( 'max-width', $option, '' ) );
+
+
+ if ( $max_width && $breakpoint == 'custom' )
+ $breakpoint = $max_width;
+
+ $breakpoint_min_max = headway_fix_data_type( headway_get( 'breakpoint-min-or-max', $option, 'max' ) );
+ $stretch = headway_fix_data_type( headway_get( 'stretch', $option, false ) );
+ $auto_center = headway_fix_data_type( headway_get( 'auto-center', $option, false ) );
+ $hide_wrapper = headway_fix_data_type( headway_get( 'hide-wrapper', $option, false ) );
+
+ /* Output Responsive CSS */
+ $return .= '@media screen and (' . $breakpoint_min_max . '-width: ' . $breakpoint . ' ) { ';
+
+ if ( $stretch )
+ $return .= $wrapper_selector . ' .column {
+ width: 100%;
+ clear: both;
+ margin-left: 0;
+ margin-right: 0;
+ }';
+
+ if ( $auto_center )
+ $return .=
+ $wrapper_selector . ' .block, #whitewrap ' . $wrapper_selector . ' .block ul {
+ text-align: center;
+ }';
+
+ if ( $hide_wrapper )
+ $return .= $wrapper_selector . ' { display: none!important; }';
+
+
+ $return .= '}'; //close media query
+
+
+ }
+
+ }
+
+ }
+
+ }
+
+ return $return;
+
+ }
+
+
+ static function fixed_grid(array $wrapper) {
+
+ global $wrapper_css_flags;
+
+ $wrapper_settings = headway_get('settings', $wrapper, array());
+
+ /* If wrapper is mirrored then use settings from it for the grid */
+ if ( $potential_wrapper_mirror = HeadwayWrappersData::get_wrapper_mirror($wrapper_settings) )
+ $wrapper_settings = $potential_wrapper_mirror;
+
+ $grid_number = HeadwayWrappers::get_columns($wrapper);
+
+ $column_width = HeadwayWrappers::get_column_width($wrapper);
+ $gutter_width = HeadwayWrappers::get_gutter_width($wrapper);
+
+ /* Keep extraneous CSS from be created by wrappers that have the same settings */
+ $grid_class = 'grid-fixed-' . $grid_number . '-' . $column_width . '-' . $gutter_width;
+
+ if ( isset($wrapper_css_flags[$grid_class]) )
+ return;
+ /* End extraneous CSS check */
+
+ $grid_wrapper_width = ($column_width * $grid_number) + ($grid_number * $gutter_width);
+
+ /* Add CSS prefix */
+ $prefix = 'div.' . $grid_class . ' ';
+
+ /* Column left margins */
+ $return = $prefix . '.column { margin-left: ' . ($gutter_width) . 'px; }';
+
+ /* Widths and Lefts */
+ for ( $i = 1; $i <= $grid_number; $i++ ) {
+
+ /* Vars */
+ $grid_width = $column_width * $i + (($i - 1) * $gutter_width);
+ $grid_left_margin = (($column_width + $gutter_width) * $i) + $gutter_width;
+
+ $return .= $prefix . '.grid-width-' . $i . ' { width:' . ($grid_width) . 'px; }';
+ $return .= $prefix . '.grid-left-' . $i . ' { margin-left: ' . ($grid_left_margin) . 'px; }';
+
+ /**
+ * If it's the first column in a row and the column doesn't start on the far left,
+ * then the additional gutter doesn't have to be taken into consideration
+ **/
+ $return .= $prefix . '.column-1.grid-left-' . $i . ' { margin-left: ' . ($grid_left_margin - $gutter_width) . 'px; }';
+
+ }
+
+ /* Create a flag keeping this same Grid CSS from being outputted */
+ $wrapper_css_flags['grid-fixed-' . $grid_number . '-' . $column_width . '-' . $gutter_width] = true;
+
+ return $return;
+
+ }
+
+
+ static function responsive_grid(array $wrapper) {
+
+ global $wrapper_css_flags;
+
+ $wrapper_settings = headway_get('settings', $wrapper, array());
+
+ /* If wrapper is mirrored then use settings from it for the grid */
+ if ( $potential_wrapper_mirror = HeadwayWrappersData::get_wrapper_mirror($wrapper_settings) )
+ $wrapper_settings = $potential_wrapper_mirror;
+
+ $round_precision = 9;
+ $return = '';
+
+ $grid_number = HeadwayWrappers::get_columns($wrapper);
+
+ $column_width = HeadwayWrappers::get_column_width($wrapper);
+ $gutter_width = HeadwayWrappers::get_gutter_width($wrapper);
+
+ /* Render the Grid into arrays to see if sub column CSS will be needed */
+ if ( $wrapper_mirror = HeadwayWrappersData::get_wrapper_mirror( $wrapper['id'] ) ) {
+ $wrapper_blocks = HeadwayBlocksData::get_blocks_by_wrapper( $wrapper_mirror['layout'], $wrapper_mirror['id'] );
+ } else {
+ $wrapper_blocks = HeadwayBlocksData::get_blocks_by_wrapper( headway_get( 'layout-in-use' ), $wrapper['original-id'] );
+ }
+
+ $wrapper_rendered = new HeadwayGridRenderer($wrapper_blocks, $wrapper_settings);
+
+ /* Process the blocks into arrays */
+ $wrapper_rendered->process();
+
+ $blocks_in_sub_columns = !empty($wrapper_rendered->blocks_in_sub_columns) ? true : false;
+
+ /* Keep extraneous CSS from be created by wrappers that have the same settings */
+ $grid_class = 'grid-fluid-' . $grid_number . '-' . $column_width . '-' . $gutter_width;
+
+ /* If there are no sub columns and the main CSS has already been outputted, just stop here */
+ if ( isset($wrapper_css_flags[$grid_class]) && !$blocks_in_sub_columns )
+ return;
+ /* End extraneous CSS check */
+
+ /* Make calculations for the percentages */
+ $grid_wrapper_width = ($column_width * $grid_number) + (($grid_number - 1) * $gutter_width);
+
+ $resp_width_ratio = ($column_width * $grid_number) / $grid_wrapper_width;
+ $resp_gutter_ratio = ($gutter_width * $grid_number) / $grid_wrapper_width;
+ $resp_single_column_width = (100 / $grid_number) * $resp_width_ratio;
+ $resp_single_column_margin = (100 / $grid_number) * $resp_gutter_ratio;
+
+ /* Add CSS prefix */
+ $prefix = 'div.' . $grid_class . ' ';
+
+ /* Generate the main Grid CSS */
+ if ( !isset($wrapper_css_flags[$grid_class]) ) {
+
+ $return .= $prefix . '.column { margin-left: ' . round($resp_single_column_margin, $round_precision) . '%; }' . "\n";
+
+ for ( $i = 1; $i <= $grid_number; $i++ ) {
+
+ /* Vars */
+ $resp_grid_width = ($resp_single_column_width * $i) + ($i * $resp_single_column_margin);
+ $resp_grid_left_margin = (($resp_single_column_width + $resp_single_column_margin) * $i) + $resp_single_column_margin;
+
+ /* Output */
+ $return .= $prefix . '.grid-width-' . $i . ' { width: ' . round($resp_grid_width - $resp_single_column_margin, $round_precision) . '%; }' . "\n";
+
+ if ( $i < $grid_number ) {
+
+ $return .= $prefix . '.grid-left-' . $i . ' { margin-left: ' . round($resp_grid_left_margin, $round_precision) . '%; }' . "\n";
+
+ /**
+ * If it's the first column in a row and the column doesn't start on the far left,
+ * then the additional gutter doesn't have to be taken into consideration
+ **/
+ $return .= $prefix . '.column-1.grid-left-' . $i . ' { margin-left: ' . round($resp_grid_left_margin - $resp_single_column_margin, $round_precision) . '%; }';
+
+ }
+
+ }
+
+ /* Create a flag keeping this same Grid CSS from being outputted */
+ $wrapper_css_flags['grid-fluid-' . $grid_number . '-' . $column_width . '-' . $gutter_width] = true;
+
+ }
+ /* End main grid CSS */
+
+ /* Responsive Sub Column CSS */
+ if ( $blocks_in_sub_columns ) {
+
+ /* Get the columns required for sub columns */
+ $required_columns_for_sub_columns = array();
+
+ foreach ( $wrapper_rendered->blocks_in_sub_columns as $block_in_sub_column_id ) {
+
+ if ( isset( $wrapper_rendered->blocks[ $block_in_sub_column_id ]['parent-column-width'] ) ) {
+
+ $required_columns_for_sub_columns[] = $wrapper_rendered->blocks[ $block_in_sub_column_id ]['parent-column-width'];
+
+ }
+
+ }
+
+ $required_columns_for_sub_columns = array_filter(array_unique($required_columns_for_sub_columns));
+ /* End getting columns required for sub columns */
+
+ for ( $i = 1; $i <= $grid_number; $i++ ) {
+
+ /* Don't output the sub column CSS if there's no column of this number with sub columns and don't output it if has already by a previous wrapper. */
+ if ( !in_array($i, $required_columns_for_sub_columns) || isset($wrapper_css_flags['grid-fluid-' . $grid_number . '-' . $column_width . '-' . $gutter_width . '-sub-columns-column-' . $i]) )
+ continue;
+
+ /* Vars */
+ $resp_grid_width = ($resp_single_column_width * $i) + ($i * $resp_single_column_margin);
+ $resp_grid_left_margin = (($resp_single_column_width + $resp_single_column_margin) * $i) + $resp_single_column_margin;
+
+ $sub_column_single_width = ($resp_single_column_width / $resp_grid_width) * 100;
+ $sub_column_single_margin = ($resp_single_column_margin / $resp_grid_width) * 100;
+
+ $return .= $prefix . '.grid-width-' . $i . ' .sub-column { margin-left: ' . round($sub_column_single_margin, $round_precision) . '%; }' . "\n";
+
+ for ( $sub_column_i = 1; $sub_column_i < $i; $sub_column_i++ ) {
+
+ /* Sub column vars */
+ $sub_column_width = ($sub_column_single_width * $sub_column_i) + ($sub_column_i * $sub_column_single_margin);
+ $sub_column_margin = (($sub_column_single_width + $sub_column_single_margin) * $sub_column_i) + $sub_column_single_margin;
+
+ $return .= $prefix . '.grid-width-' . $i . ' .sub-column.grid-width-' . $sub_column_i . ' { width: ' . round($sub_column_width - $sub_column_single_margin, $round_precision) . '%; }' . "\n";
+ $return .= $prefix . '.grid-width-' . $i . ' .sub-column.grid-width-' . $sub_column_i . '.column-1 { width: ' . round($sub_column_width, $round_precision) . '%; }' . "\n";
+
+ $return .= $prefix . '.grid-width-' . $i . ' .sub-column.grid-left-' . $sub_column_i . ' { margin-left: ' . round($sub_column_margin, $round_precision) . '%; }' . "\n";
+ $return .= $prefix . '.grid-width-' . $i . ' .sub-column.grid-left-' . $sub_column_i . '.column-1 { margin-left: ' . round($sub_column_margin - $sub_column_single_margin, $round_precision) . '%; }' . "\n";
+
+ }
+
+ /* Create a flag keeping this same sub column CSS from being outputted */
+ $wrapper_css_flags['grid-fluid-' . $grid_number . '-' . $column_width . '-' . $gutter_width . '-sub-columns-column-' . $i] = true;
+
+ }
+
+ }
+ /* End responsive sub column CSS */
+
+ return $return;
+
+ }
+
+
+ static function block_heights() {
+
+ if ( !($blocks = HeadwayBlocksData::get_all_blocks()) )
+ return false;
+
+ $return = '';
+
+ //Retrieve the blocks so we can check if the block type is fixed or fluid height
+ $block_types = HeadwayBlocks::get_block_types();
+
+ foreach ( $blocks as $block ) {
+
+ /* Use legacy ID if present */
+ $block['id'] = HeadwayBlocksData::get_legacy_id( $block );
+
+ $selector = '#block-' . $block['id'];
+
+ /* If the block is mirrored then change the selector */
+ if ( $mirrored_block_id = HeadwayBlocksData::is_block_mirrored($block) )
+ $selector = '#block-' . $mirrored_block_id . '.block-original-' . $block['id'];
+
+ //If it's a fluid block (which blocks ARE by default), then we need to use min-height. Otherwise, if it's fixed, we use height.
+ if ( headway_get('fixed-height', headway_get($block['type'], $block_types), false) !== true )
+ $return .= $selector . ' { min-height: ' . $block['dimensions']['height'] . 'px; }';
+ else
+ $return .= $selector . ' { height: ' . $block['dimensions']['height'] . 'px; }';
+
+ $responsive_options = headway_get('responsive-options', $block['settings'], array());
+
+ $options = self::get_repeater_options($responsive_options, 'blocks-breakpoint');
+
+ if($options) {
+
+ foreach ($options as $option) {
+
+ /* Responsive CSS - some magic to make the columns work with the smartphone setting */
+ $breakpoint = headway_fix_data_type(headway_get('blocks-breakpoint', $option, 'off'));
+
+ if( !$breakpoint )
+ continue;
+
+ $max_width = headway_fix_data_type(headway_get('max-width', $option, ''));
+
+ if($max_width && $breakpoint == 'custom')
+ $breakpoint = $max_width;
+
+ $disable_block_height = headway_fix_data_type(headway_get( 'disable-block-height', $option, false));
+ $mobile_auto_center = headway_fix_data_type(headway_get( 'mobile-center-elements', $option, false));
+ $breakpoint_min_max = headway_fix_data_type(headway_get( 'breakpoint-min-or-max', $option, 'max'));
+
+ $fixed_height = headway_get('fixed-height', headway_get($block['type'], $block_types));
+
+ /* Griddify Lists */
+ $griddify_lists = headway_fix_data_type(headway_get( 'griddify-lists', $option, false));
+
+ $hide_block = headway_fix_data_type(headway_get('hide-block', $option, false));
+
+ /* Output Responsive CSS */
+ $return .= '@media screen and ('. $breakpoint_min_max .'-width: ' . $breakpoint . ' ) { ';
+
+ $return .= '#whitewrap ' . $selector . ' {';
+
+ if ($hide_block)
+ $return .= 'display: none!important;';
+ if ($disable_block_height && $fixed_height !== true)
+ $return .= 'min-height: inherit;';
+ if ($disable_block_height && $fixed_height)
+ $return .= 'height: auto;';
+
+ $return .= '}';//close $selector
+
+ if ($mobile_auto_center)
+ $return .= '#whitewrap ' . $selector . ' * {
+ text-align: center;
+ }';
+
+
+
+ if ( $griddify_lists ) {
+ $return .= '#whitewrap ' . $selector . ' ul > li {
+ float: left;
+ margin: 0;
+ width: 50%;
+ font-size: 120%;
+ -webkit-box-sizing: border-box;
+ -moz-box-sizing: border-box;
+ box-sizing: border-box;';
+
+ if ($mobile_auto_center)
+ $return .= 'text-align: center;';
+
+ $return .= '}';
+
+ $selector . ' ul li:nth-child(2n) {
+ border-right: none;
+ }';
+
+ }
+
+ $return .= '}';//close media query
+
+
+ }
+
+ }
+
+ }
+
+ return $return;
+
+ }
+
+ static function get_repeater_options($options, $default) {
+
+ $has_options = false;
+
+ foreach ( $options as $option )
+ if ( $option[$default] ) {
+ $has_options = true;
+ break;
+ }
+
+ if ( $has_options )
+ return $options;
+
+ }
+
+
+ static function live_css() {
+
+ if ( headway_get('visual-editor-open') )
+ return null;
+
+ return HeadwaySkinOption::get('live-css');
+
+ }
+
+}
\ No newline at end of file
--- /dev/null
+/*
+ HTML5 Shiv v3.7.0 | @afarkas @jdalton @jon_neal @rem | MIT/GPL2 Licensed
+ */
+(function(l,f){function m(){var a=e.elements;return"string"==typeof a?a.split(" "):a}function i(a){var b=n[a[o]];b||(b={},h++,a[o]=h,n[h]=b);return b}function p(a,b,c){b||(b=f);if(g)return b.createElement(a);c||(c=i(b));b=c.cache[a]?c.cache[a].cloneNode():r.test(a)?(c.cache[a]=c.createElem(a)).cloneNode():c.createElem(a);return b.canHaveChildren&&!s.test(a)?c.frag.appendChild(b):b}function t(a,b){if(!b.cache)b.cache={},b.createElem=a.createElement,b.createFrag=a.createDocumentFragment,b.frag=b.createFrag();
+ a.createElement=function(c){return!e.shivMethods?b.createElem(c):p(c,a,b)};a.createDocumentFragment=Function("h,f","return function(){var n=f.cloneNode(),c=n.createElement;h.shivMethods&&("+m().join().replace(/[\w\-]+/g,function(a){b.createElem(a);b.frag.createElement(a);return'c("'+a+'")'})+");return n}")(e,b.frag)}function q(a){a||(a=f);var b=i(a);if(e.shivCSS&&!j&&!b.hasCSS){var c,d=a;c=d.createElement("p");d=d.getElementsByTagName("head")[0]||d.documentElement;c.innerHTML="x<style>article,aside,dialog,figcaption,figure,footer,header,hgroup,main,nav,section{display:block}mark{background:#FF0;color:#000}template{display:none}</style>";
+ c=d.insertBefore(c.lastChild,d.firstChild);b.hasCSS=!!c}g||t(a,b);return a}var k=l.html5||{},s=/^<|^(?:button|map|select|textarea|object|iframe|option|optgroup)$/i,r=/^(?:a|b|code|div|fieldset|h1|h2|h3|h4|h5|h6|i|label|li|ol|p|q|span|strong|style|table|tbody|td|th|tr|ul)$/i,j,o="_html5shiv",h=0,n={},g;(function(){try{var a=f.createElement("a");a.innerHTML="<xyz></xyz>";j="hidden"in a;var b;if(!(b=1==a.childNodes.length)){f.createElement("a");var c=f.createDocumentFragment();b="undefined"==typeof c.cloneNode||
+ "undefined"==typeof c.createDocumentFragment||"undefined"==typeof c.createElement}g=b}catch(d){g=j=!0}})();var e={elements:k.elements||"abbr article aside audio bdi canvas data datalist details dialog figcaption figure footer header hgroup main mark meter nav output progress section summary template time video",version:"3.7.0",shivCSS:!1!==k.shivCSS,supportsUnknownElements:g,shivMethods:!1!==k.shivMethods,type:"default",shivDocument:q,createElement:p,createDocumentFragment:function(a,b){a||(a=f);
+ if(g)return a.createDocumentFragment();for(var b=b||i(a),c=b.frag.cloneNode(),d=0,e=m(),h=e.length;d<h;d++)c.createElement(e[d]);return c}};l.html5=e;q(f)})(this,document);
\ No newline at end of file
--- /dev/null
+/*
+ IE7/IE8/IE9.js - copyright 2004-2010, Dean Edwards
+ http://code.google.com/p/ie7-js/
+ http://www.opensource.org/licenses/mit-license.php
+*/
+;(function(L,r){var h=L.IE7={version:"2.1(beta4)",toString:bJ("[IE7]")};h.compat=8;var s=h.appVersion=navigator.appVersion.match(/MSIE (\d\.\d)/)[1]-0;if(/ie7_off/.test(top.location.search)||s<5.5||s>=h.compat)return;var C=s<6,bh=bJ(),bt=r.documentElement,A,w,ci="!",X=":link{ie7-link:link}:visited{ie7-link:visited}",cj=/^[\w\.]+[^:]*$/;function bi(b,a){if(cj.test(b))b=(a||"")+b;return b};function bu(b,a){b=bi(b,a);return b.slice(0,b.lastIndexOf("/")+1)};var bK=r.scripts[r.scripts.length-1],ck=bu(bK.src);try{var Q=new ActiveXObject("Microsoft.XMLHTTP")}catch(ex){}var bj={};function cl(b,a){try{b=bi(b,a);if(!bj[b]){Q.open("GET",b,false);Q.send();if(Q.status==0||Q.status==200){bj[b]=Q.responseText}}}catch(ex){}return bj[b]||""};var dl=Array.prototype.slice,dm=/%([1-9])/g,cm=/^\s\s*/,cn=/\s\s*$/,co=/([\/()[\]{}|*+-.,^$?\\])/g,bL=/\bbase\b/,bM=["constructor","toString"],bk;function D(){};D.extend=function(f,d){bk=true;var c=new this;Y(c,f);bk=false;var b=c.constructor;function a(){if(!bk)b.apply(this,arguments)};c.constructor=a;a.extend=arguments.callee;Y(a,d);a.prototype=c;return a};D.prototype.extend=function(a){return Y(this,a)};var M="#",N="#",Z=".",bl="/",dn=/\\(\d+)/g,cp=/\[(\\.|[^\]\\])+\]|\\.|\(\?/g,cq=/\(/g,cr=/\$(\d+)/,cs=/^\$\d+$/,ct=/(\[(\\.|[^\]\\])+\]|\\.|\(\?)|\(/g,cu=/^<#\w+>$/,cv=/<#(\w+)>/g,E=D.extend({constructor:function(a){this[Z]=[];this[N]={};this.merge(a)},add:function(b,a){delete this[bl];if(b instanceof RegExp){b=b.source}if(!this[M+b])this[Z].push(String(b));return this[N][M+b]=new E.Item(b,a,this)},compile:function(a){if(a||!this[bl]){this[bl]=new RegExp(this,this.ignoreCase?"gi":"g")}return this[bl]},merge:function(b){for(var a in b)this.add(a,b[a])},exec:function(n){var j=this,k=j[Z],l=j[N],i,g=this.compile(true).exec(n);if(g){var f=0,d=1;while((i=l[M+k[f++]])){var c=d+i.length+1;if(g[d]){if(i.replacement===0){return j.exec(n)}else{var b=g.slice(d,c),a=b.length;while(--a)b[a]=b[a]||"";b[0]={match:b[0],item:i};return b}}d=c}}return null},parse:function(n){n+="";var j=this,k=j[Z],l=j[N];return n.replace(this.compile(),function(i){var g=[],f,d=1,c=arguments.length;while(--c)g[c]=arguments[c]||"";while((f=l[M+k[c++]])){var b=d+f.length+1;if(g[d]){var a=f.replacement;switch(typeof a){case"function":return a.apply(j,g.slice(d,b));case"number":return g[d+a];default:return a}}d=b}return i})},toString:function(){var f=[],d=this[Z],c=this[N],b;for(var a=0;b=c[M+d[a]];a++){f[a]=b.source}return"("+f.join(")|(")+")"}},{IGNORE:null,Item:D.extend({constructor:function(j,k,l){var i=j.indexOf("(")===-1?0:E.count(j),g=l.dictionary;if(g&&j.indexOf("<#")!==-1){if(cu.test(j)){var f=g[N][M+j.slice(2,-1)];j=f.replacement;i=f._4}else{j=g.parse(j)}}if(typeof k=="number")k=String(k);else if(k==null)k=0;if(typeof k=="string"&&cr.test(k)){if(cs.test(k)){var d=k.slice(1)-0;if(d&&d<=i)k=d}else{var c=k,b;k=function(a){if(!b){b=new RegExp(j,"g"+(this.ignoreCase?"i":""))}return a.replace(b,c)}}}this.length=i;this.source=String(j);this.replacement=k}}),count:function(a){return(String(a).replace(cp,"").match(cq)||"").length}}),cw=E.extend({parse:function(d){var c=this[N];return d.replace(cv,function(b,a){a=c[M+a];return a?a._5:b})},add:function(f,d){if(d instanceof RegExp){d=d.source}var c=d.replace(ct,cx);if(d.indexOf("(")!==-1){var b=E.count(d)}if(d.indexOf("<#")!==-1){d=this.parse(d);c=this.parse(c)}var a=this.base(f,d);a._5=c;a._4=b||a.length;return a},toString:function(){return"(<#"+this[PATTERNS].join(">)|(<#")+">)"}});function cx(b,a){return a||"(?:"};function Y(g,f){if(g&&f){var d=(typeof f=="function"?Function:Object).prototype;var c=bM.length,b;if(bk)while(b=bM[--c]){var a=f[b];if(a!=d[b]){if(bL.test(a)){bN(g,b,a)}else{g[b]=a}}}for(b in f)if(typeof d[b]=="undefined"){var a=f[b];if(g[b]&&typeof a=="function"&&bL.test(a)){bN(g,b,a)}else{g[b]=a}}}return g};function bN(g,f,d){var c=g[f];g[f]=function(){var b=this.base;this.base=c;var a=d.apply(this,arguments);this.base=b;return a}};function cy(d,c){if(!c)c=d;var b={};for(var a in d)b[a]=c[a];return b};function F(f){var d=arguments,c=new RegExp("%([1-"+arguments.length+"])","g");return String(f).replace(c,function(b,a){return a<d.length?d[a]:b})};function bm(b,a){return String(b).match(a)||[]};function bO(a){return String(a).replace(co,"\\$1")};function bP(a){return String(a).replace(cm,"").replace(cn,"")};function bJ(a){return function(){return a}};var bQ=E.extend({ignoreCase:true}),cz=/'/g,bR=/'(\d+)'/g,o0=/\\/g,bv=/\\([nrtf'"])/g,R=[],bS=new bQ({"<!\\-\\-|\\-\\->":"","\\/\\*[^*]*\\*+([^\\/][^*]*\\*+)*\\/":"","@(namespace|import)[^;\\n]+[;\\n]":"","'(\\\\.|[^'\\\\])*'":bT,'"(\\\\.|[^"\\\\])*"':bT,"\\s+":" "});function cA(a){return bS.parse(a).replace(bv,"$1")};function ba(a){return a.replace(bR,cB)};function bT(b){var a=R.length;R[a]=b.slice(1,-1).replace(bv,"$1").replace(cz,"\\'");return"'"+a+"'"};function cB(c,b){var a=R[b];if(a==null)return c;return"'"+R[b]+"'"};function bn(a){return a.indexOf("'")===0?R[a.slice(1,-1)]:a};var cC=new E({Width:"Height",width:"height",Left:"Top",left:"top",Right:"Bottom",right:"bottom",onX:"onY"});function bU(a){return cC.parse(a)};var bV=[];function bw(a){cD(a);x(L,"onresize",a)};function x(c,b,a){c.attachEvent(b,a);bV.push(arguments)};function cE(c,b,a){try{c.detachEvent(b,a)}catch(ex){}};x(L,"onunload",function(){var a;while(a=bV.pop()){cE(a[0],a[1],a[2])}});function bb(c,b,a){if(!c.elements)c.elements={};if(a)c.elements[b.uniqueID]=b;else delete c.elements[b.uniqueID];return a};x(L,"onbeforeprint",function(){if(!h.CSS.print)new bW("print");h.CSS.print.recalc()});var bX=/^\d+(px)?$/i,S=/^\d+%$/,B=function(d,c){if(bX.test(c))return parseInt(c);var b=d.style.left,a=d.runtimeStyle.left;d.runtimeStyle.left=d.currentStyle.left;d.style.left=c||0;c=d.style.pixelLeft;d.style.left=b;d.runtimeStyle.left=a;return c},bx="ie7-",bY=D.extend({constructor:function(){this.fixes=[];this.recalcs=[]},init:bh}),by=[];function cD(a){by.push(a)};h.recalc=function(){h.HTML.recalc();h.CSS.recalc();for(var a=0;a<by.length;a++)by[a]()};function bo(a){return a.currentStyle["ie7-position"]=="fixed"};function bz(b,a){return b.currentStyle[bx+a]||b.currentStyle[a]};function T(c,b,a){if(c.currentStyle[bx+b]==null){c.runtimeStyle[bx+b]=c.currentStyle[b]}c.runtimeStyle[b]=a};function bZ(b){var a=r.createElement(b||"object");a.style.cssText="position:absolute;padding:0;display:block;border:none;clip:rect(0 0 0 0);left:-9999";a.ie7_anon=true;return a};var cF="(e.nextSibling&&IE7._1(e,'next'))",cG=cF.replace(/next/g,"previous"),ca="e.nodeName>'@'",cb="if("+ca+"){",cH="(e.nodeName==='FORM'?IE7._0(e,'id'):e.id)",cI=/a(#[\w-]+)?(\.[\w-]+)?:(hover|active)/i,cJ=/(.*)(:first-(line|letter))/,cK=/\s/,cL=/((?:\\.|[^{\\])+)\{((?:\\.|[^}\\])+)\}/g,cM=/(?:\\.|[^,\\])+/g,G=r.styleSheets,bA=[];h.CSS=new(bY.extend({parser:new bQ,screen:"",print:"",styles:[],rules:[],pseudoClasses:s<7?"first\\-child":"",dynamicPseudoClasses:{toString:function(){var b=[];for(var a in this)b.push(a);return b.join("|")}},init:function(){var i="^\x01$",g="\\[class=?[^\\]]*\\]",f=[];if(this.pseudoClasses)f.push(this.pseudoClasses);var d=this.dynamicPseudoClasses.toString();if(d)f.push(d);f=f.join("|");var c=s<7?["[>+~\\[(]|([:.])[\\w-]+\\1"]:[g];if(f)c.push(":("+f+")");this.UNKNOWN=new RegExp(c.join("|")||i,"i");var b=s<7?["\\[[^\\]]+\\]|[^\\s(\\[]+\\s*[+~]"]:[g],a=b.concat();if(f)a.push(":("+f+")");t.COMPLEX=new RegExp(a.join("|")||i,"ig");if(this.pseudoClasses)b.push(":("+this.pseudoClasses+")");bc.COMPLEX=new RegExp(b.join("|")||i,"i");d="not\\(:"+d.split("|").join("\\)|not\\(:")+"\\)|"+d;bc.MATCH=new RegExp(d?"(.*?):("+d+")(.*)":i,"i");this.createStyleSheet();this.refresh()},addEventHandler:function(){x.apply(null,arguments)},addFix:function(b,a){this.parser.add(b,a)},addRecalc:function(g,f,d,c){g=g.source||g;f=new RegExp("([{;\\s])"+g+"\\s*:\\s*"+f+"[^;}]*");var b=this.recalcs.length;if(typeof c=="string")c=g+":"+c;this.addFix(f,function(a){if(typeof c=="function")c=c(a);return(c?c:a)+";ie7-"+a.slice(1)+";ie7_recalc"+b+":1"});this.recalcs.push(arguments);return b},apply:function(){this.getInlineCSS();new bW("screen");this.trash()},createStyleSheet:function(){r.getElementsByTagName("head")[0].appendChild(r.createElement("style"));this.styleSheet=G[G.length-1];this.styleSheet.ie7=true;this.styleSheet.owningElement.ie7=true;this.styleSheet.cssText=X},getInlineCSS:function(){var c=r.getElementsByTagName("style"),b;for(var a=c.length-1;b=c[a];a--){if(!b.disabled&&!b.ie7){b._6=b.innerHTML}}},getText:function(c,b){try{var a=c.cssText}catch(e){a=""}if(Q)a=cl(c.href,b)||a;return a},recalc:function(){this.screen.recalc();var o=/ie7_recalc\d+/g,m=X.match(/[{,]/g).length,n=this.styleSheet.rules,j,k,l,i,g,f,d,c,b;for(f=m;j=n[f];f++){var a=j.style.cssText;if(k=a.match(o)){i=H(j.selectorText);if(i.length)for(d=0;d<k.length;d++){b=k[d];l=h.CSS.recalcs[b.slice(10)][2];for(c=0;(g=i[c]);c++){if(g.currentStyle[b])l(g,a)}}}}},refresh:function(){this.styleSheet.cssText=X+this.screen+this.print},trash:function(){for(var b=0;b<G.length;b++){if(!G[b].ie7){try{var a=G[b].cssText}catch(e){a=""}if(a)G[b].cssText=""}}}}));var bW=D.extend({constructor:function(a){this.media=a;this.load();h.CSS[a]=this;h.CSS.refresh()},createRule:function(c,b){var a;if(O&&(a=c.match(O.MATCH))){return new O(a[1],a[2],b)}else if(a=c.match(bc.MATCH)){if(!cI.test(a[0])||bc.COMPLEX.test(a[0])){return new bc(c,a[1],a[2],a[3],b)}}else{return new t(c,b)}return c+" {"+b+"}"},getText:function(){var u=/@media\s+([^{]+?)\s*\{([^@]+\})\s*\}/gi,U=/@import[^;\n]+/gi,P=/@import\s+url\s*\(\s*["']?|["']?\s*\)\s*/gi,V=/(url\s*\(\s*['"]?)([\w\.]+[^:\)]*['"]?\))/gi,I=this,J={};function y(j,k,l,i){var g="";if(!i){l=o(j.media);i=0}if(l==="none"){j.disabled=true;return""}if(l==="all"||l===I.media){try{var f=!!j.cssText}catch(exe){}if(i<3&&f){var d=j.cssText.match(U);for(var c=0,b;c<j.imports.length;c++){var b=j.imports[c];var a=j._2||j.href;b._2=d[c].replace(P,"");g+=y(b,bu(a,k),l,i+1)}}g+=cA(j.href?m(j,k):j.owningElement._6);g=z(g,I.media)}return g};for(var v=0;v<G.length;v++){var p=G[v];if(!p.disabled&&!p.ie7)this.cssText+=y(p)}function z(b,a){q.value=a;return b.replace(u,q)};function q(c,b,a){b=o(b);switch(b){case"screen":case"print":if(b!==q.value)return"";case"all":return a}return""};function o(c){if(!c)return"all";var b=c.toLowerCase().split(/\s*,\s*/);c="none";for(var a=0;a<b.length;a++){if(b[a]==="all")return"all";if(b[a]==="screen"){if(c==="print")return"all";c="screen"}else if(b[a]==="print"){if(c==="screen")return"all";c="print"}}return c};function m(d,c){var b=d._2||d.href,a=bi(b,c);if(J[a])return"";J[a]=d.disabled?"":n(h.CSS.getText(d,c),bu(b,c));return J[a]};function n(b,a){return b.replace(V,"$1"+a.slice(0,a.lastIndexOf("/")+1)+"$2")}},load:function(){this.cssText="";this.getText();this.parse();if(bA.length){this.cssText=cN(this.cssText)}this.cssText=ba(this.cssText);bj={}},parse:function(){var i=h.CSS.parser.parse(this.cssText),n="";this.cssText=i.replace(/@charset[^;]+;|@font\-face[^\}]+\}/g,function(a){n+=a+"\n";return""});this.declarations=ba(n);var j=h.CSS.rules.length,k=[],l;while((l=cL.exec(this.cssText))){var i=l[2];if(i){var g=s<7&&i.indexOf("AlphaImageLoader")!==-1;var f=l[1].match(cM),d;for(var c=0;d=f[c];c++){d=bP(d);var b=h.CSS.UNKNOWN.test(d);f[c]=b?this.createRule(d,i):d+"{"+i+"}";if(g)f[c]+=this.createRule(d+">*","position:relative")}k.push(f.join("\n"))}}this.cssText=k.join("\n");this.rules=h.CSS.rules.slice(j)},recalc:function(){var b,a;for(a=0;(b=this.rules[a]);a++)b.recalc()},toString:function(){return this.declarations+"@media "+this.media+"{"+this.cssText+"}"}}),O,t=h.Rule=D.extend({constructor:function(c,b){this.id=h.CSS.rules.length;this.className=t.PREFIX+this.id;var a=c.match(cJ);this.selector=(a?a[1]:c)||"*";this.selectorText=this.parse(this.selector)+(a?a[2]:"");this.cssText=b;this.MATCH=new RegExp("\\s"+this.className+"(\\s|$)","g");h.CSS.rules.push(this);this.init()},init:bh,add:function(a){a.className+=" "+this.className},recalc:function(){var b=H(this.selector);for(var a=0;a<b.length;a++)this.add(b[a])},parse:function(f){var d=f.replace(t.CHILD," ").replace(t.COMPLEX,"");if(s<7)d=d.replace(t.MULTI,"");var c=bm(d,t.TAGS).length-bm(f,t.TAGS).length,b=bm(d,t.CLASSES).length-bm(f,t.CLASSES).length+1;while(b>0&&t.CLASS.test(d)){d=d.replace(t.CLASS,"");b--}while(c>0&&t.TAG.test(d)){d=d.replace(t.TAG,"$1*");c--}d+="."+this.className;b=Math.min(b,2);c=Math.min(c,2);var a=-10*b-c;if(a>0){d=d+","+t.MAP[a]+" "+d}return d},remove:function(a){a.className=a.className.replace(this.MATCH,"$1")},toString:function(){return F("%1 {%2}",this.selectorText,this.cssText)}},{CHILD:/>/g,CLASS:/\.[\w-]+/,CLASSES:/[.:\[]/g,MULTI:/(\.[\w-]+)+/g,PREFIX:"ie7_class",TAG:/^\w+|([\s>+~])\w+/,TAGS:/^\w|[\s>+~]\w/g,MAP:{"1":"html","2":"html body","10":".ie7_html","11":"html.ie7_html","12":"html.ie7_html body","20":".ie7_html .ie7_body","21":"html.ie7_html .ie7_body","22":"html.ie7_html body.ie7_body"}}),bc=t.extend({constructor:function(f,d,c,b,a){this.negated=c.indexOf("not")===0;if(this.negated)c=c.slice(5,-1);this.attach=d||"*";this.dynamicPseudoClass=h.CSS.dynamicPseudoClasses[c];this.target=b;this.base(f,a)},recalc:function(){var d=H(this.attach),c;for(var b=0;c=d[b];b++){var a=this.target?H(this.target,c):[c];if(a.length)this.dynamicPseudoClass.apply(c,a,this)}}}),bB=D.extend({constructor:function(b,a){this.name=b;this.apply=a;this.instances={};h.CSS.dynamicPseudoClasses[b]=this},register:function(f,d){var c=f[2];if(!d&&c.negated){this.unregister(f,true)}else{f.id=c.id+f[0].uniqueID;if(!this.instances[f.id]){var b=f[1],a;for(a=0;a<b.length;a++)c.add(b[a]);this.instances[f.id]=f}}},unregister:function(f,d){var c=f[2];if(!d&&c.negated){this.register(f,true)}else{if(this.instances[f.id]){var b=f[1],a;for(a=0;a<b.length;a++)c.remove(b[a]);delete this.instances[f.id]}}}}),bp=new bB("hover",function(b){var a=arguments;h.CSS.addEventHandler(b,"onmouseenter",function(){bp.register(a)});h.CSS.addEventHandler(b,"onmouseleave",function(){bp.unregister(a)})});x(r,"onmouseup",function(){var b=bp.instances;for(var a in b)if(!b[a][0].contains(event.srcElement))bp.unregister(b[a])});var cc={"=":"%1==='%2'","~=":"(' '+%1+' ').indexOf(' %2 ')!==-1","|=":"%1==='%2'||%1.indexOf('%2-')===0","^=":"%1.indexOf('%2')===0","$=":"%1.slice(-'%2'.length)==='%2'","*=":"%1.indexOf('%2')!==-1"};cc[""]="%1!=null";var bd={"<#attr>":function(f,d,c,b){var a="IE7._0(e,'"+d+"')";b=bn(b);if(c.length>1){if(!b||c==="~="&&cK.test(b)){return"false&&"}a="("+a+"||'')"}return"("+F(cc[c],a,b)+")&&"},"<#id>":cH+"==='$1'&&","<#class>":"e.className&&(' '+e.className+' ').indexOf(' $1 ')!==-1&&",":first-child":"!"+cG+"&&",":link":"e.currentStyle['ie7-link']=='link'&&",":visited":"e.currentStyle['ie7-link']=='visited'&&"};h.HTML=new(bY.extend({fixed:{},init:bh,addFix:function(){this.fixes.push(arguments)},apply:function(){for(var d=0;d<this.fixes.length;d++){var c=H(this.fixes[d][0]);var b=this.fixes[d][1];for(var a=0;a<c.length;a++)b(c[a])}},addRecalc:function(){this.recalcs.push(arguments)},recalc:function(){for(var i=0;i<this.recalcs.length;i++){var g=H(this.recalcs[i][0]);var f=this.recalcs[i][1],d;var c=Math.pow(2,i);for(var b=0;(d=g[b]);b++){var a=d.uniqueID;if((this.fixed[a]&c)===0){d=f(d)||d;this.fixed[a]|=c}}}}}));if(s<7){r.createElement("abbr");h.HTML.addRecalc("label",function(b){if(!b.htmlFor){var a=H("input,textarea",b,true);if(a){x(b,"onclick",function(){a.click()})}}})}var be="[.\\d]";(function(){var u=h.Layout={};X+="*{boxSizing:content-box}";u.boxSizing=function(a){if(!a.currentStyle.hasLayout){a.style.height="0cm";if(a.currentStyle.verticalAlign==="auto")a.runtimeStyle.verticalAlign="top";U(a)}};function U(a){if(a!=w&&a.currentStyle.position!=="absolute"){P(a,"marginTop");P(a,"marginBottom")}};function P(f,d){if(!f.runtimeStyle[d]){var c=f.parentElement;var b=d==="marginTop";if(c&&c.currentStyle.hasLayout&&!h._1(f,b?"previous":"next"))return;var a=f[b?"firstChild":"lastChild"];if(a&&a.nodeName<"@")a=h._1(a,b?"next":"previous");if(a&&a.currentStyle.styleFloat==="none"&&a.currentStyle.hasLayout){P(a,d);margin=V(f,f.currentStyle[d]);childMargin=V(a,a.currentStyle[d]);if(margin<0||childMargin<0){f.runtimeStyle[d]=margin+childMargin}else{f.runtimeStyle[d]=Math.max(childMargin,margin)}a.runtimeStyle[d]="0px"}}};function V(b,a){return a==="auto"?0:B(b,a)};var I=/^[.\d][\w]*$/,J=/^(auto|0cm)$/,y={};u.borderBox=function(a){y.Width(a);y.Height(a)};var v=function(p){y.Width=function(a){if(!S.test(a.currentStyle.width))z(a);if(p)U(a)};function z(b,a){if(!b.runtimeStyle.fixedWidth){if(!a)a=b.currentStyle.width;b.runtimeStyle.fixedWidth=I.test(a)?Math.max(0,m(b,a))+"px":a;T(b,"width",b.runtimeStyle.fixedWidth)}};function q(b){if(!bo(b)){var a=b.offsetParent;while(a&&!a.currentStyle.hasLayout)a=a.offsetParent}return(a||w).clientWidth};function o(b,a){if(S.test(a))return parseInt(parseFloat(a)/100*q(b));return B(b,a)};var m=function(d,c){var b=d.currentStyle["ie7-box-sizing"]==="border-box",a=0;if(C&&!b)a+=n(d)+j(d,"padding");else if(!C&&b)a-=n(d)+j(d,"padding");return o(d,c)+a};function n(a){return a.offsetWidth-a.clientWidth};function j(b,a){return o(b,b.currentStyle[a+"Left"])+o(b,b.currentStyle[a+"Right"])};X+="*{minWidth:none;maxWidth:none;min-width:none;max-width:none}";u.minWidth=function(a){if(a.currentStyle["min-width"]!=null){a.style.minWidth=a.currentStyle["min-width"]}if(bb(arguments.callee,a,a.currentStyle.minWidth!=="none")){u.boxSizing(a);z(a);k(a)}};eval("IE7.Layout.maxWidth="+String(u.minWidth).replace(/min/g,"max"));function k(c){if(c==r.body){var b=c.clientWidth}else{var a=c.getBoundingClientRect();b=a.right-a.left}if(c.currentStyle.minWidth!=="none"&&b<m(c,c.currentStyle.minWidth)){c.runtimeStyle.width=c.currentStyle.minWidth}else if(c.currentStyle.maxWidth!=="none"&&b>=m(c,c.currentStyle.maxWidth)){c.runtimeStyle.width=c.currentStyle.maxWidth}else{c.runtimeStyle.width=c.runtimeStyle.fixedWidth}};function l(a){if(bb(l,a,/^(fixed|absolute)$/.test(a.currentStyle.position)&&bz(a,"left")!=="auto"&&bz(a,"right")!=="auto"&&J.test(bz(a,"width")))){i(a);u.boxSizing(a)}};u.fixRight=l;function i(c){var b=o(c,c.runtimeStyle._3||c.currentStyle.left),a=q(c)-o(c,c.currentStyle.right)-b-j(c,"margin");if(parseInt(c.runtimeStyle.width)===a)return;c.runtimeStyle.width="";if(bo(c)||p||c.offsetWidth<a){if(!C)a-=n(c)+j(c,"padding");if(a<0)a=0;c.runtimeStyle.fixedWidth=a;T(c,"width",a)}};var g=0;bw(function(){if(!w)return;var f,d=(g<w.clientWidth);g=w.clientWidth;var c=u.minWidth.elements;for(f in c){var b=c[f];var a=(parseInt(b.runtimeStyle.width)===m(b,b.currentStyle.minWidth));if(d&&a)b.runtimeStyle.width="";if(d==a)k(b)}var c=u.maxWidth.elements;for(f in c){var b=c[f];var a=(parseInt(b.runtimeStyle.width)===m(b,b.currentStyle.maxWidth));if(!d&&a)b.runtimeStyle.width="";if(d!==a)k(b)}for(f in l.elements)i(l.elements[f])});if(C){h.CSS.addRecalc("width",be,y.Width)}if(s<7){h.CSS.addRecalc("max-width",be,u.maxWidth);h.CSS.addRecalc("right",be,l)}else if(s==7){if(p)h.CSS.addRecalc("height","[\\d.]+%",function(element){element.runtimeStyle.pixelHeight=parseInt(q(element)*element.currentStyle["ie7-height"].slice(0,-1)/100)})}};eval("var _7="+bU(v));v();_7(true);if(s<7){h.CSS.addRecalc("min-width",be,u.minWidth);h.CSS.addFix(/\bmin-height\s*/,"height")}})();var bC=bi("blank.gif",ck),bD="DXImageTransform.Microsoft.AlphaImageLoader",cd="progid:"+bD+"(src='%1',sizingMethod='%2')",bf,bg=[];function ce(b){if(bf.test(b.src)){var a=new Image(b.width,b.height);a.onload=function(){b.width=a.width;b.height=a.height;a=null};a.src=b.src;b.pngSrc=b.src;bq(b)}};if(s<7){h.CSS.addFix(/background(-image)?\s*:\s*([^};]*)?url\(([^\)]+)\)([^;}]*)?/,function(f,d,c,b,a){b=bn(b);return bf.test(b)?"filter:"+F(cd,b,a.indexOf("no-repeat")===-1?"scale":"crop")+";zoom:1;background"+(d||"")+":"+(c||"")+"none"+(a||""):f});h.CSS.addRecalc(/list\-style(\-image)?/,"[^};]*url",function(d){var c=d.currentStyle.listStyleImage.slice(5,-2);if(bf.test(c)){if(d.nodeName==="LI"){cf(d,c)}else if(d.nodeName==="UL"){for(var b=0,a;a=d.childNodes[b];b++){if(a.nodeName==="LI")cf(a,c)}}}});function cf(g,f){var d=g.runtimeStyle,c=g.offsetHeight,b=new Image;b.onload=function(){var a=g.currentStyle.paddingLeft;a=a==="0px"?0:B(g,a);d.paddingLeft=(a+this.width)+"px";d.marginLeft=-this.width+"px";d.listStyleType="none";d.listStyleImage="none";d.paddingTop=Math.max(c-g.offsetHeight,0)+"px";bq(g,"crop",f);g.style.zoom="100%"};b.src=f};h.HTML.addRecalc("img,input",function(a){if(a.nodeName==="INPUT"&&a.type!=="image")return;ce(a);x(a,"onpropertychange",function(){if(!bE&&event.propertyName==="src"&&a.src.indexOf(bC)===-1)ce(a)})});var bE=false;x(L,"onbeforeprint",function(){bE=true;for(var a=0;a<bg.length;a++)cO(bg[a])});x(L,"onafterprint",function(){for(var a=0;a<bg.length;a++)bq(bg[a]);bE=false})}function bq(d,c,b){var a=d.filters[bD];if(a){a.src=b||d.src;a.enabled=true}else{d.runtimeStyle.filter=F(cd,b||d.src,c||"scale");bg.push(d)}d.src=bC};function cO(a){a.src=a.pngSrc;a.filters[bD].enabled=false};(function(){if(s>=7)return;h.CSS.addRecalc("position","fixed",n,"absolute");h.CSS.addRecalc("background(-attachment)?","[^};]*fixed",o);var y=C?"body":"documentElement";function v(){if(A.currentStyle.backgroundAttachment!=="fixed"){if(A.currentStyle.backgroundImage==="none"){A.runtimeStyle.backgroundRepeat="no-repeat";A.runtimeStyle.backgroundImage="url("+bC+")"}A.runtimeStyle.backgroundAttachment="fixed"}v=bh};var p=bZ("img");function z(a){return a?bo(a)||z(a.parentElement):false};function q(c,b,a){setTimeout("document.all."+c.uniqueID+".runtimeStyle.setExpression('"+b+"','"+a+"')",0)};function o(a){if(bb(o,a,a.currentStyle.backgroundAttachment==="fixed"&&!a.contains(A))){v();i.bgLeft(a);i.bgTop(a);m(a)}};function m(b){p.src=b.currentStyle.backgroundImage.slice(5,-2);var a=b.canHaveChildren?b:b.parentElement;a.appendChild(p);i.setOffsetLeft(b);i.setOffsetTop(b);a.removeChild(p)};function n(a){if(bb(n,a,bo(a))){T(a,"position","absolute");T(a,"left",a.currentStyle.left);T(a,"top",a.currentStyle.top);v();h.Layout.fixRight(a);j(a)}};function j(c,b){r.body.getBoundingClientRect();i.positionTop(c,b);i.positionLeft(c,b,true);if(!c.runtimeStyle.autoLeft&&c.currentStyle.marginLeft==="auto"&&c.currentStyle.right!=="auto"){var a=w.clientWidth-i.getPixelWidth(c,c.currentStyle.right)-i.getPixelWidth(c,c.runtimeStyle._3)-c.clientWidth;if(c.currentStyle.marginRight==="auto")a=parseInt(a/2);if(z(c.offsetParent))c.runtimeStyle.pixelLeft+=a;else c.runtimeStyle.shiftLeft=a}if(!c.runtimeStyle.fixedWidth)i.clipWidth(c);if(!c.runtimeStyle.fixedHeight)i.clipHeight(c)};function k(){var b=o.elements;for(var a in b)m(b[a]);b=n.elements;for(a in b){j(b[a],true);j(b[a],true)}l=0};var l;bw(function(){if(!l)l=setTimeout(k,100)});var i={},g=function(f){f.bgLeft=function(a){a.style.backgroundPositionX=a.currentStyle.backgroundPositionX;if(!z(a)){q(a,"backgroundPositionX","(parseInt(runtimeStyle.offsetLeft)+document."+y+".scrollLeft)||0")}};f.setOffsetLeft=function(b){var a=z(b)?"backgroundPositionX":"offsetLeft";b.runtimeStyle[a]=f.getOffsetLeft(b,b.style.backgroundPositionX)-b.getBoundingClientRect().left-b.clientLeft+2};f.getOffsetLeft=function(b,a){switch(a){case"left":case"top":return 0;case"right":case"bottom":return w.clientWidth-p.offsetWidth;case"center":return(w.clientWidth-p.offsetWidth)/2;default:if(S.test(a)){return parseInt((w.clientWidth-p.offsetWidth)*parseFloat(a)/100)}p.style.left=a;return p.offsetLeft}};f.clipWidth=function(d){var c=d.runtimeStyle.fixWidth;d.runtimeStyle.borderRightWidth="";d.runtimeStyle.width=c?f.getPixelWidth(d,c)+"px":"";if(d.currentStyle.width!=="auto"){var b=d.getBoundingClientRect();var a=d.offsetWidth-w.clientWidth+b.left-2;if(a>=0){d.runtimeStyle.borderRightWidth="0px";a=Math.max(B(d,d.currentStyle.width)-a,0);T(d,"width",a);return a}}};f.positionLeft=function(b,a){if(!a&&S.test(b.currentStyle.width)){b.runtimeStyle.fixWidth=b.currentStyle.width}if(b.runtimeStyle.fixWidth){b.runtimeStyle.width=f.getPixelWidth(b,b.runtimeStyle.fixWidth)}b.runtimeStyle.shiftLeft=0;b.runtimeStyle._3=b.currentStyle.left;b.runtimeStyle.autoLeft=b.currentStyle.right!=="auto"&&b.currentStyle.left==="auto";b.runtimeStyle.left="";b.runtimeStyle.screenLeft=f.getScreenLeft(b);b.runtimeStyle.pixelLeft=b.runtimeStyle.screenLeft;if(!a&&!z(b.offsetParent)){q(b,"pixelLeft","runtimeStyle.screenLeft+runtimeStyle.shiftLeft+document."+y+".scrollLeft")}};f.getScreenLeft=function(c){var b=c.offsetLeft,a=1;if(c.runtimeStyle.autoLeft){b=w.clientWidth-c.offsetWidth-f.getPixelWidth(c,c.currentStyle.right)}if(c.currentStyle.marginLeft!=="auto"){b-=f.getPixelWidth(c,c.currentStyle.marginLeft)}while(c=c.offsetParent){if(c.currentStyle.position!=="static")a=-1;b+=c.offsetLeft*a}return b};f.getPixelWidth=function(b,a){return S.test(a)?parseInt(parseFloat(a)/100*w.clientWidth):B(b,a)}};eval("var _8="+bU(g));g(i);_8(i)})();if(s<7){var bF={backgroundColor:"transparent",backgroundImage:"none",backgroundPositionX:null,backgroundPositionY:null,backgroundRepeat:null,borderTopWidth:0,borderRightWidth:0,borderBottomWidth:0,borderLeftStyle:"none",borderTopStyle:"none",borderRightStyle:"none",borderBottomStyle:"none",borderLeftWidth:0,borderLeftColor:"#000",borderTopColor:"#000",borderRightColor:"#000",borderBottomColor:"#000",height:null,marginTop:0,marginBottom:0,marginRight:0,marginLeft:0,width:"100%"};h.CSS.addRecalc("overflow","visible",function(c){if(c.currentStyle.position==="absolute")return;if(c.parentNode.ie7_wrapped)return;if(h.Layout&&c.currentStyle["max-height"]!=="auto"){h.Layout.maxHeight(c)}if(c.currentStyle.marginLeft==="auto")c.style.marginLeft=0;if(c.currentStyle.marginRight==="auto")c.style.marginRight=0;var b=r.createElement(ci);b.ie7_wrapped=c;for(var a in bF){b.style[a]=c.currentStyle[a];if(bF[a]!=null){c.runtimeStyle[a]=bF[a]}}b.style.display="block";b.style.position="relative";c.runtimeStyle.position="absolute";c.parentNode.insertBefore(b,c);b.appendChild(c)})}function cP(){var q="xx-small,x-small,small,medium,large,x-large,xx-large".split(",");for(var o=0;o<q.length;o++){q[q[o]]=q[o-1]||"0.67em"}h.CSS.addFix(/(font(-size)?\s*:\s*)([\w.-]+)/,function(d,c,b,a){return c+(q[a]||a)});var m=/^\-/,n=/(em|ex)$/i,j=/em$/i,k=/ex$/i;B=function(c,b){if(bX.test(b))return parseInt(b)||0;var a=m.test(b)?-1:1;if(n.test(b))a*=i(c);l.style.width=a<0?b.slice(1):b;A.appendChild(l);b=a*l.offsetWidth;l.removeNode();return parseInt(b)};var l=bZ();function i(c){var b=1;l.style.fontFamily=c.currentStyle.fontFamily;l.style.lineHeight=c.currentStyle.lineHeight;while(c!=A){var a=c.currentStyle["ie7-font-size"];if(a){if(j.test(a))b*=parseFloat(a);else if(S.test(a))b*=(parseFloat(a)/100);else if(k.test(a))b*=(parseFloat(a)/2);else{l.style.fontSize=a;return 1}}c=c.parentElement}return b};h.CSS.addFix(/cursor\s*:\s*pointer/,"cursor:hand");h.CSS.addFix(/display\s*:\s*list-item/,"display:block");function g(d){var c=d.parentElement,b=c.offsetWidth-d.offsetWidth-f(c),a=(d.currentStyle["ie7-margin"]&&d.currentStyle.marginRight==="auto")||d.currentStyle["ie7-margin-right"]==="auto";switch(c.currentStyle.textAlign){case"right":b=a?parseInt(b/2):0;d.runtimeStyle.marginRight=b+"px";break;case"center":if(a)b=0;default:if(a)b/=2;d.runtimeStyle.marginLeft=parseInt(b)+"px"}};function f(a){return B(a,a.currentStyle.paddingLeft)+B(a,a.currentStyle.paddingRight)};h.CSS.addRecalc("margin(-left|-right)?","[^};]*auto",function(a){if(bb(g,a,a.parentElement&&a.currentStyle.display==="block"&&a.currentStyle.marginLeft==="auto"&&a.currentStyle.position!=="absolute")){g(a)}});bw(function(){for(var b in g.elements){var a=g.elements[b];a.runtimeStyle.marginLeft=a.runtimeStyle.marginRight="";g(a)}})};var cQ="\\([^)]+\\)";bS.add(/::(before|after)/,":$1");if(s<8){if(h.CSS.pseudoClasses)h.CSS.pseudoClasses+="|";h.CSS.pseudoClasses+="before|after|lang"+cQ;function cN(a){return a.replace(new RegExp("([{;\\s])("+bA.join("|")+")\\s*:\\s*([^;}]+)","g"),"$1$2:$3;ie7-$2:$3")};var cR=/[\w-]+\s*:\s*inherit/g;var cS=/ie7\-|\s*:\s*inherit/g;var cT=/\-([a-z])/g;function cU(b,a){return a.toUpperCase()};h.CSS.addRecalc("[\\w-]+","inherit",function(f,d){if(f.parentElement){var c=d.match(cR);for(var b=0;b<c.length;b++){var a=c[b].replace(cS,"");if(f.currentStyle["ie7-"+a]==="inherit"){a=a.replace(cT,cU);f.runtimeStyle[a]=f.parentElement.currentStyle[a]}}}},function(a){bA.push(bO(a.slice(1).split(":")[0]));return a});var br=new bB("focus",function(b){var a=arguments;h.CSS.addEventHandler(b,"onfocus",function(){br.unregister(a);br.register(a)});h.CSS.addEventHandler(b,"onblur",function(){br.unregister(a)});if(b==r.activeElement){br.register(a)}});var bG=new bB("active",function(b){var a=arguments;h.CSS.addEventHandler(b,"onmousedown",function(){bG.register(a)})});x(r,"onmouseup",function(){var b=bG.instances;for(var a in b)bG.unregister(b[a])});var cV=/^url\s*\(\s*([^)]*)\)$/;var cW={before0:"beforeBegin",before1:"afterBegin",after0:"afterEnd",after1:"beforeEnd"};var O=h.PseudoElement=t.extend({constructor:function(i,g,f){this.position=g;var d=f.match(O.CONTENT),c,b;if(d){d=d[1];c=d.split(/\s+/);for(var a=0;(b=c[a]);a++){c[a]=/^attr/.test(b)?{attr:b.slice(5,-1)}:b.charAt(0)==="'"?bn(b):ba(b)}d=c}this.content=d;this.base(i,ba(f))},init:function(){this.match=H(this.selector);for(var b=0;b<this.match.length;b++){var a=this.match[b].runtimeStyle;if(!a[this.position])a[this.position]={cssText:""};a[this.position].cssText+=";"+this.cssText;if(this.content!=null)a[this.position].content=this.content}},create:function(m){var n=m.runtimeStyle[this.position];if(n){var j=[].concat(n.content||"");for(var k=0;k<j.length;k++){if(typeof j[k]=="object"){j[k]=m.getAttribute(j[k].attr)}}j=j.join("");var l=j.match(cV);var i="overflow:hidden;"+n.cssText.replace(/'/g,'"');var g=cW[this.position+Number(m.canHaveChildren)];var f='ie7_pseudo'+O.count++;m.insertAdjacentHTML(g,F(O.ANON,this.className,f,i,l?"":j));if(l){var d=bn(l[1]);var c=r.getElementById(f);c.src=d;bq(c,"crop");var b=m.currentStyle.styleFloat!=="none";if(c.currentStyle.display==="inline"||b){if(s<7&&b&&m.canHaveChildren){m.runtimeStyle.display="inline";m.runtimeStyle.position="relative";c.runtimeStyle.position="absolute"}c.style.display="inline-block";if(m.currentStyle.styleFloat!=="none"){c.style.pixelWidth=m.offsetWidth}var a=new Image;a.onload=function(){c.style.pixelWidth=this.width;c.style.pixelHeight=Math.max(this.height,c.offsetHeight)};a.src=d}}m.runtimeStyle[this.position]=null}},recalc:function(){if(this.content==null)return;for(var a=0;a<this.match.length;a++){this.create(this.match[a])}},toString:function(){return"."+this.className+"{display:inline}"}},{CONTENT:/content\s*:\s*([^;]*)(;|$)/,ANON:"<ie7:! class='ie7_anon %1' id=%2 style='%3'>%4</ie7:!>",MATCH:/(.*):(before|after).*/,count:0});h._getLang=function(b){var a="";while(b&&b.nodeType===1){a=b.lang||b.getAttribute("lang")||"";if(a)break;b=b.parentNode}return a};bd=Y(bd,{":lang\\(([^)]+)\\)":"((ii=IE7._getLang(e))==='$1'||ii.indexOf('$1-')===0)&&"})}var cX=/^(submit|reset|button)$/;h.HTML.addRecalc("button,input",function(b){if(b.nodeName==="BUTTON"){var a=b.outerHTML.match(/ value="([^"]*)"/i);b.runtimeStyle.value=a?a[1]:""}if(b.type==="submit"){x(b,"onclick",function(){b.runtimeStyle.clicked=true;setTimeout("document.all."+b.uniqueID+".runtimeStyle.clicked=false",1)})}});h.HTML.addRecalc("form",function(c){x(c,"onsubmit",function(){for(var b,a=0;b=c[a];a++){if(cX.test(b.type)&&!b.disabled&&!b.runtimeStyle.clicked){b.disabled=true;setTimeout("document.all."+b.uniqueID+".disabled=false",1)}else if(b.nodeName==="BUTTON"&&b.type==="submit"){setTimeout("document.all."+b.uniqueID+".value='"+b.value+"'",1);b.value=b.runtimeStyle.value}}})});h.HTML.addRecalc("img",function(a){if(a.alt&&!a.title)a.title=""});if(s<8){h.CSS.addRecalc("border-spacing",be,function(a){if(a.currentStyle.borderCollapse!=="collapse"){a.cellSpacing=B(a,a.currentStyle["ie7-border-spacing"].split(" ")[0])}});h.CSS.addRecalc("box-sizing","content-box",h.Layout.boxSizing);h.CSS.addRecalc("box-sizing","border-box",h.Layout.borderBox)}if(s<8){var cY=/^image/i;h.HTML.addRecalc("object",function(a){if(cY.test(a.type)){a.body.style.cssText="margin:0;padding:0;border:none;overflow:hidden";return a}})}var K,H=(function(){var cZ=/^[>+~]/,bs=false;function da(d,c,b){d=bP(d);if(!c)c=r;var a=c;bs=cZ.test(d);if(bs){c=c.parentNode;d="*"+d}try{return m.create(d,bs)(c,b?null:[],a)}catch(ex){return b?null:[]}};var db=/^(\\.|[' >+~#.\[\]:*(),\w-\^|$=]|[^\x00-\xa0])+$/,dp=/^(href|src)$/,cg={"class":"className","for":"htmlFor"},dq=/\sie7_\w+/g,dc=/^(action|cite|codebase|data|dynsrc|href|longdesc|lowsrc|src|usemap|url)$/i;h._0=function(d,c){if(d.getAttributeNode){var b=d.getAttributeNode(c)}c=cg[c.toLowerCase()]||c;if(!b)b=d.attributes[c];var a=b&&b.specified;if(d[c]&&typeof d[c]=="boolean")return c.toLowerCase();if((a&&dc.test(c))||(!b&&C)||c==="value"||c==="type"){return d.getAttribute(c,2)}if(c==="style")return d.style.cssText.toLowerCase()||null;return a?String(b.nodeValue):null};var ch="colSpan,rowSpan,vAlign,dateTime,accessKey,tabIndex,encType,maxLength,readOnly,longDesc";Y(cg,cy(ch.toLowerCase().split(","),ch.split(",")));h._1=function(b,a){a+="Sibling";do{b=b[a];if(b&&b.nodeName>"@")break}while(b);return b};var dd=/(^|[, >+~])([#.:\[])/g,dr=/\)\{/g,de=/,/,ds=/^['"]/,df=/\\([\da-f]{2,2})/gi,dt=/last/i;h._9=function(d,c){var b=d.all[c]||null;if(!b||(b.nodeType&&h._0(b,"id")===c))return b;for(var a=0;a<b.length;a++){if(h._0(b[a],"id")===c)return b[a]}return null};var W=E.extend({dictionary:new cw({ident:/\-?(\\.|[_a-z]|[^\x00-\xa0])(\\.|[\w-]|[^\x00-\xa0])*/,combinator:/[\s>+~]/,operator:/[\^~|$*]?=/,nth_arg:/[+-]?\d+|[+-]?\d*n(?:\s*[+-]\s*\d+)?|even|odd/,tag:/\*|<#ident>/,id:/#(<#ident>)/,'class':/\.(<#ident>)/,pseudo:/\:([\w-]+)(?:\(([^)]+)\))?/,attr:/\[(<#ident>)(?:(<#operator>)((?:\\.|[^\[\]#.:])+))?\]/,negation:/:not\((<#tag>|<#id>|<#class>|<#attr>|<#pseudo>)\)/,sequence:/(\\.|[~*]=|\+\d|\+?\d*n\s*\+\s*\d|[^\s>+~,\*])+/,filter:/[#.:\[]<#sequence>/,selector:/[^>+~](\\.|[^,])*?/,grammar:/^(<#selector>)((,<#selector>)*)$/}),ignoreCase:true}),dg=new W({"\\\\.|[~*]\\s+=|\\+\\s+\\d":E.IGNORE,"\\[\\s+":"[","\\(\\s+":"(","\\s+\\)":")","\\s+\\]":"]","\\s*([,>+~]|<#operator>)\\s*":"$1","\\s+$":"","\\s+":" "});function dh(a){a=dg.parse(a.replace(df,"\\x$1")).replace(bv,"$1").replace(dd,"$1*$2");if(!db.test(a))bH();return a};function du(a){return a.replace(bR,di)};function di(b,a){return R[a]};var dj=/\{/g,dk=/\\{/g;function bI(a){return Array((a.replace(dk,"").match(dj)||"").length+1).join("}")};bd=new W(bd);var u=/:target/i,U=/:root/i;function P(b){var a="";if(U.test(b))a+=",R=d.documentElement";if(u.test(b))a+=",H=d.location;H=H&&H.hash.replace('#','')";if(a||b.indexOf("#")!==-1){a=",t=c.nodeType,d=t===9?c:c.ownerDocument||(c.document||c).parentWindow.document"+a}return"var ii"+a+";"};var V={" ":";while(e!=s&&(e=e.parentNode)&&e.nodeType===1){",">":".parentElement;if(e){","+":";while((e=e.previousSibling)&&!("+ca+"))continue;if(e){","~":";while((e=e.previousSibling)){"+cb},I=/\be\b/g;K=new W({"(?:(<#selector>)(<#combinator>))?(<#tag>)(<#filter>)?$":function(i,g,f,d,c){var b="";if(d!=="*"){var a=d.toUpperCase();b+="if(e.nodeName==='"+a+(a===d?"":"'||e.nodeName==='"+d)+"'){"}if(c){b+="if("+bd.parse(c).slice(0,-2)+"){"}b=b.replace(I,"e"+this.index);if(f){b+="var e=e"+(this.index++)+V[f];b=b.replace(I,"e"+this.index)}if(g){b+=this.parse(g)}return b}});var J="e0=IE7._9(d,'%1');if(e0){",y="var n=c.getElementsByTagName('%1');",v="if(r==null)return e0;r[k++]=e0;",p=1,z=new W({"^((?:<#selector>)?(?:<#combinator>))(<#tag>)(<#filter>)?$":true}),q={},o=new W({"^(<#tag>)#(<#ident>)(<#filter>)?( [^,]*)?$":function(i,g,f,d,c){var b=F(J,f),a="}";if(d){b+=K.parse(g+d);a=bI(b)}if(c){b+="s=c=e0;"+m.parse("*"+c)}else{b+=v}return b+a},"^([^#,]+)#(<#ident>)(<#filter>)?$":function(f,d,c,b){var a=F(J,c);if(d==="*"){a+=v}else{a+=K.parse(d+b)+v+"break"}return a+bI(a)},"^.*$":""}),m=new W({"<#grammar>":function(j,k,l){if(!this.groups)this.groups=[];var i=z.exec(" "+k);if(!i)bH();this.groups.push(i.slice(1));if(l){return this.parse(l.replace(de,""))}var g=this.groups,f=g[0][p];for(var b=1;i=g[b];b++){if(f!==i[p]){f="*";break}}var d="",c=v+"continue filtering;";for(var b=0;i=g[b];b++){K.index=0;if(f!=="*")i[p]="*";i=i.join("");if(i===" *"){d=c;break}else{i=K.parse(i);if(bs)i+="if(e"+K.index+"==s){";d+=i+c+bI(i)}}var a=f==="*";return(a?"var n=c.all;":F(y,f))+"filtering:while((e0=n[i++]))"+(a?cb.replace(I,"e0"):"{")+d+"}"},"^.*$":bH}),n=/\&\&(e\d+)\.nodeType===1(\)\{\s*if\(\1\.nodeName=)/g;m.create=function(c){if(!q[c]){c=dh(c);this.groups=null;K.index=0;var b=this.parse(c);this.groups=null;K.index=0;if(c.indexOf("#")!==-1){var a=o.parse(c);if(a){b="if(t===1||t===11|!c.getElementById){"+b+"}else{"+a+"}"}}b=b.replace(n,"$2");b=P(c)+ba(b);q[c]=new Function("return function(c,r,s){var i=0,k=0,e0;"+b+"return r}")()}return q[c]};return da})();function bH(){throw new SyntaxError("Invalid selector.");};h.loaded=true;(function(){try{if(!r.body)throw"continue";bt.doScroll("left")}catch(ex){setTimeout(arguments.callee,1);return}try{eval(bK.innerHTML)}catch(ex){}if(typeof IE7_PNG_SUFFIX=="object"){bf=IE7_PNG_SUFFIX}else{bf=new RegExp(bO(L.IE7_PNG_SUFFIX||"-trans.png")+"(\\?.*)?$","i")}A=r.body;w=C?A:bt;A.className+=" ie7_body";bt.className+=" ie7_html";if(C)cP();h.CSS.init();h.HTML.init();h.HTML.apply();h.CSS.apply();h.recalc()})()})(this,document);
\ No newline at end of file
--- /dev/null
+/*global jQuery */
+/*jshint multistr:true browser:true */
+/*!
+ * FitVids 1.0.3
+ *
+ * Copyright 2013, Chris Coyier - http://css-tricks.com + Dave Rupert - http://daverupert.com
+ * Credit to Thierry Koblentz - http://www.alistapart.com/articles/creating-intrinsic-ratios-for-video/
+ * Released under the WTFPL license - http://sam.zoy.org/wtfpl/
+ *
+ * Date: Thu Sept 01 18:00:00 2011 -0500
+ */
+
+(function( $ ){
+
+ "use strict";
+
+ $.fn.fitVids = function( options ) {
+ var settings = {
+ customSelector: null
+ };
+
+ if(!document.getElementById('fit-vids-style')) {
+
+ var div = document.createElement('div'),
+ ref = document.getElementsByTagName('base')[0] || document.getElementsByTagName('script')[0],
+ cssStyles = '­<style>.fluid-width-video-wrapper{width:100%;position:relative;padding:0;}.fluid-width-video-wrapper iframe,.fluid-width-video-wrapper object,.fluid-width-video-wrapper embed {position:absolute;top:0;left:0;width:100%;height:100%;}</style>';
+
+ div.className = 'fit-vids-style';
+ div.id = 'fit-vids-style';
+ div.style.display = 'none';
+ div.innerHTML = cssStyles;
+
+ ref.parentNode.insertBefore(div,ref);
+
+ }
+
+ if ( options ) {
+ $.extend( settings, options );
+ }
+
+ return this.each(function(){
+ var selectors = [
+ "iframe[src*='player.vimeo.com']",
+ "iframe[src*='youtube.com']",
+ "iframe[src*='youtube-nocookie.com']",
+ "iframe[src*='kickstarter.com'][src*='video.html']",
+ "object",
+ "embed"
+ ];
+
+ if (settings.customSelector) {
+ selectors.push(settings.customSelector);
+ }
+
+ var $allVideos = $(this).find(selectors.join(','));
+ $allVideos = $allVideos.not("object object"); // SwfObj conflict patch
+
+ $allVideos.each(function(){
+ var $this = $(this);
+ if (this.tagName.toLowerCase() === 'embed' && $this.parent('object').length || $this.parent('.fluid-width-video-wrapper').length) { return; }
+ var height = ( this.tagName.toLowerCase() === 'object' || ($this.attr('height') && !isNaN(parseInt($this.attr('height'), 10))) ) ? parseInt($this.attr('height'), 10) : $this.height(),
+ width = !isNaN(parseInt($this.attr('width'), 10)) ? parseInt($this.attr('width'), 10) : $this.width(),
+ aspectRatio = height / width;
+ if(!$this.attr('id')){
+ var videoID = 'fitvid' + Math.floor(Math.random()*999999);
+ $this.attr('id', videoID);
+ }
+ $this.wrap('<div class="fluid-width-video-wrapper"></div>').parent('.fluid-width-video-wrapper').css('padding-top', (aspectRatio * 100)+"%");
+ $this.removeAttr('height').removeAttr('width');
+ });
+ });
+ };
+// Works with either jQuery or Zepto
+})( window.jQuery || window.Zepto );
\ No newline at end of file
--- /dev/null
+/*!
+ * hoverIntent r7 // 2013.03.11 // jQuery 1.9.1+
+ * http://cherne.net/brian/resources/jquery.hoverIntent.html
+ *
+ * You may use hoverIntent under the terms of the MIT license. Basically that
+ * means you are free to use hoverIntent as long as this header is left intact.
+ * Copyright 2007, 2013 Brian Cherne
+ */
+
+/* hoverIntent is similar to jQuery's built-in "hover" method except that
+ * instead of firing the handlerIn function immediately, hoverIntent checks
+ * to see if the user's mouse has slowed down (beneath the sensitivity
+ * threshold) before firing the event. The handlerOut function is only
+ * called after a matching handlerIn.
+ *
+ * // basic usage ... just like .hover()
+ * .hoverIntent( handlerIn, handlerOut )
+ * .hoverIntent( handlerInOut )
+ *
+ * // basic usage ... with event delegation!
+ * .hoverIntent( handlerIn, handlerOut, selector )
+ * .hoverIntent( handlerInOut, selector )
+ *
+ * // using a basic configuration object
+ * .hoverIntent( config )
+ *
+ * @param handlerIn function OR configuration object
+ * @param handlerOut function OR selector for delegation OR undefined
+ * @param selector selector OR undefined
+ * @author Brian Cherne <brian(at)cherne(dot)net>
+ */
+(function($) {
+ $.fn.hoverIntent = function(handlerIn,handlerOut,selector) {
+
+ // default configuration values
+ var cfg = {
+ interval: 100,
+ sensitivity: 7,
+ timeout: 0
+ };
+
+ if ( typeof handlerIn === "object" ) {
+ cfg = $.extend(cfg, handlerIn );
+ } else if ($.isFunction(handlerOut)) {
+ cfg = $.extend(cfg, { over: handlerIn, out: handlerOut, selector: selector } );
+ } else {
+ cfg = $.extend(cfg, { over: handlerIn, out: handlerIn, selector: handlerOut } );
+ }
+
+ // instantiate variables
+ // cX, cY = current X and Y position of mouse, updated by mousemove event
+ // pX, pY = previous X and Y position of mouse, set by mouseover and polling interval
+ var cX, cY, pX, pY;
+
+ // A private function for getting mouse position
+ var track = function(ev) {
+ cX = ev.pageX;
+ cY = ev.pageY;
+ };
+
+ // A private function for comparing current and previous mouse position
+ var compare = function(ev,ob) {
+ ob.hoverIntent_t = clearTimeout(ob.hoverIntent_t);
+ // compare mouse positions to see if they've crossed the threshold
+ if ( ( Math.abs(pX-cX) + Math.abs(pY-cY) ) < cfg.sensitivity ) {
+ $(ob).off("mousemove.hoverIntent",track);
+ // set hoverIntent state to true (so mouseOut can be called)
+ ob.hoverIntent_s = 1;
+ return cfg.over.apply(ob,[ev]);
+ } else {
+ // set previous coordinates for next time
+ pX = cX; pY = cY;
+ // use self-calling timeout, guarantees intervals are spaced out properly (avoids JavaScript timer bugs)
+ ob.hoverIntent_t = setTimeout( function(){compare(ev, ob);} , cfg.interval );
+ }
+ };
+
+ // A private function for delaying the mouseOut function
+ var delay = function(ev,ob) {
+ ob.hoverIntent_t = clearTimeout(ob.hoverIntent_t);
+ ob.hoverIntent_s = 0;
+ return cfg.out.apply(ob,[ev]);
+ };
+
+ // A private function for handling mouse 'hovering'
+ var handleHover = function(e) {
+ // copy objects to be passed into t (required for event object to be passed in IE)
+ var ev = jQuery.extend({},e);
+ var ob = this;
+
+ // cancel hoverIntent timer if it exists
+ if (ob.hoverIntent_t) { ob.hoverIntent_t = clearTimeout(ob.hoverIntent_t); }
+
+ // if e.type == "mouseenter"
+ if (e.type == "mouseenter") {
+ // set "previous" X and Y position based on initial entry point
+ pX = ev.pageX; pY = ev.pageY;
+ // update "current" X and Y position based on mousemove
+ $(ob).on("mousemove.hoverIntent",track);
+ // start polling interval (self-calling timeout) to compare mouse coordinates over time
+ if (ob.hoverIntent_s != 1) { ob.hoverIntent_t = setTimeout( function(){compare(ev,ob);} , cfg.interval );}
+
+ // else e.type == "mouseleave"
+ } else {
+ // unbind expensive mousemove event
+ $(ob).off("mousemove.hoverIntent",track);
+ // if hoverIntent state is true, then call the mouseOut function after the specified delay
+ if (ob.hoverIntent_s == 1) { ob.hoverIntent_t = setTimeout( function(){delay(ev,ob);} , cfg.timeout );}
+ }
+ };
+
+ // listen for mouseenter and mouseleave
+ return this.on({'mouseenter.hoverIntent':handleHover,'mouseleave.hoverIntent':handleHover}, cfg.selector);
+ };
+})(jQuery);
\ No newline at end of file
--- /dev/null
+<?php
+// Add dynamic_loop function for LoopBuddy
+
+/*
+Copyright 2011 iThemes (email: support@ithemes.com)
+
+Written by Chris Jean
+Version 0.0.1
+
+Version History
+ 0.0.1 - 2011-02-28 - Chris Jean
+ Initial version
+*/
+
+
+if ( ! function_exists( 'dynamic_loop' ) ) {
+ function dynamic_loop() {
+ global $dynamic_loop_handlers;
+
+ if ( empty( $dynamic_loop_handlers ) || ! is_array( $dynamic_loop_handlers ) )
+ return false;
+
+ ksort( $dynamic_loop_handlers );
+
+ foreach ( (array) $dynamic_loop_handlers as $handlers ) {
+ foreach ( (array) $handlers as $function ) {
+ if ( is_callable( $function ) && ( false != call_user_func( $function ) ) ) {
+ return true;
+ }
+ }
+ }
+
+ return false;
+ }
+}
+
+if ( ! function_exists( 'register_dynamic_loop_handler' ) ) {
+ function register_dynamic_loop_handler( $function, $priority = 10 ) {
+ global $dynamic_loop_handlers;
+
+ if ( ! is_numeric( $priority ) )
+ $priority = 10;
+
+ if ( ! isset( $dynamic_loop_handlers ) || ! is_array( $dynamic_loop_handlers ) )
+ $dynamic_loop_handlers = array();
+
+ if ( ! isset( $dynamic_loop_handlers[$priority] ) || ! is_array( $dynamic_loop_handlers[$priority] ) )
+ $dynamic_loop_handlers[$priority] = array();
+
+ $dynamic_loop_handlers[$priority][] = $function;
+ }
+}
\ No newline at end of file
--- /dev/null
+<?php
+
+/**
+ * lessphp v0.4.0
+ * http://leafo.net/lessphp
+ *
+ * LESS css compiler, adapted from http://lesscss.org
+ *
+ * Copyright 2012, Leaf Corcoran <leafot@gmail.com>
+ * Licensed under MIT or GPLv3, see LICENSE
+ */
+
+
+/**
+ * The less compiler and parser.
+ *
+ * Converting LESS to CSS is a three stage process. The incoming file is parsed
+ * by `lessc_parser` into a syntax tree, then it is compiled into another tree
+ * representing the CSS structure by `lessc`. The CSS tree is fed into a
+ * formatter, like `lessc_formatter` which then outputs CSS as a string.
+ *
+ * During the first compile, all values are *reduced*, which means that their
+ * types are brought to the lowest form before being dump as strings. This
+ * handles math equations, variable dereferences, and the like.
+ *
+ * The `parse` function of `lessc` is the entry point.
+ *
+ * In summary:
+ *
+ * The `lessc` class creates an intstance of the parser, feeds it LESS code,
+ * then transforms the resulting tree to a CSS tree. This class also holds the
+ * evaluation context, such as all available mixins and variables at any given
+ * time.
+ *
+ * The `lessc_parser` class is only concerned with parsing its input.
+ *
+ * The `lessc_formatter` takes a CSS tree, and dumps it to a formatted string,
+ * handling things like indentation.
+ */
+class lessc {
+ static public $VERSION = "v0.4.0";
+ static protected $TRUE = array("keyword", "true");
+ static protected $FALSE = array("keyword", "false");
+
+ protected $libFunctions = array();
+ protected $registeredVars = array();
+ protected $preserveComments = false;
+
+ public $vPrefix = '@'; // prefix of abstract properties
+ public $mPrefix = '$'; // prefix of abstract blocks
+ public $parentSelector = '&';
+
+ public $importDisabled = false;
+ public $importDir = '';
+
+ protected $numberPrecision = null;
+
+ protected $allParsedFiles = array();
+
+ // set to the parser that generated the current line when compiling
+ // so we know how to create error messages
+ protected $sourceParser = null;
+ protected $sourceLoc = null;
+
+ static public $defaultValue = array("keyword", "");
+
+ static protected $nextImportId = 0; // uniquely identify imports
+
+ // attempts to find the path of an import url, returns null for css files
+ protected function findImport($url) {
+ foreach ((array)$this->importDir as $dir) {
+ $full = $dir.(substr($dir, -1) != '/' ? '/' : '').$url;
+ if ($this->fileExists($file = $full.'.less') || $this->fileExists($file = $full)) {
+ return $file;
+ }
+ }
+
+ return null;
+ }
+
+ protected function fileExists($name) {
+ return is_file($name);
+ }
+
+ static public function compressList($items, $delim) {
+ if (!isset($items[1]) && isset($items[0])) return $items[0];
+ else return array('list', $delim, $items);
+ }
+
+ static public function preg_quote($what) {
+ return preg_quote($what, '/');
+ }
+
+ protected function tryImport($importPath, $parentBlock, $out) {
+ if ($importPath[0] == "function" && $importPath[1] == "url") {
+ $importPath = $this->flattenList($importPath[2]);
+ }
+
+ $str = $this->coerceString($importPath);
+ if ($str === null) return false;
+
+ $url = $this->compileValue($this->lib_e($str));
+
+ // don't import if it ends in css
+ if (substr_compare($url, '.css', -4, 4) === 0) return false;
+
+ $realPath = $this->findImport($url);
+
+ if ($realPath === null) return false;
+
+ if ($this->importDisabled) {
+ return array(false, "/* import disabled */");
+ }
+
+ if (isset($this->allParsedFiles[realpath($realPath)])) {
+ return array(false, null);
+ }
+
+ $this->addParsedFile($realPath);
+ $parser = $this->makeParser($realPath);
+ $root = $parser->parse(file_get_contents($realPath));
+
+ // set the parents of all the block props
+ foreach ($root->props as $prop) {
+ if ($prop[0] == "block") {
+ $prop[1]->parent = $parentBlock;
+ }
+ }
+
+ // copy mixins into scope, set their parents
+ // bring blocks from import into current block
+ // TODO: need to mark the source parser these came from this file
+ foreach ($root->children as $childName => $child) {
+ if (isset($parentBlock->children[$childName])) {
+ $parentBlock->children[$childName] = array_merge(
+ $parentBlock->children[$childName],
+ $child);
+ } else {
+ $parentBlock->children[$childName] = $child;
+ }
+ }
+
+ $pi = pathinfo($realPath);
+ $dir = $pi["dirname"];
+
+ list($top, $bottom) = $this->sortProps($root->props, true);
+ $this->compileImportedProps($top, $parentBlock, $out, $parser, $dir);
+
+ return array(true, $bottom, $parser, $dir);
+ }
+
+ protected function compileImportedProps($props, $block, $out, $sourceParser, $importDir) {
+ $oldSourceParser = $this->sourceParser;
+
+ $oldImport = $this->importDir;
+
+ // TODO: this is because the importDir api is stupid
+ $this->importDir = (array)$this->importDir;
+ array_unshift($this->importDir, $importDir);
+
+ foreach ($props as $prop) {
+ $this->compileProp($prop, $block, $out);
+ }
+
+ $this->importDir = $oldImport;
+ $this->sourceParser = $oldSourceParser;
+ }
+
+ /**
+ * Recursively compiles a block.
+ *
+ * A block is analogous to a CSS block in most cases. A single LESS document
+ * is encapsulated in a block when parsed, but it does not have parent tags
+ * so all of it's children appear on the root level when compiled.
+ *
+ * Blocks are made up of props and children.
+ *
+ * Props are property instructions, array tuples which describe an action
+ * to be taken, eg. write a property, set a variable, mixin a block.
+ *
+ * The children of a block are just all the blocks that are defined within.
+ * This is used to look up mixins when performing a mixin.
+ *
+ * Compiling the block involves pushing a fresh environment on the stack,
+ * and iterating through the props, compiling each one.
+ *
+ * See lessc::compileProp()
+ *
+ */
+ protected function compileBlock($block) {
+ switch ($block->type) {
+ case "root":
+ $this->compileRoot($block);
+ break;
+ case null:
+ $this->compileCSSBlock($block);
+ break;
+ case "media":
+ $this->compileMedia($block);
+ break;
+ case "directive":
+ $name = "@" . $block->name;
+ if (!empty($block->value)) {
+ $name .= " " . $this->compileValue($this->reduce($block->value));
+ }
+
+ $this->compileNestedBlock($block, array($name));
+ break;
+ default:
+ $this->throwError("unknown block type: $block->type\n");
+ }
+ }
+
+ protected function compileCSSBlock($block) {
+ $env = $this->pushEnv();
+
+ $selectors = $this->compileSelectors($block->tags);
+ $env->selectors = $this->multiplySelectors($selectors);
+ $out = $this->makeOutputBlock(null, $env->selectors);
+
+ $this->scope->children[] = $out;
+ $this->compileProps($block, $out);
+
+ $block->scope = $env; // mixins carry scope with them!
+ $this->popEnv();
+ }
+
+ protected function compileMedia($media) {
+ $env = $this->pushEnv($media);
+ $parentScope = $this->mediaParent($this->scope);
+
+ $query = $this->compileMediaQuery($this->multiplyMedia($env));
+
+ $this->scope = $this->makeOutputBlock($media->type, array($query));
+ $parentScope->children[] = $this->scope;
+
+ $this->compileProps($media, $this->scope);
+
+ if (count($this->scope->lines) > 0) {
+ $orphanSelelectors = $this->findClosestSelectors();
+ if (!is_null($orphanSelelectors)) {
+ $orphan = $this->makeOutputBlock(null, $orphanSelelectors);
+ $orphan->lines = $this->scope->lines;
+ array_unshift($this->scope->children, $orphan);
+ $this->scope->lines = array();
+ }
+ }
+
+ $this->scope = $this->scope->parent;
+ $this->popEnv();
+ }
+
+ protected function mediaParent($scope) {
+ while (!empty($scope->parent)) {
+ if (!empty($scope->type) && $scope->type != "media") {
+ break;
+ }
+ $scope = $scope->parent;
+ }
+
+ return $scope;
+ }
+
+ protected function compileNestedBlock($block, $selectors) {
+ $this->pushEnv($block);
+ $this->scope = $this->makeOutputBlock($block->type, $selectors);
+ $this->scope->parent->children[] = $this->scope;
+
+ $this->compileProps($block, $this->scope);
+
+ $this->scope = $this->scope->parent;
+ $this->popEnv();
+ }
+
+ protected function compileRoot($root) {
+ $this->pushEnv();
+ $this->scope = $this->makeOutputBlock($root->type);
+ $this->compileProps($root, $this->scope);
+ $this->popEnv();
+ }
+
+ protected function compileProps($block, $out) {
+ foreach ($this->sortProps($block->props) as $prop) {
+ $this->compileProp($prop, $block, $out);
+ }
+
+ $out->lines = array_values(array_unique($out->lines));
+ }
+
+ protected function sortProps($props, $split = false) {
+ $vars = array();
+ $imports = array();
+ $other = array();
+
+ foreach ($props as $prop) {
+ switch ($prop[0]) {
+ case "assign":
+ if (isset($prop[1][0]) && $prop[1][0] == $this->vPrefix) {
+ $vars[] = $prop;
+ } else {
+ $other[] = $prop;
+ }
+ break;
+ case "import":
+ $id = self::$nextImportId++;
+ $prop[] = $id;
+ $imports[] = $prop;
+ $other[] = array("import_mixin", $id);
+ break;
+ default:
+ $other[] = $prop;
+ }
+ }
+
+ if ($split) {
+ return array(array_merge($vars, $imports), $other);
+ } else {
+ return array_merge($vars, $imports, $other);
+ }
+ }
+
+ protected function compileMediaQuery($queries) {
+ $compiledQueries = array();
+ foreach ($queries as $query) {
+ $parts = array();
+ foreach ($query as $q) {
+ switch ($q[0]) {
+ case "mediaType":
+ $parts[] = implode(" ", array_slice($q, 1));
+ break;
+ case "mediaExp":
+ if (isset($q[2])) {
+ $parts[] = "($q[1]: " .
+ $this->compileValue($this->reduce($q[2])) . ")";
+ } else {
+ $parts[] = "($q[1])";
+ }
+ break;
+ case "variable":
+ $parts[] = $this->compileValue($this->reduce($q));
+ break;
+ }
+ }
+
+ if (count($parts) > 0) {
+ $compiledQueries[] = implode(" and ", $parts);
+ }
+ }
+
+ $out = "@media";
+ if (!empty($parts)) {
+ $out .= " " .
+ implode($this->formatter->selectorSeparator, $compiledQueries);
+ }
+ return $out;
+ }
+
+ protected function multiplyMedia($env, $childQueries = null) {
+ if (is_null($env) ||
+ !empty($env->block->type) && $env->block->type != "media")
+ {
+ return $childQueries;
+ }
+
+ // plain old block, skip
+ if (empty($env->block->type)) {
+ return $this->multiplyMedia($env->parent, $childQueries);
+ }
+
+ $out = array();
+ $queries = $env->block->queries;
+ if (is_null($childQueries)) {
+ $out = $queries;
+ } else {
+ foreach ($queries as $parent) {
+ foreach ($childQueries as $child) {
+ $out[] = array_merge($parent, $child);
+ }
+ }
+ }
+
+ return $this->multiplyMedia($env->parent, $out);
+ }
+
+ protected function expandParentSelectors(&$tag, $replace) {
+ $parts = explode("$&$", $tag);
+ $count = 0;
+ foreach ($parts as &$part) {
+ $part = str_replace($this->parentSelector, $replace, $part, $c);
+ $count += $c;
+ }
+ $tag = implode($this->parentSelector, $parts);
+ return $count;
+ }
+
+ protected function findClosestSelectors() {
+ $env = $this->env;
+ $selectors = null;
+ while ($env !== null) {
+ if (isset($env->selectors)) {
+ $selectors = $env->selectors;
+ break;
+ }
+ $env = $env->parent;
+ }
+
+ return $selectors;
+ }
+
+
+ // multiply $selectors against the nearest selectors in env
+ protected function multiplySelectors($selectors) {
+ // find parent selectors
+
+ $parentSelectors = $this->findClosestSelectors();
+ if (is_null($parentSelectors)) {
+ // kill parent reference in top level selector
+ foreach ($selectors as &$s) {
+ $this->expandParentSelectors($s, "");
+ }
+
+ return $selectors;
+ }
+
+ $out = array();
+ foreach ($parentSelectors as $parent) {
+ foreach ($selectors as $child) {
+ $count = $this->expandParentSelectors($child, $parent);
+
+ // don't prepend the parent tag if & was used
+ if ($count > 0) {
+ $out[] = trim($child);
+ } else {
+ $out[] = trim($parent . ' ' . $child);
+ }
+ }
+ }
+
+ return $out;
+ }
+
+ // reduces selector expressions
+ protected function compileSelectors($selectors) {
+ $out = array();
+
+ foreach ($selectors as $s) {
+ if (is_array($s)) {
+ list(, $value) = $s;
+ $out[] = trim($this->compileValue($this->reduce($value)));
+ } else {
+ $out[] = $s;
+ }
+ }
+
+ return $out;
+ }
+
+ protected function eq($left, $right) {
+ return $left == $right;
+ }
+
+ protected function patternMatch($block, $orderedArgs, $keywordArgs) {
+ // match the guards if it has them
+ // any one of the groups must have all its guards pass for a match
+ if (!empty($block->guards)) {
+ $groupPassed = false;
+ foreach ($block->guards as $guardGroup) {
+ foreach ($guardGroup as $guard) {
+ $this->pushEnv();
+ $this->zipSetArgs($block->args, $orderedArgs, $keywordArgs);
+
+ $negate = false;
+ if ($guard[0] == "negate") {
+ $guard = $guard[1];
+ $negate = true;
+ }
+
+ $passed = $this->reduce($guard) == self::$TRUE;
+ if ($negate) $passed = !$passed;
+
+ $this->popEnv();
+
+ if ($passed) {
+ $groupPassed = true;
+ } else {
+ $groupPassed = false;
+ break;
+ }
+ }
+
+ if ($groupPassed) break;
+ }
+
+ if (!$groupPassed) {
+ return false;
+ }
+ }
+
+ if (empty($block->args)) {
+ return $block->isVararg || empty($orderedArgs) && empty($keywordArgs);
+ }
+
+ $remainingArgs = $block->args;
+ if ($keywordArgs) {
+ $remainingArgs = array();
+ foreach ($block->args as $arg) {
+ if ($arg[0] == "arg" && isset($keywordArgs[$arg[1]])) {
+ continue;
+ }
+
+ $remainingArgs[] = $arg;
+ }
+ }
+
+ $i = -1; // no args
+ // try to match by arity or by argument literal
+ foreach ($remainingArgs as $i => $arg) {
+ switch ($arg[0]) {
+ case "lit":
+ if (empty($orderedArgs[$i]) || !$this->eq($arg[1], $orderedArgs[$i])) {
+ return false;
+ }
+ break;
+ case "arg":
+ // no arg and no default value
+ if (!isset($orderedArgs[$i]) && !isset($arg[2])) {
+ return false;
+ }
+ break;
+ case "rest":
+ $i--; // rest can be empty
+ break 2;
+ }
+ }
+
+ if ($block->isVararg) {
+ return true; // not having enough is handled above
+ } else {
+ $numMatched = $i + 1;
+ // greater than becuase default values always match
+ return $numMatched >= count($orderedArgs);
+ }
+ }
+
+ protected function patternMatchAll($blocks, $orderedArgs, $keywordArgs, $skip=array()) {
+ $matches = null;
+ foreach ($blocks as $block) {
+ // skip seen blocks that don't have arguments
+ if (isset($skip[$block->id]) && !isset($block->args)) {
+ continue;
+ }
+
+ if ($this->patternMatch($block, $orderedArgs, $keywordArgs)) {
+ $matches[] = $block;
+ }
+ }
+
+ return $matches;
+ }
+
+ // attempt to find blocks matched by path and args
+ protected function findBlocks($searchIn, $path, $orderedArgs, $keywordArgs, $seen=array()) {
+ if ($searchIn == null) return null;
+ if (isset($seen[$searchIn->id])) return null;
+ $seen[$searchIn->id] = true;
+
+ $name = $path[0];
+
+ if (isset($searchIn->children[$name])) {
+ $blocks = $searchIn->children[$name];
+ if (count($path) == 1) {
+ $matches = $this->patternMatchAll($blocks, $orderedArgs, $keywordArgs, $seen);
+ if (!empty($matches)) {
+ // This will return all blocks that match in the closest
+ // scope that has any matching block, like lessjs
+ return $matches;
+ }
+ } else {
+ $matches = array();
+ foreach ($blocks as $subBlock) {
+ $subMatches = $this->findBlocks($subBlock,
+ array_slice($path, 1), $orderedArgs, $keywordArgs, $seen);
+
+ if (!is_null($subMatches)) {
+ foreach ($subMatches as $sm) {
+ $matches[] = $sm;
+ }
+ }
+ }
+
+ return count($matches) > 0 ? $matches : null;
+ }
+ }
+ if ($searchIn->parent === $searchIn) return null;
+ return $this->findBlocks($searchIn->parent, $path, $orderedArgs, $keywordArgs, $seen);
+ }
+
+ // sets all argument names in $args to either the default value
+ // or the one passed in through $values
+ protected function zipSetArgs($args, $orderedValues, $keywordValues) {
+ $assignedValues = array();
+
+ $i = 0;
+ foreach ($args as $a) {
+ if ($a[0] == "arg") {
+ if (isset($keywordValues[$a[1]])) {
+ // has keyword arg
+ $value = $keywordValues[$a[1]];
+ } elseif (isset($orderedValues[$i])) {
+ // has ordered arg
+ $value = $orderedValues[$i];
+ $i++;
+ } elseif (isset($a[2])) {
+ // has default value
+ $value = $a[2];
+ } else {
+ $this->throwError("Failed to assign arg " . $a[1]);
+ $value = null; // :(
+ }
+
+ $value = $this->reduce($value);
+ $this->set($a[1], $value);
+ $assignedValues[] = $value;
+ } else {
+ // a lit
+ $i++;
+ }
+ }
+
+ // check for a rest
+ $last = end($args);
+ if ($last[0] == "rest") {
+ $rest = array_slice($orderedValues, count($args) - 1);
+ $this->set($last[1], $this->reduce(array("list", " ", $rest)));
+ }
+
+ // wow is this the only true use of PHP's + operator for arrays?
+ $this->env->arguments = $assignedValues + $orderedValues;
+ }
+
+ // compile a prop and update $lines or $blocks appropriately
+ protected function compileProp($prop, $block, $out) {
+ // set error position context
+ $this->sourceLoc = isset($prop[-1]) ? $prop[-1] : -1;
+
+ switch ($prop[0]) {
+ case 'assign':
+ list(, $name, $value) = $prop;
+ if ($name[0] == $this->vPrefix) {
+ $this->set($name, $value);
+ } else {
+ $out->lines[] = $this->formatter->property($name,
+ $this->compileValue($this->reduce($value)));
+ }
+ break;
+ case 'block':
+ list(, $child) = $prop;
+ $this->compileBlock($child);
+ break;
+ case 'mixin':
+ list(, $path, $args, $suffix) = $prop;
+
+ $orderedArgs = array();
+ $keywordArgs = array();
+ foreach ((array)$args as $arg) {
+ $argval = null;
+ switch ($arg[0]) {
+ case "arg":
+ if (!isset($arg[2])) {
+ $orderedArgs[] = $this->reduce(array("variable", $arg[1]));
+ } else {
+ $keywordArgs[$arg[1]] = $this->reduce($arg[2]);
+ }
+ break;
+
+ case "lit":
+ $orderedArgs[] = $this->reduce($arg[1]);
+ break;
+ default:
+ $this->throwError("Unknown arg type: " . $arg[0]);
+ }
+ }
+
+ $mixins = $this->findBlocks($block, $path, $orderedArgs, $keywordArgs);
+
+ if ($mixins === null) {
+ // fwrite(STDERR,"failed to find block: ".implode(" > ", $path)."\n");
+ break; // throw error here??
+ }
+
+ foreach ($mixins as $mixin) {
+ if ($mixin === $block && !$orderedArgs) {
+ continue;
+ }
+
+ $haveScope = false;
+ if (isset($mixin->parent->scope)) {
+ $haveScope = true;
+ $mixinParentEnv = $this->pushEnv();
+ $mixinParentEnv->storeParent = $mixin->parent->scope;
+ }
+
+ $haveArgs = false;
+ if (isset($mixin->args)) {
+ $haveArgs = true;
+ $this->pushEnv();
+ $this->zipSetArgs($mixin->args, $orderedArgs, $keywordArgs);
+ }
+
+ $oldParent = $mixin->parent;
+ if ($mixin != $block) $mixin->parent = $block;
+
+ foreach ($this->sortProps($mixin->props) as $subProp) {
+ if ($suffix !== null &&
+ $subProp[0] == "assign" &&
+ is_string($subProp[1]) &&
+ $subProp[1]{0} != $this->vPrefix)
+ {
+ $subProp[2] = array(
+ 'list', ' ',
+ array($subProp[2], array('keyword', $suffix))
+ );
+ }
+
+ $this->compileProp($subProp, $mixin, $out);
+ }
+
+ $mixin->parent = $oldParent;
+
+ if ($haveArgs) $this->popEnv();
+ if ($haveScope) $this->popEnv();
+ }
+
+ break;
+ case 'raw':
+ $out->lines[] = $prop[1];
+ break;
+ case "directive":
+ list(, $name, $value) = $prop;
+ $out->lines[] = "@$name " . $this->compileValue($this->reduce($value)).';';
+ break;
+ case "comment":
+ $out->lines[] = $prop[1];
+ break;
+ case "import";
+ list(, $importPath, $importId) = $prop;
+ $importPath = $this->reduce($importPath);
+
+ if (!isset($this->env->imports)) {
+ $this->env->imports = array();
+ }
+
+ $result = $this->tryImport($importPath, $block, $out);
+
+ $this->env->imports[$importId] = $result === false ?
+ array(false, "@import " . $this->compileValue($importPath).";") :
+ $result;
+
+ break;
+ case "import_mixin":
+ list(,$importId) = $prop;
+ $import = $this->env->imports[$importId];
+ if ($import[0] === false) {
+ if (isset($import[1])) {
+ $out->lines[] = $import[1];
+ }
+ } else {
+ list(, $bottom, $parser, $importDir) = $import;
+ $this->compileImportedProps($bottom, $block, $out, $parser, $importDir);
+ }
+
+ break;
+ default:
+ $this->throwError("unknown op: {$prop[0]}\n");
+ }
+ }
+
+
+ /**
+ * Compiles a primitive value into a CSS property value.
+ *
+ * Values in lessphp are typed by being wrapped in arrays, their format is
+ * typically:
+ *
+ * array(type, contents [, additional_contents]*)
+ *
+ * The input is expected to be reduced. This function will not work on
+ * things like expressions and variables.
+ */
+ protected function compileValue($value) {
+ switch ($value[0]) {
+ case 'list':
+ // [1] - delimiter
+ // [2] - array of values
+ return implode($value[1], array_map(array($this, 'compileValue'), $value[2]));
+ case 'raw_color':
+ if (!empty($this->formatter->compressColors)) {
+ return $this->compileValue($this->coerceColor($value));
+ }
+ return $value[1];
+ case 'keyword':
+ // [1] - the keyword
+ return $value[1];
+ case 'number':
+ list(, $num, $unit) = $value;
+ // [1] - the number
+ // [2] - the unit
+ if ($this->numberPrecision !== null) {
+ $num = round($num, $this->numberPrecision);
+ }
+ return $num . $unit;
+ case 'string':
+ // [1] - contents of string (includes quotes)
+ list(, $delim, $content) = $value;
+ foreach ($content as &$part) {
+ if (is_array($part)) {
+ $part = $this->compileValue($part);
+ }
+ }
+ return $delim . implode($content) . $delim;
+ case 'color':
+ // [1] - red component (either number or a %)
+ // [2] - green component
+ // [3] - blue component
+ // [4] - optional alpha component
+ list(, $r, $g, $b) = $value;
+ $r = round($r);
+ $g = round($g);
+ $b = round($b);
+
+ if (count($value) == 5 && $value[4] != 1) { // rgba
+ return 'rgba('.$r.','.$g.','.$b.','.$value[4].')';
+ }
+
+ $h = sprintf("#%02x%02x%02x", $r, $g, $b);
+
+ if (!empty($this->formatter->compressColors)) {
+ // Converting hex color to short notation (e.g. #003399 to #039)
+ if ($h[1] === $h[2] && $h[3] === $h[4] && $h[5] === $h[6]) {
+ $h = '#' . $h[1] . $h[3] . $h[5];
+ }
+ }
+
+ return $h;
+
+ case 'function':
+ list(, $name, $args) = $value;
+ return $name.'('.$this->compileValue($args).')';
+ default: // assumed to be unit
+ $this->throwError("unknown value type: $value[0]");
+ }
+ }
+
+ protected function lib_pow($args) {
+ list($base, $exp) = $this->assertArgs($args, 2, "pow");
+ return pow($this->assertNumber($base), $this->assertNumber($exp));
+ }
+
+ protected function lib_pi() {
+ return pi();
+ }
+
+ protected function lib_mod($args) {
+ list($a, $b) = $this->assertArgs($args, 2, "mod");
+ return $this->assertNumber($a) % $this->assertNumber($b);
+ }
+
+ protected function lib_tan($num) {
+ return tan($this->assertNumber($num));
+ }
+
+ protected function lib_sin($num) {
+ return sin($this->assertNumber($num));
+ }
+
+ protected function lib_cos($num) {
+ return cos($this->assertNumber($num));
+ }
+
+ protected function lib_atan($num) {
+ $num = atan($this->assertNumber($num));
+ return array("number", $num, "rad");
+ }
+
+ protected function lib_asin($num) {
+ $num = asin($this->assertNumber($num));
+ return array("number", $num, "rad");
+ }
+
+ protected function lib_acos($num) {
+ $num = acos($this->assertNumber($num));
+ return array("number", $num, "rad");
+ }
+
+ protected function lib_sqrt($num) {
+ return sqrt($this->assertNumber($num));
+ }
+
+ protected function lib_extract($value) {
+ list($list, $idx) = $this->assertArgs($value, 2, "extract");
+ $idx = $this->assertNumber($idx);
+ // 1 indexed
+ if ($list[0] == "list" && isset($list[2][$idx - 1])) {
+ return $list[2][$idx - 1];
+ }
+ }
+
+ protected function lib_isnumber($value) {
+ return $this->toBool($value[0] == "number");
+ }
+
+ protected function lib_isstring($value) {
+ return $this->toBool($value[0] == "string");
+ }
+
+ protected function lib_iscolor($value) {
+ return $this->toBool($this->coerceColor($value));
+ }
+
+ protected function lib_iskeyword($value) {
+ return $this->toBool($value[0] == "keyword");
+ }
+
+ protected function lib_ispixel($value) {
+ return $this->toBool($value[0] == "number" && $value[2] == "px");
+ }
+
+ protected function lib_ispercentage($value) {
+ return $this->toBool($value[0] == "number" && $value[2] == "%");
+ }
+
+ protected function lib_isem($value) {
+ return $this->toBool($value[0] == "number" && $value[2] == "em");
+ }
+
+ protected function lib_isrem($value) {
+ return $this->toBool($value[0] == "number" && $value[2] == "rem");
+ }
+
+ protected function lib_rgbahex($color) {
+ $color = $this->coerceColor($color);
+ if (is_null($color))
+ $this->throwError("color expected for rgbahex");
+
+ return sprintf("#%02x%02x%02x%02x",
+ isset($color[4]) ? $color[4]*255 : 255,
+ $color[1],$color[2], $color[3]);
+ }
+
+ protected function lib_argb($color){
+ return $this->lib_rgbahex($color);
+ }
+
+ // utility func to unquote a string
+ protected function lib_e($arg) {
+ switch ($arg[0]) {
+ case "list":
+ $items = $arg[2];
+ if (isset($items[0])) {
+ return $this->lib_e($items[0]);
+ }
+ return self::$defaultValue;
+ case "string":
+ $arg[1] = "";
+ return $arg;
+ case "keyword":
+ return $arg;
+ default:
+ return array("keyword", $this->compileValue($arg));
+ }
+ }
+
+ protected function lib__sprintf($args) {
+ if ($args[0] != "list") return $args;
+ $values = $args[2];
+ $string = array_shift($values);
+ $template = $this->compileValue($this->lib_e($string));
+
+ $i = 0;
+ if (preg_match_all('/%[dsa]/', $template, $m)) {
+ foreach ($m[0] as $match) {
+ $val = isset($values[$i]) ?
+ $this->reduce($values[$i]) : array('keyword', '');
+
+ // lessjs compat, renders fully expanded color, not raw color
+ if ($color = $this->coerceColor($val)) {
+ $val = $color;
+ }
+
+ $i++;
+ $rep = $this->compileValue($this->lib_e($val));
+ $template = preg_replace('/'.self::preg_quote($match).'/',
+ $rep, $template, 1);
+ }
+ }
+
+ $d = $string[0] == "string" ? $string[1] : '"';
+ return array("string", $d, array($template));
+ }
+
+ protected function lib_floor($arg) {
+ $value = $this->assertNumber($arg);
+ return array("number", floor($value), $arg[2]);
+ }
+
+ protected function lib_ceil($arg) {
+ $value = $this->assertNumber($arg);
+ return array("number", ceil($value), $arg[2]);
+ }
+
+ protected function lib_round($arg) {
+ $value = $this->assertNumber($arg);
+ return array("number", round($value), $arg[2]);
+ }
+
+ protected function lib_unit($arg) {
+ if ($arg[0] == "list") {
+ list($number, $newUnit) = $arg[2];
+ return array("number", $this->assertNumber($number),
+ $this->compileValue($this->lib_e($newUnit)));
+ } else {
+ return array("number", $this->assertNumber($arg), "");
+ }
+ }
+
+ /**
+ * Helper function to get arguments for color manipulation functions.
+ * takes a list that contains a color like thing and a percentage
+ */
+ protected function colorArgs($args) {
+ if ($args[0] != 'list' || count($args[2]) < 2) {
+ return array(array('color', 0, 0, 0), 0);
+ }
+ list($color, $delta) = $args[2];
+ $color = $this->assertColor($color);
+ $delta = floatval($delta[1]);
+
+ return array($color, $delta);
+ }
+
+ protected function lib_darken($args) {
+ list($color, $delta) = $this->colorArgs($args);
+
+ $hsl = $this->toHSL($color);
+ $hsl[3] = $this->clamp($hsl[3] - $delta, 100);
+ return $this->toRGB($hsl);
+ }
+
+ protected function lib_lighten($args) {
+ list($color, $delta) = $this->colorArgs($args);
+
+ $hsl = $this->toHSL($color);
+ $hsl[3] = $this->clamp($hsl[3] + $delta, 100);
+ return $this->toRGB($hsl);
+ }
+
+ protected function lib_saturate($args) {
+ list($color, $delta) = $this->colorArgs($args);
+
+ $hsl = $this->toHSL($color);
+ $hsl[2] = $this->clamp($hsl[2] + $delta, 100);
+ return $this->toRGB($hsl);
+ }
+
+ protected function lib_desaturate($args) {
+ list($color, $delta) = $this->colorArgs($args);
+
+ $hsl = $this->toHSL($color);
+ $hsl[2] = $this->clamp($hsl[2] - $delta, 100);
+ return $this->toRGB($hsl);
+ }
+
+ protected function lib_spin($args) {
+ list($color, $delta) = $this->colorArgs($args);
+
+ $hsl = $this->toHSL($color);
+
+ $hsl[1] = $hsl[1] + $delta % 360;
+ if ($hsl[1] < 0) $hsl[1] += 360;
+
+ return $this->toRGB($hsl);
+ }
+
+ protected function lib_fadeout($args) {
+ list($color, $delta) = $this->colorArgs($args);
+ $color[4] = $this->clamp((isset($color[4]) ? $color[4] : 1) - $delta/100);
+ return $color;
+ }
+
+ protected function lib_fadein($args) {
+ list($color, $delta) = $this->colorArgs($args);
+ $color[4] = $this->clamp((isset($color[4]) ? $color[4] : 1) + $delta/100);
+ return $color;
+ }
+
+ protected function lib_hue($color) {
+ $hsl = $this->toHSL($this->assertColor($color));
+ return round($hsl[1]);
+ }
+
+ protected function lib_saturation($color) {
+ $hsl = $this->toHSL($this->assertColor($color));
+ return round($hsl[2]);
+ }
+
+ protected function lib_lightness($color) {
+ $hsl = $this->toHSL($this->assertColor($color));
+ return round($hsl[3]);
+ }
+
+ // get the alpha of a color
+ // defaults to 1 for non-colors or colors without an alpha
+ protected function lib_alpha($value) {
+ if (!is_null($color = $this->coerceColor($value))) {
+ return isset($color[4]) ? $color[4] : 1;
+ }
+ }
+
+ // set the alpha of the color
+ protected function lib_fade($args) {
+ list($color, $alpha) = $this->colorArgs($args);
+ $color[4] = $this->clamp($alpha / 100.0);
+ return $color;
+ }
+
+ protected function lib_percentage($arg) {
+ $num = $this->assertNumber($arg);
+ return array("number", $num*100, "%");
+ }
+
+ // mixes two colors by weight
+ // mix(@color1, @color2, [@weight: 50%]);
+ // http://sass-lang.com/docs/yardoc/Sass/Script/Functions.html#mix-instance_method
+ protected function lib_mix($args) {
+ if ($args[0] != "list" || count($args[2]) < 2)
+ $this->throwError("mix expects (color1, color2, weight)");
+
+ list($first, $second) = $args[2];
+ $first = $this->assertColor($first);
+ $second = $this->assertColor($second);
+
+ $first_a = $this->lib_alpha($first);
+ $second_a = $this->lib_alpha($second);
+
+ if (isset($args[2][2])) {
+ $weight = $args[2][2][1] / 100.0;
+ } else {
+ $weight = 0.5;
+ }
+
+ $w = $weight * 2 - 1;
+ $a = $first_a - $second_a;
+
+ $w1 = (($w * $a == -1 ? $w : ($w + $a)/(1 + $w * $a)) + 1) / 2.0;
+ $w2 = 1.0 - $w1;
+
+ $new = array('color',
+ $w1 * $first[1] + $w2 * $second[1],
+ $w1 * $first[2] + $w2 * $second[2],
+ $w1 * $first[3] + $w2 * $second[3],
+ );
+
+ if ($first_a != 1.0 || $second_a != 1.0) {
+ $new[] = $first_a * $weight + $second_a * ($weight - 1);
+ }
+
+ return $this->fixColor($new);
+ }
+
+ protected function lib_contrast($args) {
+ if ($args[0] != 'list' || count($args[2]) < 3) {
+ return array(array('color', 0, 0, 0), 0);
+ }
+
+ list($inputColor, $darkColor, $lightColor) = $args[2];
+
+ $inputColor = $this->assertColor($inputColor);
+ $darkColor = $this->assertColor($darkColor);
+ $lightColor = $this->assertColor($lightColor);
+ $hsl = $this->toHSL($inputColor);
+
+ if ($hsl[3] > 50) {
+ return $darkColor;
+ }
+
+ return $lightColor;
+ }
+
+ protected function assertColor($value, $error = "expected color value") {
+ $color = $this->coerceColor($value);
+ if (is_null($color)) $this->throwError($error);
+ return $color;
+ }
+
+ protected function assertNumber($value, $error = "expecting number") {
+ if ($value[0] == "number") return $value[1];
+ $this->throwError($error);
+ }
+
+ protected function assertArgs($value, $expectedArgs, $name="") {
+ if ($expectedArgs == 1) {
+ return $value;
+ } else {
+ if ($value[0] !== "list" || $value[1] != ",") $this->throwError("expecting list");
+ $values = $value[2];
+ $numValues = count($values);
+ if ($expectedArgs != $numValues) {
+ if ($name) {
+ $name = $name . ": ";
+ }
+
+ $this->throwError("${name}expecting $expectedArgs arguments, got $numValues");
+ }
+
+ return $values;
+ }
+ }
+
+ protected function toHSL($color) {
+ if ($color[0] == 'hsl') return $color;
+
+ $r = $color[1] / 255;
+ $g = $color[2] / 255;
+ $b = $color[3] / 255;
+
+ $min = min($r, $g, $b);
+ $max = max($r, $g, $b);
+
+ $L = ($min + $max) / 2;
+ if ($min == $max) {
+ $S = $H = 0;
+ } else {
+ if ($L < 0.5)
+ $S = ($max - $min)/($max + $min);
+ else
+ $S = ($max - $min)/(2.0 - $max - $min);
+
+ if ($r == $max) $H = ($g - $b)/($max - $min);
+ elseif ($g == $max) $H = 2.0 + ($b - $r)/($max - $min);
+ elseif ($b == $max) $H = 4.0 + ($r - $g)/($max - $min);
+
+ }
+
+ $out = array('hsl',
+ ($H < 0 ? $H + 6 : $H)*60,
+ $S*100,
+ $L*100,
+ );
+
+ if (count($color) > 4) $out[] = $color[4]; // copy alpha
+ return $out;
+ }
+
+ protected function toRGB_helper($comp, $temp1, $temp2) {
+ if ($comp < 0) $comp += 1.0;
+ elseif ($comp > 1) $comp -= 1.0;
+
+ if (6 * $comp < 1) return $temp1 + ($temp2 - $temp1) * 6 * $comp;
+ if (2 * $comp < 1) return $temp2;
+ if (3 * $comp < 2) return $temp1 + ($temp2 - $temp1)*((2/3) - $comp) * 6;
+
+ return $temp1;
+ }
+
+ /**
+ * Converts a hsl array into a color value in rgb.
+ * Expects H to be in range of 0 to 360, S and L in 0 to 100
+ */
+ protected function toRGB($color) {
+ if ($color[0] == 'color') return $color;
+
+ $H = $color[1] / 360;
+ $S = $color[2] / 100;
+ $L = $color[3] / 100;
+
+ if ($S == 0) {
+ $r = $g = $b = $L;
+ } else {
+ $temp2 = $L < 0.5 ?
+ $L*(1.0 + $S) :
+ $L + $S - $L * $S;
+
+ $temp1 = 2.0 * $L - $temp2;
+
+ $r = $this->toRGB_helper($H + 1/3, $temp1, $temp2);
+ $g = $this->toRGB_helper($H, $temp1, $temp2);
+ $b = $this->toRGB_helper($H - 1/3, $temp1, $temp2);
+ }
+
+ // $out = array('color', round($r*255), round($g*255), round($b*255));
+ $out = array('color', $r*255, $g*255, $b*255);
+ if (count($color) > 4) $out[] = $color[4]; // copy alpha
+ return $out;
+ }
+
+ protected function clamp($v, $max = 1, $min = 0) {
+ return min($max, max($min, $v));
+ }
+
+ /**
+ * Convert the rgb, rgba, hsl color literals of function type
+ * as returned by the parser into values of color type.
+ */
+ protected function funcToColor($func) {
+ $fname = $func[1];
+ if ($func[2][0] != 'list') return false; // need a list of arguments
+ $rawComponents = $func[2][2];
+
+ if ($fname == 'hsl' || $fname == 'hsla') {
+ $hsl = array('hsl');
+ $i = 0;
+ foreach ($rawComponents as $c) {
+ $val = $this->reduce($c);
+ $val = isset($val[1]) ? floatval($val[1]) : 0;
+
+ if ($i == 0) $clamp = 360;
+ elseif ($i < 3) $clamp = 100;
+ else $clamp = 1;
+
+ $hsl[] = $this->clamp($val, $clamp);
+ $i++;
+ }
+
+ while (count($hsl) < 4) $hsl[] = 0;
+ return $this->toRGB($hsl);
+
+ } elseif ($fname == 'rgb' || $fname == 'rgba') {
+ $components = array();
+ $i = 1;
+ foreach ($rawComponents as $c) {
+ $c = $this->reduce($c);
+ if ($i < 4) {
+ if ($c[0] == "number" && $c[2] == "%") {
+ $components[] = 255 * ($c[1] / 100);
+ } else {
+ $components[] = floatval($c[1]);
+ }
+ } elseif ($i == 4) {
+ if ($c[0] == "number" && $c[2] == "%") {
+ $components[] = 1.0 * ($c[1] / 100);
+ } else {
+ $components[] = floatval($c[1]);
+ }
+ } else break;
+
+ $i++;
+ }
+ while (count($components) < 3) $components[] = 0;
+ array_unshift($components, 'color');
+ return $this->fixColor($components);
+ }
+
+ return false;
+ }
+
+ protected function reduce($value, $forExpression = false) {
+ switch ($value[0]) {
+ case "interpolate":
+ $reduced = $this->reduce($value[1]);
+ $var = $this->compileValue($reduced);
+ $res = $this->reduce(array("variable", $this->vPrefix . $var));
+
+ if ($res[0] == "raw_color") {
+ $res = $this->coerceColor($res);
+ }
+
+ if (empty($value[2])) $res = $this->lib_e($res);
+
+ return $res;
+ case "variable":
+ $key = $value[1];
+ if (is_array($key)) {
+ $key = $this->reduce($key);
+ $key = $this->vPrefix . $this->compileValue($this->lib_e($key));
+ }
+
+ $seen =& $this->env->seenNames;
+
+ if (!empty($seen[$key])) {
+ $this->throwError("infinite loop detected: $key");
+ }
+
+ $seen[$key] = true;
+ $out = $this->reduce($this->get($key, self::$defaultValue));
+ $seen[$key] = false;
+ return $out;
+ case "list":
+ foreach ($value[2] as &$item) {
+ $item = $this->reduce($item, $forExpression);
+ }
+ return $value;
+ case "expression":
+ return $this->evaluate($value);
+ case "string":
+ foreach ($value[2] as &$part) {
+ if (is_array($part)) {
+ $strip = $part[0] == "variable";
+ $part = $this->reduce($part);
+ if ($strip) $part = $this->lib_e($part);
+ }
+ }
+ return $value;
+ case "escape":
+ list(,$inner) = $value;
+ return $this->lib_e($this->reduce($inner));
+ case "function":
+ $color = $this->funcToColor($value);
+ if ($color) return $color;
+
+ list(, $name, $args) = $value;
+ if ($name == "%") $name = "_sprintf";
+ $f = isset($this->libFunctions[$name]) ?
+ $this->libFunctions[$name] : array($this, 'lib_'.$name);
+
+ if (is_callable($f)) {
+ if ($args[0] == 'list')
+ $args = self::compressList($args[2], $args[1]);
+
+ $ret = call_user_func($f, $this->reduce($args, true), $this);
+
+ if (is_null($ret)) {
+ return array("string", "", array(
+ $name, "(", $args, ")"
+ ));
+ }
+
+ // convert to a typed value if the result is a php primitive
+ if (is_numeric($ret)) $ret = array('number', $ret, "");
+ elseif (!is_array($ret)) $ret = array('keyword', $ret);
+
+ return $ret;
+ }
+
+ // plain function, reduce args
+ $value[2] = $this->reduce($value[2]);
+ return $value;
+ case "unary":
+ list(, $op, $exp) = $value;
+ $exp = $this->reduce($exp);
+
+ if ($exp[0] == "number") {
+ switch ($op) {
+ case "+":
+ return $exp;
+ case "-":
+ $exp[1] *= -1;
+ return $exp;
+ }
+ }
+ return array("string", "", array($op, $exp));
+ }
+
+ if ($forExpression) {
+ switch ($value[0]) {
+ case "keyword":
+ if ($color = $this->coerceColor($value)) {
+ return $color;
+ }
+ break;
+ case "raw_color":
+ return $this->coerceColor($value);
+ }
+ }
+
+ return $value;
+ }
+
+
+ // coerce a value for use in color operation
+ protected function coerceColor($value) {
+ switch($value[0]) {
+ case 'color': return $value;
+ case 'raw_color':
+ $c = array("color", 0, 0, 0);
+ $colorStr = substr($value[1], 1);
+ $num = hexdec($colorStr);
+ $width = strlen($colorStr) == 3 ? 16 : 256;
+
+ for ($i = 3; $i > 0; $i--) { // 3 2 1
+ $t = $num % $width;
+ $num /= $width;
+
+ $c[$i] = $t * (256/$width) + $t * floor(16/$width);
+ }
+
+ return $c;
+ case 'keyword':
+ $name = $value[1];
+ if (isset(self::$cssColors[$name])) {
+ $rgba = explode(',', self::$cssColors[$name]);
+
+ if(isset($rgba[3]))
+ return array('color', $rgba[0], $rgba[1], $rgba[2], $rgba[3]);
+
+ return array('color', $rgba[0], $rgba[1], $rgba[2]);
+ }
+ return null;
+ }
+ }
+
+ // make something string like into a string
+ protected function coerceString($value) {
+ switch ($value[0]) {
+ case "string":
+ return $value;
+ case "keyword":
+ return array("string", "", array($value[1]));
+ }
+ return null;
+ }
+
+ // turn list of length 1 into value type
+ protected function flattenList($value) {
+ if ($value[0] == "list" && count($value[2]) == 1) {
+ return $this->flattenList($value[2][0]);
+ }
+ return $value;
+ }
+
+ protected function toBool($a) {
+ if ($a) return self::$TRUE;
+ else return self::$FALSE;
+ }
+
+ // evaluate an expression
+ protected function evaluate($exp) {
+ list(, $op, $left, $right, $whiteBefore, $whiteAfter) = $exp;
+
+ $left = $this->reduce($left, true);
+ $right = $this->reduce($right, true);
+
+ if ($leftColor = $this->coerceColor($left)) {
+ $left = $leftColor;
+ }
+
+ if ($rightColor = $this->coerceColor($right)) {
+ $right = $rightColor;
+ }
+
+ $ltype = $left[0];
+ $rtype = $right[0];
+
+ // operators that work on all types
+ if ($op == "and") {
+ return $this->toBool($left == self::$TRUE && $right == self::$TRUE);
+ }
+
+ if ($op == "=") {
+ return $this->toBool($this->eq($left, $right) );
+ }
+
+ if ($op == "+" && !is_null($str = $this->stringConcatenate($left, $right))) {
+ return $str;
+ }
+
+ // type based operators
+ $fname = "op_${ltype}_${rtype}";
+ if (is_callable(array($this, $fname))) {
+ $out = $this->$fname($op, $left, $right);
+ if (!is_null($out)) return $out;
+ }
+
+ // make the expression look it did before being parsed
+ $paddedOp = $op;
+ if ($whiteBefore) $paddedOp = " " . $paddedOp;
+ if ($whiteAfter) $paddedOp .= " ";
+
+ return array("string", "", array($left, $paddedOp, $right));
+ }
+
+ protected function stringConcatenate($left, $right) {
+ if ($strLeft = $this->coerceString($left)) {
+ if ($right[0] == "string") {
+ $right[1] = "";
+ }
+ $strLeft[2][] = $right;
+ return $strLeft;
+ }
+
+ if ($strRight = $this->coerceString($right)) {
+ array_unshift($strRight[2], $left);
+ return $strRight;
+ }
+ }
+
+
+ // make sure a color's components don't go out of bounds
+ protected function fixColor($c) {
+ foreach (range(1, 3) as $i) {
+ if ($c[$i] < 0) $c[$i] = 0;
+ if ($c[$i] > 255) $c[$i] = 255;
+ }
+
+ return $c;
+ }
+
+ protected function op_number_color($op, $lft, $rgt) {
+ if ($op == '+' || $op == '*') {
+ return $this->op_color_number($op, $rgt, $lft);
+ }
+ }
+
+ protected function op_color_number($op, $lft, $rgt) {
+ if ($rgt[0] == '%') $rgt[1] /= 100;
+
+ return $this->op_color_color($op, $lft,
+ array_fill(1, count($lft) - 1, $rgt[1]));
+ }
+
+ protected function op_color_color($op, $left, $right) {
+ $out = array('color');
+ $max = count($left) > count($right) ? count($left) : count($right);
+ foreach (range(1, $max - 1) as $i) {
+ $lval = isset($left[$i]) ? $left[$i] : 0;
+ $rval = isset($right[$i]) ? $right[$i] : 0;
+ switch ($op) {
+ case '+':
+ $out[] = $lval + $rval;
+ break;
+ case '-':
+ $out[] = $lval - $rval;
+ break;
+ case '*':
+ $out[] = $lval * $rval;
+ break;
+ case '%':
+ $out[] = $lval % $rval;
+ break;
+ case '/':
+ if ($rval == 0) $this->throwError("evaluate error: can't divide by zero");
+ $out[] = $lval / $rval;
+ break;
+ default:
+ $this->throwError('evaluate error: color op number failed on op '.$op);
+ }
+ }
+ return $this->fixColor($out);
+ }
+
+ function lib_red($color){
+ $color = $this->coerceColor($color);
+ if (is_null($color)) {
+ $this->throwError('color expected for red()');
+ }
+
+ return $color[1];
+ }
+
+ function lib_green($color){
+ $color = $this->coerceColor($color);
+ if (is_null($color)) {
+ $this->throwError('color expected for green()');
+ }
+
+ return $color[2];
+ }
+
+ function lib_blue($color){
+ $color = $this->coerceColor($color);
+ if (is_null($color)) {
+ $this->throwError('color expected for blue()');
+ }
+
+ return $color[3];
+ }
+
+
+ // operator on two numbers
+ protected function op_number_number($op, $left, $right) {
+ $unit = empty($left[2]) ? $right[2] : $left[2];
+
+ $value = 0;
+ switch ($op) {
+ case '+':
+ $value = $left[1] + $right[1];
+ break;
+ case '*':
+ $value = $left[1] * $right[1];
+ break;
+ case '-':
+ $value = $left[1] - $right[1];
+ break;
+ case '%':
+ $value = $left[1] % $right[1];
+ break;
+ case '/':
+ if ($right[1] == 0) $this->throwError('parse error: divide by zero');
+ $value = $left[1] / $right[1];
+ break;
+ case '<':
+ return $this->toBool($left[1] < $right[1]);
+ case '>':
+ return $this->toBool($left[1] > $right[1]);
+ case '>=':
+ return $this->toBool($left[1] >= $right[1]);
+ case '=<':
+ return $this->toBool($left[1] <= $right[1]);
+ default:
+ $this->throwError('parse error: unknown number operator: '.$op);
+ }
+
+ return array("number", $value, $unit);
+ }
+
+
+ /* environment functions */
+
+ protected function makeOutputBlock($type, $selectors = null) {
+ $b = new stdclass;
+ $b->lines = array();
+ $b->children = array();
+ $b->selectors = $selectors;
+ $b->type = $type;
+ $b->parent = $this->scope;
+ return $b;
+ }
+
+ // the state of execution
+ protected function pushEnv($block = null) {
+ $e = new stdclass;
+ $e->parent = $this->env;
+ $e->store = array();
+ $e->block = $block;
+
+ $this->env = $e;
+ return $e;
+ }
+
+ // pop something off the stack
+ protected function popEnv() {
+ $old = $this->env;
+ $this->env = $this->env->parent;
+ return $old;
+ }
+
+ // set something in the current env
+ protected function set($name, $value) {
+ $this->env->store[$name] = $value;
+ }
+
+
+ // get the highest occurrence entry for a name
+ protected function get($name, $default=null) {
+ $current = $this->env;
+
+ $isArguments = $name == $this->vPrefix . 'arguments';
+ while ($current) {
+ if ($isArguments && isset($current->arguments)) {
+ return array('list', ' ', $current->arguments);
+ }
+
+ if (isset($current->store[$name]))
+ return $current->store[$name];
+ else {
+ $current = isset($current->storeParent) ?
+ $current->storeParent : $current->parent;
+ }
+ }
+
+ return $default;
+ }
+
+ // inject array of unparsed strings into environment as variables
+ protected function injectVariables($args) {
+ $this->pushEnv();
+ $parser = new lessc_parser($this, __METHOD__);
+ foreach ($args as $name => $strValue) {
+ if ($name{0} != '@') $name = '@'.$name;
+ $parser->count = 0;
+ $parser->buffer = (string)$strValue;
+ if (!$parser->propertyValue($value)) {
+ throw new Exception("failed to parse passed in variable $name: $strValue");
+ }
+
+ $this->set($name, $value);
+ }
+ }
+
+ /**
+ * Initialize any static state, can initialize parser for a file
+ * $opts isn't used yet
+ */
+ public function __construct($fname = null) {
+ if ($fname !== null) {
+ // used for deprecated parse method
+ $this->_parseFile = $fname;
+ }
+ }
+
+ public function compile($string, $name = null) {
+ $locale = setlocale(LC_NUMERIC, 0);
+ setlocale(LC_NUMERIC, "C");
+
+ $this->parser = $this->makeParser($name);
+ $root = $this->parser->parse($string);
+
+ $this->env = null;
+ $this->scope = null;
+
+ $this->formatter = $this->newFormatter();
+
+ if (!empty($this->registeredVars)) {
+ $this->injectVariables($this->registeredVars);
+ }
+
+ $this->sourceParser = $this->parser; // used for error messages
+ $this->compileBlock($root);
+
+ ob_start();
+ $this->formatter->block($this->scope);
+ $out = ob_get_clean();
+ setlocale(LC_NUMERIC, $locale);
+ return $out;
+ }
+
+ public function compileFile($fname, $outFname = null) {
+ if (!is_readable($fname)) {
+ throw new Exception('load error: failed to find '.$fname);
+ }
+
+ $pi = pathinfo($fname);
+
+ $oldImport = $this->importDir;
+
+ $this->importDir = (array)$this->importDir;
+ $this->importDir[] = $pi['dirname'].'/';
+
+ $this->addParsedFile($fname);
+
+ $out = $this->compile(file_get_contents($fname), $fname);
+
+ $this->importDir = $oldImport;
+
+ if ($outFname !== null) {
+ return file_put_contents($outFname, $out);
+ }
+
+ return $out;
+ }
+
+ // compile only if changed input has changed or output doesn't exist
+ public function checkedCompile($in, $out) {
+ if (!is_file($out) || filemtime($in) > filemtime($out)) {
+ $this->compileFile($in, $out);
+ return true;
+ }
+ return false;
+ }
+
+ /**
+ * Execute lessphp on a .less file or a lessphp cache structure
+ *
+ * The lessphp cache structure contains information about a specific
+ * less file having been parsed. It can be used as a hint for future
+ * calls to determine whether or not a rebuild is required.
+ *
+ * The cache structure contains two important keys that may be used
+ * externally:
+ *
+ * compiled: The final compiled CSS
+ * updated: The time (in seconds) the CSS was last compiled
+ *
+ * The cache structure is a plain-ol' PHP associative array and can
+ * be serialized and unserialized without a hitch.
+ *
+ * @param mixed $in Input
+ * @param bool $force Force rebuild?
+ * @return array lessphp cache structure
+ */
+ public function cachedCompile($in, $force = false) {
+ // assume no root
+ $root = null;
+
+ if (is_string($in)) {
+ $root = $in;
+ } elseif (is_array($in) and isset($in['root'])) {
+ if ($force or ! isset($in['files'])) {
+ // If we are forcing a recompile or if for some reason the
+ // structure does not contain any file information we should
+ // specify the root to trigger a rebuild.
+ $root = $in['root'];
+ } elseif (isset($in['files']) and is_array($in['files'])) {
+ foreach ($in['files'] as $fname => $ftime ) {
+ if (!file_exists($fname) or filemtime($fname) > $ftime) {
+ // One of the files we knew about previously has changed
+ // so we should look at our incoming root again.
+ $root = $in['root'];
+ break;
+ }
+ }
+ }
+ } else {
+ // TODO: Throw an exception? We got neither a string nor something
+ // that looks like a compatible lessphp cache structure.
+ return null;
+ }
+
+ if ($root !== null) {
+ // If we have a root value which means we should rebuild.
+ $out = array();
+ $out['root'] = $root;
+ $out['compiled'] = $this->compileFile($root);
+ $out['files'] = $this->allParsedFiles();
+ $out['updated'] = time();
+ return $out;
+ } else {
+ // No changes, pass back the structure
+ // we were given initially.
+ return $in;
+ }
+
+ }
+
+ // parse and compile buffer
+ // This is deprecated
+ public function parse($str = null, $initialVariables = null) {
+ if (is_array($str)) {
+ $initialVariables = $str;
+ $str = null;
+ }
+
+ $oldVars = $this->registeredVars;
+ if ($initialVariables !== null) {
+ $this->setVariables($initialVariables);
+ }
+
+ if ($str == null) {
+ if (empty($this->_parseFile)) {
+ throw new exception("nothing to parse");
+ }
+
+ $out = $this->compileFile($this->_parseFile);
+ } else {
+ $out = $this->compile($str);
+ }
+
+ $this->registeredVars = $oldVars;
+ return $out;
+ }
+
+ protected function makeParser($name) {
+ $parser = new lessc_parser($this, $name);
+ $parser->writeComments = $this->preserveComments;
+
+ return $parser;
+ }
+
+ public function setFormatter($name) {
+ $this->formatterName = $name;
+ }
+
+ protected function newFormatter() {
+ $className = "lessc_formatter_lessjs";
+ if (!empty($this->formatterName)) {
+ if (!is_string($this->formatterName))
+ return $this->formatterName;
+ $className = "lessc_formatter_$this->formatterName";
+ }
+
+ return new $className;
+ }
+
+ public function setPreserveComments($preserve) {
+ $this->preserveComments = $preserve;
+ }
+
+ public function registerFunction($name, $func) {
+ $this->libFunctions[$name] = $func;
+ }
+
+ public function unregisterFunction($name) {
+ unset($this->libFunctions[$name]);
+ }
+
+ public function setVariables($variables) {
+ $this->registeredVars = array_merge($this->registeredVars, $variables);
+ }
+
+ public function unsetVariable($name) {
+ unset($this->registeredVars[$name]);
+ }
+
+ public function setImportDir($dirs) {
+ $this->importDir = (array)$dirs;
+ }
+
+ public function addImportDir($dir) {
+ $this->importDir = (array)$this->importDir;
+ $this->importDir[] = $dir;
+ }
+
+ public function allParsedFiles() {
+ return $this->allParsedFiles;
+ }
+
+ protected function addParsedFile($file) {
+ $this->allParsedFiles[realpath($file)] = filemtime($file);
+ }
+
+ /**
+ * Uses the current value of $this->count to show line and line number
+ */
+ protected function throwError($msg = null) {
+ if ($this->sourceLoc >= 0) {
+ $this->sourceParser->throwError($msg, $this->sourceLoc);
+ }
+ throw new exception($msg);
+ }
+
+ // compile file $in to file $out if $in is newer than $out
+ // returns true when it compiles, false otherwise
+ public static function ccompile($in, $out, $less = null) {
+ if ($less === null) {
+ $less = new self;
+ }
+ return $less->checkedCompile($in, $out);
+ }
+
+ public static function cexecute($in, $force = false, $less = null) {
+ if ($less === null) {
+ $less = new self;
+ }
+ return $less->cachedCompile($in, $force);
+ }
+
+ static protected $cssColors = array(
+ 'aliceblue' => '240,248,255',
+ 'antiquewhite' => '250,235,215',
+ 'aqua' => '0,255,255',
+ 'aquamarine' => '127,255,212',
+ 'azure' => '240,255,255',
+ 'beige' => '245,245,220',
+ 'bisque' => '255,228,196',
+ 'black' => '0,0,0',
+ 'blanchedalmond' => '255,235,205',
+ 'blue' => '0,0,255',
+ 'blueviolet' => '138,43,226',
+ 'brown' => '165,42,42',
+ 'burlywood' => '222,184,135',
+ 'cadetblue' => '95,158,160',
+ 'chartreuse' => '127,255,0',
+ 'chocolate' => '210,105,30',
+ 'coral' => '255,127,80',
+ 'cornflowerblue' => '100,149,237',
+ 'cornsilk' => '255,248,220',
+ 'crimson' => '220,20,60',
+ 'cyan' => '0,255,255',
+ 'darkblue' => '0,0,139',
+ 'darkcyan' => '0,139,139',
+ 'darkgoldenrod' => '184,134,11',
+ 'darkgray' => '169,169,169',
+ 'darkgreen' => '0,100,0',
+ 'darkgrey' => '169,169,169',
+ 'darkkhaki' => '189,183,107',
+ 'darkmagenta' => '139,0,139',
+ 'darkolivegreen' => '85,107,47',
+ 'darkorange' => '255,140,0',
+ 'darkorchid' => '153,50,204',
+ 'darkred' => '139,0,0',
+ 'darksalmon' => '233,150,122',
+ 'darkseagreen' => '143,188,143',
+ 'darkslateblue' => '72,61,139',
+ 'darkslategray' => '47,79,79',
+ 'darkslategrey' => '47,79,79',
+ 'darkturquoise' => '0,206,209',
+ 'darkviolet' => '148,0,211',
+ 'deeppink' => '255,20,147',
+ 'deepskyblue' => '0,191,255',
+ 'dimgray' => '105,105,105',
+ 'dimgrey' => '105,105,105',
+ 'dodgerblue' => '30,144,255',
+ 'firebrick' => '178,34,34',
+ 'floralwhite' => '255,250,240',
+ 'forestgreen' => '34,139,34',
+ 'fuchsia' => '255,0,255',
+ 'gainsboro' => '220,220,220',
+ 'ghostwhite' => '248,248,255',
+ 'gold' => '255,215,0',
+ 'goldenrod' => '218,165,32',
+ 'gray' => '128,128,128',
+ 'green' => '0,128,0',
+ 'greenyellow' => '173,255,47',
+ 'grey' => '128,128,128',
+ 'honeydew' => '240,255,240',
+ 'hotpink' => '255,105,180',
+ 'indianred' => '205,92,92',
+ 'indigo' => '75,0,130',
+ 'ivory' => '255,255,240',
+ 'khaki' => '240,230,140',
+ 'lavender' => '230,230,250',
+ 'lavenderblush' => '255,240,245',
+ 'lawngreen' => '124,252,0',
+ 'lemonchiffon' => '255,250,205',
+ 'lightblue' => '173,216,230',
+ 'lightcoral' => '240,128,128',
+ 'lightcyan' => '224,255,255',
+ 'lightgoldenrodyellow' => '250,250,210',
+ 'lightgray' => '211,211,211',
+ 'lightgreen' => '144,238,144',
+ 'lightgrey' => '211,211,211',
+ 'lightpink' => '255,182,193',
+ 'lightsalmon' => '255,160,122',
+ 'lightseagreen' => '32,178,170',
+ 'lightskyblue' => '135,206,250',
+ 'lightslategray' => '119,136,153',
+ 'lightslategrey' => '119,136,153',
+ 'lightsteelblue' => '176,196,222',
+ 'lightyellow' => '255,255,224',
+ 'lime' => '0,255,0',
+ 'limegreen' => '50,205,50',
+ 'linen' => '250,240,230',
+ 'magenta' => '255,0,255',
+ 'maroon' => '128,0,0',
+ 'mediumaquamarine' => '102,205,170',
+ 'mediumblue' => '0,0,205',
+ 'mediumorchid' => '186,85,211',
+ 'mediumpurple' => '147,112,219',
+ 'mediumseagreen' => '60,179,113',
+ 'mediumslateblue' => '123,104,238',
+ 'mediumspringgreen' => '0,250,154',
+ 'mediumturquoise' => '72,209,204',
+ 'mediumvioletred' => '199,21,133',
+ 'midnightblue' => '25,25,112',
+ 'mintcream' => '245,255,250',
+ 'mistyrose' => '255,228,225',
+ 'moccasin' => '255,228,181',
+ 'navajowhite' => '255,222,173',
+ 'navy' => '0,0,128',
+ 'oldlace' => '253,245,230',
+ 'olive' => '128,128,0',
+ 'olivedrab' => '107,142,35',
+ 'orange' => '255,165,0',
+ 'orangered' => '255,69,0',
+ 'orchid' => '218,112,214',
+ 'palegoldenrod' => '238,232,170',
+ 'palegreen' => '152,251,152',
+ 'paleturquoise' => '175,238,238',
+ 'palevioletred' => '219,112,147',
+ 'papayawhip' => '255,239,213',
+ 'peachpuff' => '255,218,185',
+ 'peru' => '205,133,63',
+ 'pink' => '255,192,203',
+ 'plum' => '221,160,221',
+ 'powderblue' => '176,224,230',
+ 'purple' => '128,0,128',
+ 'red' => '255,0,0',
+ 'rosybrown' => '188,143,143',
+ 'royalblue' => '65,105,225',
+ 'saddlebrown' => '139,69,19',
+ 'salmon' => '250,128,114',
+ 'sandybrown' => '244,164,96',
+ 'seagreen' => '46,139,87',
+ 'seashell' => '255,245,238',
+ 'sienna' => '160,82,45',
+ 'silver' => '192,192,192',
+ 'skyblue' => '135,206,235',
+ 'slateblue' => '106,90,205',
+ 'slategray' => '112,128,144',
+ 'slategrey' => '112,128,144',
+ 'snow' => '255,250,250',
+ 'springgreen' => '0,255,127',
+ 'steelblue' => '70,130,180',
+ 'tan' => '210,180,140',
+ 'teal' => '0,128,128',
+ 'thistle' => '216,191,216',
+ 'tomato' => '255,99,71',
+ 'transparent' => '0,0,0,0',
+ 'turquoise' => '64,224,208',
+ 'violet' => '238,130,238',
+ 'wheat' => '245,222,179',
+ 'white' => '255,255,255',
+ 'whitesmoke' => '245,245,245',
+ 'yellow' => '255,255,0',
+ 'yellowgreen' => '154,205,50'
+ );
+}
+
+// responsible for taking a string of LESS code and converting it into a
+// syntax tree
+class lessc_parser {
+ static protected $nextBlockId = 0; // used to uniquely identify blocks
+
+ static protected $precedence = array(
+ '=<' => 0,
+ '>=' => 0,
+ '=' => 0,
+ '<' => 0,
+ '>' => 0,
+
+ '+' => 1,
+ '-' => 1,
+ '*' => 2,
+ '/' => 2,
+ '%' => 2,
+ );
+
+ static protected $whitePattern;
+ static protected $commentMulti;
+
+ static protected $commentSingle = "//";
+ static protected $commentMultiLeft = "/*";
+ static protected $commentMultiRight = "*/";
+
+ // regex string to match any of the operators
+ static protected $operatorString;
+
+ // these properties will supress division unless it's inside parenthases
+ static protected $supressDivisionProps =
+ array('/border-radius$/i', '/^font$/i');
+
+ protected $blockDirectives = array("font-face", "keyframes", "page", "-moz-document", "viewport", "-moz-viewport", "-o-viewport", "-ms-viewport");
+ protected $lineDirectives = array("charset");
+
+ /**
+ * if we are in parens we can be more liberal with whitespace around
+ * operators because it must evaluate to a single value and thus is less
+ * ambiguous.
+ *
+ * Consider:
+ * property1: 10 -5; // is two numbers, 10 and -5
+ * property2: (10 -5); // should evaluate to 5
+ */
+ protected $inParens = false;
+
+ // caches preg escaped literals
+ static protected $literalCache = array();
+
+ public function __construct($lessc, $sourceName = null) {
+ $this->eatWhiteDefault = true;
+ // reference to less needed for vPrefix, mPrefix, and parentSelector
+ $this->lessc = $lessc;
+
+ $this->sourceName = $sourceName; // name used for error messages
+
+ $this->writeComments = false;
+
+ if (!self::$operatorString) {
+ self::$operatorString =
+ '('.implode('|', array_map(array('lessc', 'preg_quote'),
+ array_keys(self::$precedence))).')';
+
+ $commentSingle = lessc::preg_quote(self::$commentSingle);
+ $commentMultiLeft = lessc::preg_quote(self::$commentMultiLeft);
+ $commentMultiRight = lessc::preg_quote(self::$commentMultiRight);
+
+ self::$commentMulti = $commentMultiLeft.'.*?'.$commentMultiRight;
+ self::$whitePattern = '/'.$commentSingle.'[^\n]*\s*|('.self::$commentMulti.')\s*|\s+/Ais';
+ }
+ }
+
+ public function parse($buffer) {
+ $this->count = 0;
+ $this->line = 1;
+
+ $this->env = null; // block stack
+ $this->buffer = $this->writeComments ? $buffer : $this->removeComments($buffer);
+ $this->pushSpecialBlock("root");
+ $this->eatWhiteDefault = true;
+ $this->seenComments = array();
+
+ // trim whitespace on head
+ // if (preg_match('/^\s+/', $this->buffer, $m)) {
+ // $this->line += substr_count($m[0], "\n");
+ // $this->buffer = ltrim($this->buffer);
+ // }
+ $this->whitespace();
+
+ // parse the entire file
+ $lastCount = $this->count;
+ while (false !== $this->parseChunk());
+
+ if ($this->count != strlen($this->buffer))
+ $this->throwError();
+
+ // TODO report where the block was opened
+ if (!is_null($this->env->parent))
+ throw new exception('parse error: unclosed block');
+
+ return $this->env;
+ }
+
+ /**
+ * Parse a single chunk off the head of the buffer and append it to the
+ * current parse environment.
+ * Returns false when the buffer is empty, or when there is an error.
+ *
+ * This function is called repeatedly until the entire document is
+ * parsed.
+ *
+ * This parser is most similar to a recursive descent parser. Single
+ * functions represent discrete grammatical rules for the language, and
+ * they are able to capture the text that represents those rules.
+ *
+ * Consider the function lessc::keyword(). (all parse functions are
+ * structured the same)
+ *
+ * The function takes a single reference argument. When calling the
+ * function it will attempt to match a keyword on the head of the buffer.
+ * If it is successful, it will place the keyword in the referenced
+ * argument, advance the position in the buffer, and return true. If it
+ * fails then it won't advance the buffer and it will return false.
+ *
+ * All of these parse functions are powered by lessc::match(), which behaves
+ * the same way, but takes a literal regular expression. Sometimes it is
+ * more convenient to use match instead of creating a new function.
+ *
+ * Because of the format of the functions, to parse an entire string of
+ * grammatical rules, you can chain them together using &&.
+ *
+ * But, if some of the rules in the chain succeed before one fails, then
+ * the buffer position will be left at an invalid state. In order to
+ * avoid this, lessc::seek() is used to remember and set buffer positions.
+ *
+ * Before parsing a chain, use $s = $this->seek() to remember the current
+ * position into $s. Then if a chain fails, use $this->seek($s) to
+ * go back where we started.
+ */
+ protected function parseChunk() {
+ if (empty($this->buffer)) return false;
+ $s = $this->seek();
+
+ // setting a property
+ if ($this->keyword($key) && $this->assign() &&
+ $this->propertyValue($value, $key) && $this->end())
+ {
+ $this->append(array('assign', $key, $value), $s);
+ return true;
+ } else {
+ $this->seek($s);
+ }
+
+
+ // look for special css blocks
+ if ($this->literal('@', false)) {
+ $this->count--;
+
+ // media
+ if ($this->literal('@media')) {
+ if (($this->mediaQueryList($mediaQueries) || true)
+ && $this->literal('{'))
+ {
+ $media = $this->pushSpecialBlock("media");
+ $media->queries = is_null($mediaQueries) ? array() : $mediaQueries;
+ return true;
+ } else {
+ $this->seek($s);
+ return false;
+ }
+ }
+
+ if ($this->literal("@", false) && $this->keyword($dirName)) {
+ if ($this->isDirective($dirName, $this->blockDirectives)) {
+ if (($this->openString("{", $dirValue, null, array(";")) || true) &&
+ $this->literal("{"))
+ {
+ $dir = $this->pushSpecialBlock("directive");
+ $dir->name = $dirName;
+ if (isset($dirValue)) $dir->value = $dirValue;
+ return true;
+ }
+ } elseif ($this->isDirective($dirName, $this->lineDirectives)) {
+ if ($this->propertyValue($dirValue) && $this->end()) {
+ $this->append(array("directive", $dirName, $dirValue));
+ return true;
+ }
+ }
+ }
+
+ $this->seek($s);
+ }
+
+ // setting a variable
+ if ($this->variable($var) && $this->assign() &&
+ $this->propertyValue($value) && $this->end())
+ {
+ $this->append(array('assign', $var, $value), $s);
+ return true;
+ } else {
+ $this->seek($s);
+ }
+
+ if ($this->import($importValue)) {
+ $this->append($importValue, $s);
+ return true;
+ }
+
+ // opening parametric mixin
+ if ($this->tag($tag, true) && $this->argumentDef($args, $isVararg) &&
+ ($this->guards($guards) || true) &&
+ $this->literal('{'))
+ {
+ $block = $this->pushBlock($this->fixTags(array($tag)));
+ $block->args = $args;
+ $block->isVararg = $isVararg;
+ if (!empty($guards)) $block->guards = $guards;
+ return true;
+ } else {
+ $this->seek($s);
+ }
+
+ // opening a simple block
+ if ($this->tags($tags) && $this->literal('{')) {
+ $tags = $this->fixTags($tags);
+ $this->pushBlock($tags);
+ return true;
+ } else {
+ $this->seek($s);
+ }
+
+ // closing a block
+ if ($this->literal('}', false)) {
+ try {
+ $block = $this->pop();
+ } catch (exception $e) {
+ $this->seek($s);
+ $this->throwError($e->getMessage());
+ }
+
+ $hidden = false;
+ if (is_null($block->type)) {
+ $hidden = true;
+ if (!isset($block->args)) {
+ foreach ($block->tags as $tag) {
+ if (!is_string($tag) || $tag{0} != $this->lessc->mPrefix) {
+ $hidden = false;
+ break;
+ }
+ }
+ }
+
+ foreach ($block->tags as $tag) {
+ if (is_string($tag)) {
+ $this->env->children[$tag][] = $block;
+ }
+ }
+ }
+
+ if (!$hidden) {
+ $this->append(array('block', $block), $s);
+ }
+
+ // this is done here so comments aren't bundled into he block that
+ // was just closed
+ $this->whitespace();
+ return true;
+ }
+
+ // mixin
+ if ($this->mixinTags($tags) &&
+ ($this->argumentDef($argv, $isVararg) || true) &&
+ ($this->keyword($suffix) || true) && $this->end())
+ {
+ $tags = $this->fixTags($tags);
+ $this->append(array('mixin', $tags, $argv, $suffix), $s);
+ return true;
+ } else {
+ $this->seek($s);
+ }
+
+ // spare ;
+ if ($this->literal(';')) return true;
+
+ return false; // got nothing, throw error
+ }
+
+ protected function isDirective($dirname, $directives) {
+ // TODO: cache pattern in parser
+ $pattern = implode("|",
+ array_map(array("lessc", "preg_quote"), $directives));
+ $pattern = '/^(-[a-z-]+-)?(' . $pattern . ')$/i';
+
+ return preg_match($pattern, $dirname);
+ }
+
+ protected function fixTags($tags) {
+ // move @ tags out of variable namespace
+ foreach ($tags as &$tag) {
+ if ($tag{0} == $this->lessc->vPrefix)
+ $tag[0] = $this->lessc->mPrefix;
+ }
+ return $tags;
+ }
+
+ // a list of expressions
+ protected function expressionList(&$exps) {
+ $values = array();
+
+ while ($this->expression($exp)) {
+ $values[] = $exp;
+ }
+
+ if (count($values) == 0) return false;
+
+ $exps = lessc::compressList($values, ' ');
+ return true;
+ }
+
+ /**
+ * Attempt to consume an expression.
+ * @link http://en.wikipedia.org/wiki/Operator-precedence_parser#Pseudo-code
+ */
+ protected function expression(&$out) {
+ if ($this->value($lhs)) {
+ $out = $this->expHelper($lhs, 0);
+
+ // look for / shorthand
+ if (!empty($this->env->supressedDivision)) {
+ unset($this->env->supressedDivision);
+ $s = $this->seek();
+ if ($this->literal("/") && $this->value($rhs)) {
+ $out = array("list", "",
+ array($out, array("keyword", "/"), $rhs));
+ } else {
+ $this->seek($s);
+ }
+ }
+
+ return true;
+ }
+ return false;
+ }
+
+ /**
+ * recursively parse infix equation with $lhs at precedence $minP
+ */
+ protected function expHelper($lhs, $minP) {
+ $this->inExp = true;
+ $ss = $this->seek();
+
+ while (true) {
+ $whiteBefore = isset($this->buffer[$this->count - 1]) &&
+ ctype_space($this->buffer[$this->count - 1]);
+
+ // If there is whitespace before the operator, then we require
+ // whitespace after the operator for it to be an expression
+ $needWhite = $whiteBefore && !$this->inParens;
+
+ if ($this->match(self::$operatorString.($needWhite ? '\s' : ''), $m) && self::$precedence[$m[1]] >= $minP) {
+ if (!$this->inParens && isset($this->env->currentProperty) && $m[1] == "/" && empty($this->env->supressedDivision)) {
+ foreach (self::$supressDivisionProps as $pattern) {
+ if (preg_match($pattern, $this->env->currentProperty)) {
+ $this->env->supressedDivision = true;
+ break 2;
+ }
+ }
+ }
+
+
+ $whiteAfter = isset($this->buffer[$this->count - 1]) &&
+ ctype_space($this->buffer[$this->count - 1]);
+
+ if (!$this->value($rhs)) break;
+
+ // peek for next operator to see what to do with rhs
+ if ($this->peek(self::$operatorString, $next) && self::$precedence[$next[1]] > self::$precedence[$m[1]]) {
+ $rhs = $this->expHelper($rhs, self::$precedence[$next[1]]);
+ }
+
+ $lhs = array('expression', $m[1], $lhs, $rhs, $whiteBefore, $whiteAfter);
+ $ss = $this->seek();
+
+ continue;
+ }
+
+ break;
+ }
+
+ $this->seek($ss);
+
+ return $lhs;
+ }
+
+ // consume a list of values for a property
+ public function propertyValue(&$value, $keyName = null) {
+ $values = array();
+
+ if ($keyName !== null) $this->env->currentProperty = $keyName;
+
+ $s = null;
+ while ($this->expressionList($v)) {
+ $values[] = $v;
+ $s = $this->seek();
+ if (!$this->literal(',')) break;
+ }
+
+ if ($s) $this->seek($s);
+
+ if ($keyName !== null) unset($this->env->currentProperty);
+
+ if (count($values) == 0) return false;
+
+ $value = lessc::compressList($values, ', ');
+ return true;
+ }
+
+ protected function parenValue(&$out) {
+ $s = $this->seek();
+
+ // speed shortcut
+ if (isset($this->buffer[$this->count]) && $this->buffer[$this->count] != "(") {
+ return false;
+ }
+
+ $inParens = $this->inParens;
+ if ($this->literal("(") &&
+ ($this->inParens = true) && $this->expression($exp) &&
+ $this->literal(")"))
+ {
+ $out = $exp;
+ $this->inParens = $inParens;
+ return true;
+ } else {
+ $this->inParens = $inParens;
+ $this->seek($s);
+ }
+
+ return false;
+ }
+
+ // a single value
+ protected function value(&$value) {
+ $s = $this->seek();
+
+ // speed shortcut
+ if (isset($this->buffer[$this->count]) && $this->buffer[$this->count] == "-") {
+ // negation
+ if ($this->literal("-", false) &&
+ (($this->variable($inner) && $inner = array("variable", $inner)) ||
+ $this->unit($inner) ||
+ $this->parenValue($inner)))
+ {
+ $value = array("unary", "-", $inner);
+ return true;
+ } else {
+ $this->seek($s);
+ }
+ }
+
+ if ($this->parenValue($value)) return true;
+ if ($this->unit($value)) return true;
+ if ($this->color($value)) return true;
+ if ($this->func($value)) return true;
+ if ($this->string($value)) return true;
+
+ if ($this->keyword($word)) {
+ $value = array('keyword', $word);
+ return true;
+ }
+
+ // try a variable
+ if ($this->variable($var)) {
+ $value = array('variable', $var);
+ return true;
+ }
+
+ // unquote string (should this work on any type?
+ if ($this->literal("~") && $this->string($str)) {
+ $value = array("escape", $str);
+ return true;
+ } else {
+ $this->seek($s);
+ }
+
+ // css hack: \0
+ if ($this->literal('\\') && $this->match('([0-9]+)', $m)) {
+ $value = array('keyword', '\\'.$m[1]);
+ return true;
+ } else {
+ $this->seek($s);
+ }
+
+ return false;
+ }
+
+ // an import statement
+ protected function import(&$out) {
+ $s = $this->seek();
+ if (!$this->literal('@import')) return false;
+
+ // @import "something.css" media;
+ // @import url("something.css") media;
+ // @import url(something.css) media;
+
+ if ($this->propertyValue($value)) {
+ $out = array("import", $value);
+ return true;
+ }
+ }
+
+ protected function mediaQueryList(&$out) {
+ if ($this->genericList($list, "mediaQuery", ",", false)) {
+ $out = $list[2];
+ return true;
+ }
+ return false;
+ }
+
+ protected function mediaQuery(&$out) {
+ $s = $this->seek();
+
+ $expressions = null;
+ $parts = array();
+
+ if (($this->literal("only") && ($only = true) || $this->literal("not") && ($not = true) || true) && $this->keyword($mediaType)) {
+ $prop = array("mediaType");
+ if (isset($only)) $prop[] = "only";
+ if (isset($not)) $prop[] = "not";
+ $prop[] = $mediaType;
+ $parts[] = $prop;
+ } else {
+ $this->seek($s);
+ }
+
+
+ if (!empty($mediaType) && !$this->literal("and")) {
+ // ~
+ } else {
+ $this->genericList($expressions, "mediaExpression", "and", false);
+ if (is_array($expressions)) $parts = array_merge($parts, $expressions[2]);
+ }
+
+ if (count($parts) == 0) {
+ $this->seek($s);
+ return false;
+ }
+
+ $out = $parts;
+ return true;
+ }
+
+ protected function mediaExpression(&$out) {
+ $s = $this->seek();
+ $value = null;
+ if ($this->literal("(") &&
+ $this->keyword($feature) &&
+ ($this->literal(":") && $this->expression($value) || true) &&
+ $this->literal(")"))
+ {
+ $out = array("mediaExp", $feature);
+ if ($value) $out[] = $value;
+ return true;
+ } elseif ($this->variable($variable)) {
+ $out = array('variable', $variable);
+ return true;
+ }
+
+ $this->seek($s);
+ return false;
+ }
+
+ // an unbounded string stopped by $end
+ protected function openString($end, &$out, $nestingOpen=null, $rejectStrs = null) {
+ $oldWhite = $this->eatWhiteDefault;
+ $this->eatWhiteDefault = false;
+
+ $stop = array("'", '"', "@{", $end);
+ $stop = array_map(array("lessc", "preg_quote"), $stop);
+ // $stop[] = self::$commentMulti;
+
+ if (!is_null($rejectStrs)) {
+ $stop = array_merge($stop, $rejectStrs);
+ }
+
+ $patt = '(.*?)('.implode("|", $stop).')';
+
+ $nestingLevel = 0;
+
+ $content = array();
+ while ($this->match($patt, $m, false)) {
+ if (!empty($m[1])) {
+ $content[] = $m[1];
+ if ($nestingOpen) {
+ $nestingLevel += substr_count($m[1], $nestingOpen);
+ }
+ }
+
+ $tok = $m[2];
+
+ $this->count-= strlen($tok);
+ if ($tok == $end) {
+ if ($nestingLevel == 0) {
+ break;
+ } else {
+ $nestingLevel--;
+ }
+ }
+
+ if (($tok == "'" || $tok == '"') && $this->string($str)) {
+ $content[] = $str;
+ continue;
+ }
+
+ if ($tok == "@{" && $this->interpolation($inter)) {
+ $content[] = $inter;
+ continue;
+ }
+
+ if (!empty($rejectStrs) && in_array($tok, $rejectStrs)) {
+ break;
+ }
+
+ $content[] = $tok;
+ $this->count+= strlen($tok);
+ }
+
+ $this->eatWhiteDefault = $oldWhite;
+
+ if (count($content) == 0) return false;
+
+ // trim the end
+ if (is_string(end($content))) {
+ $content[count($content) - 1] = rtrim(end($content));
+ }
+
+ $out = array("string", "", $content);
+ return true;
+ }
+
+ protected function string(&$out) {
+ $s = $this->seek();
+ if ($this->literal('"', false)) {
+ $delim = '"';
+ } elseif ($this->literal("'", false)) {
+ $delim = "'";
+ } else {
+ return false;
+ }
+
+ $content = array();
+
+ // look for either ending delim , escape, or string interpolation
+ $patt = '([^\n]*?)(@\{|\\\\|' .
+ lessc::preg_quote($delim).')';
+
+ $oldWhite = $this->eatWhiteDefault;
+ $this->eatWhiteDefault = false;
+
+ while ($this->match($patt, $m, false)) {
+ $content[] = $m[1];
+ if ($m[2] == "@{") {
+ $this->count -= strlen($m[2]);
+ if ($this->interpolation($inter, false)) {
+ $content[] = $inter;
+ } else {
+ $this->count += strlen($m[2]);
+ $content[] = "@{"; // ignore it
+ }
+ } elseif ($m[2] == '\\') {
+ $content[] = $m[2];
+ if ($this->literal($delim, false)) {
+ $content[] = $delim;
+ }
+ } else {
+ $this->count -= strlen($delim);
+ break; // delim
+ }
+ }
+
+ $this->eatWhiteDefault = $oldWhite;
+
+ if ($this->literal($delim)) {
+ $out = array("string", $delim, $content);
+ return true;
+ }
+
+ $this->seek($s);
+ return false;
+ }
+
+ protected function interpolation(&$out) {
+ $oldWhite = $this->eatWhiteDefault;
+ $this->eatWhiteDefault = true;
+
+ $s = $this->seek();
+ if ($this->literal("@{") &&
+ $this->openString("}", $interp, null, array("'", '"', ";")) &&
+ $this->literal("}", false))
+ {
+ $out = array("interpolate", $interp);
+ $this->eatWhiteDefault = $oldWhite;
+ if ($this->eatWhiteDefault) $this->whitespace();
+ return true;
+ }
+
+ $this->eatWhiteDefault = $oldWhite;
+ $this->seek($s);
+ return false;
+ }
+
+ protected function unit(&$unit) {
+ // speed shortcut
+ if (isset($this->buffer[$this->count])) {
+ $char = $this->buffer[$this->count];
+ if (!ctype_digit($char) && $char != ".") return false;
+ }
+
+ if ($this->match('([0-9]+(?:\.[0-9]*)?|\.[0-9]+)([%a-zA-Z]+)?', $m)) {
+ $unit = array("number", $m[1], empty($m[2]) ? "" : $m[2]);
+ return true;
+ }
+ return false;
+ }
+
+ // a # color
+ protected function color(&$out) {
+ if ($this->match('(#(?:[0-9a-f]{8}|[0-9a-f]{6}|[0-9a-f]{3}))', $m)) {
+ if (strlen($m[1]) > 7) {
+ $out = array("string", "", array($m[1]));
+ } else {
+ $out = array("raw_color", $m[1]);
+ }
+ return true;
+ }
+
+ return false;
+ }
+
+ // consume an argument definition list surrounded by ()
+ // each argument is a variable name with optional value
+ // or at the end a ... or a variable named followed by ...
+ // arguments are separated by , unless a ; is in the list, then ; is the
+ // delimiter.
+ protected function argumentDef(&$args, &$isVararg) {
+ $s = $this->seek();
+ if (!$this->literal('(')) return false;
+
+ $values = array();
+ $delim = ",";
+ $method = "expressionList";
+
+ $isVararg = false;
+ while (true) {
+ if ($this->literal("...")) {
+ $isVararg = true;
+ break;
+ }
+
+ if ($this->$method($value)) {
+ if ($value[0] == "variable") {
+ $arg = array("arg", $value[1]);
+ $ss = $this->seek();
+
+ if ($this->assign() && $this->$method($rhs)) {
+ $arg[] = $rhs;
+ } else {
+ $this->seek($ss);
+ if ($this->literal("...")) {
+ $arg[0] = "rest";
+ $isVararg = true;
+ }
+ }
+
+ $values[] = $arg;
+ if ($isVararg) break;
+ continue;
+ } else {
+ $values[] = array("lit", $value);
+ }
+ }
+
+
+ if (!$this->literal($delim)) {
+ if ($delim == "," && $this->literal(";")) {
+ // found new delim, convert existing args
+ $delim = ";";
+ $method = "propertyValue";
+
+ // transform arg list
+ if (isset($values[1])) { // 2 items
+ $newList = array();
+ foreach ($values as $i => $arg) {
+ switch($arg[0]) {
+ case "arg":
+ if ($i) {
+ $this->throwError("Cannot mix ; and , as delimiter types");
+ }
+ $newList[] = $arg[2];
+ break;
+ case "lit":
+ $newList[] = $arg[1];
+ break;
+ case "rest":
+ $this->throwError("Unexpected rest before semicolon");
+ }
+ }
+
+ $newList = array("list", ", ", $newList);
+
+ switch ($values[0][0]) {
+ case "arg":
+ $newArg = array("arg", $values[0][1], $newList);
+ break;
+ case "lit":
+ $newArg = array("lit", $newList);
+ break;
+ }
+
+ } elseif ($values) { // 1 item
+ $newArg = $values[0];
+ }
+
+ if ($newArg) {
+ $values = array($newArg);
+ }
+ } else {
+ break;
+ }
+ }
+ }
+
+ if (!$this->literal(')')) {
+ $this->seek($s);
+ return false;
+ }
+
+ $args = $values;
+
+ return true;
+ }
+
+ // consume a list of tags
+ // this accepts a hanging delimiter
+ protected function tags(&$tags, $simple = false, $delim = ',') {
+ $tags = array();
+ while ($this->tag($tt, $simple)) {
+ $tags[] = $tt;
+ if (!$this->literal($delim)) break;
+ }
+ if (count($tags) == 0) return false;
+
+ return true;
+ }
+
+ // list of tags of specifying mixin path
+ // optionally separated by > (lazy, accepts extra >)
+ protected function mixinTags(&$tags) {
+ $s = $this->seek();
+ $tags = array();
+ while ($this->tag($tt, true)) {
+ $tags[] = $tt;
+ $this->literal(">");
+ }
+
+ if (count($tags) == 0) return false;
+
+ return true;
+ }
+
+ // a bracketed value (contained within in a tag definition)
+ protected function tagBracket(&$parts, &$hasExpression) {
+ // speed shortcut
+ if (isset($this->buffer[$this->count]) && $this->buffer[$this->count] != "[") {
+ return false;
+ }
+
+ $s = $this->seek();
+
+ $hasInterpolation = false;
+
+ if ($this->literal("[", false)) {
+ $attrParts = array("[");
+ // keyword, string, operator
+ while (true) {
+ if ($this->literal("]", false)) {
+ $this->count--;
+ break; // get out early
+ }
+
+ if ($this->match('\s+', $m)) {
+ $attrParts[] = " ";
+ continue;
+ }
+ if ($this->string($str)) {
+ // escape parent selector, (yuck)
+ foreach ($str[2] as &$chunk) {
+ $chunk = str_replace($this->lessc->parentSelector, "$&$", $chunk);
+ }
+
+ $attrParts[] = $str;
+ $hasInterpolation = true;
+ continue;
+ }
+
+ if ($this->keyword($word)) {
+ $attrParts[] = $word;
+ continue;
+ }
+
+ if ($this->interpolation($inter, false)) {
+ $attrParts[] = $inter;
+ $hasInterpolation = true;
+ continue;
+ }
+
+ // operator, handles attr namespace too
+ if ($this->match('[|-~\$\*\^=]+', $m)) {
+ $attrParts[] = $m[0];
+ continue;
+ }
+
+ break;
+ }
+
+ if ($this->literal("]", false)) {
+ $attrParts[] = "]";
+ foreach ($attrParts as $part) {
+ $parts[] = $part;
+ }
+ $hasExpression = $hasExpression || $hasInterpolation;
+ return true;
+ }
+ $this->seek($s);
+ }
+
+ $this->seek($s);
+ return false;
+ }
+
+ // a space separated list of selectors
+ protected function tag(&$tag, $simple = false) {
+ if ($simple)
+ $chars = '^@,:;{}\][>\(\) "\'';
+ else
+ $chars = '^@,;{}["\'';
+
+ $s = $this->seek();
+
+ $hasExpression = false;
+ $parts = array();
+ while ($this->tagBracket($parts, $hasExpression));
+
+ $oldWhite = $this->eatWhiteDefault;
+ $this->eatWhiteDefault = false;
+
+ while (true) {
+ if ($this->match('(['.$chars.'0-9]['.$chars.']*)', $m)) {
+ $parts[] = $m[1];
+ if ($simple) break;
+
+ while ($this->tagBracket($parts, $hasExpression));
+ continue;
+ }
+
+ if (isset($this->buffer[$this->count]) && $this->buffer[$this->count] == "@") {
+ if ($this->interpolation($interp)) {
+ $hasExpression = true;
+ $interp[2] = true; // don't unescape
+ $parts[] = $interp;
+ continue;
+ }
+
+ if ($this->literal("@")) {
+ $parts[] = "@";
+ continue;
+ }
+ }
+
+ if ($this->unit($unit)) { // for keyframes
+ $parts[] = $unit[1];
+ $parts[] = $unit[2];
+ continue;
+ }
+
+ break;
+ }
+
+ $this->eatWhiteDefault = $oldWhite;
+ if (!$parts) {
+ $this->seek($s);
+ return false;
+ }
+
+ if ($hasExpression) {
+ $tag = array("exp", array("string", "", $parts));
+ } else {
+ $tag = trim(implode($parts));
+ }
+
+ $this->whitespace();
+ return true;
+ }
+
+ // a css function
+ protected function func(&$func) {
+ $s = $this->seek();
+
+ if ($this->match('(%|[\w\-_][\w\-_:\.]+|[\w_])', $m) && $this->literal('(')) {
+ $fname = $m[1];
+
+ $sPreArgs = $this->seek();
+
+ $args = array();
+ while (true) {
+ $ss = $this->seek();
+ // this ugly nonsense is for ie filter properties
+ if ($this->keyword($name) && $this->literal('=') && $this->expressionList($value)) {
+ $args[] = array("string", "", array($name, "=", $value));
+ } else {
+ $this->seek($ss);
+ if ($this->expressionList($value)) {
+ $args[] = $value;
+ }
+ }
+
+ if (!$this->literal(',')) break;
+ }
+ $args = array('list', ',', $args);
+
+ if ($this->literal(')')) {
+ $func = array('function', $fname, $args);
+ return true;
+ } elseif ($fname == 'url') {
+ // couldn't parse and in url? treat as string
+ $this->seek($sPreArgs);
+ if ($this->openString(")", $string) && $this->literal(")")) {
+ $func = array('function', $fname, $string);
+ return true;
+ }
+ }
+ }
+
+ $this->seek($s);
+ return false;
+ }
+
+ // consume a less variable
+ protected function variable(&$name) {
+ $s = $this->seek();
+ if ($this->literal($this->lessc->vPrefix, false) &&
+ ($this->variable($sub) || $this->keyword($name)))
+ {
+ if (!empty($sub)) {
+ $name = array('variable', $sub);
+ } else {
+ $name = $this->lessc->vPrefix.$name;
+ }
+ return true;
+ }
+
+ $name = null;
+ $this->seek($s);
+ return false;
+ }
+
+ /**
+ * Consume an assignment operator
+ * Can optionally take a name that will be set to the current property name
+ */
+ protected function assign($name = null) {
+ if ($name) $this->currentProperty = $name;
+ return $this->literal(':') || $this->literal('=');
+ }
+
+ // consume a keyword
+ protected function keyword(&$word) {
+ if ($this->match('([\w_\-\*!"][\w\-_"]*)', $m)) {
+ $word = $m[1];
+ return true;
+ }
+ return false;
+ }
+
+ // consume an end of statement delimiter
+ protected function end() {
+ if ($this->literal(';')) {
+ return true;
+ } elseif ($this->count == strlen($this->buffer) || $this->buffer[$this->count] == '}') {
+ // if there is end of file or a closing block next then we don't need a ;
+ return true;
+ }
+ return false;
+ }
+
+ protected function guards(&$guards) {
+ $s = $this->seek();
+
+ if (!$this->literal("when")) {
+ $this->seek($s);
+ return false;
+ }
+
+ $guards = array();
+
+ while ($this->guardGroup($g)) {
+ $guards[] = $g;
+ if (!$this->literal(",")) break;
+ }
+
+ if (count($guards) == 0) {
+ $guards = null;
+ $this->seek($s);
+ return false;
+ }
+
+ return true;
+ }
+
+ // a bunch of guards that are and'd together
+ // TODO rename to guardGroup
+ protected function guardGroup(&$guardGroup) {
+ $s = $this->seek();
+ $guardGroup = array();
+ while ($this->guard($guard)) {
+ $guardGroup[] = $guard;
+ if (!$this->literal("and")) break;
+ }
+
+ if (count($guardGroup) == 0) {
+ $guardGroup = null;
+ $this->seek($s);
+ return false;
+ }
+
+ return true;
+ }
+
+ protected function guard(&$guard) {
+ $s = $this->seek();
+ $negate = $this->literal("not");
+
+ if ($this->literal("(") && $this->expression($exp) && $this->literal(")")) {
+ $guard = $exp;
+ if ($negate) $guard = array("negate", $guard);
+ return true;
+ }
+
+ $this->seek($s);
+ return false;
+ }
+
+ /* raw parsing functions */
+
+ protected function literal($what, $eatWhitespace = null) {
+ if ($eatWhitespace === null) $eatWhitespace = $this->eatWhiteDefault;
+
+ // shortcut on single letter
+ if (!isset($what[1]) && isset($this->buffer[$this->count])) {
+ if ($this->buffer[$this->count] == $what) {
+ if (!$eatWhitespace) {
+ $this->count++;
+ return true;
+ }
+ // goes below...
+ } else {
+ return false;
+ }
+ }
+
+ if (!isset(self::$literalCache[$what])) {
+ self::$literalCache[$what] = lessc::preg_quote($what);
+ }
+
+ return $this->match(self::$literalCache[$what], $m, $eatWhitespace);
+ }
+
+ protected function genericList(&$out, $parseItem, $delim="", $flatten=true) {
+ $s = $this->seek();
+ $items = array();
+ while ($this->$parseItem($value)) {
+ $items[] = $value;
+ if ($delim) {
+ if (!$this->literal($delim)) break;
+ }
+ }
+
+ if (count($items) == 0) {
+ $this->seek($s);
+ return false;
+ }
+
+ if ($flatten && count($items) == 1) {
+ $out = $items[0];
+ } else {
+ $out = array("list", $delim, $items);
+ }
+
+ return true;
+ }
+
+
+ // advance counter to next occurrence of $what
+ // $until - don't include $what in advance
+ // $allowNewline, if string, will be used as valid char set
+ protected function to($what, &$out, $until = false, $allowNewline = false) {
+ if (is_string($allowNewline)) {
+ $validChars = $allowNewline;
+ } else {
+ $validChars = $allowNewline ? "." : "[^\n]";
+ }
+ if (!$this->match('('.$validChars.'*?)'.lessc::preg_quote($what), $m, !$until)) return false;
+ if ($until) $this->count -= strlen($what); // give back $what
+ $out = $m[1];
+ return true;
+ }
+
+ // try to match something on head of buffer
+ protected function match($regex, &$out, $eatWhitespace = null) {
+ if ($eatWhitespace === null) $eatWhitespace = $this->eatWhiteDefault;
+
+ $r = '/'.$regex.($eatWhitespace && !$this->writeComments ? '\s*' : '').'/Ais';
+ if (preg_match($r, $this->buffer, $out, null, $this->count)) {
+ $this->count += strlen($out[0]);
+ if ($eatWhitespace && $this->writeComments) $this->whitespace();
+ return true;
+ }
+ return false;
+ }
+
+ // match some whitespace
+ protected function whitespace() {
+ if ($this->writeComments) {
+ $gotWhite = false;
+ while (preg_match(self::$whitePattern, $this->buffer, $m, null, $this->count)) {
+ if (isset($m[1]) && empty($this->commentsSeen[$this->count])) {
+ $this->append(array("comment", $m[1]));
+ $this->commentsSeen[$this->count] = true;
+ }
+ $this->count += strlen($m[0]);
+ $gotWhite = true;
+ }
+ return $gotWhite;
+ } else {
+ $this->match("", $m);
+ return strlen($m[0]) > 0;
+ }
+ }
+
+ // match something without consuming it
+ protected function peek($regex, &$out = null, $from=null) {
+ if (is_null($from)) $from = $this->count;
+ $r = '/'.$regex.'/Ais';
+ $result = preg_match($r, $this->buffer, $out, null, $from);
+
+ return $result;
+ }
+
+ // seek to a spot in the buffer or return where we are on no argument
+ protected function seek($where = null) {
+ if ($where === null) return $this->count;
+ else $this->count = $where;
+ return true;
+ }
+
+ /* misc functions */
+
+ public function throwError($msg = "parse error", $count = null) {
+ $count = is_null($count) ? $this->count : $count;
+
+ $line = $this->line +
+ substr_count(substr($this->buffer, 0, $count), "\n");
+
+ if (!empty($this->sourceName)) {
+ $loc = "$this->sourceName on line $line";
+ } else {
+ $loc = "line: $line";
+ }
+
+ // TODO this depends on $this->count
+ if ($this->peek("(.*?)(\n|$)", $m, $count)) {
+ throw new exception("$msg: failed at `$m[1]` $loc");
+ } else {
+ throw new exception("$msg: $loc");
+ }
+ }
+
+ protected function pushBlock($selectors=null, $type=null) {
+ $b = new stdclass;
+ $b->parent = $this->env;
+
+ $b->type = $type;
+ $b->id = self::$nextBlockId++;
+
+ $b->isVararg = false; // TODO: kill me from here
+ $b->tags = $selectors;
+
+ $b->props = array();
+ $b->children = array();
+
+ $this->env = $b;
+ return $b;
+ }
+
+ // push a block that doesn't multiply tags
+ protected function pushSpecialBlock($type) {
+ return $this->pushBlock(null, $type);
+ }
+
+ // append a property to the current block
+ protected function append($prop, $pos = null) {
+ if ($pos !== null) $prop[-1] = $pos;
+ $this->env->props[] = $prop;
+ }
+
+ // pop something off the stack
+ protected function pop() {
+ $old = $this->env;
+ $this->env = $this->env->parent;
+ return $old;
+ }
+
+ // remove comments from $text
+ // todo: make it work for all functions, not just url
+ protected function removeComments($text) {
+ $look = array(
+ 'url(', '//', '/*', '"', "'"
+ );
+
+ $out = '';
+ $min = null;
+ while (true) {
+ // find the next item
+ foreach ($look as $token) {
+ $pos = strpos($text, $token);
+ if ($pos !== false) {
+ if (!isset($min) || $pos < $min[1]) $min = array($token, $pos);
+ }
+ }
+
+ if (is_null($min)) break;
+
+ $count = $min[1];
+ $skip = 0;
+ $newlines = 0;
+ switch ($min[0]) {
+ case 'url(':
+ if (preg_match('/url\(.*?\)/', $text, $m, 0, $count))
+ $count += strlen($m[0]) - strlen($min[0]);
+ break;
+ case '"':
+ case "'":
+ if (preg_match('/'.$min[0].'.*?(?<!\\\\)'.$min[0].'/', $text, $m, 0, $count))
+ $count += strlen($m[0]) - 1;
+ break;
+ case '//':
+ $skip = strpos($text, "\n", $count);
+ if ($skip === false) $skip = strlen($text) - $count;
+ else $skip -= $count;
+ break;
+ case '/*':
+ if (preg_match('/\/\*.*?\*\//s', $text, $m, 0, $count)) {
+ $skip = strlen($m[0]);
+ $newlines = substr_count($m[0], "\n");
+ }
+ break;
+ }
+
+ if ($skip == 0) $count += strlen($min[0]);
+
+ $out .= substr($text, 0, $count).str_repeat("\n", $newlines);
+ $text = substr($text, $count + $skip);
+
+ $min = null;
+ }
+
+ return $out.$text;
+ }
+
+}
+
+class lessc_formatter_classic {
+ public $indentChar = " ";
+
+ public $break = "\n";
+ public $open = " {";
+ public $close = "}";
+ public $selectorSeparator = ", ";
+ public $assignSeparator = ":";
+
+ public $openSingle = " { ";
+ public $closeSingle = " }";
+
+ public $disableSingle = false;
+ public $breakSelectors = false;
+
+ public $compressColors = false;
+
+ public function __construct() {
+ $this->indentLevel = 0;
+ }
+
+ public function indentStr($n = 0) {
+ return str_repeat($this->indentChar, max($this->indentLevel + $n, 0));
+ }
+
+ public function property($name, $value) {
+ return $name . $this->assignSeparator . $value . ";";
+ }
+
+ protected function isEmpty($block) {
+ if (empty($block->lines)) {
+ foreach ($block->children as $child) {
+ if (!$this->isEmpty($child)) return false;
+ }
+
+ return true;
+ }
+ return false;
+ }
+
+ public function block($block) {
+ if ($this->isEmpty($block)) return;
+
+ $inner = $pre = $this->indentStr();
+
+ $isSingle = !$this->disableSingle &&
+ is_null($block->type) && count($block->lines) == 1;
+
+ if (!empty($block->selectors)) {
+ $this->indentLevel++;
+
+ if ($this->breakSelectors) {
+ $selectorSeparator = $this->selectorSeparator . $this->break . $pre;
+ } else {
+ $selectorSeparator = $this->selectorSeparator;
+ }
+
+ echo $pre .
+ implode($selectorSeparator, $block->selectors);
+ if ($isSingle) {
+ echo $this->openSingle;
+ $inner = "";
+ } else {
+ echo $this->open . $this->break;
+ $inner = $this->indentStr();
+ }
+
+ }
+
+ if (!empty($block->lines)) {
+ $glue = $this->break.$inner;
+ echo $inner . implode($glue, $block->lines);
+ if (!$isSingle && !empty($block->children)) {
+ echo $this->break;
+ }
+ }
+
+ foreach ($block->children as $child) {
+ $this->block($child);
+ }
+
+ if (!empty($block->selectors)) {
+ if (!$isSingle && empty($block->children)) echo $this->break;
+
+ if ($isSingle) {
+ echo $this->closeSingle . $this->break;
+ } else {
+ echo $pre . $this->close . $this->break;
+ }
+
+ $this->indentLevel--;
+ }
+ }
+}
+
+class lessc_formatter_compressed extends lessc_formatter_classic {
+ public $disableSingle = true;
+ public $open = "{";
+ public $selectorSeparator = ",";
+ public $assignSeparator = ":";
+ public $break = "";
+ public $compressColors = true;
+
+ public function indentStr($n = 0) {
+ return "";
+ }
+}
+
+class lessc_formatter_lessjs extends lessc_formatter_classic {
+ public $disableSingle = true;
+ public $breakSelectors = true;
+ public $assignSeparator = ": ";
+ public $selectorSeparator = ",";
+}
\ No newline at end of file
--- /dev/null
+html {
+ margin: 0;
+ padding: 0;
+}
+body {
+ margin: 0;
+ padding: 10px;
+ font-family: Arial, Helvetica, Verdana, Tahoma, sans-serif;
+}
+
+code,
+pre {
+ font-family: Menlo, Monaco, monospace, sans-serif;
+}
+
+div,
+p,
+ul,
+ol,
+table,
+dl,
+blockquote,
+pre {
+ font-size: 15px;
+ line-height: 1.5rem;
+}
+div {
+ border: 1px dashed #bbb !important;
+}
+a {
+ color: #15c;
+ text-decoration: underline;
+}
+.redactor_placeholder {
+ color: #999 !important;
+ display: block !important;
+ margin-bottom: 10px !important;
+}
+
+object,
+embed,
+video,
+img {
+ max-width: 100%;
+ width: auto;
+}
+video,
+img {
+ height: auto;
+}
+
+div,
+p,
+ul,
+ol,
+table,
+dl,
+blockquote,
+pre {
+ margin: 0;
+ margin-bottom: 15px;
+ border: none;
+ background: none;
+ box-shadow: none;
+}
+iframe,
+object,
+hr {
+ margin-bottom: 15px;
+}
+blockquote {
+ margin-left: 1.5em !important;
+ padding-left: 0;
+ color: #777;
+ font-style: italic;
+}
+ul,
+ol {
+ padding-left: 2em;
+}
+ul ul,
+ol ol,
+ul ol,
+ol ul {
+ margin: 2px;
+ padding: 0;
+ padding-left: 2em;
+ border: none;
+}
+dl dt { font-weight: bold; }
+dd { margin-left: 1em;}
+
+table {
+ border-collapse: collapse;
+ font-size: 1em;
+}
+table td {
+ padding: 5px;
+ border: 1px solid #ddd;
+ vertical-align: top;
+}
+table thead td {
+ border-bottom: 2px solid #000;
+ font-weight: bold;
+}
+code {
+ background-color: #d8d7d7;
+}
+pre {
+ overflow: auto;
+ padding: 1em;
+ border: 1px solid #ddd;
+ border-radius: 3px;
+ background: #f8f8f8;
+ white-space: pre;
+ font-size: 90%;
+}
+hr {
+ display: block;
+ height: 1px;
+ border: 0;
+ border-top: 1px solid #ccc;
+}
+
+h1,
+h2,
+h3,
+h4,
+h5 {
+ margin: 0;
+ padding: 0;
+ background: none;
+ color: #000;
+ font-weight: bold;
+}
+
+h1 {
+ margin-bottom: 10px;
+ font-size: 36px;
+ line-height: 40px;
+}
+h2 {
+ margin-bottom: 15px;
+ font-size: 30px;
+ line-height: 38px;
+}
+h3 {
+ margin-bottom: 10px;
+ font-size: 24px;
+ line-height: 30px;
+}
+h4 {
+ margin-bottom: 10px;
+ font-size: 18px;
+ line-height: 24px;
+}
+h5 {
+ margin-bottom: 10px;
+ font-size: 1em;
+}
+
+body.redactor_editor_wym {
+ background: #f4f4f4;
+}
+.redactor_editor_wym div,
+.redactor_editor_wym p,
+.redactor_editor_wym ul,
+.redactor_editor_wym ol,
+.redactor_editor_wym table,
+.redactor_editor_wym dl,
+.redactor_editor_wym pre,
+.redactor_editor_wym h1,
+.redactor_editor_wym h2,
+.redactor_editor_wym h3,
+.redactor_editor_wym h4,
+.redactor_editor_wym h5,
+.redactor_editor_wym blockquote {
+ margin: 0 0 10px 0;
+ padding: 7px 10px;
+ border: 1px solid #e4e4e4;
+ background-color: #fff;
+}
+.redactor_editor_wym div {
+ border: 1px dashed #bbb !important;
+}
+.redactor_editor_wym pre {
+ border: 2px dashed #e4e4e4 !important;
+ background-color: #fafafa !important;
+}
+.redactor_editor_wym code {
+ background-color: #f4f4f4 !important;
+}
+.redactor_editor_wym ul,
+.redactor_editor_wym ol {
+ padding-left: 2em !important;
+}
+.redactor_editor_wym ul li ul,
+.redactor_editor_wym ul li ol,
+.redactor_editor_wym ol li ol,
+.redactor_editor_wym ol li ul {
+ border: none !important;
+}
+
--- /dev/null
+/*
+ Icon font
+*/
+@font-face {
+ font-family: 'RedactorFont';
+ src: url('redactor-font.eot');
+}
+@font-face {
+ font-family: 'RedactorFont';
+ src: url(data:application/x-font-ttf;charset=utf-8;base64,AAEAAAALAIAAAwAwT1MvMg6yA0gAAAC8AAAAYGNtYXDmMACHAAABHAAAAERnYXNwAAAAEAAAAWAAAAAIZ2x5ZvdGdCMAAAFoAAATTGhlYWQBMDlfAAAUtAAAADZoaGVhB8MD4QAAFOwAAAAkaG10eH4BB7kAABUQAAAAhGxvY2FNXlLIAAAVlAAAAERtYXhwACwAkgAAFdgAAAAgbmFtZRHEcGwAABX4AAABZnBvc3QAAwAAAAAXYAAAACAAAwQAAZAABQAAApkCzAAAAI8CmQLMAAAB6wAzAQkAAAAAAAAAAAAAAAAAAAABEAAAAAAAAAAAAAAAAAAAAABAACDmHgPA/8D/wAPAAEAAAAABAAAAAAAAAAAAAAAgAAAAAAACAAAAAwAAABQAAwABAAAAFAAEADAAAAAIAAgAAgAAACDmHv/9//8AAAAg5gD//f///+EaAgADAAEAAAAAAAAAAAABAAH//wAPAAEAAAAAAAAAAAACAAA3OQEAAAAAAwAAAEkEAAMlAAQACQANAAA3ESURJQElESURARENAQAEAPwAA7f8kgNu/bcBJP7cSQLbAf0jAQKRAf22AQJI/gEBttrdAAAABgAAAJIEAALbAAQACQAOABMAGAAdAAABIRUhNRUhFSE1FSEVITUBMxUjNRUzFSM1FTMVIzUBJQLb/SUC2/0lAtv9Jf7bkpKSkpKSAtuSktuSktuTkwG2kpLbkpLbk5MAAgAAAEkD7gMlABYALgAAJS4DJxUULgInPgM1FTYeAgcBNRQOAgceAzUXJx4DFzYuAgcD7h1Sf7eDOHKqcn+tay+d7ZEuIf2WGDtkTEFhQSABAUqrlW4NE0GPznpJMEkzIQjVAS5cjl5liFUkAdcaWqHMWAGqewETLUQzN0goEAEgmgYQHikeNW9SHB0AAAAAAgDbAEkDJQMkAAQAMwAANyEXITc3HgMzMj4CNz4DNwMjAxYOAgcOAyMiLgInLgMnEyMTBh4CF9sCSQH9tQF9DiErMR4bMykjDA4TDgUBAX4BAQQFCgUIDRITCwoVEA8GBwgHAgEBgAEBBw0UDJJJSX4NFA4GBg4UDQ0jKjMdAWr+eQoUEQ4GBgkGAwMGCQYGDxAUCgGH/pYdMyojDQAAAAUAAP/+BAADbgAGAA4AFgBHAF8AAAEzAzMHIwMTDQEnIyczJy0CBzMHIwcXHgMHFg4CBw4DBzIeAhceAx8BIycmNC4BJy4DKwEXIxMzMh4CFwczMj4CNz4DNyY0LgEnLgMrARcCk0YBlgHZAUsBIv7eAdwB3gH+R/7cASQB3gHcARgFCgYEAQEDAwYDBQgMCwgDAwUCAwEEAwUCN0IjAQIBAQMKCAsEFAE8AVQPGBYQB24dBQsICAEEAwMBAQEEAwQBCAgLBR0BA23+00ABbf4BuLiUSZOQuLiTSZSqBhEUGA4JEQ8NBgYIBwUBAgMDAgIGBwoGg1wBAgMDAgoQCgWQAW0DBgoGhwEDBQMCCAoLBwYMCQgDAwQDAWMAAwDaAAADJQMlAAMADAARAAABIzcXBTM3MxczAyMDFyEVITUCRYxGRv6VlS3GLpTKtcsBAkr9tgHL8PDwkZECSv22SZKSAAAACgAAAEkEAAMlAAQACQAOABMAGAAdACIAJwAsADEAADcRJRElLQE1JRU1BTUFFQMnFTc1FQcVFzUVJxU3NRMVJTUlBScVNzUVBxUXNRUnFTc1AAQA/AABbgEk/twBJP7cSdzc3Nzc3EkBJP7cAknc3Nzc3NxJAtsB/SMBSAGSAZTdAZMBkQFsAZMBkdoBkQGT3AGUAZIBt5MBkQEBAZMBkdoBkQGT3AGUAZIAAAIAEgBJBAADJQAWAC4AAAEOAzE1DgMHJj4CFzUwHgIXBT4DNxU1MD4CNy4DMRUmDgIXBAByqnI4g7d/Uh0hLpHtnS9rrX/8dw1ulatKIEFhQUxkOxh6zo9BEwG/X41dLdYJIDRIMVnLolkZ1iVUiWS/HSodEQWZHw8pRzgyRSwUeh4dUXA0AAACAJIAkgNtAtwARwCPAAABDgMVFB4CFx4DNxY+Ajc+AzU0LgInLgMnDgMHDgMnBiYiJicuAjQ1ND4CNz4DNzUOAwcFDgMVFB4CFx4DNxY+Ajc+AzU0LgInLgMnDgMHDgMnBiYiJicuAzU0PgI3PgM3NQ4DBwJyEhoSCQYNFA0NHB8hEhAcGhgLChALBQQKDgkJFBYXDAoTEg8HAgQDAwEBAgIBAQECAgYNEg0MHiMnFyZCOC4R/mYRGxIIBg0UDA0dHyESDx0aFwsLEAsFBQkOCQoUFRcMCxMRDwcCBAMDAQECAgIBAQIBAQcMEw0MHiMnFiZCOC0SAkUXMzQ5HBssKiIRDhcPCAEBBwoRCwwXGxoQDRsXGAkLDgwEAQECBgYGAQMBAgEBAgMBAwQHBgUSJyQmERMeGxQKKg4iJCwWARczNDkcGywqIhEOFw8IAQEHChELDBcbGhANGxcYCQsODAQBAQIGBgYBAwECAQECAwEDBAcGBRInJCYREx4bFAoqDiIkLBYAAAT//wCSBAAC2wAEAAkADgASAAATIRUhNQUhFSE1FSEVITUHEQ0BAAQA/AABbgKS/W4Ckv1uSf7aASYC25KS25KS25OTkwFut7cAAAAFAAAAkgQAAtsABAAJAA4AGgBtAAABIRUhNRUhFSE1FSEVITUlMzUjNSMHFTcVIxUTPgM3PgM3PgM1NC4CJy4DIyoBDgEHIg4CBxU+Azc+AjIzMh4CFx4DFRQOAgcOAwcOAw8BFTM1Iz4DNzEBJQLb/SUC2/0lAtv9Jf7liC8pLS0wQQgOCwcCAgUDAwEBAgEBAwUHBQULDg8IBAcHBwQDCAcIBAQIBwcEAwcGBgMEBwYGAgIDAwEBAQIBAQMEBQMCCA0QCheIWwMHBwgFAtuSktuSktuTk9UouQsoDJIo/t8IDwwIAwMHBgYDAwYHBgMHDQwKBAQGBAIBAQECAwICKQIEBAICAQIBAQIDAgIFBgYEAgUFBQMCBgYGAwMJDhMLGiYnAwcICQUAAAADAAAAkgQAAtsALAAxAGwAACUiLgIvATMeAzMyPgI3LgMjIg4CByM3PgMzMh4CFw4DIwEhFyE3JyIOAgcjFw4DBx4DFwczHgMzMj4CNzMXDgMjIi4CNyY+AjMyHgIXByMuAyMC3BQnJCQPAT4IFhQYCydBMxsBARszQScLGBQWCD4BDyQkJxQ9alAtAQEtUGo9/pMBIwH+2wFLChgUFgk8AQoNCgQBAQQKDQoBPQgWFBgKDRYWFAo8AREiJiUWO2xOLwEBL05sOxYlJiIRATwKFBYWDZIGCxAJaAUHBQMaLT0jIzwuGgMFCARnChALBS5Pazw9alAuAW6Skl4DBQgELwsXGRsODhsZGAovBQcFAwMFBwVoCRALBi5Qaj08a08uBQsQCmcECAUDAAABAAABbgQAAgAABAAAEyEVITUABAD8AAIAkpIAAQEkAJIDJAMkAAwAAAEDIwchNyMTMzchBzMCDVKAFwGCFoFSgRb+fhaBArH+VHNzAaxzcwAAAAAEAAAAkgQAAtsABAAJAA4AEgAAEyEVITUFIRUhNRUhFSE1BRENAQAEAPwAAW4Ckv1uApL9bv6SASb+2gLbkpLbkpLbk5OTAW63twAAAwAAAEkEAAMlAAQACQASAAA3ESURJQElESURARc3FxUFNRsBAAQA/AADt/ySA27+kklgfP0k3NtJAtsB/SMBApEB/bYBAkj+lAHAwJIBlAEj/t0ABABJAAADtwNvAAMAGgAeADUAAAETASUHHgIGDwEOAS4BJy4CNj8BPgEeARcBBQERNx4CNj8BPgEuAScuAgYPAQ4BHgEXA7YB/kkBtlMFBgEDBOcECgwMBQUGAgME5wQLDAwF/OYBt/5JVgULDAsE5QQDAQYFBQwMCgTmBAMCBQYDb/5IAbcBVwUMDAoE5gQDAQYFBQwMCwTlBAMBBgX86QEBt/5KVAUGAQME5gQLCwwFBQYCAwTmBAsMDAUAAAAABAAA/7cEAAO3AAMAGgAeADUAAAEDAQU3LgI2PwE+AR4BFx4CBg8BDgEuAScHJQERBy4CBg8BDgEeARceAjY/AT4BLgEnAkoBAbf+SlMFBgEDBOcECgwMBQUGAgME5wQLDAwF5v5JAbdWBQsMCwTlBAMBBgUFDAwKBOYEAwIFBgH/Abj+SQFXBQwLCwTmBAMBBgUFDAwLBOYEAwIGBekB/kkBtlUFBgIDBOYECwwMBQUGAQME5gQLCwwFAAABANsASQLbAyUAEgAAJREjESMRIi4CNTQ+AjMhESMCkkmSLlA7IyM7UC4BJElJApL9bgElIjxQLS5QOyP9JAAAAwBKAAEDuANsAAoAVwB4AAABMwsBMxMjGwEjAwUOAwcOAyMiLgInLgM3Jj4CNz4DOwE3LgMnLgMjIg4CBw4DByc+Azc+AzMyHgIXHgMHFyM3JyMiDgIHDgMXBh4CFx4DMzI+Ajc+AzcnAyWUubeSAZS5t5IB/ioGCg0NCAcQEBIIEh4cFgoJDwkFAQEGCxIKDRwkKRlIAQEBBgYGAw0MEQgLERQRCQgTEhQIAQkRExAKCBQSFQkZKSQaCwkQCQYBAWoBASkQGBYPBwUJBQQBAQMDBwMFCQwLCAkUDw8FBwcHAgEBAST+3QEjASYBIv7e/toOBw0KCQQEBQQCBQkOCgkXGh4REiAbFgkJDQgFEgcLCgkDBAUDAgEDBAIDBggJBl4DBwUFAgEDAgEFCw8LCh0lLRvuL5UCBAYDBAsNEQkHDQsKBAUGBAIECAwICRMXGg8HAAQASgCTA7cC3AADAAwALQB6AAABIzcXBTM3MxczAyMDJRUUDgIHDgMjIi4CJy4DNTQ+Ajc+AzsBNy4DIyIOAgcOAwcVPgM3PgMzMh4CFx4DHQEjIg4CBw4DFRQeAhceAzMyPgI3PgM3FTM1NC4CJwFdajQ2/u1wIpYjcJmJmQL+AwYJBgYPERMLCA0MCgQEBwQCAwYKBgYRFhoQLEULHCUsGgsUFBQJChMTEgkKFBMTCgkTExQKChAPDAUFBwUCTRksJR8MDBIMBwYKDwoKGB0gEgkTEREHCA8NCwVvBQsQCgGJ6+vrjo4CPv3CyggPGhgUCAkMCQQCBAcEBQoLDQgKEA4LBAQGBALECxAKBgECAwIBBQYGBGAFCggHAgMEAgEBBAUEAwkKDAcTBAkOCQkWHCETER8bFwoKDgoFAgQGBAMKCwwHMPYbLyYdCwAAAAIAkgCSA24DJgAEAIEAABMhFyE3BR4DFx4DBxYOAgcOAyMiLgInLgMnFx4DFx4DMzI+Ajc+AzcuAycuAy8BLgMnLgMnPgM3PgMzMh4CFx4DFzcuAycuAyMiDgIHDgMXBh4CFx4DHwGSAtsB/SMBAX0JDg4KBgMIAwQBAQUGCwUIDxQVDQsZFxoLDhgaGQ4BChkXGQwNGBoYDR02LCYOEBYQBgEBBAoNCwgaHCQTOg4ZEhADBgYGAQEBAggICAUQEhYLDBQXFAwKFxUWCgENFRgWDQoYFhgLGiwpIRANFw4IAQEFCA4IChkiKRpAAgBJSWIDCAgKBQYLDQ0HChEODQUGCAUCAgQHBAQLDg8JggUKCAcDAwQDAQYLEgwMHiQqGBIgHRoMDBUSEQcUBQoKCQQFCQsMBwgPDgsEBQcEAwIEBgMECQsNB3sFCAgGAwIEAgIHDBMMDB4iJhYRHhsXCgoTExMJFwAAAAQAAACSBAAC3AAEAAkADgATAAATNwEHATUBFwEnBScBFwE1AQcBNwBJAW1J/pMBbUn+k0kEAEn+k0kBbf6TSQFtSQG3O/7bOgEkAQEkOv7aPAE7/ts6ASQBASQ6/to8AAUAAP+3BAADtwAEAAkADgATABgAABcRIREhASERIREDITUhFRUhNSEVFSE1IRUABAD8AAO3/JIDbpL9tgJK/bYCSv22AkpJBAD8AAO3/JIDbv7bkpLbkpLck5MAAwElAJIC2wMlABcALwBbAAABMh4CFx4DFRQOAgcOAysBNTMRMh4CFx4DFRQOAgcOAysBNTMDMzI+Ajc+AzU0LgInLgMnPgM3PgM1NC4CJy4DKwERAfEOGRQRBgYKBgMDBgkGBhAVGQ9TUwsUEQ4FBQgFAgIFCAUFDREVC1NTzMwfNS0kDg0VDgcFCQ4JCRcbIBIPGxcTCAgLCAQHDRQNDSEoLhrMAb0DBgkFBhATFw0NFxIOBgUIBQPDAQACBQcEBQwOEgoKEQ8MBAQHBAOZ/dUGChALCxwiKRgTIx4aCgsRDQgCAgYLDgkIFhgdEBQlHxoKChAKBv1tAAAAAwBJAAADtwNuAAQADQARAAA3ESERIQEjAzM3MxczAwcXIzdJA278kgH6h5hvIpQjb5hENWk0AANu/JIC3P21kZECS2rw8AAAAgCFAD8DeAMyACEASwAACQEnDgEuAScHFwcOASImLwEuATQ2NwE+ATIWHwEeARQGBycuAQ4BBwEOAhYXHgE+AT8BLgMnLgI2PwE+AhYXBxcBPgImJwN4/tgIChYXGAtBOx0fTVFNHx0fHx8fAa0fTVBOHh4fHh4fShY2OTcW/nUWFgEVFhU3OTcWTQYLCwoFFBcHDA+lCx4hIxH6SgEMFhcBFhUB7P7YCAMBAwgGQTwdHx8fHx0fTVFNHwGtHx4eHx4eTVFNH/wWFQEXFv52Fjc5NxUWFQEWFk4DBggJBRQuLioPpQsNAQgJ+koBDBY3OTcVAAMAAACSBAEC2wAEAAkADgAAEyEVITUFIRUhNQUhFSE1AAQA/AABJQLa/SYBJAG4/kgC25KS25KS25OTAAMAAACSBAAC2wAEAAkADgAAEyEVITUVIRUhNRUhFSE1AAQA/AAC2/0lAbj+SALbkpLbkpLbk5MAAwAAAJIEAALbAAQACQAOAAATIRUhNRUhFSE1FSEVITUAA/78AgP9/AMEAPwAAtuSktuSktuTkwADAAAAkgQAAtsABAAJAA4AABMhFyE3ByEHIScXIRchN9sCSQH9tQHcBAEB/AEB3AJJAf21AQLbkpLbkpLbk5MAAQAAAAEAAJlYhVVfDzz1AAsEAAAAAADPCHp6AAAAAM8Ienr///+3BAEDtwAAAAgAAgAAAAAAAAABAAADwP/AAAAEAP////8EAQABAAAAAAAAAAAAAAAAAAAAIQAAAAACAAAABAAAAAQAAAAEAAAABAAA2wQAAAAEAADaBAAAAAQAABIEAACSBAD//wQAAAAEAAAABAAAAAQAASQEAAAABAAAAAQAAEkEAAAABAAA2wQAAEoEAABKBAAAkgQAAAAEAAAABAABJQQAAEkEAACFBAAAAAQAAAAEAAAABAAAAAAAAAAACgAuAF4ApgD2AYQBqAH+AkIDBgMsA8IEWARmBIIEqATSBTIFkAWwBloHAge2B+YIFAiSCLYJMAlOCWoJhgmmAAEAAAAhAJAACgAAAAAAAgAAAAAAAAAAAAAAAAAAAAAAAAAOAK4AAQAAAAAAAQAYAAAAAQAAAAAAAgAOAGoAAQAAAAAAAwAYAC4AAQAAAAAABAAYAHgAAQAAAAAABQAWABgAAQAAAAAABgAMAEYAAQAAAAAACgAoAJAAAwABBAkAAQAYAAAAAwABBAkAAgAOAGoAAwABBAkAAwAYAC4AAwABBAkABAAYAHgAAwABBAkABQAWABgAAwABBAkABgAYAFIAAwABBAkACgAoAJAAUgBlAGQAYQBjAHQAbwByAEYAbwBuAHQAVgBlAHIAcwBpAG8AbgAgADAALgAwAFIAZQBkAGEAYwB0AG8AcgBGAG8AbgB0UmVkYWN0b3JGb250AFIAZQBkAGEAYwB0AG8AcgBGAG8AbgB0AFIAZQBnAHUAbABhAHIAUgBlAGQAYQBjAHQAbwByAEYAbwBuAHQARwBlAG4AZQByAGEAdABlAGQAIABiAHkAIABJAGMAbwBNAG8AbwBuAAAAAwAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA==) format('truetype'), url(data:application/font-woff;charset=utf-8;base64,d09GRk9UVE8AABRAAAoAAAAAE/gAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAABDRkYgAAAA9AAAEDAAABAw7Fi3rU9TLzIAABEkAAAAYAAAAGAOsgNIY21hcAAAEYQAAABEAAAAROYwAIdnYXNwAAARyAAAAAgAAAAIAAAAEGhlYWQAABHQAAAANgAAADYBMDlfaGhlYQAAEggAAAAkAAAAJAfDA+FobXR4AAASLAAAAIQAAACEfgEHuW1heHAAABKwAAAABgAAAAYAIVAAbmFtZQAAErgAAAFmAAABZhHEcGxwb3N0AAAUIAAAACAAAAAgAAMAAAEABAQAAQEBDVJlZGFjdG9yRm9udAABAgABAD74HAL4GwP4GAQeCgAJdlYl/4uLHgoACXZWJf+LiwwHikL6lfpLBR0AAAE3Dx0AAAE8ER0AAAAJHQAAECcSACIBAQ0ZHCEmKzA1Oj9ESU5TWF1iZ2xxdnuAhYqPlJmeo6itsrdSZWRhY3RvckZvbnRSZWRhY3RvckZvbnR1MjB1RTYwMHVFNjAxdUU2MDJ1RTYwM3VFNjA0dUU2MDV1RTYwNnVFNjA3dUU2MDh1RTYwOXVFNjBBdUU2MEJ1RTYwQ3VFNjBEdUU2MEV1RTYwRnVFNjEwdUU2MTF1RTYxMnVFNjEzdUU2MTR1RTYxNXVFNjE2dUU2MTd1RTYxOHVFNjE5dUU2MUF1RTYxQnVFNjFDdUU2MUR1RTYxRQAAAgGJAB8AIQIAAQAEAAcAQwC+ASsBlAJ0AsADiAP2BMoFGgYEBtQG6QcfB3AHwAg3CK4I4wnCCqkLdwvGDCwMyw0UDawN6w4oDmUOpf6UDvyUDovUFYv5bwX6lIsFi/1vBf6UiwX6S/kmFf4CiwWL/N0F+gKLBYv43QX83fyUFYv4SwX3uftvBfu5+28FDve5+W8V+W+LBYv7JgX9b4sFi/cmBYv7bxX5b4sFi/smBf1viwWL9yYFi/tvFflviwWL+yYF/W+LBYv3JgX7ufhLFfcmiwWL+yYF+yaLBYv3JgWL+28V9yaLBYv7JgX7JosFi/cmBYv7bxX3JosFi/smBfsmiwWL9yYFDvqC1BU+9xX7Esn78aEIi/tpBYuL+yr3C/vE95II9+X3n/cJ5ouLCIv7aQX4Nsz3dPvuMfuBCPz++D8Vi/cOBYuLVFn7X/sZCPdB+yjgaYuLCIxsBYr3LAX3W373r2yvPQi+9x77iPdP+9k6CA73b/cmFfjdiwWLQgX83YsFi9QF9xL3EhWuaMN52IsI2IvDna6uCK6unMSL2QiL9/4F+xOLBYv8GwWLboN1e3sIe3t0g26LCG6LdJN7mwh7m4Oii6gIi/gbBfsTiwWL+/4Fiz2cUq5oCA75J/oBFdGLBYv7wQX3KYsFi0sF+2+LBYv4AQXW/JMV97f7TAX7t/tMBYv3KQX7cYsFi9QF93GLBYv3JwX8TvckFfu390wF97f3TAWL+ycF93GLBYtCBftxiwWL+ykFovs9FZx6k3CLZgiLcoZ3gXwIgXx9gniICJGKkIiPhgiPhpCBkXwIwfsXBUqLBWfnBYqOio+JkAiAp3+ZfYsIeIsFi/skBVCLBYv4AQXgiwWxi6eDnHoI+wH7GxWniwWbi5ePkpMIkpOPmIudCIudiJiEkwiEk3+Pe4sIb4sFiygFDvjZ+F8V+yCLBdH3hAXR+4QF+//7hBX3KIsFuPclBfdaiwW5+yUF9yiLBfte+N4F+0mLBfte/N4FjEIV+N2LBYv7JgX83YsFi/cmBQ6L1BWL+W8F+pSLBYv9bwX+lIsF+ALUFfe5iwWL9yYF+7mLBYv7JgWL928V97mLBYv3JgX7uYsFi/smBUL4AhX7b4sFi/smBfdviwWL9yYFi/tvFftviwWL+yYF92+LBYv3JgWL+28V+2+LBYv7JgX3b4sFi/cmBdT4SxWL+yYF97mLBYv3JgX7uYsF+N2LFftviwWL+yYF92+LBYv3JgWL+28V+2+LBYv7JgX3b4sFi/cmBYv7bxX7b4sFi/smBfdviwWL9yYFDvqU+FMV+8T7kvsq+wuLiwiL92kF+/F1+xJNPvsVCDH3gfd09+74NkoIi/dpBYuL9wkw9+X7nwj+HftTFa/Z96+q91uYCIr7LAWMqgWLi+Ct90H3KAj7X/cZU72LiwiL+w4F+9nc+4j7T777HggO+Qb42RVcTHNEizwIi0ecVa5jCK5jtHe7iwi0i66aqKkIqKmZrouyCIuwf6typghypm6Za4sIb4t0hHl+CIWHh4mIiwiIi4iNiY8IiJCJk4uWCIu+nL2suwisu7muxqEIi7YFJWVBWVxMCPwtixVcTHNEizwIi0ecVa5jCK5jtHe7iwi0i66aqKkIqKmZrouyCIuwf6typghypm6Za4sIb4t0hHl+CIWHh4mIiwiIi4iNiY8IiJCJk4uWCIu+nL2suwisu7muxqEIi7YFJWVBWVxMCA6L+W8V+pSLBYv7JgX+lIsFi/cmBfgC+28V+SaLBYv7JgX9JosFi/cmBYv7bxX5JosFi/smBf0miwWL9yYFQvsmFYv4AgX7uvtLBfe6+0oFDve5+W8V+W+LBYv7JgX9b4sFi/cmBYv7bxX5b4sFi/smBf1viwWL9yYFi/tvFflviwWL+yYF/W+LBYv3JgX7rvdqFfcciwWLsgVciwWL904FYosFX4AFi2MFt5YFi/smBVyLBYtkBcz7thWio5makJIIkpSQlI6TCI6TjJOLlAiLnoWafpYIfpZ5kXSLCIKLgoqBiQiBiYGIgYcIi2IFlZGVkJSOCJSOk42TiwiWi5OIkYYIkYaOg4uBCIuEiYSIhAiIhIaDhIIIhYR6eHBtCHRxBYtlBfcciwWLsgUxiwWSk5WVl5gIi4sFDvlw9yYVVYtam2ClCIvzBciLBaV+qIOqiwjwi93Wi+cIi+c51iaLCGyLboNxfghOiwWL8wW2pbybwYsI9zWL9xf7F4v7NgiL+zb7F/sX+zWLCPwC+AIV97mLBYv7JgX7uYsFi/cmBULpFWyLboNxfghPiwWLXAV0b31pi2UIi2WZaaJvCItcBceLBaV+qIOqiwiqi6iTpZgIyIsFiyMFYHFae1WLCPs1i/sX9xeL9zYIi/c29xf3F/c1iwjBi7x7tnEIiyMFTosFcZhuk2yLCA6L+JQV+pSLBYv7JgX+lIsFi/cmBQ74oflFFTn8QAX7FYsFdfsGBfgViwWi9wYF+xWLBd34QAX3FYsFofcGBfwWiwV1+wYF9xWLBQ6L+W8V+pSLBYv7JgX+lIsFi/cmBfgC+28V+SaLBYv7JgX9JosFi/cmBYv7bxX5JosFi/smBf0miwWL9yYF/AL7JhWL+AIF97r7SwX7uvtKBQ6L1BWL+W8F+pSLBYv9bwX+lIsF+kv5JhX+AosFi/zdBfoCiwWL+N0F/AL8AhXUiwXq91MF9xD7UwWL+yYF/W+LBYv3JgX3b/e5Bfdv+7kFDvpK+gMVjPxMBfxL+EsF+EqMBTg0FZl+jXiAgAj7e/t6BYCAd419mQh9mImelpYI93v3egWWlp+JmX4I/a79qxX4S4oF/Ev4SwWL/EoF4N8VmH6eiZaWCPd593oFlpaJnn6ZCH6YeI2AgAj7eft6BYCAjXiYfggO+N74kxWK+EwF+Ev8SwX8SooF3uIVfZiJnpaWCPd793oFlpafiZl+CJl+jXeAgAj7e/t6BYCAd419mAj7evt9FfxLjAX4S/xLBYv4SgU2NxV9mXiNgIAI+3n7egWAgI14mH4ImH6eiZaWCPd593oFlpaJnn6YCA75JtQVi/kmBUKLBYv9JgX7JosFi/e5BfsNiynti/cNCIv3De3t9w2LCPe5iwWL/W8FQosFDvm597gV9yiLBftM+7cF+0z3twX3KIsFi/e6BfsoiwX3TPe3BfdM+7cF+yiLBYv7ugX8a30Vfnl7fXeBCHeBdYZziwhdi2eYcaQIcaR+rou4CIu8mq+qogiqorqXy4sI1IsFi50Fi52FmH+UCH+UeZBziwhyi3OIc4QIc4RygXF9CIvoBaKVo5KjkAijkKSNposIzYu5faZvCKVvmFqLRAiL+4IFIosFi7oFi/cqFWGLBWSLb4Z7gQh7gYN5i3IIi3iQfJaACJaAmoWeiwini6GWmqEImqGTqYuyCIuSBQ738fgdFSGLBcD3fwXA+38F+6f7fxX3BIsFrfciBfcqiwWu+yIF9wSLBfst+NEF+x2LBfst/NEF+ZL3XhWLgwWLY4Nse3UIe3V0gG6LCHeLfJGAlgiAloWbi54Ii6WTnZuWCJuWqJC0iwi3iwXQ91gVb6damUaLCG+LcIlyhghyhnKDcoEIiysFppqllqSSCKSSpY6miwiki56GmIIImIKSfYt5CIt4BT6LBUiLWX9rcwhrc3tmi1kIi12ZZ6ZxCKZxsX67iwiki6KQoJUIoJWcmpieCItbBfcDiwWL94kFi9R9vm+nCA73JviUFflviwWLQgX9b4sFi9QF+BIpFaKDnICXfQiXfZF6i3gIi3KCd3l9CHl9coRriwhri2qRapcIapdpnWijCIv7FgWqfKuArIMIrIOsh6yLCNuLx5uzqwizq5+7i8sIi7p+snKqCHKqZKRVnghSnwVkmXGYf5YIf5eFmYudCIuik5yclwicl6ORq4sIqIuohqiBCKiBqH2neAiL9w8FbZhtlWySCGySbI5siwhHi1Z7ZGoIZGp4XotRCItel2eicAiicLhyzXMIzHQFDov4SxXUxgX4Avu5BUJQBfwC97kFi4sV+AL3uQXUUAX8Avu5BULGBfqVixVCxgX8Avu5BdRQBfgC97kFi4sV/AL3uQVCUAX4Avu5BdTGBQ6LQhWL+pQF+pSLBYv+lAX+lIsF+kv6SxX+AosFi/4CBfoCiwWL+gIF+yb7uRX83YsFi/cmBfjdiwWL+yYFi/tvFfzdiwWL9yYF+N2LBYv7JgWL+28V/N2LBYv3JgX43YsFi/smBQ74hfhRFbGLp4Ocewice5Nxi2cIi2iDcnt9CHt9b4Rjiwg4iwWL91cF3osFi/eUFaqLoYWZfwiZf5J3i3AIi3CEeH5/CH5/dYVriwg4iwWL9y0F3osF+1/8vxX3X4sF3ovHmbCnCLCnnbmLygiLv3+zc6gIc6hnnFuQCLOPqpmgowigo5Wsi7UIi8J5tGinCGinVplFiwj7X4sFi/0mBQ7UixWL+gIF+gKLBYv+AgX+AosF+I75cBX7HIsF+yv83wX3A4sFrfclBfcoiwWu+yUF9wOLBfsr+N8FRyEVwPuEBSKLBb/3hAUO+gz4gBX7vPu8BYOTBXCDa5BtmwhKSgXGUAVtbQU5OfsZizndCG2pBTndi/cZ3d0I+EH4QQXd3fcZi905CKltBd05i/sZOTkIQfeQFVLELYpQUAj8H/wfBVBQii3EUgjEUumMxsYI2NgFfJN8lX6YCFbAgdezswj3Ofc5BaqpvY25cwj7jvuPBdVBBfeg96AFxsaM6VLECA6L+W8V+pSLBYv7JgX+lIsFi/cmBfe5+28V+W+LBYv7JgX9b4sFi/cmBfe5+28V+EyLBYv7JgX8TIsFi/cmBQ6L+W8V+pSLBYv7JgX+lIsFi/cmBYv7bxX5b4sFi/smBf1viwWL9yYFi/tvFfhMiwWL+yYF/EyLBYv3JgUOi/lvFfqSiwWL+yYF/pKLBYv3JgWL+28V+pGLBYv7JgX+kYsFi/cmBYv7bxX6lIsFi/smBf6UiwWL9yYFDvdv+W8V+N2LBYv7JgX83YsFi/cmBftv+28V+pSLBYv7JgX+lIsFi/cmBfdv+28V+N2LBYv7JgX83YsFi/cmBQ76lBT6lBWLDAoAAwQAAZAABQAAApkCzAAAAI8CmQLMAAAB6wAzAQkAAAAAAAAAAAAAAAAAAAABEAAAAAAAAAAAAAAAAAAAAABAACDmHgPA/8D/wAPAAEAAAAABAAAAAAAAAAAAAAAgAAAAAAACAAAAAwAAABQAAwABAAAAFAAEADAAAAAIAAgAAgAAACDmHv/9//8AAAAg5gD//f///+EaAgADAAEAAAAAAAAAAAABAAH//wAPAAEAAAABAACLSUTLXw889QALBAAAAAAAzwh6egAAAADPCHp6////twQBA7cAAAAIAAIAAAAAAAAAAQAAA8D/wAAABAD/////BAEAAQAAAAAAAAAAAAAAAAAAACEAAAAAAgAAAAQAAAAEAAAABAAAAAQAANsEAAAABAAA2gQAAAAEAAASBAAAkgQA//8EAAAABAAAAAQAAAAEAAEkBAAAAAQAAAAEAABJBAAAAAQAANsEAABKBAAASgQAAJIEAAAABAAAAAQAASUEAABJBAAAhQQAAAAEAAAABAAAAAQAAAAAAFAAACEAAAAAAA4ArgABAAAAAAABABgAAAABAAAAAAACAA4AagABAAAAAAADABgALgABAAAAAAAEABgAeAABAAAAAAAFABYAGAABAAAAAAAGAAwARgABAAAAAAAKACgAkAADAAEECQABABgAAAADAAEECQACAA4AagADAAEECQADABgALgADAAEECQAEABgAeAADAAEECQAFABYAGAADAAEECQAGABgAUgADAAEECQAKACgAkABSAGUAZABhAGMAdABvAHIARgBvAG4AdABWAGUAcgBzAGkAbwBuACAAMAAuADAAUgBlAGQAYQBjAHQAbwByAEYAbwBuAHRSZWRhY3RvckZvbnQAUgBlAGQAYQBjAHQAbwByAEYAbwBuAHQAUgBlAGcAdQBsAGEAcgBSAGUAZABhAGMAdABvAHIARgBvAG4AdABHAGUAbgBlAHIAYQB0AGUAZAAgAGIAeQAgAEkAYwBvAE0AbwBvAG4AAAADAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA) format('woff');
+ font-weight: normal;
+ font-style: normal;
+}
+/* =Selection
+-----------------------------------------------------------------------------*/
+.redactor_box ::selection {
+ background: #ffff9e;
+}
+.redactor_box ::-moz-selection {
+ background: #ffff9e;
+}
+.redactor_box img::selection {
+ background: transparent;
+}
+.redactor_box img::-moz-selection {
+ background: transparent;
+}
+/*
+ BOX
+*/
+.redactor_box {
+ position: relative;
+ overflow: visible;
+ background: #fff;
+}
+.redactor_box iframe {
+ display: block;
+ margin: 0;
+ padding: 0;
+ border: 1px solid #eee;
+}
+.redactor_box textarea {
+ position: relative;
+ z-index: 1004;
+ display: block;
+ overflow: auto;
+ margin: 0;
+ padding: 0;
+ width: 100%;
+ outline: none;
+ border: none;
+ background-color: #222;
+ box-shadow: none;
+ color: #ccc;
+ font-size: 13px;
+ font-family: Menlo, Monaco, monospace, sans-serif;
+ resize: none;
+}
+.redactor_box textarea:focus {
+ outline: none;
+}
+/*
+ AIR
+
+*/
+body .redactor_air {
+ position: absolute;
+ z-index: 102;
+}
+/*
+ FULLSCREEN
+*/
+body .redactor_box_fullscreen {
+ position: fixed;
+ top: 0;
+ left: 0;
+ z-index: 49000;
+ overflow: hidden;
+ width: 100%;
+}
+/*
+ LINK TOOLTIP
+*/
+.redactor-link-tooltip {
+ position: absolute;
+ z-index: 49999;
+ padding: 10px;
+ line-height: 1;
+ display: inline-block;
+ background-color: #000;
+ color: #555 !important;
+}
+.redactor-link-tooltip,
+.redactor-link-tooltip a {
+ font-size: 12px;
+ font-family: Arial, Helvetica, Verdana, Tahoma, sans-serif;
+}
+.redactor-link-tooltip a {
+ color: #ccc;
+ margin: 0 5px;
+ text-decoration: none;
+}
+.redactor-link-tooltip a:hover {
+ color: #fff;
+}
+/*
+ IMAGE BOX
+*/
+#redactor-image-box img {
+ width: 100%;
+}
+.redactor_editor {
+ position: relative;
+ overflow: auto;
+ margin: 0 !important;
+ padding: 10px 20px;
+ padding-bottom: 5px;
+ outline: none;
+ background: none;
+ background: #fff;
+ box-shadow: none !important;
+ white-space: normal;
+ border: 1px solid #eee;
+}
+.redactor_editor:focus {
+ outline: none;
+}
+.redactor_editor div,
+.redactor_editor p,
+.redactor_editor ul,
+.redactor_editor ol,
+.redactor_editor table,
+.redactor_editor dl,
+.redactor_editor blockquote,
+.redactor_editor pre,
+.redactor_editor h1,
+.redactor_editor h2,
+.redactor_editor h3,
+.redactor_editor h4,
+.redactor_editor h5,
+.redactor_editor h6 {
+ font-family: Arial, Helvetica, Verdana, Tahoma, sans-serif;
+}
+.redactor_editor code,
+.redactor_editor pre {
+ font-family: Menlo, Monaco, monospace, sans-serif;
+}
+.redactor_editor div,
+.redactor_editor p,
+.redactor_editor ul,
+.redactor_editor ol,
+.redactor_editor table,
+.redactor_editor dl,
+.redactor_editor blockquote,
+.redactor_editor pre {
+ font-size: 14px;
+ line-height: 1.6em;
+}
+.redactor_editor a {
+ color: #15c !important;
+ text-decoration: underline !important;
+}
+.redactor_editor .redactor_placeholder {
+ color: #999 !important;
+ display: block !important;
+}
+/*
+ TYPOGRAPHY
+*/
+.redactor_editor object,
+.redactor_editor embed,
+.redactor_editor video,
+.redactor_editor img {
+ max-width: 100%;
+ width: auto;
+}
+.redactor_editor video,
+.redactor_editor img {
+ height: auto;
+}
+.redactor_editor div,
+.redactor_editor p,
+.redactor_editor ul,
+.redactor_editor ol,
+.redactor_editor table,
+.redactor_editor dl,
+.redactor_editor blockquote,
+.redactor_editor pre {
+ margin: 0;
+ margin-bottom: 10px !important;
+ border: none;
+ background: none !important;
+ box-shadow: none !important;
+}
+.redactor_editor iframe,
+.redactor_editor object,
+.redactor_editor hr {
+ margin-bottom: 15px !important;
+}
+.redactor_editor blockquote {
+ margin-left: 1.5em !important;
+ padding-left: 0 !important;
+ color: #777;
+ font-style: italic !important;
+}
+.redactor_editor ul,
+.redactor_editor ol {
+ padding-left: 2em !important;
+}
+.redactor_editor ul ul,
+.redactor_editor ol ol,
+.redactor_editor ul ol,
+.redactor_editor ol ul {
+ margin: 2px !important;
+ padding: 0 !important;
+ padding-left: 2em !important;
+ border: none;
+}
+.redactor_editor dl dt {
+ font-weight: bold;
+}
+.redactor_editor dd {
+ margin-left: 1em;
+}
+.redactor_editor table {
+ border-collapse: collapse;
+ font-size: 1em !important;
+}
+.redactor_editor table td {
+ padding: 5px !important;
+ border: 1px solid #ddd;
+ vertical-align: top;
+}
+.redactor_editor table thead td {
+ border-bottom: 2px solid #000 !important;
+ font-weight: bold !important;
+}
+.redactor_editor code {
+ background-color: #d8d7d7 !important;
+}
+.redactor_editor pre {
+ overflow: auto;
+ padding: 1em !important;
+ border: 1px solid #ddd !important;
+ border-radius: 3px !important;
+ background: #f8f8f8 !important;
+ white-space: pre;
+ font-size: 90% !important;
+}
+.redactor_editor hr {
+ display: block;
+ height: 1px;
+ border: 0;
+ border-top: 1px solid #ccc;
+}
+/*
+ HEADERS
+*/
+.redactor_editor h1,
+.redactor_editor h2,
+.redactor_editor h3,
+.redactor_editor h4,
+.redactor_editor h5,
+.redactor_editor h6 {
+ margin-top: 0 !important;
+ padding: 0 !important;
+ background: none;
+ color: #000;
+ font-weight: bold;
+}
+.redactor_editor h1 {
+ font-size: 36px !important;
+ line-height: 1.111em !important;
+ margin-bottom: .15em !important;
+}
+.redactor_editor h2 {
+ font-size: 30px !important;
+ line-height: 1.111em !important;
+ margin-bottom: .25em !important;
+}
+.redactor_editor h3 {
+ font-size: 24px !important;
+ line-height: 1.333em !important;
+ margin-bottom: .2em !important;
+}
+.redactor_editor h4 {
+ font-size: 18px !important;
+ line-height: 1.5em !important;
+ margin-bottom: .2em !important;
+}
+.redactor_editor h5 {
+ font-size: 1em !important;
+ line-height: 1.6em !important;
+ margin-bottom: .25em !important;
+}
+.redactor_editor h6 {
+ font-size: .8em !important;
+ line-height: 1.6em !important;
+ text-transform: uppercase;
+ margin-bottom: .3em !important;
+}
+/*
+ TOOLBAR
+*/
+.redactor_toolbar {
+ position: relative;
+ top: 0;
+ left: 0;
+ margin: 0 !important;
+ padding: 0 !important;
+ list-style: none !important;
+ font-size: 14px !important;
+ font-family: Arial, Helvetica, Verdana, Tahoma, sans-serif;
+ line-height: 1 !important;
+ background: #fff;
+ border: none;
+ box-shadow: 0 1px 2px rgba(0, 0, 0, 0.2);
+ z-index: 3;
+}
+.redactor_toolbar:after {
+ content: "";
+ display: table;
+ clear: both;
+}
+.redactor_toolbar.redactor-toolbar-overflow {
+ overflow-y: auto;
+ height: 29px;
+ white-space: nowrap;
+}
+.redactor_toolbar.redactor-toolbar-external {
+ z-index: 999;
+ box-shadow: none;
+ border: 1px solid rgba(0, 0, 0, 0.1);
+}
+body .redactor_air .redactor_toolbar {
+ padding-right: 2px !important;
+}
+.redactor_toolbar li {
+ vertical-align: top;
+ display: inline-block;
+ margin: 0 !important;
+ padding: 0 !important;
+ outline: none;
+ list-style: none !important;
+ -webkit-box-sizing: content-box;
+ -moz-box-sizing: content-box;
+ box-sizing: content-box;
+}
+.redactor_toolbar li a {
+ display: block;
+ color: #333;
+ text-align: center;
+ padding: 9px 10px;
+ outline: none;
+ border: none;
+ text-decoration: none;
+ cursor: pointer;
+ zoom: 1;
+ -webkit-box-sizing: content-box;
+ -moz-box-sizing: content-box;
+ box-sizing: content-box;
+}
+.redactor_toolbar li a:hover {
+ outline: none;
+ background-color: #1f78d8;
+ color: #fff;
+}
+.redactor_toolbar li a:hover i:before {
+ color: #fff;
+}
+.redactor_toolbar li a:active,
+.redactor_toolbar li a.redactor_act {
+ outline: none;
+ background-color: #ccc;
+ color: #444;
+}
+.redactor_toolbar li a.redactor-btn-image {
+ width: 14px;
+ height: 14px;
+ background-position: center center;
+ background-repeat: no-repeat;
+}
+.redactor_button_disabled {
+ filter: alpha(opacity=30);
+ -moz-opacity: 0.3;
+ opacity: 0.3;
+}
+.redactor_button_disabled:hover {
+ outline: none;
+ background-color: transparent !important;
+ cursor: default;
+}
+.redactor_toolbar li a.fa-redactor-btn {
+ display: inline-block;
+ padding: 9px 10px 8px 10px;
+ line-height: 1;
+}
+.redactor_toolbar.redactor-toolbar-typewriter {
+ box-shadow: none;
+ background: rgba(240, 240, 240, 0.9);
+}
+.redactor_toolbar.redactor-toolbar-typewriter li a:hover {
+ outline: none;
+ background-color: #1f78d8;
+ color: #fff;
+}
+.redactor_toolbar.redactor-toolbar-typewriter li a:active,
+.redactor_toolbar.redactor-toolbar-typewriter li a.redactor_act {
+ outline: none;
+ background-color: #ccc;
+ color: #444;
+}
+.re-icon {
+ font-family: 'RedactorFont';
+ speak: none;
+ font-style: normal;
+ font-weight: normal;
+ font-variant: normal;
+ text-transform: none;
+ line-height: 1;
+ -webkit-font-smoothing: antialiased;
+ -moz-osx-font-smoothing: grayscale;
+}
+.re-icon i:before {
+ position: relative;
+ font-size: 14px;
+}
+.re-video:before {
+ content: "\e600";
+}
+.re-unorderedlist:before {
+ content: "\e601";
+}
+.re-undo:before {
+ content: "\e602";
+}
+.re-underline:before {
+ content: "\e603";
+}
+.re-textdirection:before {
+ content: "\e604";
+}
+.re-fontcolor:before {
+ content: "\e605";
+}
+.re-table:before {
+ content: "\e606";
+}
+.re-redo:before {
+ content: "\e607";
+}
+.re-quote:before {
+ content: "\e608";
+}
+.re-outdent:before {
+ content: "\e609";
+}
+.re-orderedlist:before {
+ content: "\e60a";
+}
+.re-link:before {
+ content: "\e60b";
+}
+.re-horizontalrule:before {
+ content: "\e60c";
+}
+.re-italic:before {
+ content: "\e60d";
+}
+.re-indent:before {
+ content: "\e60e";
+}
+.re-image:before {
+ content: "\e60f";
+}
+.re-fullscreen:before {
+ content: "\e610";
+}
+.re-normalscreen:before {
+ content: "\e611";
+}
+.re-formatting:before {
+ content: "\e612";
+}
+.re-fontsize:before {
+ content: "\e613";
+}
+.re-fontfamily:before {
+ content: "\e614";
+}
+.re-deleted:before {
+ content: "\e615";
+}
+.re-html:before {
+ content: "\e616";
+}
+.re-clips:before {
+ content: "\e617";
+}
+.re-bold:before {
+ content: "\e618";
+}
+.re-backcolor:before {
+ content: "\e619";
+}
+.re-file:before {
+ content: "\e61a";
+}
+.re-alignright:before {
+ content: "\e61b";
+}
+.re-alignment:before,
+.re-alignleft:before {
+ content: "\e61c";
+}
+.re-alignjustify:before {
+ content: "\e61d";
+}
+.re-aligncenter:before {
+ content: "\e61e";
+}
+/*
+ Toolbar classes
+*/
+.redactor_format_blockquote {
+ padding-left: 10px;
+ color: #666 !important;
+ font-style: italic;
+}
+.redactor_format_pre {
+ font-family: monospace, sans-serif;
+}
+.redactor_format_h1,
+.redactor_format_h2,
+.redactor_format_h3,
+.redactor_format_h4,
+.redactor_format_h5 {
+ font-weight: bold;
+}
+.redactor_format_h1 {
+ font-size: 30px;
+ line-height: 36px;
+}
+.redactor_format_h2 {
+ font-size: 24px;
+ line-height: 36px;
+}
+.redactor_format_h3 {
+ font-size: 20px;
+ line-height: 30px;
+}
+.redactor_format_h4 {
+ font-size: 16px;
+ line-height: 26px;
+}
+.redactor_format_h5 {
+ font-size: 14px;
+ line-height: 23px;
+}
+.redactor-toolbar-typewriter .redactor_dropdown .redactor_format_h1,
+.redactor-toolbar-typewriter .redactor_dropdown .redactor_format_h2,
+.redactor-toolbar-typewriter .redactor_dropdown .redactor_format_h3,
+.redactor-toolbar-typewriter .redactor_dropdown .redactor_format_h4,
+.redactor-toolbar-typewriter .redactor_dropdown .redactor_format_h5 {
+ font-size: 1em;
+ line-height: 1.6em;
+ text-transform: uppercase;
+}
+.redactor-toolbar-typewriter .redactor_dropdown .redactor_format_h2 {
+ font-size: .85em;
+}
+/*
+ Typewriter
+*/
+.redactor_editor.redactor-editor-typewriter {
+ background: #f5f5f5 !important;
+ padding: 25px 50px !important;
+}
+.redactor_editor.redactor-editor-typewriter div,
+.redactor_editor.redactor-editor-typewriter p,
+.redactor_editor.redactor-editor-typewriter ul,
+.redactor_editor.redactor-editor-typewriter ol,
+.redactor_editor.redactor-editor-typewriter table,
+.redactor_editor.redactor-editor-typewriter dl,
+.redactor_editor.redactor-editor-typewriter blockquote,
+.redactor_editor.redactor-editor-typewriter pre,
+.redactor_editor.redactor-editor-typewriter h1,
+.redactor_editor.redactor-editor-typewriter h2,
+.redactor_editor.redactor-editor-typewriter h3,
+.redactor_editor.redactor-editor-typewriter h4,
+.redactor_editor.redactor-editor-typewriter h5,
+.redactor_editor.redactor-editor-typewriter h6 {
+ font-family: 'Courier New', 'Lucida Console', Consolas, Monaco, monospace, sans-serif;
+ font-size: 18px !important;
+ line-height: 1.5em !important;
+ margin-bottom: 1.5em !important;
+}
+.redactor_editor.redactor-editor-typewriter h2 {
+ font-size: 14px !important;
+}
+.redactor_editor.redactor-editor-typewriter h1,
+.redactor_editor.redactor-editor-typewriter h2,
+.redactor_editor.redactor-editor-typewriter h3,
+.redactor_editor.redactor-editor-typewriter h4,
+.redactor_editor.redactor-editor-typewriter h5,
+.redactor_editor.redactor-editor-typewriter h6 {
+ text-transform: uppercase;
+}
+.redactor_editor.redactor-editor-typewriter a {
+ color: #000 !important;
+ text-decoration: underline !important;
+}
+/*
+ WYM
+*/
+.redactor_editor.redactor_editor_wym {
+ padding: 10px 7px 0 7px !important;
+ background: #f6f6f6 !important;
+}
+.redactor_editor.redactor_editor_wym div,
+.redactor_editor.redactor_editor_wym p,
+.redactor_editor.redactor_editor_wym ul,
+.redactor_editor.redactor_editor_wym ol,
+.redactor_editor.redactor_editor_wym table,
+.redactor_editor.redactor_editor_wym dl,
+.redactor_editor.redactor_editor_wym pre,
+.redactor_editor.redactor_editor_wym h1,
+.redactor_editor.redactor_editor_wym h2,
+.redactor_editor.redactor_editor_wym h3,
+.redactor_editor.redactor_editor_wym h4,
+.redactor_editor.redactor_editor_wym h5,
+.redactor_editor.redactor_editor_wym h6,
+.redactor_editor.redactor_editor_wym blockquote {
+ margin-top: 0;
+ margin-bottom: 5px !important;
+ padding: 10px !important;
+ border: 1px solid #e4e4e4 !important;
+ background-color: #fff !important;
+}
+.redactor_editor.redactor_editor_wym blockquote:before {
+ content: '';
+}
+.redactor_editor.redactor_editor_wym img {
+ position: relative;
+ z-index: 2;
+}
+.redactor_editor.redactor_editor_wym div {
+ border: 1px dotted #aaa !important;
+}
+.redactor_editor.redactor_editor_wym pre {
+ border: 2px dashed #e4e4e4 !important;
+ background-color: #f8f8f8 !important;
+}
+.redactor_editor.redactor_editor_wym ul,
+.redactor_editor.redactor_editor_wym ol {
+ padding-left: 2em !important;
+}
+.redactor_editor.redactor_editor_wym ul li ul,
+.redactor_editor.redactor_editor_wym ol li ul,
+.redactor_editor.redactor_editor_wym ul li ol,
+.redactor_editor.redactor_editor_wym ol li ol {
+ border: none !important;
+}
+/*
+ DROPDOWN
+*/
+.redactor_dropdown {
+ position: absolute;
+ top: 28px;
+ left: 0;
+ z-index: 2004;
+ padding: 10px;
+ width: 200px;
+ background-color: #fff;
+ box-shadow: 0 1px 5px #bbb;
+ font-size: 13px;
+ font-family: Helvetica, Arial, Verdana, Tahoma, sans-serif;
+ line-height: 21px;
+}
+.redactor-toolbar-typewriter .redactor_dropdown {
+ font-family: 'Courier New', 'Lucida Console', Consolas, Monaco, monospace, sans-serif;
+ background-color: #f5f5f5;
+}
+.redactor_separator_drop {
+ padding: 0 !important;
+ border-top: 1px solid #ddd;
+ font-size: 0;
+ line-height: 0;
+}
+.redactor_dropdown a {
+ display: block;
+ padding: 3px 5px;
+ color: #000;
+ text-decoration: none;
+}
+.redactor_dropdown a:hover {
+ background-color: #dde4ef;
+ color: #444 !important;
+ text-decoration: none;
+}
+/*
+ MODAL
+*/
+#redactor_modal_overlay {
+ position: fixed;
+ top: 0;
+ left: 0;
+ z-index: 50000;
+ margin: auto;
+ width: 100%;
+ height: 100%;
+ background-color: #000 !important;
+ filter: alpha(opacity=30);
+ -moz-opacity: 0.3;
+ opacity: 0.3;
+}
+#redactor_modal {
+ position: fixed;
+ top: 50%;
+ left: 50%;
+ z-index: 50001;
+ padding: 0;
+ background: #fff;
+ color: #000;
+ font-size: 12px !important;
+ font-family: Arial, Helvetica, Verdana, Tahoma, sans-serif;
+ box-shadow: 0 1px 10px rgba(0, 0, 0, 0.5);
+}
+#redactor_modal header {
+ padding: 20px 30px 5px 30px;
+ font-size: 16px;
+}
+#redactor_modal section {
+ padding: 20px 30px;
+}
+#redactor_modal label {
+ display: block !important;
+ float: none !important;
+ margin: 10px 0 3px 0 !important;
+ padding: 0 !important;
+ font-size: 12px !important;
+}
+#redactor_modal footer:after {
+ content: "";
+ display: table;
+ clear: both;
+}
+#redactor_modal footer div {
+ float: left;
+}
+#redactor_modal input[type="radio"],
+#redactor_modal input[type="checkbox"] {
+ position: relative;
+ top: -1px;
+}
+#redactor_modal input[type="text"],
+#redactor_modal input[type="password"],
+#redactor_modal input[type="email"],
+#redactor_modal textarea {
+ position: relative;
+ z-index: 2;
+ margin: 0;
+ padding: 1px 2px;
+ height: 23px;
+ border: 1px solid #ccc;
+ border-radius: 1px;
+ background-color: white;
+ box-shadow: 0 1px 2px rgba(0, 0, 0, 0.2) inset;
+ color: #333;
+ font-size: 13px;
+ font-family: Arial, Helvetica, Verdana, Tahoma, sans-serif;
+ line-height: 1;
+ -moz-transition: border 0.3s ease-in;
+ transition: border 0.3s ease-in;
+}
+#redactor_modal textarea {
+ display: block;
+ margin-top: 4px;
+ line-height: 1.4em;
+}
+#redactor_modal input:focus,
+#redactor_modal textarea:focus {
+ outline: none;
+ border-color: #5ca9e4;
+ box-shadow: 0 0 0 2px rgba(70, 161, 231, 0.3), 0 1px 2px rgba(0, 0, 0, 0.2) inset;
+}
+#redactor_modal_close {
+ position: absolute;
+ top: 5px;
+ right: 3px;
+ width: 20px;
+ height: 20px;
+ color: #999;
+ font-size: 26px;
+ cursor: pointer;
+}
+#redactor_modal_close:hover {
+ color: #000;
+}
+.redactor_input {
+ width: 99%;
+ font-size: 14px;
+}
+.redactor_modal_box {
+ overflow: auto;
+ margin-bottom: 10px;
+ height: 350px;
+}
+#redactor_image_box {
+ overflow: auto;
+ margin-bottom: 10px;
+ height: 270px;
+}
+#redactor_image_box_select {
+ display: block;
+ margin-bottom: 15px !important;
+ width: 200px;
+}
+#redactor_image_box img {
+ margin-right: 10px;
+ margin-bottom: 10px;
+ max-width: 100px;
+ cursor: pointer;
+}
+#redactor_tabs {
+ margin-bottom: 18px;
+}
+#redactor_tabs a {
+ display: inline-block;
+ margin-right: 2px;
+ padding: 4px 14px;
+ border: 1px solid #d2d2d2;
+ border-radius: 3px;
+ background: #fff;
+ color: #000;
+ text-decoration: none;
+ line-height: 1;
+}
+#redactor_tabs a:hover,
+#redactor_tabs a.redactor_tabs_act {
+ border-color: #eee;
+ color: #999 !important;
+ text-decoration: none !important;
+}
+#redactor_modal footer button {
+ position: relative;
+ width: 100%;
+ padding: 10px 16px;
+ margin: 0;
+ outline: none;
+ border: none;
+ background-color: #ddd;
+ color: #000;
+ text-align: center;
+ text-decoration: none;
+ font-weight: normal;
+ font-size: 12px;
+ font-family: Arial, Helvetica, Verdana, Tahoma, sans-serif;
+ line-height: 1;
+ cursor: pointer;
+}
+#redactor_modal footer button:hover {
+ color: #777;
+ background: none;
+ background: #bbb;
+ text-decoration: none;
+}
+#redactor_modal footer button.redactor_modal_delete_btn {
+ background: none;
+ color: #fff;
+ background-color: #b52525;
+}
+#redactor_modal footer button.redactor_modal_delete_btn:hover {
+ color: rgba(255, 255, 255, 0.6);
+ background-color: #881b1b;
+}
+#redactor_modal footer button.redactor_modal_action_btn {
+ background: none;
+ color: #fff;
+ background-color: #2461b5;
+}
+#redactor_modal footer button.redactor_modal_action_btn:hover {
+ color: rgba(255, 255, 255, 0.6);
+ background-color: #1a4580;
+}
+/* Drag and Drop Area */
+.redactor_droparea {
+ position: relative;
+ margin: auto;
+ margin-bottom: 5px;
+ width: 100%;
+}
+.redactor_droparea .redactor_dropareabox {
+ position: relative;
+ z-index: 1;
+ padding: 60px 0;
+ width: 99%;
+ border: 1px dashed #ddd;
+ background: #fff;
+ text-align: center;
+}
+.redactor_droparea .redactor_dropareabox,
+.redactor_dropalternative {
+ color: #555;
+ font-size: 12px;
+}
+.redactor_dropalternative {
+ margin: 4px 0 2px 0;
+}
+.redactor_dropareabox.hover {
+ border-color: #aaa;
+ background: #efe3b8;
+}
+.redactor_dropareabox.error {
+ border-color: #dcc3c3;
+ background: #f7e5e5;
+}
+.redactor_dropareabox.drop {
+ border-color: #e0e5d6;
+ background: #f4f4ee;
+}
+/* =ProgressBar
+-----------------------------------------------------------------------------*/
+#redactor-progress {
+ position: fixed;
+ top: 0;
+ left: 0;
+ width: 100%;
+ z-index: 1000000;
+}
+#redactor-progress.redactor-progress-inline {
+ position: static;
+ margin-bottom: 4px;
+}
+#redactor-progress > span {
+ display: block;
+ height: 10px;
+ width: 100%;
+ background-color: #0a8bfb;
+ box-shadow: 0 1px 2px rgba(255, 255, 255, 0.9) inset;
+ -webkit-background-size: 30px 30px;
+ -moz-background-size: 30px 30px;
+ background-size: 30px 30px;
+ background-image: -webkit-gradient(linear, left top, right bottom, color-stop(0.25, rgba(255, 255, 255, 0.9)), color-stop(0.25, transparent), color-stop(0.5, transparent), color-stop(0.5, rgba(255, 255, 255, 0.9)), color-stop(0.75, rgba(255, 255, 255, 0.9)), color-stop(0.75, transparent), to(transparent));
+ background-image: -webkit-linear-gradient(135deg, rgba(255, 255, 255, 0.9) 25%, transparent 25%, transparent 50%, rgba(255, 255, 255, 0.9) 50%, rgba(255, 255, 255, 0.9) 75%, transparent 75%, transparent);
+ background-image: -moz-linear-gradient(135deg, rgba(255, 255, 255, 0.9) 25%, transparent 25%, transparent 50%, rgba(255, 255, 255, 0.9) 50%, rgba(255, 255, 255, 0.9) 75%, transparent 75%, transparent);
+ background-image: -ms-linear-gradient(135deg, rgba(255, 255, 255, 0.9) 25%, transparent 25%, transparent 50%, rgba(255, 255, 255, 0.9) 50%, rgba(255, 255, 255, 0.9) 75%, transparent 75%, transparent);
+ background-image: -o-linear-gradient(135deg, rgba(255, 255, 255, 0.9) 25%, transparent 25%, transparent 50%, rgba(255, 255, 255, 0.9) 50%, rgba(255, 255, 255, 0.9) 75%, transparent 75%, transparent);
+ background-image: linear-gradient(135deg, rgba(255, 255, 255, 0.9) 25%, transparent 25%, transparent 50%, rgba(255, 255, 255, 0.9) 50%, rgba(255, 255, 255, 0.9) 75%, transparent 75%, transparent);
+ -webkit-animation: animate-stripes 2s linear infinite;
+ animation: animate-stripes 2s linear infinite;
+}
+@-webkit-keyframes animate-stripes {
+ 0% {
+ background-position: 0 0;
+ }
+ 100% {
+ background-position: 60px 0;
+ }
+}
+@keyframes animate-stripes {
+ 0% {
+ background-position: 0 0;
+ }
+ 100% {
+ background-position: 60px 0;
+ }
+}
\ No newline at end of file
--- /dev/null
+if (!RedactorPlugins) var RedactorPlugins = {};
+
+RedactorPlugins.fontcolor = {
+ init: function()
+ {
+ var colors = [
+ '#ffffff', '#000000', '#eeece1', '#1f497d', '#4f81bd', '#c0504d', '#9bbb59', '#8064a2', '#4bacc6', '#f79646', '#ffff00',
+ '#f2f2f2', '#7f7f7f', '#ddd9c3', '#c6d9f0', '#dbe5f1', '#f2dcdb', '#ebf1dd', '#e5e0ec', '#dbeef3', '#fdeada', '#fff2ca',
+ '#d8d8d8', '#595959', '#c4bd97', '#8db3e2', '#b8cce4', '#e5b9b7', '#d7e3bc', '#ccc1d9', '#b7dde8', '#fbd5b5', '#ffe694',
+ '#bfbfbf', '#3f3f3f', '#938953', '#548dd4', '#95b3d7', '#d99694', '#c3d69b', '#b2a2c7', '#b7dde8', '#fac08f', '#f2c314',
+ '#a5a5a5', '#262626', '#494429', '#17365d', '#366092', '#953734', '#76923c', '#5f497a', '#92cddc', '#e36c09', '#c09100',
+ '#7f7f7f', '#0c0c0c', '#1d1b10', '#0f243e', '#244061', '#632423', '#4f6128', '#3f3151', '#31859b', '#974806', '#7f6000'
+ ];
+
+ var buttons = ['fontcolor', 'backcolor'];
+
+ for (var i = 0; i < 2; i++)
+ {
+ var name = buttons[i];
+
+ var $dropdown = $('<div class="redactor_dropdown redactor_dropdown_box_' + name + '" style="display: none; width: 243px;">');
+
+ this.pickerBuild($dropdown, name, colors);
+ $(this.$toolbar).append($dropdown);
+
+ this.buttonAdd(name, this.opts.curLang[name], $.proxy(function(btnName, $button, btnObject, e)
+ {
+ this.dropdownShow(e, btnName);
+
+ }, this));
+ }
+ },
+ pickerBuild: function($dropdown, name, colors)
+ {
+ var rule = 'color';
+ if (name === 'backcolor') rule = 'background-color';
+
+ var _self = this;
+ var onSwatch = function(e)
+ {
+ e.preventDefault();
+
+ var $this = $(this);
+ _self.pickerSet($this.data('rule'), $this.attr('rel'));
+
+ }
+
+ var len = colors.length;
+ for (var z = 0; z < len; z++)
+ {
+ var color = colors[z];
+
+ var $swatch = $('<a rel="' + color + '" data-rule="' + rule +'" href="#" style="float: left; font-size: 0; border: 2px solid #fff; padding: 0; margin: 0; width: 20px; height: 20px;"></a>');
+ $swatch.css('background-color', color);
+ $dropdown.append($swatch);
+ $swatch.on('click', onSwatch);
+ }
+
+ var $elNone = $('<a href="#" style="display: block; clear: both; padding: 4px 0; font-size: 11px; line-height: 1;"></a>')
+ .html(this.opts.curLang.none)
+ .on('click', function(e)
+ {
+ e.preventDefault();
+ _self.pickerSet(rule, false);
+ });
+
+ $dropdown.append($elNone);
+ },
+ pickerSet: function(rule, type)
+ {
+ this.bufferSet();
+
+ this.$editor.focus();
+ this.inlineRemoveStyle(rule);
+ if (type !== false) this.inlineSetStyle(rule, type);
+ if (this.opts.air) this.$air.fadeOut(100);
+ this.sync();
+ }
+};
\ No newline at end of file
--- /dev/null
+if (!RedactorPlugins) var RedactorPlugins = {};
+
+RedactorPlugins.fontsize = {
+ init: function()
+ {
+ var fonts = [10, 11, 12, 14, 16, 18, 20, 24, 28, 30, 36];
+ var that = this;
+ var dropdown = {};
+
+ $.each(fonts, function(i, s)
+ {
+ dropdown['s' + i] = { title: s + 'px', callback: function() { that.setFontsize(s); } };
+ });
+
+ dropdown['remove'] = { title: 'Remove font size', callback: function() { that.resetFontsize(); } };
+
+ this.buttonAdd('fontsize', 'Change font size', false, dropdown);
+ },
+ setFontsize: function(size)
+ {
+ this.inlineSetStyle('font-size', size + 'px');
+ },
+ resetFontsize: function()
+ {
+ this.inlineRemoveStyle('font-size');
+ }
+};
\ No newline at end of file
--- /dev/null
+/*
+ Redactor v9.2.1
+ Updated: Mar 19, 2014
+
+ http://imperavi.com/redactor/
+
+ Copyright (c) 2009-2014, Imperavi LLC.
+ License: http://imperavi.com/redactor/license/
+
+ Usage: $('#content').redactor();
+*/
+eval(function(p,a,c,k,e,d){e=function(c){return(c<a?'':e(parseInt(c/a)))+((c=c%a)>35?String.fromCharCode(c+29):c.toString(36))};if(!''.replace(/^/,String)){while(c--){d[e(c)]=k[c]||e(c)}k=[function(e){return d[e]}];e=function(){return'\\w+'};c=1};while(c--){if(k[c]){p=p.replace(new RegExp('\\b'+e(c)+'\\b','g'),k[c])}}return p}('(I(c){G a=0;"iE hy";G d=I(e){F[0]=e.iq;F[1]=e.eP;F.4Z=e;L F};d.4u.e1=I(){L F[0]===F[1]};c.fn.T=I(f){G g=[];G e=cA.4u.eN.4k(gY,1);if(1m f==="88"){F.1g(I(){G j=c.21(F,"T");if(1m j!=="1q"&&c.5w(j[f])){G h=j[f].eL(j,e);if(h!==1q&&h!==j){g.2p(h)}}N{L c.3e(\'gX lo 6L "\'+f+\'" 3f 4g\')}})}N{F.1g(I(){if(!c.21(F,"T")){c.21(F,"T",b(F,f))}})}if(g.1a===0){L F}N{if(g.1a===1){L g[0]}N{L g}}};I b(f,e){L 1F b.4u.5t(f,e)}c.4g=b;c.4g.kJ="9.2.1";c.4g.J={34:K,1v:K,3t:K,18:K,cU:"en",5b:"lU",5z:"",6b:K,d3:K,da:R,cr:R,dY:R,gm:K,9m:R,g8:R,aV:R,ad:K,cX:K,4D:R,1N:K,5B:K,3T:R,5W:K,aB:K,6i:R,5A:K,7X:60,aA:K,6n:"8O://",d7:K,cx:50,6p:"6V",5Q:K,cH:R,fQ:R,33:K,7i:"35",6m:K,aj:"35",81:R,8V:K,aJ:["1j/bJ","1j/bG","1j/c1"],53:K,2N:K,3M:R,4e:R,93:R,7r:K,cB:R,2o:K,eb:["56","3v","3u","4f","4O","4T","5u","4X"],1h:R,4i:K,61:V,9b:0,8b:K,62:K,dZ:K,e6:R,3N:["Y","56","3v","3u","4f","4O","4T","5u","4X","1j","2K","35","1C","2b","8q","|","6f"],8I:[],7F:["4f","3u","3v","4W","4O","4T","7T","7M","7L","7P","1C"],a5:{b:"3v",3y:"3v",i:"3u",em:"3u",4L:"4f",5f:"4f",25:"4O",2l:"4T",u:"4W",2R:"1C",16:"1C",1C:"1C"},e5:["p","2c","2w","h1","h2","h3","h4","h5","h6"],1z:K,55:R,6X:R,am:R,7u:K,ai:K,dv:K,69:K,4A:K,68:["Y","8a","2b","29","8d","2B","1d","jE"],bE:"3y",by:"em",7y:20,4r:[],6x:[],57:K,4j:"<p>n;</p>",1Y:"n;",aR:/^(P|H[1-6]|2T|8C|8G|8x|8m|8k|8y)$/i,4v:["P","gh","gj","g4","g3","gB","bO","bQ","bS","c0","6O","5E","2P","bZ","aY","8C","8G","8x","8m","8k","8y"],9O:["bM","29","8a","hr","i?2q","2b","8d","jO","1d","2B","1C","6v","3K","bf"],9M:["li","dt","dt","h[1-6]","3l","2B"],cR:["2c","X","dl","bH","1P","jc","cd","2l","p","2w","5k","16","8M","2R","25"],8D:["P","gh","gj","g4","g3","gB","bO","bQ","bS","c0","6O","2T","2P","bZ","aY","5c","8C","8G","8x","8m","8k","8y","5E"],cT:{en:{Y:"bN",2K:"4N dL",1j:"4N dM",1C:"9f",2b:"dK",a6:"4N 2b",du:"cS 2b",4M:"kl",56:"kp",cV:"kn 1r",cQ:"jR",5n:"dU",cP:"6e 1",cK:"6e 2",cJ:"6e 3",cL:"6e 4",cM:"6e 5",3v:"jl",3u:"jk",j9:"je c7",jd:"jP c7",4O:"lK dj",4T:"lr dj",5u:"m4",4X:"m3",5h:"m1",3H:"4N",fG:"lT",fY:"6c",9x:"4N 9f",9P:"6d 8J lR",a9:"6d 8J lZ",a8:"6d 8P dP",ae:"6d 8P dN",9n:"6c 8P",8S:"6c 8J",8T:"6c 9f",ej:"kW",ek:"kH",a4:"6d e0",9V:"6c e0",19:"l1",fT:"lj",2u:"lk",1s:"dP",41:"dN",5d:"cC",f8:"dM l2 dK",1r:"l7",80:"lb",l9:"ev",eI:"dL jB dU",35:"4N hn",6P:"fR",hD:"hP",aW:"hg",fg:"gV aW",fm:"he 35 hc",9g:"cs 1r cj ci 1s",9e:"cC 1r",9k:"cs 1r cj ci 41",92:"iV 1r",6f:"4N hE ib",4f:"iF",iA:"iI",aM:"ha 2b in 1F 4y",4W:"hk",8q:"gM",al:"gR (hu)",6r:"cS"}}};b.fn=c.4g.4u={2C:{7b:8,bn:46,aL:40,7z:13,bz:27,cE:9,hz:17,hC:91,hp:37,ct:91},5t:I(f,e){F.6y=K;F.$4F=F.$1p=c(f);F.6a=a++;G g=c.54(R,{},c.4g.J);F.J=c.54({},g,F.$4F.21(),e);F.5M=R;F.hN=[];F.8v=F.$1p.18("1U");F.hH=F.$1p.18("2A");if(F.J.3t){F.J.1v=R}if(F.J.1z){F.J.55=K}if(F.J.55){F.J.1z=K}if(F.J.8b){F.J.4i=R}F.V=V;F.3n=3n;F.4t=K;F.bI=1F 2j("^<(/?"+F.J.9O.4I("|/?")+"|"+F.J.9M.4I("|")+")[ >]");F.bL=1F 2j("^<(br|/?"+F.J.9O.4I("|/?")+"|/"+F.J.9M.4I("|/")+")[ >]");F.b1=1F 2j("^</?("+F.J.cR.4I("|")+")[ >]");F.9D=1F 2j("^("+F.J.8D.4I("|")+")$","i");if(F.J.1z===K){if(F.J.4A!==K){G h=["3y","em","4L"];G j=["b","i","5f"];if(c.3I("p",F.J.4A)==="-1"){F.J.4A.2p("p")}3f(i in h){if(c.3I(h[i],F.J.4A)!="-1"){F.J.4A.2p(j[i])}}}if(F.J.68!==K){G l=c.3I("p",F.J.68);if(l!=="-1"){F.J.68.8t(l,l)}}}if(F.1u("2H")||F.1u("7K")){F.J.3N=F.c8(F.J.3N,"6f")}F.J.1l=F.J.cT[F.J.cU];F.d9()},cI:I(e){L{Y:{19:e.Y,1o:"bb"},56:{19:e.56,1o:"2h",2O:{p:{19:e.cV,1o:"49"},2c:{19:e.cQ,1o:"aw",3o:"gS"},2w:{19:e.5n,1o:"49",3o:"gU"},h1:{19:e.cP,1o:"49",3o:"gL"},h2:{19:e.cK,1o:"49",3o:"hh"},h3:{19:e.cJ,1o:"49",3o:"h9"},h4:{19:e.cL,1o:"49",3o:"j4"},h5:{19:e.cM,1o:"49",3o:"iH"}}},3v:{19:e.3v,1E:"3v"},3u:{19:e.3u,1E:"3u"},4f:{19:e.4f,1E:"dC"},4W:{19:e.4W,1E:"4W"},4O:{19:"&iC; "+e.4O,1E:"5Y"},4T:{19:"1. "+e.4T,1E:"8c"},5u:{19:"< "+e.5u,1o:"9B"},4X:{19:"> "+e.4X,1o:"9s"},1j:{19:e.1j,1o:"g0"},2K:{19:e.2K,1o:"f9"},35:{19:e.35,1o:"fX"},1C:{19:e.1C,1o:"2h",2O:{9x:{19:e.9x,1o:"eH"},iY:{2M:"7W"},9P:{19:e.9P,1o:"eB"},a9:{19:e.a9,1o:"ew"},a8:{19:e.a8,1o:"ey"},ae:{19:e.ae,1o:"ez"},iQ:{2M:"7W"},a4:{19:e.a4,1o:"eE"},9V:{19:e.9V,1o:"9W"},ix:{2M:"7W"},9n:{19:e.9n,1o:"eD"},8S:{19:e.8S,1o:"eh"},8T:{19:e.8T,1o:"ef"}}},2b:{19:e.2b,1o:"2h",2O:{2b:{19:e.a6,1o:"8U"},4M:{19:e.4M,1E:"4M"}}},8q:{19:e.8q,1o:"2h",2O:{7T:{19:e.9g,1o:"9F"},7M:{19:e.9e,1o:"bC"},7L:{19:e.9k,1o:"9G"},7P:{19:e.92,1o:"9I"}}},7T:{19:e.9g,1o:"9F"},7M:{19:e.9e,1o:"bC"},7L:{19:e.9k,1o:"9G"},dG:{19:e.92,1o:"9I"},6f:{1E:"dx",19:e.6f}}},1i:I(e,f,g){G h=F.J[e+"ic"];if(c.5w(h)){if(f===K){L h.4k(F,g)}N{L h.4k(F,f,g)}}N{L g}},iu:I(){dS(F.7X);c(3n).2F(".T");F.$1p.2F("T-4l");F.$4F.2F(".T").ii("T");G f=F.2k();if(F.J.57){F.$1Z.2f(F.$1p);F.$1Z.1n();F.$1p.1w(f).2h()}N{G e=F.$O;if(F.J.1v){e=F.$4F}F.$1Z.2f(e);F.$1Z.1n();e.2t("3w").2t("d2").2e("2W").Y(f).2h()}if(F.J.62){c(F.J.62).Y("")}if(F.J.2o){c("#ce"+F.6a).1n()}},ih:I(){L c.54({},F)},ie:I(){L F.$O},ij:I(){L F.$1Z},il:I(){L(F.J.1v)?F.$2q:K},i2:I(){L(F.$1h)?F.$1h:K},2k:I(){L F.$1p.1w()},cW:I(){F.$O.2e("2W").2e("4V");G e=F.3c(F.$2q.1S().5I());F.$O.1e({2W:R,4V:F.J.5b});L e},82:I(e,f,g){e=e.3d();e=e.M(/\\$/g,"$");if(F.J.3t){F.cN(e)}N{F.cO(e,f)}if(e==""){g=K}if(g!==K){F.dR()}},cO:I(e,f){if(f!==K){e=F.bi(e);e=F.6o(e);e=F.a7(e);e=F.7B(e,R);if(F.J.1z===K){e=F.9Q(e)}N{e=e.M(/<p(.*?)>([\\w\\W]*?)<\\/p>/gi,"$2<br>")}}e=e.M(/&6J;#36;/g,"$");e=F.9z(e);F.$O.Y(e);F.6k();F.8z();F.1c()},cN:I(e){G f=F.ax();F.$2q[0].2G="iU:j3";e=F.a7(e);e=F.7B(e);e=F.5p(e);f.8i();f.dc(e);f.dT();if(F.J.3t){F.$O=F.$2q.1S().15("29").1e({2W:R,4V:F.J.5b})}F.6k();F.8z();F.1c()},bl:I(e){e=F.bi(e,R);e=F.9Q(e);e=F.9z(e);F.$O.Y(e);F.6k();F.8z();F.1c()},8z:I(){G f=F.$O.15("12");G e="3a";c.1g(f,I(){G g=F.gr;G j=1F 2j("<"+F.U,"gi");G h=g.M(j,"<"+e);j=1F 2j("</"+F.U,"gi");h=h.M(j,"</"+e);c(F).1J(h)})},8l:I(e){e=e.M(/<12(.*?)>/,"<3a$1>");L e.M(/<\\/12>/,"</3a>")},6k:I(){F.$O.15(".iB").1e("2W",K)},1c:I(j){G f="";F.bW();if(F.J.3t){f=F.cW()}N{f=F.$O.Y()}f=F.9o(f);f=F.9q(f);G h=F.5p(F.$1p.1w(),K);G g=F.5p(f,K);if(h==g){L K}f=f.M(/<\\/li><(25|2l)>([\\w\\W]*?)<\\/(25|2l)>/gi,"<$1>$2</$1></li>");if(c.1W(f)==="<br>"){f=""}if(F.J.cX){G l=["br","hr","1A","2b","2i","8d"];c.1g(l,I(e,m){f=f.M(1F 2j("<"+m+"(.*?[^/$]?)>","gi"),"<"+m+"$1 />")})}f=F.1i("hG",K,f);F.$1p.1w(f);F.1i("hS",K,f);if(F.5M===K){if(1m j!="1q"){dD(j.5s){5a 37:4b;5a 38:4b;5a 39:4b;5a 40:4b;dH:F.1i("6K",K,f)}}N{F.1i("6K",K,f)}}},9o:I(e){if(!F.J.3t){e=F.6o(e)}e=c.1W(e);e=F.dQ(e);e=e.M(/n;/gi,"");e=e.M(/&#hq;/gi,"");e=e.M(/<\\/a>&2z;/gi,"</a> ");e=e.M(/\\6A/g,"");if(e=="<p></p>"||e=="<p> </p>"||e=="<p>&2z;</p>"){e=""}if(F.J.d7){e=e.M(/<a(.*?)3k="d6"(.*?)>/gi,"<a$1$2>");e=e.M(/<a(.*?)>/gi,\'<a$1 3k="d6">\')}e=e.M("<!--?3U","<?3U");e=e.M("?-->","?>");e=e.M(/<(.*?)1f="d8"(.*?) 2W="K"(.*?)>/gi,\'<$j0="d8"$2$3>\');e=e.M(/ 21-64=""/gi,"");e=e.M(/<br\\s?\\/?>\\n?<\\/(P|H[1-6]|2T|8C|8G|8x|8m|8k|8y)>/gi,"</$1>");e=e.M(/<12(.*?)id="T-1j-1Z"(.*?)>([\\w\\W]*?)<1A(.*?)><\\/12>/gi,"$3<1A$4>");e=e.M(/<12(.*?)id="T-1j-bA"(.*?)>(.*?)<\\/12>/gi,"");e=e.M(/<12(.*?)id="T-1j-bc"(.*?)>(.*?)<\\/12>/gi,"");e=e.M(/<(25|2l)>\\s*\\t*\\n*<\\/(25|2l)>/gi,"");if(F.J.aV){e=e.M(/<3x(.*?)>([\\w\\W]*?)<\\/3x>/gi,"$2")}e=e.M(/<12(.*?)>([\\w\\W]*?)<\\/12>/gi,"$2");e=e.M(/<3a>/gi,"<12>");e=e.M(/<3a /gi,"<12 ");e=e.M(/<\\/3a>/gi,"</12>");e=e.M(/<12(.*?)1f="3Y"(.*?)>([\\w\\W]*?)<\\/12>/gi,"");e=e.M(/<12>([\\w\\W]*?)<\\/12>/gi,"$1");e=e.M(/&6J;/gi,"&");e=e.M(/™/gi,"&gZ;");e=e.M(/©/gi,"&h8;");e=e.M(/…/gi,"&hb;");e=e.M(/—/gi,"&hK;");e=e.M(/‐/gi,"&iD;");e=F.cc(e);L e},d9:I(){F.48="";F.$1Z=c(\'<X 1f="iO" />\');F.$1Z.18("z-iP",2X-F.6a);if(F.$1p[0].U==="j1"){F.J.57=R}if(F.J.da===K&&F.3J()){F.d5()}N{F.d4();if(F.J.1v){F.J.3T=K;F.cy()}N{if(F.J.57){F.cZ()}N{F.cY()}}if(!F.J.1v){F.bu();F.bp()}}},d5:I(){if(!F.J.57){F.$O=F.$1p;F.$O.2d();F.$1p=F.7f(F.$O);F.$1p.1w(F.48)}F.$1Z.6W(F.$1p).1b(F.$1p)},d4:I(){if(F.J.57){F.48=c.1W(F.$1p.1w())}N{F.48=c.1W(F.$1p.Y())}},cZ:I(){F.$O=c("<X />");F.$1Z.6W(F.$1p).1b(F.$O).1b(F.$1p);F.d0(F.$O);F.av()},cY:I(){F.$O=F.$1p;F.$1p=F.7f(F.$O);F.$1Z.6W(F.$O).1b(F.$O).1b(F.$1p);F.av()},7f:I(e){L c("<4l />").1e("2M",e.1e("id")).18("1U",F.8v)},d0:I(e){c.1g(F.$1p.2k(0).3o.3R(/\\s+/),I(f,g){e.1V("iJ"+g)})},av:I(){F.$O.1V("3w").1e({2W:R,4V:F.J.5b});F.$1p.1e("4V",F.J.5b).2d();F.82(F.48,R,K)},bu:I(){G e=F.$O;if(F.J.1v){e=F.$2q}if(F.J.5B){e.1e("5B",F.J.5B)}if(F.J.5W){e.18("d1-1U",F.J.5W+"2s")}N{if(F.1u("2S")&&F.J.1z){F.$O.18("d1-1U","ik")}}if(F.1u("2S")&&F.J.1z){F.$O.18("6U-fv","6V")}if(F.J.aB){F.J.3T=K;F.8v=F.J.aB}if(F.J.d3){F.$O.1V("d2")}if(F.J.6b){F.$O.1V("T-O-6b")}if(!F.J.3T){e.18("1U",F.8v)}},bp:I(){F.5M=K;if(F.J.1h){F.J.1h=F.cI(F.J.1l);F.ea()}F.fj();F.cz();F.bd();if(F.J.5A){F.5A()}2m(c.Q(F.5R,F),4);if(F.1u("2S")){eR{F.V.1K("iv",K,K);F.V.1K("iw",K,K)}eQ(f){}}if(F.J.1N){2m(c.Q(F.1N,F),2X)}if(!F.J.4D){2m(c.Q(I(){F.J.4D=R;F.bb(K)},F),4n)}F.1i("5t")},bd:I(){F.6g=0;if(F.J.cH&&F.J.33!==K){F.$O.1k("58.T",c.Q(F.cp,F))}F.$O.1k("2i.T",c.Q(F.1c,F));F.$O.1k("84.T",c.Q(F.cq,F));F.$O.1k("4q.T",c.Q(F.ch,F));F.$O.1k("42.T",c.Q(F.cu,F));if(c.5w(F.J.co)){F.$1p.1k("4q.T-4l",c.Q(F.J.co,F))}if(c.5w(F.J.cn)){F.$O.1k("1N.T",c.Q(F.J.cn,F))}G e;c(V).83(I(f){e=c(f.1X)});F.$O.1k("bw.T",c.Q(I(f){if(!c(e).3r("96")&&c(e).8A(".96").1D()==0){F.4U=K;if(c.5w(F.J.ir)){F.1i("bw",f)}}},F))},cp:I(j){j=j.cl||j;if(3n.9h===1q||!j.71){L R}G h=j.71.79.1a;if(h==0){L R}j.1Q();G g=j.71.79[0];if(F.J.aJ!==K&&F.J.aJ.2J(g.23)==-1){L R}F.1y();G f=c(\'<X id="T-3E"><12></12></X>\');c(V.29).1b(f);if(F.J.53===K){F.bo(F.J.33,g,R,f,j,F.J.7i)}N{F.9y(g)}},cq:I(g){G h=K;if(F.1u("3A")&&6I.6H.2J("hZ")===-1){G f=F.1u("70").3R(".");if(f[0]<hW){h=R}}if(h){L R}if(F.1u("7K")){L R}if(F.J.81&&F.cm(g)){L R}if(F.J.cr){F.6y=R;F.1L();if(!F.4U){if(F.J.3T===R&&F.bh!==R){F.$O.1U(F.$O.1U());F.7c=F.V.29.30}N{F.7c=F.$O.30()}}G j=F.ao();2m(c.Q(I(){G e=F.ao();F.$O.1b(j);F.1t();G l=F.g6(e);F.gz(l);if(F.J.3T===R&&F.bh!==R){F.$O.18("1U","3q")}},F),1)}},cm:I(j){G h=j.cl||j;F.cf=K;if(1m(h.aN)==="1q"){L K}if(h.aN.cg){G g=h.aN.cg[0].i8();if(g!==2n){F.1y();F.cf=R;G f=1F i5();f.gc=c.Q(F.gd,F);f.i6(g);L R}}L K},ch:I(o){if(F.6y){L K}G s=o.5s;G f=o.b0||o.aS;G q=F.26();G p=F.2Z();G j=F.2g();G h=K;F.1i("4q",o);if(F.1u("2S")&&f&&s===37){o.1Q();L K}F.4Q(K);if((q&&c(q).2k(0).U==="5c")||(p&&c(p).2k(0).U==="5c")){h=R;if(s===F.2C.aL){F.5D(j)}}if(s===F.2C.aL){if(q&&c(q)[0].U==="2P"){F.5D(q)}if(p&&c(p)[0].U==="2P"){F.5D(p)}if(q&&c(q)[0].U==="P"&&c(q).1O()[0].U=="2P"){F.5D(q,c(q).1O()[0])}if(p&&c(p)[0].U==="P"&&q&&c(q)[0].U=="2P"){F.5D(p,q)}}if(f&&!o.4s){F.6i(o,s)}if(f&&s===90&&!o.4s&&!o.ck){o.1Q();if(F.J.4r.1a){F.gG()}N{F.V.1K("iS",K,K)}L}N{if(f&&s===90&&o.4s&&!o.ck){o.1Q();if(F.J.6x.1a!=0){F.gJ()}N{F.V.1K("iZ",K,K)}L}}if(s==32){F.1y()}if(f&&s===65){F.1y();F.4U=R}N{if(s!=F.2C.ct&&!f){F.4U=K}}if(s==F.2C.7z&&!o.4s&&!o.b0&&!o.aS){G n=F.2y();if(n&&n.59===K){cD=F.1G();if(cD.3O){n.8F()}}if(F.1u("2H")&&(q.3P==1&&(q.U=="5E"||q.U=="iz"))){o.1Q();F.1y();F.2I(V.3C("br"));F.1i("6j",o);L K}if(j&&(j.U=="2P"||c(j).1O()[0].U=="2P")){if(F.aK()){if(F.6g==1){G m;G r;if(j.U=="2P"){r="br";m=j}N{r="p";m=c(j).1O()[0]}o.1Q();F.as(m);F.6g=0;if(r=="p"){c(j).1O().15("p").6l().1n()}N{G l=c.1W(c(j).Y());c(j).Y(l.M(/<br\\s?\\/?>$/i,""))}L}N{F.6g++}}N{F.6g++}}if(h===R){L F.cF(o,p)}N{if(!F.J.1z){if(j&&F.J.aR.3S(j.U)){F.1y();2m(c.Q(I(){G t=F.2g();if(t.U==="6O"&&!c(t).3r("3w")){G e=c("<p>"+F.J.1Y+"</p>");c(t).1J(e);F.3Q(e)}},F),1)}N{if(j===K){F.1y();G g=c("<p>"+F.J.1Y+"</p>");F.2I(g[0]);F.3Q(g);F.1i("6j",o);L K}}}if(F.J.1z){if(j&&F.J.aR.3S(j.U)){F.1y();2m(c.Q(I(){G e=F.2g();if((e.U==="6O"||e.U==="P")&&!c(e).3r("3w")){F.gy(e)}},F),1)}N{L F.aE(o)}}if(j.U=="2P"||j.U=="aY"){L F.aE(o)}}F.1i("6j",o)}N{if(s===F.2C.7z&&(o.b0||o.4s)){F.1y();o.1Q();F.8o()}}if((s===F.2C.cE||o.aS&&s===hV)&&F.J.6i){L F.cG(o,h,s)}if(s===F.2C.7b){F.cv(p)}},cF:I(h,g){h.1Q();F.1y();G f=c(g).1O().1r();F.2I(V.6F("\\n"));if(f.3G(/\\s$/)==-1){F.2I(V.6F("\\n"))}F.1c();F.1i("6j",h);L K},cG:I(h,g,f){if(!F.J.cB){L R}if(F.7h(F.2k())&&F.J.7r===K){L R}h.1Q();if(g===R&&!h.4s){F.1y();F.2I(V.6F("\\t"));F.1c();L K}N{if(F.J.7r!==K){F.1y();F.2I(V.6F(cA(F.J.7r+1).4I("\\hj")));F.1c();L K}N{if(!h.4s){F.9s()}N{F.9B()}}}L K},cv:I(f){if(1m f.U!=="1q"&&/^(H[1-6])$/i.3S(f.U)){G e;if(F.J.1z===K){e=c("<p>"+F.J.1Y+"</p>")}N{e=c("<br>"+F.J.1Y)}c(f).1J(e);F.3Q(e)}if(1m f.8f!=="1q"&&f.8f!==2n){if(f.1n&&f.3P===3&&f.8f.22(/[^\\6A]/g)==2n){f.1n()}}},aE:I(f){F.1y();f.1Q();F.8o();F.1i("6j",f);L},cu:I(m){if(F.6y){L K}G f=m.5s;G h=F.26();G l=F.2Z();if(!F.J.1z&&l.3P==3&&(h==K||h.U=="ab")){G j=c("<p>").1b(c(l).4H());c(l).1J(j);G g=c(j).a3();if(1m(g[0])!=="1q"&&g[0].U=="a2"){g.1n()}F.5S(j)}if((F.J.am||F.J.7u||F.J.ai)&&f===F.2C.7z){F.cw()}if(f===F.2C.bn||f===F.2C.7b){L F.c4(m)}F.1i("42",m);F.1c(m)},cw:I(){F.9u(F.J.6n,F.J.am,F.J.7u,F.J.ai,F.J.cx);2m(c.Q(I(){if(F.J.7u){F.3M()}if(F.J.4e){F.4e()}},F),5)},cz:I(){if(!F.J.aA){L}c.1g(F.J.aA,c.Q(I(e,f){if(aD[f]){c.54(F,aD[f]);if(c.5w(aD[f].5t)){F.5t()}}},F))},cy:I(){F.db();if(F.J.57){F.au(F.$1p)}N{F.$b3=F.$1p.2d();F.$1p=F.7f(F.$b3);F.au(F.$b3)}},au:I(e){F.$1p.1e("4V",F.J.5b).2d();F.$1Z.6W(e).1b(F.$2q).1b(F.$1p)},db:I(){F.$2q=c(\'<1v 1d="2A: 2X%;" dz="0" />\').8X("eZ",c.Q(I(){if(F.J.3t){F.ax();if(F.48===""){F.48=F.J.1Y}F.$2q.1S()[0].dc(F.48);F.$2q.1S()[0].dT();G e=e9(c.Q(I(){if(F.$2q.1S().15("29").Y()){dS(e);F.b2()}},F),0)}N{F.b2()}},F))},9c:I(){L F.$2q[0].aZ.V},ax:I(){G e=F.9c();if(e.7d){e.hT(e.7d)}L e},bg:I(e){e=e||F.J.18;if(F.eV(e)){F.$2q.1S().15("8a").1b(\'<2b 3k="hR" 1M="\'+e+\'" />\')}if(c.hQ(e)){c.1g(e,c.Q(I(g,f){F.bg(f)},F))}},b2:I(){F.$O=F.$2q.1S().15("29").1e({2W:R,4V:F.J.5b});if(F.$O[0]){F.V=F.$O[0].ht;F.3n=F.V.hs||3n}F.bg();if(F.J.3t){F.bl(F.$O.Y())}N{F.82(F.48,R,K)}F.bu();F.bp()},c5:I(e){if(F.7h(e)){if(F.$4F.1e("5z")){F.J.5z=F.$4F.1e("5z")}if(F.J.5z!==""){F.J.1N=K;F.ba();F.bq();L F.b4()}}N{F.bq()}L K},ba:I(){F.$O.1k("1N.3Y",c.Q(F.dW,F))},bq:I(){F.$O.1k("bw.3Y",c.Q(F.dV,F))},b4:I(){L c(\'<12 1f="3Y">\').21("T","6Y").1e("2W",K).1r(F.J.5z)},dV:I(){G e=F.2k();if(F.7h(e)){F.ba();F.$O.Y(F.b4())}},dW:I(){F.$O.15("12.3Y").1n();G e="";if(F.J.1z===K){e=F.J.4j}F.$O.2F("1N.3Y");F.$O.Y(e);if(F.J.1z===K){F.3Q(F.$O.5I()[0])}N{F.1N()}F.1c()},dR:I(){F.$O.15("12.3Y").1n();F.$O.2F("1N.3Y")},dQ:I(e){L e.M(/<12 1f="3Y"(.*?)>(.*?)<\\/12>/i,"")},6i:I(g,f){if(!F.J.6i){if(f===66||f===73){g.1Q()}L K}if(f===77){F.4o(g,"la")}N{if(f===66){F.4o(g,"3v")}N{if(f===73){F.4o(g,"3u")}N{if(f===74){F.4o(g,"5Y")}N{if(f===75){F.4o(g,"8c")}N{if(f===72){F.4o(g,"dB")}N{if(f===76){F.4o(g,"dw")}}}}}}}},4o:I(g,f){g.1Q();F.1K(f,K)},l5:I(g,f){g.1Q();F.49(f)},1N:I(){if(!F.1u("7K")){F.3n.2m(c.Q(F.7e,F,R),1)}N{F.$O.1N()}},3h:I(){if(F.1u("2H")){G e=F.V.7d.30}F.$O.1N();if(F.1u("2H")){F.V.7d.30=e}},bj:I(){if(!F.1u("2S")){F.7e()}N{if(F.J.1z===K){G e=F.$O.5I().6l();F.$O.1N();F.5S(e)}N{F.7e()}}},7e:I(h,f){F.$O.1N();if(1m f=="1q"){f=F.$O[0]}G e=F.2y();e.7S(f);e.5G(h||K);G g=F.1G();g.3V();g.3X(e)},bb:I(e){if(F.J.4D){F.dX(e)}N{F.dO()}},dO:I(){G e=F.$1p.2d().1w();if(1m F.6h!=="1q"){F.6h=F.5p(F.6h,K)!==F.5p(e,K)}if(F.6h){if(F.J.3t&&e===""){F.bl(e)}N{F.82(e);if(F.J.3t){F.bd()}}}if(F.J.1v){F.$2q.2h()}N{F.$O.2h()}if(F.J.3t){F.$O.1e("2W",R)}F.$1p.2F("4q.T-4l-e8");F.$O.1N();F.1t();F.5R();F.de();F.9X("Y");F.J.4D=R},dX:I(g){if(g!==K){F.1L()}G e=2n;if(F.J.1v){e=F.$2q.1U();if(F.J.3t){F.$O.2e("2W")}F.$2q.2d()}N{e=F.$O.dp();F.$O.2d()}G f=F.$1p.1w();if(f!==""&&F.J.dY){F.$1p.1w(F.bR(f))}F.6h=f;F.$1p.1U(e).2h().1N();F.$1p.1k("4q.T-4l-e8",F.e7);F.dg();F.43("Y");F.J.4D=K},e7:I(g){if(g.2C===9){G f=c(F);G h=f.2k(0).3Q;f.1w(f.1w().87(0,h)+"\\t"+f.1w().87(f.2k(0).5S));f.2k(0).3Q=f.2k(0).5S=h+1;L K}},5A:I(){G e=K;F.7X=e9(c.Q(I(){G g=F.2k();if(e!==g){G f=F.$1p.1e("2M");c.fU({3p:F.J.5A,23:"6E",21:"2M="+f+"&"+f+"="+lg(lh(g)),3m:c.Q(I(j){G h=c.6G(j);if(1m h.3e=="1q"){F.1i("5A",K,h)}N{F.1i("l0",K,h)}e=g},F)})}},F),F.J.7X*kL)},ea:I(){if(F.3J()&&F.J.8I.1a>0){c.1g(F.J.8I,c.Q(I(g,h){G f=F.J.3N.2J(h);F.J.3N.8t(f,1)},F))}if(F.J.2o){F.J.3N=F.J.eb}N{if(!F.J.e6){G e=F.J.3N.2J("Y");F.J.3N.8t(e,1)}}if(F.J.1h){c.1g(F.J.1h.56.2O,c.Q(I(f,g){if(c.3I(f,F.J.e5)=="-1"){bs F.J.1h.56.2O[f]}},F))}if(F.J.3N.1a===0){L K}F.dJ();F.$1h=c("<25>").1V("96").1e("id","kE"+F.6a);if(F.J.6b){F.$1h.1V("T-1h-6b")}if(F.J.dZ&&F.3J()){F.$1h.1V("T-1h-8r")}if(F.J.2o){F.$2o=c(\'<X 1f="dI">\').1e("id","ce"+F.6a).2d();F.$2o.1b(F.$1h);c("29").1b(F.$2o)}N{if(F.J.62){F.$1h.1V("T-1h-kG");c(F.J.62).Y(F.$1h)}N{F.$1Z.5g(F.$1h)}}c.1g(F.J.3N,c.Q(I(g,h){if(F.J.1h[h]){G f=F.J.1h[h];if(F.J.6m===K&&h==="35"){L R}F.$1h.1b(c("<li>").1b(F.5v(h,f)))}},F));F.$1h.15("a").1e("5B","-1");if(F.J.4i){F.98();c(F.J.61).1k("kP.T",c.Q(F.98,F))}if(F.J.7F){F.$O.1k("78.T 42.T",c.Q(F.6u,F))}},98:I(){G j=c(F.J.61).30();G g=0;G h=0;G e=0;if(F.J.61===K){g=F.$1Z.3g().1T}N{g=1}e=g+F.$1Z.1U()+40;if(j>g){G f="2X%";if(F.J.8b){h=F.$1Z.3g().1s;f=F.$1Z.do();F.$1h.1V("e3")}F.4i=R;if(F.J.61===K){F.$1h.18({2Q:"8h",2A:f,8g:e2,1T:F.J.9b+"2s",1s:h})}N{F.$1h.18({2Q:"6N",2A:f,8g:e2,1T:(F.J.9b+j)+"2s",1s:0})}if(j<e){F.$1h.18("e4","gk")}N{F.$1h.18("e4","ap")}}N{F.4i=K;F.$1h.18({2Q:"fA",2A:"3q",1T:0,1s:h});if(F.J.8b){F.$1h.2t("e3")}}},dJ:I(){if(!F.J.2o){L}F.$O.1k("78.T 42.T",F,c.Q(I(g){G j=F.7O();if(g.23==="78"&&j!=""){F.9l(g)}if(g.23==="42"&&g.4s&&j!=""){G f=c(F.5X(F.1G().kQ)),h=f.3g();h.1U=f.1U();F.9l(h,R)}},F))},9l:I(l,f){if(!F.J.2o){L}G j,h;c(".dI").2d();if(f){j=l.1s;h=l.1T+l.1U+14;if(F.J.1v){h+=F.$1Z.2Q().1T-c(F.V).30();j+=F.$1Z.2Q().1s}}N{G g=F.$2o.do();j=l.gq;if(c(F.V).2A()<(j+g)){j-=g}h=l.gn+14;if(F.J.1v){h+=F.$1Z.2Q().1T;j+=F.$1Z.2Q().1s}N{h+=c(F.V).30()}}F.$2o.18({1s:j+"2s",1T:h+"2s"}).2h();F.dn()},dn:I(){if(!F.J.2o){L}G e=c.Q(I(f){c(f).1k("83.T",c.Q(I(g){if(c(g.1X).1H(F.$1h).1a===0){F.$2o.5J(2X);F.aa();c(f).2F(g)}},F)).1k("4q.T",c.Q(I(g){if(g.5s===F.2C.bz){F.1G().lq()}F.$2o.5J(2X);c(f).2F(g)},F))},F);e(V);if(F.J.1v){e(F.V)}},7J:I(){if(!F.J.2o){L}G e=c.Q(I(f){c(f).1k("fy.T",c.Q(I(g){if(c(g.1X).1H(F.$1h).1a===0){F.$2o.5J(2X);c(f).2F(g)}},F))},F);e(V);if(F.J.1v){e(F.V)}},df:I(f,e){c.1g(e,c.Q(I(j,h){if(!h.3o){h.3o=""}G g;if(h.2M==="7W"){g=c(\'<a 1f="lp">\')}N{g=c(\'<a 1M="#" 1f="\'+h.3o+" lz"+j+\'">\'+h.19+"</a>");g.1k("1B",c.Q(I(l){if(l.1Q){l.1Q()}if(F.1u("2H")){l.dr=K}if(h.1i){h.1i.4k(F,j,g,h,l)}if(h.1E){F.1K(h.1E,j)}if(h.1o){F[h.1o](j)}F.6u();if(F.J.2o){F.$2o.5J(2X)}},F))}f.1b(g)},F))},9Y:I(m,q){if(!F.J.4D){m.1Q();L K}G n=F.$1h.15(".dk"+q);G f=F.3B(q);if(f.3r("5C")){F.7I()}N{F.7I();F.1i("9Y",{2O:n,dq:q,1R:f});F.43(q);f.1V("5C");G r=f.2Q();if(F.4i){r=f.3g()}G o=n.2A();if((r.1s+o)>c(V).2A()){r.1s-=o}G h=r.1s+"2s";G j=f.dp();G l="6N";G p=j+"2s";if(F.J.4i&&F.4i){l="8h"}N{if(!F.J.2o){p=r.1T+j+"2s"}}n.18({2Q:l,1s:h,1T:p}).2h();F.1i("lW",{2O:n,dq:q,1R:f})}G g=c.Q(I(s){F.8R(s,n)},F);c(V).8X("1B",g);F.$O.8X("1B",g);m.lV();F.3h()},7I:I(){F.$1h.15("a.5C").2t("5Z").2t("5C");c(".dm").2d();F.1i("8R")},8R:I(g,f){if(!c(g.1X).3r("5C")){f.2t("5C");F.7I()}},5v:I(j,f,e){G g=c(\'<a 1M="7H:;" 19="\'+f.19+\'" 5B="-1" 1f="3D-7G 3D-\'+j+\'"></a>\');if(1m e!="1q"){g.1V("T-ac-1j")}g.1k("1B",c.Q(I(l){if(l.1Q){l.1Q()}if(F.1u("2H")){l.dr=K}if(g.3r("9U")){L K}if(F.8s()===K&&!f.1E){F.3h()}if(f.1E){F.3h();F.1K(f.1E,j);F.7J()}N{if(f.1o&&f.1o!=="2h"){F[f.1o](j);F.7J()}N{if(f.1i){f.1i.4k(F,j,g,f,l);F.7J()}N{if(f.2O){F.9Y(l,j)}}}}F.6u(K,j)},F));if(f.2O){G h=c(\'<X 1f="dm dk\'+j+\'" 1d="2r: 2u;">\');h.8E(F.$1h);F.df(h,f.2O)}L g},3B:I(e){if(!F.J.1h){L K}L c(F.$1h.15("a.3D-"+e))},m0:I(e,f){F.J.7F.2p(e);F.J.a5[f]=e},ds:I(f){G e=F.3B(f);if(e.3r("5Z")){F.9X(f)}N{F.43(f)}},43:I(f){G e=F.3B(f);e.1V("5Z")},9X:I(f){G e=F.3B(f);e.2t("5Z")},di:I(e){F.$1h.15("a.3D-7G").9T(".3D-"+e).2t("5Z")},de:I(){F.$1h.15("a.3D-7G").9T("a.3D-Y").2t("9U")},dg:I(){F.$1h.15("a.3D-7G").9T("a.3D-Y").1V("9U")},m9:I(e,f){F.3B(e).1V("3D-"+f)},m2:I(e,f){F.3B(e).2t("3D-"+f)},m5:I(g,e){G f=F.3B(g);f.2t("T-ac-1j");f.1V("fa-T-ac");f.Y(\'<i 1f="fa \'+e+\'"></i>\')},m6:I(f,g,j,h){if(!F.J.1h){L}G e=F.5v(f,{19:g,1i:j,2O:h},R);F.$1h.1b(c("<li>").1b(e));L e},m7:I(f,g,j,h){if(!F.J.1h){L}G e=F.5v(f,{19:g,1i:j,2O:h},R);F.$1h.5g(c("<li>").1b(e))},lP:I(m,f,h,l,j){if(!F.J.1h){L}G e=F.5v(f,{19:h,1i:l,2O:j},R);G g=F.3B(m);if(g.1D()!==0){g.1O().2f(c("<li>").1b(e))}N{F.$1h.1b(c("<li>").1b(e))}L e},lQ:I(j,f,h,m,l){if(!F.J.1h){L}G e=F.5v(f,{19:h,1i:m,2O:l},R);G g=F.3B(j);if(g.1D()!==0){g.1O().2U(c("<li>").1b(e))}N{F.$1h.1b(c("<li>").1b(e))}L e},lB:I(e){G f=F.3B(e);f.1n()},6u:I(h,l){G f=F.26();F.di(l);if(h===K&&l!=="Y"){if(c.3I(l,F.J.7F)!=-1){F.ds(l)}L}if(f&&f.U==="A"){F.$1h.15("a.dE").1r(F.J.1l.du)}N{F.$1h.15("a.dE").1r(F.J.1l.a6)}c.1g(F.J.a5,c.Q(I(e,m){if(c(f).1H(e,F.$O.2k()[0]).1a!=0){F.43(m)}},F));G g=c(f).1H(F.J.4v.3d().3i(),F.$O[0]);if(g.1a){G j=g.18("1r-7k");dD(j){5a"41":F.43("7L");4b;5a"5d":F.43("7M");4b;5a"7P":F.43("dG");4b;dH:F.43("7T");4b}}},9r:I(f){G l=F.1G();if(l.3b&&l.3O){G e=F.2y();e.8F();G g=F.V.3C("X");g.2V=f;G n=F.V.aU(),j,h;2D((j=g.6M)){h=n.5P(j)}G m=n.6M;e.2I(n);if(h){e=e.7R();e.7N(h);e.5G(R)}l.3V();l.3X(e)}},1E:I(f,g,e){if(f==="aq"&&F.1u("2H")){g="<"+g+">"}if(f==="45"&&F.1u("2H")){if(!F.7a()){F.3h();F.V.28.4m().9t(g)}N{F.9r(g)}}N{F.V.1K(f,K,g)}if(e!==K){F.1c()}F.1i("1K",f,g)},1K:I(g,h,f){if(!F.J.4D){F.$1p.1N();L K}if(g==="3v"||g==="3u"||g==="4W"||g==="dC"){F.1y()}if(g==="dB"||g==="dw"){G e=F.26();if(e.U==="lG"||e.U==="lH"){F.8n(e)}}if(g==="45"){F.85(h,f);F.1i("1K",g,h);L}if(F.5T("5c")&&!F.J.dv){L K}if(g==="5Y"||g==="8c"){L F.dA(g,h)}if(g==="4M"){L F.dy(g,h)}F.1E(g,h,f);if(g==="dx"){F.$O.15("hr").2e("id")}},dy:I(f,g){F.1y();G e=F.5T("A");if(e){c(e).1J(c(e).1r());F.1c();F.1i("1K",f,g);L}},dA:I(j,h){F.1y();G q=F.26();G n=c(q).1H("2l, 25");if(!F.3s(n)&&n.1D()!=0){n=K}G m=K;if(n&&n.1a){m=R;G p=n[0].U;if((j==="5Y"&&p==="kC")||(j==="8c"&&p==="kD")){m=K}}F.1L();if(m){G f=F.5N();G g=F.2L(f);if(1m f[0]!="1q"&&f.1a>1&&f[0].3P==3){g.eW(F.2g())}G l="",r="";c.1g(g,c.Q(I(v,w){if(w.U=="2T"){G u=c(w);G t=u.4H();t.15("25","2l").1n();if(F.J.1z===K){l+=F.3c(c("<p>").1b(t.1S()))}N{l+=t.Y()+"<br>"}if(v==0){u.1V("T-ca").52();r=F.3c(u)}N{u.1n()}}},F));Y=F.$O.Y().M(r,"</"+p+">"+l+"<"+p+">");F.$O.Y(Y);F.$O.15(p+":52").1n()}N{G e=c(F.26()).1H("16");F.V.1K(j);G q=F.26();G n=c(q).1H("2l, 25");if(e.1D()!=0){n.bT("<16>")}if(n.1a){G o=n.1O();if(F.3s(o)&&o[0].U!="2T"&&F.5H(o[0])){o.1J(o.1S())}}if(F.1u("2S")){F.$O.1N()}}F.1t();F.1c();F.1i("1K",j,h);L},9s:I(){F.9L("4X")},9B:I(){F.9L("5u")},9L:I(h){F.1y();if(h==="4X"){G j=F.2g();F.1L();if(j&&j.U=="2T"){G o=F.26();G l=c(o).1H("2l, 25");G n=l[0].U;G f=F.2L();c.1g(f,I(t,u){if(u.U=="2T"){G r=c(u).7D();if(r.1D()!=0&&r[0].U=="2T"){G q=r.5I("25, 2l");if(q.1D()==0){r.1b(c("<"+n+">").1b(u))}N{q.1b(u)}}}})}N{if(j===K&&F.J.1z===R){F.1E("4R","2c");G p=F.2g();G j=c(\'<X 21-64="">\').Y(c(p).Y());c(p).1J(j);G g=F.7U(c(j).18("2x-1s"))+F.J.7y;c(j).18("2x-1s",g+"2s")}N{G e=F.2L();c.1g(e,c.Q(I(r,s){G q=K;if(s.U==="5E"){L}if(c.3I(s.U,F.J.4v)!==-1){q=c(s)}N{q=c(s).1H(F.J.4v.3d().3i(),F.$O[0])}G t=F.7U(q.18("2x-1s"))+F.J.7y;q.18("2x-1s",t+"2s")},F))}}F.1t()}N{F.1L();G j=F.2g();if(j&&j.U=="2T"){G f=F.2L();G m=0;F.9N(j,m,f)}N{G e=F.2L();c.1g(e,c.Q(I(r,s){G q=K;if(c.3I(s.U,F.J.4v)!==-1){q=c(s)}N{q=c(s).1H(F.J.4v.3d().3i(),F.$O[0])}G t=F.7U(q.18("2x-1s"))-F.J.7y;if(t<=0){if(F.J.1z===R&&1m(q.21("64"))!=="1q"){q.1J(q.Y())}N{q.18("2x-1s","");F.4a(q,"1d")}}N{q.18("2x-1s",t+"2s")}},F))}F.1t()}F.1c()},9N:I(e,g,f){if(e&&e.U=="2T"){G h=c(e).1O().1O();if(h.1D()!=0&&h[0].U=="2T"){h.2f(e)}N{if(1m f[g]!="1q"){e=f[g];g++;F.9N(e,g,f)}N{F.1K("5Y")}}}},9F:I(){F.63("","jv")},9G:I(){F.63("41","jw")},bC:I(){F.63("5d","jx")},9I:I(){F.63("7P","jM")},63:I(f,h){F.1y();if(F.9a()){F.V.1K(h,K,K);L R}F.1L();G j=F.2g();if(!j&&F.J.1z){F.1E("aq","X");G e=F.2g();G j=c(\'<X 21-64="">\').Y(c(e).Y());c(e).1J(j);c(j).18("1r-7k",f);F.4a(j,"1d");if(f==""&&1m(c(j).21("64"))!=="1q"){c(j).1J(c(j).Y())}}N{G g=F.2L();c.1g(g,c.Q(I(m,n){G l=K;if(c.3I(n.U,F.J.4v)!==-1){l=c(n)}N{l=c(n).1H(F.J.4v.3d().3i(),F.$O[0])}if(l){l.18("1r-7k",f);F.4a(l,"1d")}},F))}F.1t();F.1c()},9z:I(e){G f=F.c5(e);if(f!==K){L f}if(F.J.1z===K){if(e===""){e=F.J.4j}N{if(e.3G(/^<hr\\s?\\/?>$/gi)!==-1){e="<hr>"+F.J.4j}}}L e},9Q:I(e){if(F.J.6X){e=e.M(/<X(.*?)>([\\w\\W]*?)<\\/X>/gi,"<p$1>$2</p>")}if(F.J.55){e=F.7v(e)}L e},a7:I(e){if(F.J.ad){e=e.M(/\\{\\{(.*?)\\}\\}/gi,"<!-- 7E c3 $1 -->");e=e.M(/\\{(.*?)\\}/gi,"<!-- 7E $1 -->")}e=e.M(/<2B(.*?)>([\\w\\W]*?)<\\/2B>/gi,\'<19 23="1r/7H" 1d="2r: 2u;" 1f="T-2B-3W"$1>$2</19>\');e=e.M(/<1d(.*?)>([\\w\\W]*?)<\\/1d>/gi,\'<1I$1 1d="2r: 2u;" 3k="T-1d-3W">$2</1I>\');e=e.M(/<1P(.*?)>([\\w\\W]*?)<\\/1P>/gi,\'<1I$1 3k="T-1P-3W">$2</1I>\');if(F.J.69){e=e.M(/<\\?3U([\\w\\W]*?)\\?>/gi,\'<1I 1d="2r: 2u;" 3k="T-3U-3W">$1</1I>\')}N{e=e.M(/<\\?3U([\\w\\W]*?)\\?>/gi,"")}L e},cc:I(e){if(F.J.ad){e=e.M(/<!-- 7E c3 (.*?) -->/gi,"{{$1}}");e=e.M(/<!-- 7E (.*?) -->/gi,"{$1}")}e=e.M(/<19 23="1r\\/7H" 1d="2r: 2u;" 1f="T-2B-3W"(.*?)>([\\w\\W]*?)<\\/19>/gi,\'<2B$1 23="1r/7H">$2<\\/2B>\');e=e.M(/<1I(.*?) 1d="2r: 2u;" 3k="T-1d-3W">([\\w\\W]*?)<\\/1I>/gi,"<1d$1>$2</1d>");e=e.M(/<1I(.*?)3k="T-1P-3W"(.*?)>([\\w\\W]*?)<\\/1I>/gi,"<1P$1$2>$3</1P>");if(F.J.69){e=e.M(/<1I 1d="2r: 2u;" 3k="T-3U-3W">([\\w\\W]*?)<\\/1I>/gi,"<?3U\\r\\n$1\\r\\n?>")}L e},5p:I(f,e){if(e!==K){G e=[];G h=f.22(/<(2w|1d|2B|19)(.*?)>([\\w\\W]*?)<\\/(2w|1d|2B|19)>/gi);if(h===2n){h=[]}if(F.J.69){G g=f.22(/<\\?3U([\\w\\W]*?)\\?>/gi);if(g){h=c.9d(h,g)}}if(h){c.1g(h,I(j,l){f=f.M(l,"bV"+j);e.2p(l)})}}f=f.M(/\\n/g," ");f=f.M(/[\\t]*/g,"");f=f.M(/\\n\\s*\\n/g,"\\n");f=f.M(/^[\\s\\n]*/g," ");f=f.M(/[\\s\\n]*$/g," ");f=f.M(/>\\s{2,}</g,"> <");f=F.bY(f,e);f=f.M(/\\n\\n/g,"\\n");L f},bY:I(f,e){if(e===K){L f}c.1g(e,I(g,h){f=f.M("bV"+g,h)});L f},9q:I(h){h=h.M(/<12>([\\w\\W]*?)<\\/12>/gi,"$1");h=h.M(/[\\6A-\\jJ\\jt]/g,"");G j=["<b>\\\\s*</b>","<b>&2z;</b>","<em>\\\\s*</em>"];G g=["<2w></2w>","<2c>\\\\s*</2c>","<dd></dd>","<dt></dt>","<25></25>","<2l></2l>","<li></li>","<1C></1C>","<2R></2R>","<12>\\\\s*<12>","<12>&2z;<12>","<p>\\\\s*</p>","<p></p>","<p>&2z;</p>","<p>\\\\s*<br>\\\\s*</p>","<X>\\\\s*</X>","<X>\\\\s*<br>\\\\s*</X>"];if(F.J.9m){g=g.js(j)}N{g=j}G e=g.1a;3f(G f=0;f<e;++f){h=h.M(1F 2j(g[f],"gi"),"")}L h},7v:I(l){l=c.1W(l);if(F.J.1z===R){L l}if(l===""||l==="<p></p>"){L F.J.4j}l=l+"\\n";if(F.J.9m===K){L l}G n=[];G j=l.22(/<(1C|X|2w|2Y)(.*?)>([\\w\\W]*?)<\\/(1C|X|2w|2Y)>/gi);if(!j){j=[]}G m=l.22(/<!--([\\w\\W]*?)-->/gi);if(m){j=c.9d(j,m)}if(F.J.69){G f=l.22(/<1I(.*?)3k="T-3U-3W">([\\w\\W]*?)<\\/1I>/gi);if(f){j=c.9d(j,f)}}if(j){c.1g(j,I(p,q){n[p]=q;l=l.M(q,"{M"+p+"}\\n")})}l=l.M(/<br \\/>\\s*<br \\/>/gi,"\\n\\n");I h(s,p,q){L l.M(1F 2j(s,p),q)}G e="(jf|Y|29|8a|19|8d|1d|2B|2b|1v|1C|3K|bf|ja|j6|j7|6v|2R|16|8M|X|dl|dd|dt|25|2l|li|2w|5k|3l|1P|cd|bM|2c|9E|j8|1d|p|h[1-6]|hr|bH|jg|1I|gs|fi|jh|5U|31|jo|jp|jq|jr|jn|jm)";l=h("(<"+e+"[^>]*>)","gi","\\n$1");l=h("(</"+e+">)","gi","$1\\n\\n");l=h("\\r\\n","g","\\n");l=h("\\r","g","\\n");l=h("/\\n\\n+/","g","\\n\\n");G o=l.3R(1F 2j("\\ji*\\n","g"),-1);l="";3f(G g in o){if(o.jj(g)){if(o[g].3G("{M")==-1){o[g]=o[g].M(/<p>\\n\\t<\\/p>/gi,"");o[g]=o[g].M(/<p><\\/p>/gi,"");if(o[g]!=""){l+="<p>"+o[g].M(/^\\n+|\\n+$/g,"")+"</p>"}}N{l+=o[g]}}}l=h("<p><p>","gi","<p>");l=h("</p></p>","gi","</p>");l=h("<p>s?</p>","gi","");l=h("<p>([^<]+)</(X|9E|1P)>","gi","<p>$1</p></$2>");l=h("<p>(</?"+e+"[^>]*>)</p>","gi","$1");l=h("<p>(<li.+?)</p>","gi","$1");l=h("<p>s?(</?"+e+"[^>]*>)","gi","$1");l=h("(</?"+e+"[^>]*>)s?</p>","gi","$1");l=h("(</?"+e+"[^>]*>)s?<br />","gi","$1");l=h("<br />(s*</?(?:p|li|X|dl|dd|dt|8M|2w|16|25|2l)[^>]*>)","gi","$1");l=h("\\n</p>","gi","</p>");l=h("<li><p>","gi","<li>");l=h("</p></li>","gi","</li>");l=h("</li><p>","gi","</li>");l=h("<p>\\t?\\n?<p>","gi","<p>");l=h("</dt><p>","gi","</dt>");l=h("</dd><p>","gi","</dd>");l=h("<br></p></2c>","gi","</2c>");l=h("<p>\\t*</p>","gi","");c.1g(n,I(p,q){l=l.M("{M"+p+"}",q)});L c.1W(l)},7B:I(e,h){G f="3y";if(F.J.bE==="b"){f="b"}G g="em";if(F.J.by==="i"){g="i"}e=e.M(/<12 1d="3x-1d: 3u;">([\\w\\W]*?)<\\/12>/gi,"<"+g+">$1</"+g+">");e=e.M(/<12 1d="3x-jQ: 3v;">([\\w\\W]*?)<\\/12>/gi,"<"+f+">$1</"+f+">");if(F.J.bE==="3y"){e=e.M(/<b>([\\w\\W]*?)<\\/b>/gi,"<3y>$1</3y>")}N{e=e.M(/<3y>([\\w\\W]*?)<\\/3y>/gi,"<b>$1</b>")}if(F.J.by==="em"){e=e.M(/<i>([\\w\\W]*?)<\\/i>/gi,"<em>$1</em>")}N{e=e.M(/<em>([\\w\\W]*?)<\\/em>/gi,"<i>$1</i>")}if(h!==R){e=e.M(/<5f>([\\w\\W]*?)<\\/5f>/gi,"<4L>$1</4L>")}N{e=e.M(/<4L>([\\w\\W]*?)<\\/4L>/gi,"<5f>$1</5f>")}L e},6o:I(g){if(g==""||1m g=="1q"){L g}G h=K;if(F.J.4A!==K){h=R}G e=h===R?F.J.4A:F.J.68;G f=/<\\/?([a-z][a-8H-9]*)\\b[^>]*>/gi;g=g.M(f,I(l,j){if(h===R){L c.3I(j.3i(),e)>"-1"?l:""}N{L c.3I(j.3i(),e)>"-1"?"":l}});g=F.7B(g);L g},bi:I(e,f){G g=e.22(/<(2w|5n)(.*?)>([\\w\\W]*?)<\\/(2w|5n)>/gi);if(g!==2n){c.1g(g,c.Q(I(j,l){G h=l.22(/<(2w|5n)(.*?)>([\\w\\W]*?)<\\/(2w|5n)>/i);h[3]=h[3].M(/&2z;/g," ");if(f!==K){h[3]=F.b9(h[3])}h[3]=h[3].M(/\\$/g,"$");e=e.M(l,"<"+h[1]+h[2]+">"+h[3]+"</"+h[1]+">")},F))}L e},b9:I(e){e=44(e).M(/&6J;/g,"&").M(/</g,"<").M(/>/g,">").M(/&c9;/g,\'"\');L e.M(/&/g,"&6J;").M(/</g,"<").M(/>/g,">").M(/"/g,"&c9;")},bW:I(){G e=F.$O.15("li, 1A, a, b, 3y, kg, kh, i, em, u, ki, 5f, 4L, 12, kj");e.bU(\'[1d*="7t-6q: c2;"][1d*="aT-1U"]\').18("7t-6q","").18("aT-1U","");e.bU(\'[1d*="7t-6q: c2;"]\').18("7t-6q","");e.18("aT-1U","");c.1g(e,c.Q(I(f,g){F.4a(g,"1d")},F));F.$O.15(\'X[1d="1r-7k: -3A-3q;"]\').1S().c6();F.$O.15("25, 2l, li").2e("1d")},bR:I(f){G j=0,m=f.1a,l=0,e=2n,g=2n,p="",h="",o="";F.67=0;3f(;j<m;j++){l=j;if(-1==f.3L(j).2J("<")){h+=f.3L(j);L F.aQ(h)}2D(l<m&&f.4z(l)!="<"){l++}if(j!=l){o=f.3L(j,l-j);if(!o.22(/^\\s{2,}$/g)){if("\\n"==h.4z(h.1a-1)){h+=F.5q()}N{if("\\n"==o.4z(0)){h+="\\n"+F.5q();o=o.M(/^\\s+/,"")}}h+=o}if(o.22(/\\n/)){h+="\\n"+F.5q()}}e=l;2D(l<m&&">"!=f.4z(l)){l++}p=f.3L(e,l-e);j=l;G n;if("!--"==p.3L(1,3)){if(!p.22(/--$/)){2D("-->"!=f.3L(l,3)){l++}l+=2;p=f.3L(e,l-e);j=l}if("\\n"!=h.4z(h.1a-1)){h+="\\n"}h+=F.5q();h+=p+">\\n"}N{if("!"==p[1]){h=F.7l(p+">",h)}N{if("?"==p[1]){h+=p+">\\n"}N{if(n=p.22(/^<(2B|1d|2w)/i)){n[1]=n[1].3i();p=F.aH(p);h=F.7l(p,h);g=44(f.3L(j+1)).3i().2J("</"+n[1]);if(g){o=f.3L(j+1,g);j+=g;h+=o}}N{p=F.aH(p);h=F.7l(p,h)}}}}}L F.aQ(h)},5q:I(){G f="";3f(G e=0;e<F.67;e++){f+="\\t"}L f},aQ:I(e){e=e.M(/\\n\\s*\\n/g,"\\n");e=e.M(/^[\\s\\n]*/,"");e=e.M(/[\\s\\n]*$/,"");e=e.M(/<2B(.*?)>\\n<\\/2B>/gi,"<2B$1><\\/2B>");F.67=0;L e},aH:I(f){G h="";f=f.M(/\\n/g," ");f=f.M(/\\s{2,}/g," ");f=f.M(/^\\s+|\\s+$/g," ");G g="";if(f.22(/\\/$/)){g="/";f=f.M(/\\/+$/,"")}G e;2D(e=/\\s*([^= ]+)(?:=(([\'"\']).*?\\3|[^ ]+))?/.1E(f)){if(e[2]){h+=e[1].3i()+"="+e[2]}N{if(e[1]){h+=e[1].3i()}}h+=" ";f=f.3L(e[0].1a)}L h.M(/\\s*$/,"")+g+">"},7l:I(e,g){G f=e.22(F.b1);if(e.22(F.bI)||f){g=g.M(/\\s*$/,"");g+="\\n"}if(f&&"/"==e.4z(1)){F.67--}if("\\n"==g.4z(g.1a-1)){g+=F.5q()}if(f&&"/"!=e.4z(1)){F.67++}g+=e;if(e.22(F.bL)||e.22(F.b1)){g=g.M(/ *$/,"");g+="\\n"}L g},c4:I(j){G f=c.1W(F.$O.Y());if(F.J.1z){if(f==""){j.1Q();F.$O.Y("");F.1N()}}N{f=f.M(/<br\\s?\\/?>/i,"");G h=f.M(/<p>\\s?<\\/p>/gi,"");if(f===""||h===""){j.1Q();G g=c(F.J.4j).2k(0);F.$O.Y(g);F.1N()}}F.1c()},49:I(e){F.1y();G f=F.2L();F.1L();c.1g(f,c.Q(I(g,j){if(j.U!=="2T"){G h=c(j).1O();if(e==="p"){if((j.U==="P"&&h.1D()!=0&&h[0].U==="2P")||j.U==="2P"){F.aw();L}N{if(F.J.1z){if(j&&j.U.3G(/H[1-6]/)==0){c(j).1J(j.2V+"<br>")}N{L}}N{F.4R(e,j)}}}N{F.4R(e,j)}}},F));F.1t();F.1c()},4R:I(e,j){if(j===K){j=F.2g()}if(j===K&&F.J.1z===R){F.1K("aq",e);L R}G h="";if(e!=="2w"){h=c(j).1S()}N{h=c(j).Y();if(c.1W(h)===""){h=\'<12 id="28-1x-1"></12>\'}}if(j.U==="5c"){e="p"}if(F.J.1z===R&&e==="p"){c(j).1J(c("<X>").1b(h).Y()+"<br>")}N{G f=F.26();G g=c("<"+e+">").1b(h);c(j).1J(g);if(f&&f.U=="5E"){c(g).bT("<16>")}}},eT:I(g,e,f){if(f!==K){F.1L()}G h=c("<"+e+"/>");c(g).1J(I(){L h.1b(c(F).1S())});if(f!==K){F.1t()}L h},aw:I(){F.1y();if(F.J.1z===K){F.1L();G e=F.2L();G p=K;G u=e.1a;if(e){G m="";G v="";G h=K;G r=R;c.1g(e,I(w,x){if(x.U!=="P"){r=K}});c.1g(e,c.Q(I(w,x){if(x.U==="2P"){F.4R("p",x,K)}N{if(x.U==="P"){p=c(x).1O();if(p[0].U=="2P"){G y=c(p).5I("p").1D();if(y==1){c(p).1J(x)}N{if(y==u){h="2c";m+=F.3c(x)}N{h="Y";m+=F.3c(x);if(w==0){c(x).1V("T-ca").52();v=F.3c(x)}N{c(x).1n()}}}}N{if(r===K||e.1a==1){F.4R("2c",x,K)}N{h="cb";m+=F.3c(x)}}}N{if(x.U!=="2T"){F.4R("2c",x,K)}}}},F));if(h){if(h=="cb"){c(e[0]).1J("<2c>"+m+"</2c>");c(e).1n()}N{if(h=="2c"){c(p).1J(m)}N{if(h=="Y"){G o=F.$O.Y().M(v,"</2c>"+m+"<2c>");F.$O.Y(o);F.$O.15("2c").1g(I(){if(c.1W(c(F).Y())==""){c(F).1n()}})}}}}}F.1t()}N{G j=F.2g();if(j.U==="2P"){F.1L();G o=c.1W(c(j).Y());G s=c.1W(F.f3());o=o.M(/<12(.*?)id="28-1x(.*?)<\\/12>/gi,"");if(o==s){c(j).1J(c(j).Y()+"<br>")}N{F.bP("8p");G l=F.$O.15("8p");l.52();G q=F.$O.Y().M("<8p></8p>",\'</2c><12 id="28-1x-1">\'+F.J.1Y+"</12>"+s+"<2c>");F.$O.Y(q);l.1n();F.$O.15("2c").1g(I(){if(c.1W(c(F).Y())==""){c(F).1n()}})}F.1t();F.$O.15("12#28-1x-1").1e("id",K)}N{G g=F.eS("2c");G o=c(g).Y();G t=["25","2l","1C","2R","6v","3K","bf","dl"];c.1g(t,I(w,x){o=o.M(1F 2j("<"+x+"(.*?)>","gi"),"");o=o.M(1F 2j("</"+x+">","gi"),"")});G f=F.J.8D;c.1g(f,I(w,x){o=o.M(1F 2j("<"+x+"(.*?)>","gi"),"");o=o.M(1F 2j("</"+x+">","gi"),"<br>")});c(g).Y(o);F.af(g);G n=c(g).a3();if(n.1D()!=0&&n[0].U==="a2"){n.1n()}}}F.1c()},jX:I(e,g){G f=F.2L();c(f).2e(e);F.1c()},jW:I(e,g){G f=F.2L();c(f).1e(e,g);F.1c()},jS:I(f){G e=F.2L();c(e).18(f,"");F.4a(e,"1d");F.1c()},jT:I(g,f){G e=F.2L();c(e).18(g,f);F.1c()},jU:I(f){G e=F.2L();c(e).2t(f);F.4a(e,"1f");F.1c()},jV:I(f){G e=F.2L();c(e).1V(f);F.1c()},k2:I(e){F.1L();F.bx(I(f){c(f).2t(e);F.4a(f,"1f")});F.1t();F.1c()},k3:I(e){G f=F.2Z();if(!c(f).3r(e)){F.8B("1V",e)}},ka:I(e){F.1L();F.bx(I(f){c(f).18(e,"");F.4a(f,"1d")});F.1t();F.1c()},kb:I(f,e){F.8B("18",f,e)},kc:I(e){F.1L();G g=F.2y(),h=F.5X(),f=F.5N();if(g.59||g.4P===g.6D&&h){f=c(h)}c(f).2e(e);F.bK();F.1t();F.1c()},kd:I(e,f){F.8B("1e",e,f)},8B:I(h,e,j){F.1y();F.1L();G f=F.2y();G g=F.5X();if((f.59||f.4P===f.6D)&&g&&!F.5H(g)){c(g)[h](e,j)}N{F.V.1K("6t",K,4);G l=F.$O.15("3x");c.1g(l,c.Q(I(m,n){F.ed(h,n,e,j)},F))}F.1t();F.1c()},ed:I(j,o,g,l){G m=c(o).1O(),e;G n=F.7O();G h=c(m).1r();G f=n==h;if(f&&m&&m[0].U==="ah"&&m[0].k9.1a!=0){e=m;c(o).1J(c(o).Y())}N{e=c("<3a>").1b(c(o).1S());c(o).1J(e)}c(e)[j](g,l);L e},bx:I(j){G f=F.2y(),g=F.5X(),e=F.5N(),h;if(f.59||f.4P===f.6D&&g){e=c(g);h=R}c.1g(e,c.Q(I(m,o){if(!h&&o.U!=="ah"){G l=F.7O();G p=c(o).1O().1r();G n=l==p;if(n&&o.4w.U==="ah"&&!c(o.4w).3r("3w")){o=o.4w}N{L}}j.4k(F,o)},F))},bK:I(){G e=F.$O.15("3a");c.1g(e,c.Q(I(g,h){G f=c(h);if(f.1e("1f")===1q&&f.1e("1d")===1q){f.1S().c6()}},F))},bP:I(e){F.1L();F.V.1K("6t",K,4);G g=F.$O.15("3x");G f;c.1g(g,I(h,l){G j=c("<"+e+"/>").1b(c(l).1S());c(l).1J(j);f=j});F.1t();F.1c()},k5:I(e){F.1L();G f=e.k6();G g=F.5N();G h=c(F.26()).1O();c.1g(g,I(j,l){if(l.U===f){F.8n(l)}});if(h&&h[0].U===f){F.8n(h)}F.1t();F.1c()},8n:I(e){c(e).1J(c(e).1S())},85:I(g,j){G m=F.2Z();G h=m.4w;F.3h();F.1y();G e=c("<X>").1b(c.9p(g));g=e.Y();g=F.9q(g);e=c("<X>").1b(c.9p(g));G f=F.2g();if(e.1S().1a==1){G l=e.1S()[0].U;if(l!="P"&&l==f.U||l=="5c"){e=c("<X>").1b(g)}}if(F.J.1z){g=g.M(/<p(.*?)>([\\w\\W]*?)<\\/p>/gi,"$2<br>")}if(!F.J.1z&&e.1S().1a==1&&e.1S()[0].3P==3&&(F.9K().1a>2||(!m||m.U=="ab"&&!h||h.U=="bN"))){g="<p>"+g+"</p>"}g=F.8l(g);if(e.1S().1a>1&&f||e.1S().is("p, :5U, 25, 2l, li, X, 1C, 16, 2c, 2w, 9E, 1I, 5U, 31, fi, gs")){if(F.1u("2H")){if(!F.7a()){F.V.28.4m().9t(g)}N{F.9r(g)}}N{F.V.1K("45",K,g)}}N{F.7V(g,K)}if(F.4U){F.3n.2m(c.Q(I(){if(!F.J.1z){F.5S(F.$O.1S().6l())}N{F.bj()}},F),1)}F.5R();F.6k();if(j!==K){F.1c()}},7V:I(f,l){f=F.8l(f);G m=F.1G();if(m.3b&&m.3O){G e=m.3b(0);e.8F();G g=F.V.3C("X");g.2V=f;G n=F.V.aU(),j,h;2D((j=g.6M)){h=n.5P(j)}e.2I(n);if(h){e=e.7R();e.7N(h);e.5G(R);m.3V();m.3X(e)}}if(l!==K){F.1c()}},k7:I(f){f=F.8l(f);G g=c(f);G j=V.3C("12");j.2V="\\6A";G e=F.2y();e.2I(j);e.2I(g[0]);e.5G(K);G h=F.1G();h.3V();h.3X(e);F.1c()},k4:I(f){G e=c(c.9p(f));if(e.1a){f=e.1r()}F.3h();if(F.1u("2H")&&!F.7a()){F.V.28.4m().9t(f)}N{F.V.1K("45",K,f)}F.1c()},2I:I(j){j=j[0]||j;if(j.U=="gA"){G e="3a";G f=j.gr;G h=1F 2j("<"+j.U,"i");G g=f.M(h,"<"+e);h=1F 2j("</"+j.U,"i");g=g.M(h,"</"+e);j=c(g)[0]}G l=F.1G();if(l.3b&&l.3O){4Z=l.3b(0);4Z.8F();4Z.2I(j);4Z.k8(j);4Z.7N(j);l.3V();l.3X(4Z)}},fH:I(l,j){G g;G f=l.gq,n=l.gn;if(F.V.go){G m=F.V.go(f,n);g=F.2y();g.6w(m.k1,m.3g);g.5G(R);g.2I(j)}N{if(F.V.gw){g=F.V.gw(f,n);g.2I(j)}N{if(1m V.29.gC!="1q"){g=F.V.29.gC();g.gD(f,n);G h=g.k0();h.gD(f,n);g.jZ("jY",h);g.5k()}}}},5D:I(e,f){if(1m(f)!="1q"){e=f}if(F.aK()){if(F.J.1z){G h=c("<X>").1b(c.1W(F.$O.Y())).1S();G g=h.6l()[0];if(g.U=="gA"&&g.2V==""){g=h.7D()[0]}if(F.3c(g)!=F.3c(e)){L K}}N{if(F.$O.1S().6l()[0]!==e){L K}}F.as(e)}},as:I(e){F.1y();if(F.J.1z===K){G f=c(F.J.4j);c(e).2f(f);F.3Q(f)}N{G f=c(\'<12 id="28-1x-1">\'+F.J.1Y+"</12>",F.V)[0];c(e).2f(f);c(f).2f(F.J.1Y);F.1t();F.$O.15("12#28-1x-1").2e("id")}},8o:I(g){F.1L();G f="<br>";if(g==R){f="<br><br>"}if(F.1u("2S")){G j=c("<12>").Y(F.J.1Y);F.$O.15("#28-1x-1").2U(f).2U(j).2U(F.J.1Y);F.eK(j[0]);j.1n();F.6B()}N{G h=F.26();if(h&&h.U==="A"){G n=F.at(h);G m=c.1W(c(h).1r()).M(/\\n\\r\\n/g,"");G e=m.1a;if(n==e){F.6B();G l=c(\'<12 id="28-1x-1">\'+F.J.1Y+"</12>",F.V)[0];c(h).2f(l);c(l).2U(f+(F.1u("3A")?F.J.1Y:""));F.1t();L R}}F.$O.15("#28-1x-1").2U(f+(F.1u("3A")?F.J.1Y:""));F.1t()}},ke:I(){F.8o(R)},gy:I(e){G f=c("<br>"+F.J.1Y);c(e).1J(f);F.3Q(f)},gz:I(j){j=F.1i("kf",K,j);if(F.1u("2H")){G h=c.1W(j);if(h.3G(/^<a(.*?)>(.*?)<\\/a>$/i)==0){j=j.M(/^<a(.*?)>(.*?)<\\/a>$/i,"$2")}}if(F.J.gm){G h=F.V.3C("X");j=j.M(/<br>|<\\/H[1-6]>|<\\/p>|<\\/X>/gi,"\\n");h.2V=j;j=h.89||h.9C;j=c.1W(j);j=j.M("\\n","<br>");j=F.7v(j);F.6R(j);L K}G f=K;if(F.5T("5E")){f=R;G g=F.J.8D;g.2p("2R");g.2p("1C");c.1g(g,I(m,n){j=j.M(1F 2j("<"+n+"(.*?)>","gi"),"");j=j.M(1F 2j("</"+n+">","gi"),"<br>")})}if(F.5T("5c")){j=F.gb(j);F.6R(j);L R}j=j.M(/<1A(.*?)v:kv=(.*?)>/gi,"");j=j.M(/<p(.*?)1f="ku"([\\w\\W]*?)<\\/p>/gi,"<25><li$2</li>");j=j.M(/<p(.*?)1f="kt"([\\w\\W]*?)<\\/p>/gi,"<li$2</li>");j=j.M(/<p(.*?)1f="ks"([\\w\\W]*?)<\\/p>/gi,"<li$2</li></25>");j=j.M(/<p(.*?)1f="kw"([\\w\\W]*?)<\\/p>/gi,"<25><li$2</li></25>");j=j.M(/·/g,"");j=j.M(/<!--[\\s\\S]*?-->|<\\?(?:3U)?[\\s\\S]*?\\?>/gi,"");if(F.J.g8===R){j=j.M(/(&2z;){2,}/gi,"&2z;");j=j.M(/&2z;/gi," ")}j=j.M(/<b\\kB="g9-1p-1x(.*?)">([\\w\\W]*?)<\\/b>/gi,"$2");j=j.M(/<b(.*?)id="kA-g9-kz(.*?)">([\\w\\W]*?)<\\/b>/gi,"$3");j=F.6o(j);j=j.M(/<16>\\ky*<\\/16>/gi,"[16]");j=j.M(/<16>&2z;<\\/16>/gi,"[16]");j=j.M(/<16><br><\\/16>/gi,"[16]");j=j.M(/<16(.*?)7q="(.*?)"(.*?)>([\\w\\W]*?)<\\/16>/gi,\'[16 7q="$2"]$4[/16]\');j=j.M(/<16(.*?)7x="(.*?)"(.*?)>([\\w\\W]*?)<\\/16>/gi,\'[16 7x="$2"]$4[/16]\');j=j.M(/<a(.*?)1M="(.*?)"(.*?)>([\\w\\W]*?)<\\/a>/gi,\'[a 1M="$2"]$4[/a]\');j=j.M(/<1v(.*?)>([\\w\\W]*?)<\\/1v>/gi,"[1v$1]$2[/1v]");j=j.M(/<2K(.*?)>([\\w\\W]*?)<\\/2K>/gi,"[2K$1]$2[/2K]");j=j.M(/<4p(.*?)>([\\w\\W]*?)<\\/4p>/gi,"[4p$1]$2[/4p]");j=j.M(/<3Z(.*?)>([\\w\\W]*?)<\\/3Z>/gi,"[3Z$1]$2[/3Z]");j=j.M(/<2Y(.*?)>([\\w\\W]*?)<\\/2Y>/gi,"[2Y$1]$2[/2Y]");j=j.M(/<5O(.*?)>/gi,"[5O$1]");j=j.M(/<1A(.*?)>/gi,"[1A$1]");j=j.M(/ 1f="(.*?)"/gi,"");j=j.M(/<(\\w+)([\\w\\W]*?)>/gi,"<$1>");if(F.J.1z){j=j.M(/<3y><\\/3y>/gi,"");j=j.M(/<u><\\/u>/gi,"");if(F.J.aV){j=j.M(/<3x(.*?)>([\\w\\W]*?)<\\/3x>/gi,"$2")}j=j.M(/<[^\\/>][^>]*>(\\s*|\\t*|\\n*|&2z;|<br>)<\\/[^>]+>/gi,"<br>")}N{j=j.M(/<[^\\/>][^>]*>(\\s*|\\t*|\\n*|&2z;|<br>)<\\/[^>]+>/gi,"")}j=j.M(/<X>\\s*?\\t*?\\n*?(<25>|<2l>|<p>)/gi,"$1");j=j.M(/\\[16 7q="(.*?)"\\]([\\w\\W]*?)\\[\\/16\\]/gi,\'<16 7q="$1">$2</16>\');j=j.M(/\\[16 7x="(.*?)"\\]([\\w\\W]*?)\\[\\/16\\]/gi,\'<16 7x="$1">$2</16>\');j=j.M(/\\[16\\]/gi,"<16>&2z;</16>");j=j.M(/\\[a 1M="(.*?)"\\]([\\w\\W]*?)\\[\\/a\\]/gi,\'<a 1M="$1">$2</a>\');j=j.M(/\\[1v(.*?)\\]([\\w\\W]*?)\\[\\/1v\\]/gi,"<1v$1>$2</1v>");j=j.M(/\\[2K(.*?)\\]([\\w\\W]*?)\\[\\/2K\\]/gi,"<2K$1>$2</2K>");j=j.M(/\\[4p(.*?)\\]([\\w\\W]*?)\\[\\/4p\\]/gi,"<4p$1>$2</4p>");j=j.M(/\\[3Z(.*?)\\]([\\w\\W]*?)\\[\\/3Z\\]/gi,"<3Z$1>$2</3Z>");j=j.M(/\\[2Y(.*?)\\]([\\w\\W]*?)\\[\\/2Y\\]/gi,"<2Y$1>$2</2Y>");j=j.M(/\\[5O(.*?)\\]/gi,"<5O$1>");j=j.M(/\\[1A(.*?)\\]/gi,"<1A$1>");if(F.J.6X){j=j.M(/<X(.*?)>([\\w\\W]*?)<\\/X>/gi,"<p>$2</p>");j=j.M(/<\\/X><p>/gi,"<p>");j=j.M(/<\\/p><\\/X>/gi,"</p>");j=j.M(/<p><\\/p>/gi,"<br />")}N{j=j.M(/<X><\\/X>/gi,"<br />")}if(F.5T("2T")){j=j.M(/<p>([\\w\\W]*?)<\\/p>/gi,"$1<br>")}N{if(f===K){j=F.7v(j)}}j=j.M(/<12(.*?)>([\\w\\W]*?)<\\/12>/gi,"$2");j=j.M(/<1A>/gi,"");j=j.M(/<[^\\/>][^>][^1A|5O|1p|16][^<]*>(\\s*|\\t*|\\n*| |<br>)<\\/[^>]+>/gi,"");j=j.M(/\\n{3,}/gi,"\\n");j=j.M(/<p><p>/gi,"<p>");j=j.M(/<\\/p><\\/p>/gi,"</p>");j=j.M(/<li>(\\s*|\\t*|\\n*)<p>/gi,"<li>");j=j.M(/<\\/p>(\\s*|\\t*|\\n*)<\\/li>/gi,"</li>");if(F.J.1z===R){j=j.M(/<p(.*?)>([\\w\\W]*?)<\\/p>/gi,"$2<br>")}j=j.M(/<[^\\/>][^>][^1A|5O|1p|16][^<]*>(\\s*|\\t*|\\n*| |<br>)<\\/[^>]+>/gi,"");j=j.M(/<1A 2G="3A-kq-3p\\:\\/\\/(.*?)"(.*?)>/gi,"");j=j.M(/<16(.*?)>(\\s*|\\t*|\\n*)<p>([\\w\\W]*?)<\\/p>(\\s*|\\t*|\\n*)<\\/16>/gi,"<16$1>$3</16>");if(F.J.6X){j=j.M(/<X(.*?)>([\\w\\W]*?)<\\/X>/gi,"$2");j=j.M(/<X(.*?)>([\\w\\W]*?)<\\/X>/gi,"$2")}F.bF=K;if(F.1u("2S")){if(F.J.81){G l=j.22(/<1A 2G="21:1j(.*?)"(.*?)>/gi);if(l!==2n){F.bF=l;3f(k in l){G e=l[k].M("<1A",\'<1A 21-2S-84-1j="\'+k+\'" \');j=j.M(l[k],e)}}}2D(/<br>$/gi.3S(j)){j=j.M(/<br>$/gi,"")}}j=j.M(/<p>•([\\w\\W]*?)<\\/p>/gi,"<li>$1</li>");if(F.1u("2H")){2D(/<3x>([\\w\\W]*?)<\\/3x>/gi.3S(j)){j=j.M(/<3x>([\\w\\W]*?)<\\/3x>/gi,"$1")}}if(f===K){j=j.M(/<16(.*?)>([\\w\\W]*?)<p(.*?)>([\\w\\W]*?)<\\/16>/gi,"<16$1>$2$4</16>");j=j.M(/<16(.*?)>([\\w\\W]*?)<\\/p>([\\w\\W]*?)<\\/16>/gi,"<16$1>$2$3</16>");j=j.M(/<16(.*?)>([\\w\\W]*?)<p(.*?)>([\\w\\W]*?)<\\/16>/gi,"<16$1>$2$4</16>");j=j.M(/<16(.*?)>([\\w\\W]*?)<\\/p>([\\w\\W]*?)<\\/16>/gi,"<16$1>$2$3</16>")}j=j.M(/\\n/g," ");j=j.M(/<p>\\n?<li>/gi,"<li>");F.6R(j)},gb:I(f){f=f.M(/<br>|<\\/H[1-6]>|<\\/p>|<\\/X>/gi,"\\n");G e=F.V.3C("X");e.2V=f;L F.b9(e.89||e.9C)},6R:I(e){e=F.1i("kk",K,e);if(F.4U){F.$O.Y(e);F.aa();F.bj();F.1c()}N{F.85(e)}F.4U=K;2m(c.Q(I(){F.6y=K;if(F.1u("2S")){F.$O.15("p:52").1n()}if(F.bF!==K){F.gg()}},F),2X);if(F.J.3T&&F.bh!==R){c(F.V.29).30(F.7c)}N{F.$O.30(F.7c)}},bt:I(e){if(F.J.2N!==K&&1m F.J.2N==="2Y"){c.1g(F.J.2N,c.Q(I(g,f){if(f!=2n&&f.3d().2J("#")===0){f=c(f).1w()}e[g]=f},F))}L e},gg:I(){G e=F.$O.15("1A[21-2S-84-1j]");c.1g(e,c.Q(I(j,l){G g=c(l);G f=l.2G.3R(",");G h={94:f[0].3R(";")[0].3R(":")[1],21:f[1]};h=F.bt(h);c.6E(F.J.8V,h,c.Q(I(n){G m=(1m n==="88"?c.6G(n):n);g.1e("2G",m.51);g.2e("21-2S-84-1j");F.1c();F.1i("33",g,m)},F))},F))},gd:I(j){G g=j.1X.km;G f=g.3R(",");G h={94:f[0].3R(";")[0].3R(":")[1],21:f[1]};if(F.J.81){h=F.bt(h);c.6E(F.J.8V,h,c.Q(I(m){G l=(1m m==="88"?c.6G(m):m);G e=\'<1A 2G="\'+l.51+\'" id="gE-1j-1x" />\';F.1K("45",e,K);G n=c(F.$O.15("1A#gE-1j-1x"));if(n.1a){n.2e("id")}N{n=K}F.1c();if(n){F.1i("33",n,l)}},F))}N{F.85(\'<1A 2G="\'+g+\'" />\')}},1y:I(e,f){if(e!==1q||e===K){F.J.4r.2p(e)}N{if(f!==K){F.1L()}F.J.4r.2p(F.$O.Y());F.6B("4r")}},gG:I(){if(F.J.4r.1a===0){F.3h();L}F.1L();F.J.6x.2p(F.$O.Y());F.1t(K,R);F.$O.Y(F.J.4r.gI());F.1t();2m(c.Q(F.5R,F),2X)},gJ:I(){if(F.J.6x.1a===0){F.3h();L K}F.1L();F.J.4r.2p(F.$O.Y());F.1t(K,R);F.$O.Y(F.J.6x.gI());F.1t(R);2m(c.Q(F.5R,F),4)},5R:I(){F.3M();if(F.J.4e){F.4e()}},4e:I(){F.$O.15("a").1k("1B",c.Q(F.gK,F));F.$O.1k("1B.T",c.Q(I(f){F.5m(f)},F));c(V).1k("1B.T",c.Q(I(f){F.5m(f)},F))},3M:I(){if(F.J.3M===K){L K}F.$O.15("1A").1g(c.Q(I(e,f){if(F.1u("2H")){c(f).1e("jb","1k")}F.fe(f)},F))},gK:I(h){G j=c(h.1X);if(j.1D()==0||j[0].U!=="A"){L}G m=j.3g();if(F.J.1v){G g=F.$2q.3g();m.1T=g.1T+(m.1T-c(F.V).30());m.1s+=g.1s}G p=c(\'<12 1f="T-2b-8W"></12>\');G f=j.1e("1M");if(f===1q){f=""}if(f.1a>24){f=f.87(0,24)+"..."}G l=c(\'<a 1M="\'+j.1e("1M")+\'" 1X="4K">\'+f+"</a>").1k("1B",c.Q(I(q){F.5m(K)},F));G n=c(\'<a 1M="#">\'+F.J.1l.6r+"</a>").1k("1B",c.Q(I(q){q.1Q();F.8U();F.5m(K)},F));G o=c(\'<a 1M="#">\'+F.J.1l.4M+"</a>").1k("1B",c.Q(I(q){q.1Q();F.1K("4M");F.5m(K)},F));p.1b(l);p.1b(" | ");p.1b(n);p.1b(" | ");p.1b(o);p.18({1T:(m.1T+20)+"2s",1s:m.1s+"2s"});c(".T-2b-8W").1n();c("29").1b(p)},5m:I(f){if(f!==K&&f.1X.U=="A"){L K}c(".T-2b-8W").1n()},1G:I(){if(!F.J.34){L F.V.1G()}N{if(!F.J.1v){L 34.1G()}N{L 34.1G(F.$2q[0])}}},2y:I(){if(!F.J.34){if(F.V.1G){G e=F.1G();if(e.3b&&e.3O){L e.3b(0)}}L F.V.4m()}N{if(!F.J.1v){L 34.4m()}N{L 34.4m(F.9c())}}},af:I(e){F.eO(e)},3Q:I(e){F.6C(e[0]||e,0,2n,0)},5S:I(e){F.6C(e[0]||e,1,2n,1)},6C:I(o,n,m,j){if(m==2n){m=o}if(j==2n){j=n}G h=F.1G();if(!h){L}if(o.U=="P"&&o.2V==""){o.2V=F.J.1Y}if(o.U=="a2"&&F.J.1z===K){G g=c(F.J.4j)[0];c(o).1J(g);o=g;m=o}G f=F.2y();f.6w(o,n);f.6z(m,j);eR{h.3V()}eQ(l){}h.3X(f)},eS:I(e){e=e.3i();G h=F.2g();if(h){G j=F.eT(h,e);F.1c();L j}G g=F.1G();G f=g.3b(0);G j=V.3C(e);j.5P(f.jG());f.2I(j);F.af(j);L j},jK:I(){G e=F.2y();e.7S(F.$O[0]);G f=F.1G();f.3V();f.3X(e)},aa:I(){F.1G().3V()},at:I(h){G e=0;G g=F.2y();G f=g.7R();f.7S(h);f.6z(g.6D,g.eP);e=c.1W(f.3d()).1a;L e},gu:I(){L 1F d(F.1G().3b(0))},eO:I(h,f,m){if(1m m==="1q"){m=f}h=h[0]||h;G o=F.2y();o.7S(h);G p=F.9H(h);G l=K;G e=0,q;if(p.1a==1&&f){o.6w(p[0],f);o.6z(p[0],m)}N{3f(G n=0,j;j=p[n++];){q=e+j.1a;if(!l&&f>=e&&(f<q||(f==q&&n<p.1a))){o.6w(j,f-e);l=R}if(l&&m<=q){o.6z(j,m-e);4b}e=q}}G g=F.1G();g.3V();g.3X(o)},eK:I(h){F.$O.1N();h=h[0]||h;G f=F.V.4m();G m=1;G e=-1;f.6w(h,m);f.6z(h,e+2);G g=F.3n.1G();G j=F.V.4m();G l=F.V.6F("\\6A");c(h).2f(l);j.7N(l);g.3V();g.3X(j);c(l).1n()},9H:I(j){G h=[];if(j.3P==3){h.2p(j)}N{G g=j.bX;3f(G f=0,e=g.1a;f<e;++f){h.2p.eL(h,F.9H(g[f]))}}L h},2Z:I(){G e=K;G f=F.1G();if(f&&f.3O>0){e=f.3b(0).4P}L F.3s(e)},26:I(e){e=e||F.2Z();if(e){L F.3s(c(e).1O()[0])}N{L K}},2g:I(e){if(1m e==="1q"){e=F.2Z()}2D(e){if(F.5H(e)){if(c(e).3r("3w")){L K}L e}e=e.4w}L K},2L:I(f){G g=[];if(1m f=="1q"){G e=F.2y();if(e&&e.59===R){L[F.2g()]}G f=F.5N(e)}c.1g(f,c.Q(I(h,j){if(F.J.1v===K&&c(j).8A("X.3w").1D()==0){L K}if(F.5H(j)){g.2p(j)}},F));if(g.1a===0){g=[F.2g()]}L g},5H:I(e){L e.3P==1&&F.9D.3S(e.ju)},9J:I(e){L F.9D.3S(e)},5N:I(g,e){if(1m g=="1q"||g==K){G g=F.2y()}if(g&&g.59===R){if(1m e==="1q"&&F.9J(e)){G m=F.2g();if(m.U==e){L[m]}N{L[]}}N{L[F.2Z()]}}G f=[],l=[];G j=F.V.1G();if(!j.jy){f=F.9K(j.3b(0))}c.1g(f,c.Q(I(n,o){if(F.J.1v===K&&c(o).8A("X.3w").1D()==0){L K}if(1m e==="1q"){if(c.1W(o.89)!=""){l.2p(o)}}N{if(o.U==e){l.2p(o)}}},F));if(l.1a==0){if(1m e==="1q"&&F.9J(e)){G m=F.2g();if(m.U==e){L l.2p(m)}N{L[]}}N{l.2p(F.2Z())}}G h=l[l.1a-1];if(F.5H(h)){l=l.eN(0,-1)}L l},5X:I(e){if(!e){e=F.2Z()}2D(e){if(e.3P==1){if(c(e).3r("3w")){L K}L e}e=e.4w}L K},9K:I(f){f=f||F.2y();G g=f.4P;G e=f.6D;if(g==e){L[g]}G h=[];2D(g&&g!=e){h.2p(g=F.f4(g))}g=f.4P;2D(g&&g!=f.jC){h.eW(g);g=g.4w}L h},f4:I(e){if(e.jA()){L e.6M}N{2D(e&&!e.f7){e=e.4w}if(!e){L 2n}L e.f7}},7O:I(){L F.1G().3d()},f3:I(){G h="";G j=F.1G();if(j.3O){G f=F.V.3C("X");G e=j.3O;3f(G g=0;g<e;++g){f.5P(j.3b(g).kT())}h=f.2V}L F.9o(h)},1L:I(){if(!F.8s()){F.3h()}if(!F.J.34){F.eY(F.2y())}N{F.4t=34.lI()}},eY:I(h,e){if(!h){L}G g=c(\'<12 id="28-1x-1" 1f="T-28-1x">\'+F.J.1Y+"</12>",F.V)[0];G f=c(\'<12 id="28-1x-2" 1f="T-28-1x">\'+F.J.1Y+"</12>",F.V)[0];if(h.59===R){F.7Q(h,g,R)}N{F.7Q(h,g,R);F.7Q(h,f,K)}F.4t=F.$O.Y();F.1t(K,K)},7Q:I(e,g,f){G h=e.7R();h.5G(f);h.2I(g);h.lO()},1t:I(h,e){if(!F.J.34){if(h===R&&F.4t){F.$O.Y(F.4t)}G g=F.$O.15("12#28-1x-1");G f=F.$O.15("12#28-1x-2");if(F.1u("2S")){F.$O.1N()}N{if(!F.8s()){F.3h()}}if(g.1a!=0&&f.1a!=0){F.6C(g[0],0,f[0],0)}N{if(g.1a!=0){F.6C(g[0],0,2n,0)}}if(e!==K){F.6B();F.4t=K}}N{34.lM(F.4t)}},6B:I(e){if(!F.J.34){c.1g(F.$O.15("12.T-28-1x"),I(){G f=c.1W(c(F).Y().M(/[^\\lL-\\lE]/g,""));if(f==""){c(F).1n()}N{c(F).2e("1f").2e("id")}})}N{34.lw(F.4t)}},eH:I(){F.1L();F.4Y(F.J.1l.1C,F.J.ee,lu,c.Q(I(){c("#er").1B(c.Q(F.ep,F));2m(I(){c("#aP").1N()},4n)},F))},ep:I(){F.1y(K,K);G r=c("#aP").1w(),f=c("#es").1w(),n=c("<X></X>"),e=3z.g2(3z.f6()*f2),p=c(\'<1C id="1C\'+e+\'"><6v></6v></1C>\'),g,l,m,o;3f(g=0;g<r;g++){l=c("<2R></2R>");3f(m=0;m<f;m++){o=c("<16>"+F.J.1Y+"</16>");if(g===0&&m===0){o.1b(\'<12 id="28-1x-1">\'+F.J.1Y+"</12>")}c(l).1b(o)}p.1b(l)}n.1b(p);G h=n.Y();F.2v();F.1t();G j=F.2g()||F.2Z();if(j&&j.U!="ab"){if(j.U=="2T"){G j=c(j).1H("25, 2l")}c(j).2f(h)}N{F.7V(h,K)}F.1t();G q=F.$O.15("#1C"+e);F.6u();q.15("12#28-1x-1, 3a#28-1x-1").1n();q.2e("id");F.1c()},ef:I(){G e=c(F.26()).1H("1C");if(!F.3s(e)){L K}if(e.1D()==0){L K}F.1y();e.1n();F.1c()},eh:I(){G g=F.26();G e=c(g).1H("1C");if(!F.3s(e)){L K}if(e.1D()==0){L K}F.1y();G j=c(g).1H("2R");G f=j.7D().1a?j.7D():j.a3();if(f.1a){G h=f.5I("16").eF();if(h.1a){h.5g(\'<12 id="28-1x-1">\'+F.J.1Y+"</12>")}}j.1n();F.1t();F.1c()},eD:I(){G h=F.26();G g=c(h).1H("1C");if(!F.3s(g)){L K}if(g.1D()==0){L K}F.1y();G e=c(h).1H("16");if(!(e.is("16"))){e=e.1H("16")}G f=e.2k(0).m8;g.15("2R").1g(c.Q(I(j,l){G m=f-1<0?f+1:f-1;if(j===0){c(l).15("16").eq(m).5g(\'<12 id="28-1x-1">\'+F.J.1Y+"</12>")}c(l).15("16").eq(f).1n()},F));F.1t();F.1c()},eE:I(){G e=c(F.26()).1H("1C");if(!F.3s(e)){L K}if(e.1D()==0){L K}F.1y();if(e.15("3K").1D()!==0){F.9W()}N{G f=e.15("2R").eF().4H();f.15("16").Y(F.J.1Y);$3K=c("<3K></3K>");$3K.1b(f);e.5g($3K);F.1c()}},9W:I(){G e=c(F.26()).1H("1C");if(!F.3s(e)){L K}G f=e.15("3K");if(f.1D()==0){L K}F.1y();f.1n();F.1c()},eB:I(){F.a1("2U")},ew:I(){F.a1("2f")},ey:I(){F.a0("2U")},ez:I(){F.a0("2f")},a1:I(f){G e=c(F.26()).1H("1C");if(!F.3s(e)){L K}if(e.1D()==0){L K}F.1y();G g=c(F.26()).1H("2R");G h=g.4H();h.15("16").Y(F.J.1Y);if(f==="2f"){g.2f(h)}N{g.2U(h)}F.1c()},a0:I(j){G h=F.26();G g=c(h).1H("1C");if(!F.3s(g)){L K}if(g.1D()==0){L K}F.1y();G f=0;G l=F.2Z();G m=c(l).1H("2R");G e=c(l).1H("16");m.15("16").1g(c.Q(I(n,o){if(c(o)[0]===e[0]){f=n}},F));g.15("2R").1g(c.Q(I(n,p){G o=c(p).15("16").eq(f);G q=o.4H();q.Y(F.J.1Y);j==="2f"?o.2f(q):o.2U(q)},F));F.1c()},f9:I(){F.1L();F.4Y(F.J.1l.2K,F.J.eo,lS,c.Q(I(){c("#f1").1B(c.Q(F.fN,F));2m(I(){c("#aF").1N()},4n)},F))},fN:I(){G e=c("#aF").1w();e=F.6o(e);F.1t();G f=F.2g()||F.2Z();if(f){c(f).2f(e)}N{F.7V(e,K)}F.1c();F.2v()},8U:I(){F.1L();G e=c.Q(I(){F.5L=K;G m=F.1G();G f="",o="",n="";G l=F.26();G j=c(l).1O().2k(0);if(j&&j.U==="A"){l=j}if(l&&l.U==="A"){f=l.1M;o=c(l).1r();n=l.1X;F.5L=l}N{o=m.3d()}c("#aO").1w(o);G h=fJ.fI.1M.M(/\\/$/i,"");f=f.M(h,"");f=f.M(/^\\/#/,"#");f=f.M("80:","");if(F.J.6n===K){G g=1F 2j("^(8O|ay|5o)://"+fJ.fI.lY,"i");f=f.M(g,"")}c("#7p").1w(f);if(n==="4K"){c("#5i").7Z("7Y",R)}F.8Y=K;c("#eg").1B(c.Q(F.fF,F));2m(I(){c("#7p").1N()},4n)},F);F.4Y(F.J.1l.2b,F.J.eC,lX,e)},fF:I(){if(F.8Y){L}F.8Y=R;G l="",n="";G h=c("#7p").1w();G m=c("#aO").1w();if(h.3G("@")!=-1){h="80:"+h}N{if(h.3G("#")!=0){if(c("#5i").7Z("7Y")){l=\' 1X="4K"\';n="4K"}G j="((kS--)?[a-8H-9]+(-[a-8H-9]+)*.)+[a-z]{2,}";G g=1F 2j("^(8O|ay|5o)://"+j,"i");G f=1F 2j("^"+j,"i");if(h.3G(g)==-1&&h.3G(f)==0&&F.J.6n){h=F.J.6n+h}}}m=m.M(/<|>/g,"");G e="&2z;";if(F.1u("2S")){e="&2z;"}F.fP(\'<a 1M="\'+h+\'"\'+l+">"+m+"</a>"+e,c.1W(m),h,n)},fP:I(e,j,f,h){F.1t();if(j!==""){if(F.5L){F.1y();c(F.5L).1r(j).1e("1M",f);if(h!==""){c(F.5L).1e("1X",h)}N{c(F.5L).2e("1X")}}N{G g=c(e).1V("T-8Z-2b");F.1E("45",F.3c(g),K);G f=F.$O.15("a.T-8Z-2b");f.2e("1d").2t("T-8Z-2b").1g(I(){if(F.3o==""){c(F).2e("1f")}})}F.1c()}2m(c.Q(I(){if(F.J.4e){F.4e()}},F),5);F.2v()},fX:I(){F.1L();G e=c.Q(I(){G f=F.1G();G g="";if(F.9a()){g=f.1r}N{g=f.3d()}c("#ak").1w(g);if(!F.3J()&&!F.9w()){F.an("#4x",{3p:F.J.6m,2N:F.J.2N,3m:c.Q(F.9j,F),3e:c.Q(I(j,h){F.1i("fZ",h)},F),7A:F.J.aj})}F.bm("4x",{3q:R,3p:F.J.6m,3m:c.Q(F.9j,F),3e:c.Q(I(j,h){F.1i("fZ",h)},F)})},F);F.4Y(F.J.1l.35,F.J.fB,ec,e)},9j:I(f){F.1t();if(f!==K){G h=c("#ak").1w();if(h===""){h=f.al}G g=\'<a 1M="\'+f.51+\'" id="51-1x">\'+h+"</a>";if(F.1u("3A")&&!!F.3n.8N){g=g+"&2z;"}F.1K("45",g,K);G e=c(F.$O.15("a#51-1x"));if(e.1D()!=0){e.2e("id")}N{e=K}F.1c();F.1i("6m",e,f)}F.2v()},g0:I(){F.1L();G e=c.Q(I(){if(F.J.5Q){c.kV(F.J.5Q,c.Q(I(l){G g={},j=0;c.1g(l,c.Q(I(n,o){if(1m o.8e!=="1q"){j++;g[o.8e]=j}},F));G h=K;c.1g(l,c.Q(I(q,r){G p="";if(1m r.19!=="1q"){p=r.19}G n=0;if(!c.fV(g)&&1m r.8e!=="1q"){n=g[r.8e];if(h===K){h=".5K"+n}}G o=c(\'<1A 2G="\'+r.kZ+\'" 1f="5K 5K\'+n+\'" 3k="\'+r.1j+\'" 19="\'+p+\'" />\');c("#aI").1b(o);c(o).1B(c.Q(F.fc,F))},F));if(!c.fV(g)){c(".5K").2d();c(h).2h();G m=I(n){c(".5K").2d();c(".5K"+c(n.1X).1w()).2h()};G f=c(\'<5k id="kX">\');c.1g(g,I(o,n){f.1b(c(\'<3l 4d="\'+n+\'">\'+o+"</3l>"))});c("#aI").2U(f);f.6K(m)}},F))}N{c("#T-3j-4y-2").1n()}if(F.J.33||F.J.53){if(!F.3J()&&!F.9w()&&F.J.53===K){if(c("#4x").1a){F.an("#4x",{3p:F.J.33,2N:F.J.2N,3m:c.Q(F.aC,F),3e:c.Q(I(g,f){F.1i("9Z",f)},F),7A:F.J.7i})}}if(F.J.53===K){F.bm("4x",{3q:R,3p:F.J.33,3m:c.Q(F.aC,F),3e:c.Q(I(g,f){F.1i("9Z",f)},F)})}N{c("#4x").1k("6K.T",c.Q(F.gF,F))}}N{c(".4h").2d();if(!F.J.5Q){c("#8u").1n();c("#fK").2h()}N{c("#T-3j-4y-1").1n();c("#T-3j-4y-2").1V("5y");c("#fL").2h()}}if(!F.J.fQ&&(F.J.33||F.J.5Q)){c("#T-4y-7j-3").2d()}c("#ex").1B(c.Q(F.fh,F));if(!F.J.33&&!F.J.5Q){2m(I(){c("#4J").1N()},4n)}},F);F.4Y(F.J.1l.1j,F.J.fD,kF,e)},fr:I(g){G e=g;G f=e.1O().1O();G h=c.Q(I(){c("#ar").1w(e.1e("az"));c("#kI").1e("1M",e.1e("2G"));if(e.18("2r")=="6S"&&e.18("4c")=="2u"){c("#7w").1w("5d")}N{c("#7w").1w(e.18("4c"))}if(c(f).2k(0).U==="A"){c("#4J").1w(c(f).1e("1M"));if(c(f).1e("1X")=="4K"){c("#5i").7Z("7Y",R)}}c("#fW").1B(c.Q(I(){F.b8(e)},F));c("#fO").1B(c.Q(I(){F.fl(e)},F))},F);F.4Y(F.J.1l.6r,F.J.fC,j5,h)},b8:I(h){G e=c(h).1O().1O();G g=c(h).1O();G f=K;if(e.1a&&e[0].U==="A"){f=R;c(e).1n()}N{if(g.1a&&g[0].U==="A"){f=R;c(g).1n()}N{c(h).1n()}}if(g.1a&&g[0].U==="P"){F.3h();if(f===K){F.3Q(g)}}F.1i("kN",h);F.2v();F.1c()},fl:I(h){G f=c(h);G g=f.1O();f.1e("az",c("#ar").1w());G n=c("#7w").1w();G l="";F.4Q(K);if(n==="1s"){l="0 "+F.J.6p+" "+F.J.6p+" 0";f.18({"4c":"1s",2x:l})}N{if(n==="41"){l="0 0 "+F.J.6p+" "+F.J.6p+"";f.18({"4c":"41",2x:l})}N{if(n==="5d"){f.18({"4c":"",2r:"6S",2x:"3q"})}N{f.18({"4c":"",2r:"",2x:""})}}}G j=c.1W(c("#4J").1w());if(j!==""){G m=K;if(c("#5i").7Z("7Y")){m=R}if(g.2k(0).U!=="A"){G e=c(\'<a 1M="\'+j+\'">\'+F.3c(h)+"</a>");if(m){e.1e("1X","4K")}f.1J(e)}N{g.1e("1M",j);if(m){g.1e("1X","4K")}N{g.2e("1X")}}}N{if(g.2k(0).U==="A"){g.1J(F.3c(h))}}F.2v();F.3M();F.1c()},4Q:I(g){if(g!==K&&c(g.1X).1O().1D()!=0&&c(g.1X).1O()[0].id==="T-1j-1Z"){L K}G f=F.$O.15("#T-1j-1Z");if(f.1D()==0){L K}F.$O.15("#T-1j-bc, #T-1j-bA").1n();f.15("1A").18({4B:f[0].1d.4B,6Z:f[0].1d.6Z,4E:f[0].1d.4E,6T:f[0].1d.6T});f.18("2x","");f.15("1A").18("fs","");f.1J(I(){L c(F).1S()});c(V).2F("1B.T-1j-6s-2d");F.$O.2F("1B.T-1j-6s-2d");F.$O.2F("4q.T-1j-bs");F.1c()},fe:I(f){G e=c(f);e.1k("83",c.Q(I(){F.4Q(K)},F));e.1k("le",c.Q(I(){F.$O.1k("58.T-1j-fp-58",c.Q(I(){2m(c.Q(I(){F.3M();F.$O.2F("58.T-1j-fp-58");F.1c()},F),1)},F))},F));e.1k("1B",c.Q(I(l){if(F.$O.15("#T-1j-1Z").1D()!=0){L K}G n=K,q,p,m=e.2A()/e.1U(),o=20,j=10;G g=F.fz(e);G h=K;g.1k("83",I(r){h=R;r.1Q();m=e.2A()/e.1U();q=3z.4G(r.bB-e.eq(0).3g().1s);p=3z.4G(r.bv-e.eq(0).3g().1T)});c(F.V.29).1k("fy",c.Q(I(v){if(h){G s=3z.4G(v.bB-e.eq(0).3g().1s)-q;G r=3z.4G(v.bv-e.eq(0).3g().1T)-p;G u=e.1U();G w=86(u,10)+r;G t=3z.4G(w*m);if(t>o){e.2A(t);if(t<2X){F.4S.18({4B:"-7s",4E:"-ln",6t:"lm",6U:"ll fw"})}N{F.4S.18({4B:"-6Q",4E:"-ft",6t:"6Q",6U:"7s 6V"})}}q=3z.4G(v.bB-e.eq(0).3g().1s);p=3z.4G(v.bv-e.eq(0).3g().1T);F.1c()}},F)).1k("78",I(){h=K});F.$O.1k("4q.T-1j-bs",c.Q(I(s){G r=s.5s;if(F.2C.7b==r||F.2C.bn==r){F.1y(K,K);F.4Q(K);F.b8(e)}},F));c(V).1k("1B.T-1j-6s-2d",c.Q(F.4Q,F));F.$O.1k("1B.T-1j-6s-2d",c.Q(F.4Q,F))},F))},fz:I(f){G g=c(\'<12 id="T-1j-1Z" 21-T="6Y">\');g.18({2Q:"fA",2r:"3a-6S",bD:0,l3:"fx l6 l8(0, 0, 0, .6)","4c":f.18("4c")});g.1e("2W",K);if(f[0].1d.2x!="3q"){g.18({4B:f[0].1d.4B,6Z:f[0].1d.6Z,4E:f[0].1d.4E,6T:f[0].1d.6T});f.18("2x","")}N{g.18({2r:"6S",2x:"3q"})}f.18("fs",0.5).2f(g);F.4S=c(\'<12 id="T-1j-bc" 21-T="6Y">\'+F.J.1l.6r+"</12>");F.4S.18({2Q:"6N",8g:5,1T:"50%",1s:"50%",4B:"-6Q",4E:"-ft",bD:1,ff:"#fd",6q:"#fo",6t:"6Q",6U:"7s 6V",bk:"i9"});F.4S.1e("2W",K);F.4S.1k("1B",c.Q(I(){F.fr(f)},F));g.1b(F.4S);G e=c(\'<12 id="T-1j-bA" 21-T="6Y"></12>\');e.18({2Q:"6N",8g:2,bD:1,bk:"hw-6s",fv:"-ho",41:"-fw",hO:"fx hM #fo",ff:"#fd",2A:"fb",1U:"fb"});e.1e("2W",K);g.1b(e);g.1b(f);L e},fc:I(h){G f=\'<1A id="1j-1x" 2G="\'+c(h.1X).1e("3k")+\'" az="\'+c(h.1X).1e("19")+\'" />\';G g=F.26();if(F.J.55&&c(g).1H("li").1D()==0){f="<p>"+f+"</p>"}F.7g(f,R)},fh:I(){G f=c("#4J").1w();if(f!==""){G e=\'<1A id="1j-1x" 2G="\'+f+\'" />\';if(F.J.1z===K){e="<p>"+e+"</p>"}F.7g(e,R)}N{F.2v()}},aC:I(e){F.7g(e)},7g:I(f,h){F.1t();if(f!==K){G e="";if(h!==R){e=\'<1A id="1j-1x" 2G="\'+f.51+\'" />\';G g=F.26();if(F.J.55&&c(g).1H("li").1D()==0){e="<p>"+e+"</p>"}}N{e=f}F.1K("45",e,K);G j=c(F.$O.15("1A#1j-1x"));if(j.1a){j.2e("id")}N{j=K}F.1c();h!==R&&F.1i("33",j,f)}F.2v();F.3M()},fj:I(){c.54(F.J,{fB:44()+\'<1I id="T-3j-35-3H"><X id="T-3E" 1f="T-3E-3a" 1d="2r: 2u;"><12></12></X><1P id="gP" 6L="6E" 5l="" 7o="7m/1P-21"><2a>\'+F.J.1l.al+\'</2a><2i 23="1r" id="ak" 1f="5j" /><X 1d="2x-1T: 7s;"><2i 23="35" id="4x" 2M="\'+F.J.aj+\'" /></X></1P></1I>\',fC:44()+\'<1I id="T-3j-1j-6r"><2a>\'+F.J.1l.19+\'</2a><2i 23="1r" id="ar" 1f="5j" /><2a>\'+F.J.1l.2b+\'</2a><2i 23="1r" id="4J" 1f="5j" /><2a><2i 23="ei" id="5i"> \'+F.J.1l.aM+"</2a><2a>"+F.J.1l.fT+\'</2a><5k id="7w"><3l 4d="2u">\'+F.J.1l.2u+\'</3l><3l 4d="1s">\'+F.J.1l.1s+\'</3l><3l 4d="5d">\'+F.J.1l.5d+\'</3l><3l 4d="41">\'+F.J.1l.41+\'</3l></5k></1I><31><1R id="fW" 1f="3F h0">\'+F.J.1l.fY+\'</1R><1R 1f="3F 5F">\'+F.J.1l.5h+\'</1R><1R id="fO" 1f="3F 5r">\'+F.J.1l.fG+"</1R></31>",fD:44()+\'<1I id="T-3j-1j-3H"><X id="8u"><a 1M="#" id="T-4y-7j-1" 1f="5y">\'+F.J.1l.6P+\'</a><a 1M="#" id="T-4y-7j-2">\'+F.J.1l.aW+\'</a><a 1M="#" id="T-4y-7j-3">\'+F.J.1l.2b+\'</a></X><X id="T-3E" 1f="T-3E-3a" 1d="2r: 2u;"><12></12></X><1P id="iM" 6L="6E" 5l="" 7o="7m/1P-21"><X id="iG" 1f="4h"><2i 23="35" id="4x" 2M="\'+F.J.7i+\'" /></X><X id="fL" 1f="4h" 1d="2r: 2u;"><X id="aI"></X></X></1P><X id="fK" 1f="4h" 1d="2r: 2u;"><2a>\'+F.J.1l.f8+\'</2a><2i 23="1r" 2M="4J" id="4J" 1f="5j" /><br><br></X></1I><31><1R 1f="3F 5F">\'+F.J.1l.5h+\'</1R><1R 1f="3F 5r" id="ex">\'+F.J.1l.3H+"</1R></31>",eC:44()+\'<1I id="T-3j-2b-3H"><2a>ev</2a><2i 23="1r" 1f="5j" id="7p" /><2a>\'+F.J.1l.1r+\'</2a><2i 23="1r" 1f="5j" id="aO" /><2a><2i 23="ei" id="5i"> \'+F.J.1l.aM+\'</2a></1I><31><1R 1f="3F 5F">\'+F.J.1l.5h+\'</1R><1R id="eg" 1f="3F 5r">\'+F.J.1l.3H+"</1R></31>",ee:44()+\'<1I id="T-3j-1C-3H"><2a>\'+F.J.1l.ej+\'</2a><2i 23="1r" 1D="5" 4d="2" id="aP" /><2a>\'+F.J.1l.ek+\'</2a><2i 23="1r" 1D="5" 4d="3" id="es" /></1I><31><1R 1f="3F 5F">\'+F.J.1l.5h+\'</1R><1R id="er" 1f="3F 5r">\'+F.J.1l.3H+"</1R></31>",eo:44()+\'<1I id="T-3j-2K-3H"><1P id="i1"><2a>\'+F.J.1l.eI+\'</2a><4l id="aF" 1d="2A: 99%; 1U: it;"></4l></1P></1I><31><1R 1f="3F 5F">\'+F.J.1l.5h+\'</1R><1R id="f1" 1f="3F 5r">\'+F.J.1l.3H+"</1R></31>"})},4Y:I(o,l,f,p){G m=c("#95");if(!m.1a){F.$eX=m=c(\'<X id="95" 1d="2r: 2u;"></X>\');c("29").5g(F.$eX)}if(F.J.93){m.2h().1k("1B",c.Q(F.2v,F))}G h=c("#97");if(!h.1a){F.$3j=h=c(\'<X id="97" 1d="2r: 2u;"><X id="8K">&im;</X><5U id="8w"></5U><X id="8j"></X></X>\');c("29").1b(F.$3j)}c("#8K").1k("1B",c.Q(F.2v,F));F.5V=c.Q(I(q){if(q.2C===F.2C.bz){F.2v();L K}},F);c(V).42(F.5V);F.$O.42(F.5V);F.5e=K;if(l.2J("#")==0){F.5e=c(l);c("#8j").52().1b(F.5e.Y());F.5e.Y("")}N{c("#8j").52().1b(l)}h.15("#8w").Y(o);if(1m c.fn.f5!=="1q"){h.f5({iR:"#8w"});h.15("#8w").18("bk","iX")}G e=c("#8u");if(e.1a){G j=F;e.15("a").1g(I(q,r){q++;c(r).1k("1B",I(t){t.1Q();e.15("a").2t("5y");c(F).1V("5y");c(".4h").2d();c("#4h"+q).2h();c("#j2").1w(q);if(j.3J()===K){G s=h.eU();h.18("2x-1T","-"+(s+10)/2+"2s")}})})}h.15(".5F").1k("1B",c.Q(F.2v,F));G n=h.15("31 1R");G g=n.1D();if(g>0){c(n).18("2A",(f/g)+"2s")}if(F.J.3T===R){F.5x=F.V.29.30}N{F.5x=F.$O.30()}if(F.3J()===K){h.18({2Q:"8h",1T:"-aX",1s:"50%",2A:f+"2s",4E:"-"+(f/2)+"2s"}).2h();F.9S=c(V.29).18("8r");c(V.29).18("8r","ap")}N{h.18({2Q:"8h",2A:"2X%",1U:"2X%",1T:"0",1s:"0",2x:"0",5W:"h7"}).2h()}if(1m p==="I"){p()}2m(c.Q(I(){F.1i("hd")},F),11);c(V).2F("gN.3j");if(F.3J()===K){2m(I(){G q=h.eU();h.18({1T:"50%",1U:"3q",5W:"3q",4B:"-"+(q+10)/2+"2s"})},10)}h.15("2i[23=1r]").gO(I(q){if(q.5s===13){h.15(".5r").1B();q.1Q()}})},2v:I(){c("#8K").2F("1B",F.2v);c("#97").5J("hX",c.Q(I(){G e=c("#8j");if(F.5e!==K){F.5e.Y(e.Y());F.5e=K}e.Y("");if(F.J.93){c("#95").2d().2F("1B",F.2v)}c(V).ge("42",F.5V);F.$O.ge("42",F.5V);F.1t();if(F.J.3T&&F.5x){c(F.V.29).30(F.5x)}N{if(F.J.3T===K&&F.5x){F.$O.30(F.5x)}}F.1i("i7")},F));if(F.3J()===K){c(V.29).18("8r",F.9S?F.9S:"gk")}L K},iT:I(e){c(".4h").2d();c("#8u").15("a").2t("5y").eq(e-1).1V("5y");c("#4h"+e).2h()},gF:I(l){G h=l.1X.79;3f(G g=0,j;j=h[g];g++){F.9y(j)}},9y:I(e){F.ga(e,c.Q(I(f){F.g7(e,f)},F))},ga:I(e,h){G f=1F gp();G g="?";if(F.J.53.3G(/\\?/)!="-1"){g="&"}f.8i("iK",F.J.53+g+"2M="+e.2M+"&23="+e.23,R);if(f.gx){f.gx("1r/hl; gQ=x-gT-hU")}f.hm=I(j){if(F.gv==4&&F.ag==4n){c("#T-3E").eJ();h(hJ(F.hI))}N{if(F.gv==4&&F.ag!=4n){}}};f.g1()},g5:I(g,e){G f=1F gp();if("hA"in f){f.8i(g,e,R)}N{if(1m gl!="1q"){f=1F gl();f.8i(g,e)}N{f=2n}}L f},g7:I(f,e){G g=F.g5("iW",e);if(!g){}N{g.gc=c.Q(I(){if(g.ag==4n){c("#T-3E, #T-3E-8Q").2d();G l=e.3R("?");if(!l[0]){L K}F.1t();G h="";h=\'<1A id="1j-1x" 2G="\'+l[0]+\'" />\';if(F.J.55){h="<p>"+h+"</p>"}F.1K("45",h,K);G j=c(F.$O.15("1A#1j-1x"));if(j.1a){j.2e("id")}N{j=K}F.1c();F.1i("33",j,K);F.2v();F.3M()}N{}},F);g.ia=I(){};g.6P.i4=I(h){};g.gf("i3-hY",f.23);g.gf("x-i0-iy","hf-hx");g.g1(f)}},bm:I(g,e){F.2E={3p:K,3m:K,3e:K,5M:K,b7:K,3q:K,2i:K};c.54(F.2E,e);G f=c("#"+g);if(f.1a&&f[0].U==="hF"){F.2E.2i=f;F.el=c(f[0].1P)}N{F.el=f}F.fS=F.el.1e("5l");if(F.2E.3q){c(F.2E.2i).6K(c.Q(I(h){F.el.aG(I(j){L K});F.b6(h)},F))}N{if(F.2E.b7){c("#"+F.2E.b7).1B(c.Q(F.b6,F))}}},b6:I(f){c("#T-3E").eJ();F.f0(F.4F,F.eM())},eM:I(){F.id="f"+3z.g2(3z.f6()*f2);G f=F.V.3C("X");G e=\'<1v 1d="2r:2u" id="\'+F.id+\'" 2M="\'+F.id+\'"></1v>\';f.2V=e;c(f).8E("29");if(F.2E.5M){F.2E.5M()}c("#"+F.id).eZ(c.Q(F.fM,F));L F.id},f0:I(j,h){if(F.2E.2i){G l="io"+F.id,e="ip"+F.id;F.1P=c(\'<1P 5l="\'+F.2E.3p+\'" 6L="9i" 1X="\'+h+\'" 2M="\'+l+\'" id="\'+l+\'" 7o="7m/1P-21" />\');if(F.J.2N!==K&&1m F.J.2N==="2Y"){c.1g(F.J.2N,c.Q(I(n,f){if(f!=2n&&f.3d().2J("#")===0){f=c(f).1w()}G o=c("<2i/>",{23:"ap",2M:n,4d:f});c(F.1P).1b(o)},F))}G g=F.2E.2i;G m=c(g).4H();c(g).1e("id",e).2U(m).8E(F.1P);c(F.1P).18("2Q","6N").18("1T","-aX").18("1s","-aX").8E("29");F.1P.aG()}N{j.1e("1X",h).1e("6L","9i").1e("7o","7m/1P-21").1e("5l",F.2E.3p);F.4F.aG()}},fM:I(){G h=c("#"+F.id)[0],j;if(h.fE){j=h.fE}N{if(h.aZ){j=h.aZ.V}N{j=3n.iN[F.id].V}}if(F.2E.3m){c("#T-3E").2d();if(1m j!=="1q"){G g=j.29.2V;G f=g.22(/\\{(.|\\n)*\\}/)[0];f=f.M(/^\\[/,"");f=f.M(/\\]$/,"");G e=c.6G(f);if(1m e.3e=="1q"){F.2E.3m(e)}N{F.2E.3e(F,e);F.2v()}}N{F.2v();iL("fR hi!")}}F.el.1e("5l",F.fS);F.el.1e("1X","")},an:I(f,e){F.4C=c.54({3p:K,3m:K,3e:K,gW:K,2N:K,1r:F.J.1l.fm,fu:F.J.1l.fg,7A:K},e);if(3n.9h===1q){L K}F.b5=c(\'<X 1f="hL"></X>\');F.47=c(\'<X 1f="hv">\'+F.4C.1r+"</X>");F.fq=c(\'<X 1f="hB">\'+F.4C.fu+"</X>");F.b5.1b(F.47);c(f).2U(F.b5);c(f).2U(F.fq);F.47.1k("l4",c.Q(I(){L F.eA()},F));F.47.1k("lc",c.Q(I(){L F.eG()},F));F.47.2k(0).ld=c.Q(I(g){g.1Q();F.47.2t("9R").1V("58");F.bo(F.4C.3p,g.71.79[0],K,K,K,F.4C.7A)},F)},bo:I(h,l,f,g,n,m){if(!f){G o=c.lf.fk();if(o.6P){o.6P.kK("3E",c.Q(F.eu,F),K)}c.kM({fk:I(){L o}})}F.1i("58",n);G j=1F 9h();if(m!==K){j.1b(m,l)}N{j.1b("35",l)}if(F.J.2N!==K&&1m F.J.2N==="2Y"){c.1g(F.J.2N,c.Q(I(p,e){if(e!=2n&&e.3d().2J("#")===0){e=c(e).1w()}j.1b(p,e)},F))}c.fU({3p:h,kO:"Y",21:j,kY:K,94:K,kU:K,23:"9i",3m:c.Q(I(q){q=q.M(/^\\[/,"");q=q.M(/\\]$/,"");G p=(1m q==="88"?c.6G(q):q);if(f){g.5J("kR",I(){c(F).1n()});G e=c("<1A>");e.1e("2G",p.51).1e("id","8Q-1j-1x");F.fH(n,e[0]);G r=c(F.$O.15("1A#8Q-1j-1x"));if(r.1a){r.2e("id")}N{r=K}F.1c();F.3M();if(r){F.1i("33",r,p)}if(1m p.3e!=="1q"){F.1i("9Z",p)}}N{if(1m p.3e=="1q"){F.4C.3m(p)}N{F.4C.3e(F,p);F.4C.3m(K)}}},F)})},eA:I(){F.47.1V("9R");L K},eG:I(){F.47.2t("9R");L K},eu:I(g,h){G f=g.et?86(g.et/g.lC*2X,10):g;F.47.1r("ly "+f+"% "+(h||""))},3J:I(){L/(lx|ls|lv|lD)/.3S(6I.6H)},9w:I(){L/lN/.3S(6I.6H)},7U:I(e){if(1m(e)==="1q"){L 0}L 86(e.M("2s",""),10)},3c:I(e){L c("<X>").1b(c(e).eq(0).4H()).Y()},lF:I(f){G e=V.3C("6O");e.2V=f;L e.89||e.9C||""},eV:I(e){L jz.4u.3d.4k(e)=="[2Y 44]"},7h:I(e){e=e.M(/n;|<br>|<br\\/>|&2z;/gi,"");e=e.M(/\\s/g,"");e=e.M(/^<p>[^\\W\\w\\D\\d]*?<\\/p>$/i,"");L e==""},7a:I(){L!!6I.6H.22(/jF\\/7\\./)},1u:I(f){G g=6I.6H.3i();G e=/(gH)[\\/]([\\w.]+)/.1E(g)||/(8N)[ \\/]([\\w.]+)/.1E(g)||/(3A)[ \\/]([\\w.]+).*(jL)[ \\/]([\\w.]+)/.1E(g)||/(3A)[ \\/]([\\w.]+)/.1E(g)||/(7K)(?:.*70|)[ \\/]([\\w.]+)/.1E(g)||/(2H) ([\\w.]+)/.1E(g)||g.2J("jH")>=0&&/(8L)(?::| )([\\w.]+)/.1E(g)||g.2J("jI")<0&&/(2S)(?:.*? 8L:([\\w.]+)|)/.1E(g)||[];if(f=="70"){L e[2]}if(f=="3A"){L(e[1]=="8N"||e[1]=="3A")}if(e[1]=="8L"){L f=="2H"}if(e[1]=="gH"){L f=="3A"}L f==e[1]},9a:I(){if(F.1u("2H")&&86(F.1u("70"),10)<9){L R}L K},g6:I(f){G e=f.kr(R);G g=F.V.3C("X");g.5P(e);L g.2V},ao:I(){G e=F.$O[0];G g=F.V.aU();G f;2D((f=e.6M)){g.5P(f)}L g},3s:I(e){if(!e){L K}if(F.J.1v){L e}if(c(e).8A("X.3w").1a==0||c(e).3r("3w")){L K}N{L e}},5T:I(e){G f=F.26(),g=F.2Z();L f&&f.U===e?f:g&&g.U===e?g:K},aK:I(){G f=F.2g();G h=F.at(f);G g=c.1W(c(f).1r()).M(/\\n\\r\\n/g,"");G e=g.1a;if(h==e){L R}N{L K}},8s:I(){G e,f=F.1G();if(f&&f.3O&&f.3O>0){e=f.3b(0).4P}if(!e){L K}if(F.J.1v){if(F.gu().e1()){L!F.$O.is(e)}N{L R}}L c(e).1H("X.3w").1a!=0},4a:I(f,e){if(c(f).1e(e)==""){c(f).2e(e)}},c8:I(g,f){G e=2n;2D((e=g.2J(f))!==-1){g.8t(e,1)}L g}};b.4u.5t.4u=b.4u;c.4g.fn.9u=I(s,z,e,C,E){G h=/(^|<|\\s)(9v\\..+?\\..+?)([.),]?)(\\s|\\.\\s+|\\)|>|$)/,g=/(^|<|\\s)(((5o?|ay):\\/\\/|80:).+?)([.),]?)(\\s|\\.\\s+|\\)|>|$)/,u=/(5o?:\\/\\/.*\\.(?:bJ|kx|bG|c1))/gi,D=/5o?:\\/\\/(?:[0-9A-Z-]+\\.)?(?:ko\\.be\\/|dF\\.7C\\S*[^\\w\\-\\s])([\\w\\-]{11})(?=[^\\w\\-]|$)(?![?=&+%\\w.-]*(?:[\'"][^<>]*>|<\\/a>))[?=&+%\\w.-]*/ig,B=/5o?:\\/\\/(9v\\.)?dh.7C\\/(\\d+)($|\\/)/;G f=(F.$O?F.$O.2k(0):F).bX,A=f.1a;2D(A--){G t=f[A];if(t.3P===3){G p=t.8f;if(C&&p){G q=\'<1v 2A="ec" 1U="jD" 2G="\',x=\'" dz="0" lJ></1v>\';if(p.22(D)){p=p.M(D,q+"//9v.dF.7C/3Z/$1"+x);c(t).2f(p).1n()}N{if(p.22(B)){p=p.M(B,q+"//lA.dh.7C/2K/$2"+x);c(t).2f(p).1n()}}}if(e&&p&&p.22(u)){p=p.M(u,\'<1A 2G="$1">\');c(t).2f(p).1n()}if(z&&p&&(p.22(h)||p.22(g))){G r=R;G o=R;2D(r){G y;G j=h;G w=h.1E(p);G v=g.1E(p);if(w&&w[2]&&v&&v[2]){G m=p.2J(w[2]);G l=p.2J(v[2]);if(m<l){y=w;j=h}N{y=v;j=g}}N{if(w&&w[2]){y=w;j=h}N{if(v&&v[2]){y=v;j=g}}}r=(y&&y.1a);if(r){y=y[2]}if(r&&y&&y.1a>E){y=y.87(0,E)+"..."}if(o){p=p.M(/&/g,"&6J;").M(/</g,"<").M(/>/g,">")}if(r&&y){if(j==h){p=p.M(h,\'$1<a 1M="\'+s+\'$2">\'+c.1W(y)+"</a>$3$4")}N{p=p.M(g,\'$1<a 1M="$2">\'+c.1W(y)+"</a>$5$6")}}o=K}c(t).2f(p).1n()}}N{if(t.3P===1&&!/^(a|1R|4l)$/i.3S(t.U)){c.4g.fn.9u.4k(t,s,z,e,C,E)}}}}})(jN);',62,1374,'|||||||||||||||||||||||||||||||||||||||||this|var||function|opts|false|return|replace|else|editor||proxy|true||redactor|tagName|document||div|html||||span|||find|td||css|title|length|append|sync|style|attr|class|each|toolbar|callback|image|on|curLang|typeof|remove|func|source|undefined|text|left|selectionRestore|browser|iframe|val|marker|bufferSet|linebreaks|img|click|table|size|exec|new|getSelection|closest|section|replaceWith|execCommand|selectionSave|href|focus|parent|form|preventDefault|button|contents|top|height|addClass|trim|target|invisibleSpace|box||data|match|type||ul|getParent||selection|body|label|link|blockquote|hide|removeAttr|after|getBlock|show|input|RegExp|get|ol|setTimeout|null|air|push|frame|display|px|removeClass|none|modalClose|pre|margin|getRange|nbsp|width|script|keyCode|while|uploadOptions|off|src|msie|insertNode|indexOf|video|getBlocks|name|uploadFields|dropdown|BLOCKQUOTE|position|tr|mozilla|LI|before|innerHTML|contenteditable|100|object|getCurrent|scrollTop|footer||imageUpload|rangy|file|||||inline|getRangeAt|outerHtml|toString|error|for|offset|focusWithSaveScroll|toLowerCase|modal|rel|option|success|window|className|url|auto|hasClass|isParentRedactor|fullpage|italic|bold|redactor_editor|font|strong|Math|webkit|buttonGet|createElement|re|progress|redactor_modal_btn|search|insert|inArray|isMobile|thead|substr|observeImages|buttons|rangeCount|nodeType|selectionStart|split|test|autoresize|php|removeAllRanges|tag|addRange|redactor_placeholder|embed||right|keyup|buttonActive|String|inserthtml||dropareabox|content|formatBlocks|removeEmptyAttr|break|float|value|observeLinks|deleted|Redactor|redactor_tab|toolbarFixed|emptyHtml|call|textarea|createRange|200|shortcutsLoad|audio|keydown|buffer|shiftKey|savedSel|prototype|alignmentTags|parentNode|redactor_file|tab|charAt|allowedTags|marginTop|draguploadOptions|visual|marginLeft|element|round|clone|join|redactor_file_link|_blank|del|unlink|Insert|unorderedlist|startContainer|imageResizeHide|formatBlock|imageEditter|orderedlist|selectall|dir|underline|indent|modalInit|range||filelink|empty|s3|extend|paragraphy|formatting|textareamode|drop|collapsed|case|direction|PRE|center|modalcontent|strike|prepend|cancel|redactor_link_blank|redactor_input|select|action|linkObserverTooltipClose|code|https|cleanRemoveSpaces|cleanGetTabs|redactor_modal_action_btn|which|init|outdent|buttonBuild|isFunction|saveModalScroll|redactor_tabs_act|placeholder|autosave|tabindex|dropact|insertAfterLastElement|TD|redactor_btn_modal_close|collapse|nodeTestBlocks|children|fadeOut|redactorfolder|insert_link_node|start|getNodes|param|appendChild|imageGetJson|observeStart|selectionEnd|currentOrParentIs|header|hdlModalClose|minHeight|getElement|insertunorderedlist|redactor_act||toolbarFixedTarget|toolbarExternal|alignmentSet|tagblock|||cleanlevel|deniedTags|phpTags|uuid|typewriter|Delete|Add|Header|horizontalrule|dblEnter|modified|shortcuts|enter|setNonEditable|last|fileUpload|linkProtocol|cleanStripTags|imageFloatMargin|color|edit|resize|fontSize|buttonActiveObserver|tbody|setStart|rebuffer|rtePaste|setEnd|u200B|selectionRemoveMarkers|selectionSet|endContainer|post|createTextNode|parseJSON|userAgent|navigator|amp|change|method|firstChild|absolute|DIV|upload|11px|pasteInsert|block|marginRight|padding|10px|insertAfter|convertDivs|verified|marginBottom|version|dataTransfer|||||||mouseup|files|isIe11|BACKSPACE|saveScroll|documentElement|focusSet|buildCodearea|imageInsert|isEmpty|imageUploadParam|control|align|placeTag|multipart|x200b|enctype|redactor_link_url|colspan|tabSpaces|7px|background|convertImageLinks|cleanParagraphy|redactor_form_image_align|rowspan|indentValue|ENTER|uploadParam|cleanConvertInlineTags|com|prev|template|activeButtons|icon|javascript|dropdownHideAll|airBindMousemoveHide|opera|alignright|aligncenter|setStartAfter|getSelectionText|justify|selectionSetMarker|cloneRange|selectNodeContents|alignleft|normalize|insertHtmlAdvanced|separator|autosaveInterval|checked|prop|mailto|clipboardUpload|set|mousedown|paste|insertHtml|parseInt|substring|string|textContent|head|toolbarFixedBox|insertorderedlist|meta|folder|nodeValue|zIndex|fixed|open|redactor_modal_inner|ASIDE|setSpansVerifiedHtml|FOOTER|inlineRemoveFormatReplace|insertLineBreak|tmp|alignment|overflow|isFocused|splice|redactor_tabs|sourceHeight|redactor_modal_header|HEADER|ARTICLE|setSpansVerified|parents|inlineMethods|ADDRESS|blockLevelElements|appendTo|deleteContents|SECTION|z0|buttonsHideOnMobile|Row|redactor_modal_close|rv|th|chrome|http|Column|drag|dropdownHide|delete_row|delete_table|linkShow|clipboardUploadUrl|tooltip|one|linkInsertPressed|added|||align_justify|modalOverlay|contentType|redactor_modal_overlay|redactor_toolbar|redactor_modal|toolbarObserveScroll||oldIE|toolbarFixedTopOffset|iframeDoc|merge|align_center|Table|align_left|FormData|POST|fileCallback|align_right|airShow|removeEmptyTags|delete_column|syncClean|parseHTML|cleanRemoveEmptyTags|execPasteFrag|indentingIndent|pasteHTML|formatLinkify|www|isIPad|insert_table|s3uploadFile|cleanEmpty||indentingOutdent|innerText|rTestBlock|address|alignmentLeft|alignmentRight|getTextNodesIn|alignmentJustify|tagTestBlock|getRangeSelectedNodes|indentingStart|contOwnLine|insideOutdent|ownLine|insert_row_above|cleanConverters|hover|modalSaveBodyOveflow|not|redactor_button_disabled|delete_head|tableDeleteHead|buttonInactive|dropdownShow|imageUploadError|tableAddColumn|tableAddRow|BR|next|add_head|activeButtonsStates|link_insert|cleanConvertProtected|insert_column_left|insert_row_below|selectionRemove|BODY|btn|templateVars|insert_column_right|selectionElement|status|INLINE|convertVideoLinks|fileUploadParam|redactor_filename|filename|convertLinks|draguploadInit|extractContent|hidden|formatblock|redactor_file_alt|insertingAfterLastElement|getCaretOffset|iframeAppend|buildEnable|formatQuote|iframePage|ftp|alt|plugins|maxHeight|imageCallback|RedactorPlugins|buildEventKeydownInsertLineBreak|redactor_insert_video_area|submit|cleanTag|redactor_image_box|dnbImageTypes|isEndOfElement|DOWN|link_new_tab|clipboardData|redactor_link_url_text|redactor_table_rows|cleanFinish|rBlockTest|metaKey|line|createDocumentFragment|cleanFontTag|choose|2000px|FIGCAPTION|contentWindow|ctrlKey|cleannewLevel|iframeLoad|sourceOld|placeholderGet|droparea|uploadSubmit|trigger|imageRemove|cleanEncodeEntities|placeholderOnFocus|toggle|editter|buildBindKeyboard||tfoot|iframeAddCss|fullscreen|cleanSavePreCode|focusEnd|cursor|setFullpageOnInit|uploadInit|DELETE|dragUploadAjax|buildAfter|placeholderOnBlur||delete|pasteClipboardAppendFields|buildOptions|pageY|blur|inlineEachNodes|italicTag|ESC|resizer|pageX|alignmentCenter|lineHeight|boldTag|pasteClipboardMozilla|jpeg|fieldset|cleanlineBefore|png|inlineUnwrapSpan|cleanlineAfter|area|HTML|H6|inlineFormat|DD|cleanHtml|DL|wrapAll|filter|buffer_|cleanUnverified|childNodes|cleanReplacer|OUTPUT|DT|gif|transparent|double|formatEmpty|placeholderStart|unwrap|Color|removeFromArrayByValue|quot|replaced|paragraphs|cleanReConvertProtected|map|redactor_air_|clipboardFilePaste|items|buildEventKeydown|the|to|altKey|originalEvent|buildEventClipboardUpload|focusCallback|textareaKeydownCallback|buildEventDrop|buildEventPaste|cleanup|Align|LEFT_WIN|buildEventKeyup|buildEventKeydownBackspace|buildEventKeyupConverters|linkSize|iframeStart|buildPlugins|Array|tabFocus|Center|sel|TAB|buildEventKeydownPre|buildEventKeydownTab|dragUpload|toolbarInit|header3|header2|header4|header5|setCodeIframe|setEditor|header1|quote|newLevel|Edit|langs|lang|paragraph|getCodeIframe|xhtml|buildFromElement|buildFromTextarea|buildAddClasses|min|redactor_editor_wym|wym|buildContent|buildMobile|nofollow|linkNofollow|noeditable|buildStart|mobile|iframeCreate|write||buttonActiveVisual|dropdownBuild|buttonInactiveVisual|vimeo|buttonInactiveAll|List|redactor_dropdown_box_||redactor_dropdown|airBindHide|innerWidth|innerHeight|key|returnValue|buttonActiveToggle||link_edit|formattingPre|subscript|inserthorizontalrule|execUnlink|frameborder|execLists|superscript|strikethrough|switch|redactor_dropdown_link|youtube|alignjustify|default|redactor_air|airEnable|Link|Video|Image|Right|toggleVisual|Left|placeholderRemoveFromCode|placeholderRemoveFromEditor|clearInterval|close|Code|placeholderBlur|placeholderFocus|toggleCode|tidyHtml|toolbarOverflow|Head|equals|10005|toolbar_fixed_box|visibility|formattingTags|buttonSource|textareaIndenting|indenting|setInterval|toolbarBuild|airButtons|500|inlineSetMethods|modal_table|tableDeleteTable|redactor_insert_link_btn|tableDeleteRow|checkbox|rows|columns||||modal_video|tableInsert||redactor_insert_table_btn|redactor_table_columns|loaded|uploadProgress|URL|tableAddRowBelow|redactor_upload_btn|tableAddColumnLeft|tableAddColumnRight|draguploadOndrag|tableAddRowAbove|modal_link|tableDeleteColumn|tableAddHead|first|draguploadOndragleave|tableShow|video_html_code|fadeIn|setCaretAfter|apply|uploadFrame|slice|setCaret|endOffset|catch|try|selectionWrap|formatChangeTag|outerHeight|isString|unshift|overlay|selectionCreateMarker|load|uploadForm|redactor_insert_video_btn|99999|getSelectionHtml|nextNode|draggable|random|nextSibling|image_web_link|videoShow||8px|imageThumbClick|000|imageResize|backgroundColor|or_choose|imageCallbackLink|aside|modalTemplatesInit|xhr|imageSave|drop_file_here||fff|inside|dropalternative|imageEdit|opacity|18px|atext|bottom|5px|1px|mousemove|imageResizeControls|relative|modal_file|modal_image_edit|modal_image|contentDocument|linkProcess|save|insertNodeToCaretPositionFromPoint|location|self|redactor_tab3|redactor_tab2|uploadLoaded|videoInsert|redactorSaveBtn|linkInsert|imageTabLink|Upload|element_action|image_position|ajax|isEmptyObject|redactor_image_delete_btn|fileShow|_delete|fileUploadError|imageShow|send|floor|H4|H3|s3createCORSRequest|getFragmentHtml|s3uploadToS3|cleanSpaces|internal|s3executeOnSignedUrl|pastePre|onload|pasteClipboardUpload|unbind|setRequestHeader|pasteClipboardUploadMozilla|H1||H2|visible|XDomainRequest|pastePlainText|clientY|caretPositionFromPoint|XMLHttpRequest|clientX|outerHTML|article||getCaretOffsetRange|readyState|caretRangeFromPoint|overrideMimeType|replaceLineBreak|pasteClean|SPAN|H5|createTextRange|moveToPoint|clipboard|s3handleFileSelect|bufferUndo|opr|pop|bufferRedo|linkObserver|redactor_format_h1|Alignment|focusin|keypress|redactorUploadFileForm|charset|Name|redactor_format_blockquote|user|redactor_format_pre|Or|preview|No|arguments|trade|redactor_modal_delete_btn|||||||300px|copy|redactor_format_h3|Open|hellip|here|modalOpened|Drop|public|Choose|redactor_format_h2|failed|u00a0|Underline|plain|onreadystatechange|File|4px|LEFT|8203||defaultView|ownerDocument|optional|redactor_dropareabox|nw|read|strict|CTRL|withCredentials|redactor_dropalternative|META|download|Horizontal|INPUT|syncBefore|sourceWidth|responseText|decodeURIComponent|mdash|redactor_droparea|solid|dropdowns|border|Download|isArray|stylesheet|syncAfter|removeChild|defined|219|536|fast|Type|Chrome|amz|redactorInsertVideoForm|getToolbar|Content|onprogress|FileReader|readAsDataURL|modalClosed|getAsFile|pointer|onerror|Rule|Callback||getEditor|||getObject|removeData|getBox|45px|getIframe|times||redactorUploadForm|redactorUploadFile|startOffset|blurCallback||160px|destroy|enableObjectResizing|enableInlineTableEditing|separator_drop3|acl|TH|anchor|noneditable|bull|dash|use|Deleted|redactor_tab1|redactor_format_h5|Anchor|redactor_|GET|alert|redactorInsertImageForm|frames|redactor_box|index|separator_drop2|handle|undo|modalSetTab|about|Justify|PUT|move|separator_drop1|redo|1class|TEXTAREA|redactor_tab_selected|blank|redactor_format_h4|380|col|colgroup|math|fontcolor|caption|unselectable|frameset|backcolor|Font|comment|legend|hgroup|ns|hasOwnProperty|Italic|Bold|summary|menu|nav|figure|figcaption|details|concat|uFEFF|nodeName|JustifyLeft|JustifyRight|JustifyCenter|isCollapsed|Object|hasChildNodes|Embed|commonAncestorContainer|281|applet|Trident|extractContents|trident|compatible|u200D|selectionAll|safari|JustifyFull|jQuery|noscript|Back|weight|Quote|blockRemoveStyle|blockSetStyle|blockRemoveClass|blockSetClass|blockSetAttr|blockRemoveAttr|EndToEnd|setEndPoint|duplicate|offsetNode|inlineRemoveClass|inlineSetClass|insertText|inlineRemoveFormat|toUpperCase|insertBeforeCursor|setEndAfter|attributes|inlineRemoveStyle|inlineSetStyle|inlineRemoveAttr|inlineSetAttr|insertDoubleLineBreak|pasteBefore|sub|sup|small|cite|pasteAfter|Unlink|result|Normal|youtu|Formatting|fake|cloneNode|MsoListParagraphCxSpLast|MsoListParagraphCxSpMiddle|MsoListParagraphCxSpFirst|shapes|MsoListParagraph|jpg|u200b|guid|docs|sid|OL|UL|redactor_toolbar_|610|external|Columns|redactor_image_edit_src|VERSION|addEventListener|1000|ajaxSetup|imageDelete|dataType|scroll|focusNode|slow|xn|cloneContents|processData|getJSON|Rows|redactor_image_box_select|cache|thumb|autosaveError|Title|Web|outline|dragover|shortcutsLoadFormat|dashed|Text|rgba|web|removeFormat|Email|dragleave|ondrop|dragstart|ajaxSettings|escape|encodeURIComponent||Position|None|3px|9px|13px|such|redactor_separator_drop|collapseToStart|Ordered|iPod||300|BlackBerry|removeMarkers|iPhone|Loading|redactor_dropdown_|player|buttonRemove|total|Android|u1C7F|stripHtml|SUP|SUB|saveSelection|allowfullscreen|Unordered|u0000|restoreSelection|iPad|detach|buttonAddAfter|buttonAddBefore|Above|600|Save|ltr|stopPropagation|dropdownShown|460|host|Below|buttonTagToActiveState|Cancel|buttonRemoveIcon|Indent|Outdent|buttonAwesome|buttonAdd|buttonAddFirst|cellIndex|buttonChangeIcon'.split('|'),0,{}))
\ No newline at end of file
--- /dev/null
+<?php
+class HeadwayUpdaterAPI {
+ private $api_url = '';
+ private $api_data = array();
+ private $name = '';
+ private $slug = '';
+
+ /**
+ * Class constructor.
+ *
+ * @uses plugin_basename()
+ * @uses hook()
+ *
+ * @param string $_api_url The URL pointing to the custom API endpoint.
+ * @param string $_plugin_file Path to the plugin file.
+ * @param array $_api_data Optional data to send with API calls.
+ * @return void
+ */
+ function __construct( $args = null ) {
+
+ $this->api_url = trailingslashit(HEADWAY_SITE_URL);
+ $this->name = $args['path'];
+ $this->slug = basename( $args['path'], '.php');
+ $this->version = $args['current_version'];
+
+ $this->item_slug = $args['slug'];
+ $this->item_name = $args['name'];
+
+ $this->api_data = urlencode_deep(array(
+ 'item_slug' => $args['slug'],
+ 'item_name' => $args['name'],
+ 'license' => headway_get_license_key($args['slug']),
+ 'author' => ''
+ ));
+
+ // Set up hooks.
+ $this->hook();
+ }
+
+ /**
+ * Set up Wordpress filters to hook into WP's update process.
+ *
+ * @uses add_filter()
+ *
+ * @return void
+ */
+ private function hook() {
+
+ add_filter( 'pre_set_site_transient_update_plugins', array( $this, 'pre_set_site_transient_update_plugins_filter' ) );
+ add_filter( 'plugins_api', array( $this, 'plugins_api_filter' ), 10, 3 );
+ add_filter( 'http_request_args', array( $this, 'http_request_args' ), 10, 2 );
+
+ add_filter( 'headway_updater_products', array( $this, 'add_theme_license_input' ) );
+
+ }
+
+
+ function add_theme_license_input($other_products) {
+
+ $other_products[$this->item_slug] = $this->item_name;
+
+ return $other_products;
+
+ }
+
+
+ /**
+ * Check for Updates at the defined API endpoint and modify the update array.
+ *
+ * This function dives into the update api just when Wordpress creates its update array,
+ * then adds a custom API call and injects the custom plugin data retrieved from the API.
+ * It is reassembled from parts of the native Wordpress plugin update code.
+ * See wp-includes/update.php line 121 for the original wp_update_plugins() function.
+ *
+ * @uses api_request()
+ *
+ * @param array $_transient_data Update array build by Wordpress.
+ * @return array Modified update array with custom plugin data.
+ */
+ function pre_set_site_transient_update_plugins_filter( $_transient_data ) {
+
+
+ if( empty( $_transient_data ) ) return $_transient_data;
+
+ $to_send = array( 'slug' => $this->slug );
+
+ $api_response = $this->api_request( 'plugin_latest_version', $to_send );
+
+ if( false !== $api_response && is_object( $api_response ) && isset( $api_response->new_version ) ) {
+ if( version_compare( $this->version, $api_response->new_version, '<' ) )
+ $_transient_data->response[$this->name] = $api_response;
+ }
+ return $_transient_data;
+ }
+
+
+ /**
+ * Updates information on the "View version x.x details" page with custom data.
+ *
+ * @uses api_request()
+ *
+ * @param mixed $_data
+ * @param string $_action
+ * @param object $_args
+ * @return object $_data
+ */
+ function plugins_api_filter( $_data, $_action = '', $_args = null ) {
+ if ( ( $_action != 'plugin_information' ) || !isset( $_args->slug ) || ( $_args->slug != $this->slug ) ) return $_data;
+
+ $to_send = array( 'slug' => $this->slug );
+
+ $api_response = $this->api_request( 'plugin_information', $to_send );
+ if ( false !== $api_response ) $_data = $api_response;
+
+ return $_data;
+ }
+
+
+ /**
+ * Disable SSL verification in order to prevent download update failures
+ *
+ * @param array $args
+ * @param string $url
+ * @return object $array
+ */
+ function http_request_args( $args, $url ) {
+ // If it is an https request and we are performing a package download, disable ssl verification
+ if( strpos( $url, 'https://' ) !== false && strpos( $url, 'edd_action=package_download' ) ) {
+ $args['sslverify'] = false;
+ }
+ return $args;
+ }
+
+ /**
+ * Calls the API and, if successfull, returns the object delivered by the API.
+ *
+ * @uses get_bloginfo()
+ * @uses wp_remote_post()
+ * @uses is_wp_error()
+ *
+ * @param string $_action The requested action.
+ * @param array $_data Parameters for the API action.
+ * @return false||object
+ */
+ private function api_request( $_action, $_data ) {
+
+ global $wp_version;
+
+ $data = array_merge( $this->api_data, $_data );
+
+ if( $data['slug'] != $this->slug )
+ return;
+
+ if( empty( $data['license'] ) )
+ return;
+
+ $api_params = array(
+ 'edd_action' => 'get_version',
+ 'license' => $data['license'],
+ 'name' => $data['item_name'],
+ 'slug' => $this->slug,
+ 'author' => $data['author']
+ );
+ $request = wp_remote_post( $this->api_url, array( 'timeout' => 15, 'sslverify' => false, 'body' => $api_params ) );
+
+ if ( ! is_wp_error( $request ) ):
+ $request = json_decode( wp_remote_retrieve_body( $request ) );
+ if( $request && isset( $request->sections ) )
+ $request->sections = maybe_unserialize( $request->sections );
+ return $request;
+ else:
+ return false;
+ endif;
+ }
+}
\ No newline at end of file
--- /dev/null
+<?php
+class Headway_Theme_Updater {
+ private $remote_api_url;
+ private $request_data;
+ private $response_key;
+ private $theme_slug;
+ private $license_key;
+ private $version;
+ private $author;
+
+ function __construct( $args = array() ) {
+ $args = wp_parse_args( $args, array(
+ 'remote_api_url' => HEADWAY_SITE_URL,
+ 'request_data' => array(),
+ 'theme_slug' => get_template(),
+ 'item_name' => '',
+ 'license' => '',
+ 'version' => '',
+ 'author' => ''
+ ) );
+ extract( $args );
+
+ $theme = wp_get_theme( sanitize_key( $theme_slug ) );
+ $this->license = $license;
+ $this->item_name = $item_name;
+ $this->version = ! empty( $version ) ? $version : $theme->get( 'Version' );
+ $this->theme_slug = sanitize_key( $theme_slug );
+ $this->author = $author;
+ $this->remote_api_url = $remote_api_url;
+ $this->response_key = $this->theme_slug . '-update-response';
+
+
+ $input_priority = $this->theme_slug == 'headway' ? -50 : 10;
+ add_filter( 'headway_updater_products', array( &$this, 'add_theme_license_input' ), $input_priority );
+
+ add_filter( 'site_transient_update_themes', array( &$this, 'theme_update_transient' ) );
+ add_filter( 'delete_site_transient_update_themes', array( &$this, 'delete_theme_update_transient' ) );
+ add_action( 'load-update-core.php', array( &$this, 'delete_theme_update_transient' ) );
+ add_action( 'load-themes.php', array( &$this, 'delete_theme_update_transient' ) );
+ add_action( 'load-themes.php', array( &$this, 'load_themes_screen' ) );
+ }
+
+
+ function add_theme_license_input($other_products) {
+
+ $other_products[$this->theme_slug] = $this->item_name;
+
+ return $other_products;
+
+ }
+
+ function load_themes_screen() {
+ add_thickbox();
+ add_action( 'admin_notices', array( &$this, 'update_nag' ) );
+ }
+
+ function update_nag() {
+ $theme = wp_get_theme( $this->theme_slug );
+
+ $api_response = get_transient( $this->response_key );
+
+ if( false === $api_response )
+ return;
+
+ $update_url = wp_nonce_url( 'update.php?action=upgrade-theme&theme=' . urlencode( $this->theme_slug ), 'upgrade-theme_' . $this->theme_slug );
+ $update_onclick = ' onclick="if ( confirm(\'' . esc_js( __( "Before clicking OK to update, be sure that you have a backup of your website." ) ) . '\') ) {return true;}return false;"';
+
+ if ( version_compare( $this->version, $api_response->new_version, '<' ) ) {
+
+ echo '<div id="update-nag">';
+ printf( '<strong>%1$s %2$s</strong> is available. <a href="%3$s" class="thickbox" title="%4s">Check out what\'s new</a> or <a href="%5$s"%6$s>update now</a>.',
+ $theme->get( 'Name' ),
+ $api_response->new_version,
+ '#TB_inline?width=640&inlineId=' . $this->theme_slug . '_changelog',
+ $theme->get( 'Name' ),
+ $update_url,
+ $update_onclick
+ );
+ echo '</div>';
+ echo '<div id="' . $this->theme_slug . '_' . 'changelog" style="display:none;">';
+ echo wpautop( $api_response->sections['changelog'] );
+ echo '</div>';
+ }
+ }
+
+ function theme_update_transient( $value ) {
+ $update_data = $this->check_for_update();
+ if ( $update_data ) {
+ $value->response[ $this->theme_slug ] = $update_data;
+ }
+ return $value;
+ }
+
+ function delete_theme_update_transient() {
+ delete_transient( $this->response_key );
+ }
+
+ function check_for_update() {
+
+ if( empty( $this->license ) )
+ return false;
+
+ $theme = wp_get_theme( $this->theme_slug );
+
+ $update_data = get_transient( $this->response_key );
+
+ if ( false === $update_data ) {
+ $failed = false;
+
+ $api_params = array(
+ 'edd_action' => 'get_version',
+ 'license' => $this->license,
+ 'name' => $this->item_name,
+ 'slug' => $this->theme_slug,
+ 'author' => $this->author,
+ 'url' => home_url()
+ );
+
+ $response = wp_remote_post( $this->remote_api_url, array( 'timeout' => 15, 'sslverify' => false, 'body' => $api_params ) );
+
+ // make sure the response was successful
+ if ( is_wp_error( $response ) || 200 != wp_remote_retrieve_response_code( $response ) ) {
+ $failed = true;
+ }
+
+ $update_data = json_decode( wp_remote_retrieve_body( $response ) );
+
+ if ( ! is_object( $update_data ) ) {
+ $failed = true;
+ }
+
+ // if the response failed, try again in 30 minutes
+ if ( $failed ) {
+ $data = new stdClass;
+ $data->new_version = $this->version;
+ set_transient( $this->response_key, $data, strtotime( '+30 minutes' ) );
+ return false;
+ }
+
+ // if the status is 'ok', return the update arguments
+ if ( ! $failed ) {
+ $update_data->sections = maybe_unserialize( $update_data->sections );
+ set_transient( $this->response_key, $update_data, strtotime( '+12 hours' ) );
+ }
+ }
+
+ if ( version_compare( $this->version, $update_data->new_version, '>=' ) ) {
+ return false;
+ }
+
+ return (array) $update_data;
+ }
+}
\ No newline at end of file
--- /dev/null
+<!DOCTYPE HTML>
+<html <?php language_attributes(); ?>>
+
+<head>
+
+<meta charset="<?php echo get_bloginfo('charset'); ?>" />
+<link rel="profile" href="http://gmpg.org/xfn/11" />
+
+<style type="text/css">
+#ace-editor {
+ position: absolute;
+ top: 0;
+ right: 0;
+ bottom: 0;
+ left: 0;
+}
+</style>
+
+<script type="text/javascript" src="<?php echo headway_url() . '/library/visual-editor/' . ((defined('SCRIPT_DEBUG') && SCRIPT_DEBUG) ? 'scripts' : 'scripts-min') . '/deps/ace/ace.min.js'; ?> " charset="utf-8"></script>
+
+</head>
+
+<body>
+
+ <div id="ace-editor"></div>
+
+</body>
+</html>
\ No newline at end of file
--- /dev/null
+<?php
+headway_register_visual_editor_box('HeadwayGridWizardBox');
+class HeadwayGridWizardBox extends HeadwayVisualEditorBoxAPI {
+
+ /**
+ * Slug/ID of panel. Will be used for HTML IDs and whatnot.
+ **/
+ protected $id = 'grid-wizard';
+
+
+ /**
+ * Name of panel. This will be shown in the title.
+ **/
+ protected $title = 'Grid Wizard';
+
+ protected $description = 'Choose a preset or a page to clone';
+
+
+ /**
+ * Which mode to put the panel on.
+ **/
+ protected $mode = 'grid';
+
+ protected $center = false;
+
+ protected $width = 600;
+
+ protected $height = 420;
+
+ protected $closable = true;
+
+ protected $draggable = false;
+
+ protected $resizable = false;
+
+ protected $black_overlay = true;
+
+ protected $black_overlay_opacity = 0.3;
+
+ protected $black_overlay_iframe = true;
+
+ protected $load_with_ajax = true;
+
+ protected $load_with_ajax_callback = '$(\'div#box-grid-wizard div.box-content\').tabs({active: 0});';
+
+
+
+ public function content() {
+
+ $current_layout = headway_post('layout');
+
+ $pages_to_clone_select_options = self::clone_pages_select_walker(HeadwayLayout::get_pages());
+ $templates_to_assign_select_options = self::templates_to_assign_select_options();
+
+?>
+ <ul id="grid-wizard-tabs" class="tabs">
+ <?php
+ if ( $pages_to_clone_select_options !== '' || $templates_to_assign_select_options !== '' ) {
+
+ echo '<li><a href="#grid-wizard-tab-clone-page">Clone Existing Layout</a></li>';
+ echo '<li><a href="#grid-wizard-tab-presets">Presets</a></li>';
+
+ } else {
+
+ echo '<li><a href="#grid-wizard-tab-presets">Presets</a></li>';
+
+ }
+
+ if ( $templates_to_assign_select_options !== '' && strpos($current_layout, 'template-') === false )
+ echo '<li><a href="#grid-wizard-tab-assign-template">Use Shared Layout</a></li>';
+
+ echo '<li><a href="#grid-wizard-tab-import-export">Import/Export</a></li>';
+ ?>
+ </ul>
+
+ <div id="grid-wizard-tab-presets" class="tab-content">
+
+ <div id="grid-wizard-presets-step-1">
+ <div class="grid-wizard-presets-row">
+ <span class="layout-preset layout-preset-selected" id="layout-right-sidebar" title="Content | Sidebar">
+ <img src="<?php echo headway_url() . '/library/visual-editor/images/layouts/layout-right-sidebar.png'; ?>" alt="" />
+ </span>
+
+ <span class="layout-preset" id="layout-left-sidebar" title="Sidebar | Content">
+ <img src="<?php echo headway_url() . '/library/visual-editor/images/layouts/layout-left-sidebar.png'; ?>" alt="" />
+ </span>
+
+ <span class="layout-preset" id="layout-two-right" title="Content | Sidebar 1 | Sidebar 2">
+ <img src="<?php echo headway_url() . '/library/visual-editor/images/layouts/layout-two-right.png'; ?>" alt="" />
+ </span>
+ </div>
+
+ <div class="grid-wizard-presets-row">
+ <span class="layout-preset" id="layout-two-both" title="Sidebar 1 | Content | Sidebar 2">
+ <img src="<?php echo headway_url() . '/library/visual-editor/images/layouts/layout-two-both.png'; ?>" alt="" />
+ </span>
+
+ <span class="layout-preset" id="layout-all-content" title="Content">
+ <img src="<?php echo headway_url() . '/library/visual-editor/images/layouts/layout-all-content.png'; ?>" alt="" />
+ </span>
+ </div>
+ </div><!-- #grid-wizard-presets-step-1 -->
+
+ <div id="grid-wizard-presets-step-2">
+
+ <h4>Select Which Blocks to Mirror</h4>
+
+ <p class="grid-wizard-info">To save time, Headway allows you to "mirror" your blocks. If you already have a widget area or sidebar that's configured, you may choose to use it by using the select boxes below.</p>
+
+ <div id="grid-wizard-presets-mirroring-column-1" class="grid-wizard-presets-mirroring-column">
+ <div id="grid-wizard-presets-mirroring-select-header">
+ <h5>Header</h5>
+
+ <div class="select-container">
+ <select>
+ <option value="">— Do Not Mirror —</option>
+ <?php
+ echo self::get_blocks_select_options_for_mirroring('header');
+ ?>
+ </select>
+ </div><!-- .select-container -->
+ </div>
+
+ <div id="grid-wizard-presets-mirroring-select-navigation">
+ <h5>Navigation</h5>
+
+ <div class="select-container">
+ <select>
+ <option value="">— Do Not Mirror —</option>
+ <?php
+ echo self::get_blocks_select_options_for_mirroring('navigation');
+ ?>
+ </select>
+ </div><!-- .select-container -->
+ </div>
+
+ <div id="grid-wizard-presets-mirroring-select-content">
+ <h5>Content</h5>
+
+ <div class="select-container">
+ <select>
+ <option value="">— Do Not Mirror —</option>
+ <?php
+ echo self::get_blocks_select_options_for_mirroring('content');
+ ?>
+ </select>
+ </div><!-- .select-container -->
+ </div>
+ </div>
+
+ <div id="grid-wizard-presets-mirroring-column-2" class="grid-wizard-presets-mirroring-column">
+ <div id="grid-wizard-presets-mirroring-select-sidebar-1">
+ <h5>Sidebar 1</h5>
+
+ <div class="select-container">
+ <select>
+ <option value="">— Do Not Mirror —</option>
+ <?php
+ echo self::get_blocks_select_options_for_mirroring('widget-area');
+ ?>
+ </select>
+ </div><!-- .select-container -->
+ </div>
+
+ <div id="grid-wizard-presets-mirroring-select-sidebar-2">
+ <h5>Sidebar 2</h5>
+
+ <div class="select-container">
+ <select>
+ <option value="">— Do Not Mirror —</option>
+ <?php
+ echo self::get_blocks_select_options_for_mirroring('widget-area');
+ ?>
+ </select>
+ </div><!-- .select-container -->
+ </div>
+
+ <div id="grid-wizard-presets-mirroring-select-footer">
+ <h5>Footer</h5>
+
+ <div class="select-container">
+ <select>
+ <option value="">— Do Not Mirror —</option>
+ <?php
+ echo self::get_blocks_select_options_for_mirroring('footer');
+ ?>
+ </select>
+ </div><!-- .select-container -->
+ </div>
+ </div>
+
+ </div><!-- #grid-wizard-presets-step-2 -->
+
+ <div class="grid-wizard-buttons">
+ <span class="grid-wizard-use-empty-grid">Use Empty Grid</span>
+
+ <?php
+ if ( $pages_to_clone_select_options !== '' ) {
+
+ $next_button_style = null;
+ $use_button_style = ' style="display: none;"';
+
+ } else {
+
+ $next_button_style = ' style="display: none;"';
+ $use_button_style = null;
+
+ }
+
+ echo '<span id="grid-wizard-button-preset-next" class="button grid-wizard-button-next"' . $next_button_style . '>Next →</span>';
+ echo '<span id="grid-wizard-button-preset-use-preset" class="button grid-wizard-button-next"' . $use_button_style . '>Finish →</span>';
+ echo '<span id="grid-wizard-button-preset-previous" class="button grid-wizard-button-previous" style="display: none;">← Previous</span>';
+ ?>
+ </div>
+
+ </div><!-- #grid-wizard-tab-presets -->
+
+ <?php
+ if ( $pages_to_clone_select_options !== '' || $templates_to_assign_select_options !== '' ) {
+ ?>
+ <div id="grid-wizard-tab-clone-page" class="tab-content">
+
+ <h4>Choose a Layout to Clone</h4>
+
+ <?php
+ echo '<div class="select-container"><select id="grid-wizard-pages-to-clone">';
+
+ echo '<option value="" disabled="disabled">— Pages —</option>';
+
+ echo $pages_to_clone_select_options;
+
+ echo '<option value="" disabled="disabled">— Templates —</option>';
+
+ echo $templates_to_assign_select_options;
+
+ echo '</select></div><!-- .select-container -->';
+ ?>
+
+ <div class="grid-wizard-buttons">
+ <span class="grid-wizard-use-empty-grid">Use Empty Grid</span>
+
+ <span id="grid-wizard-button-clone-page" class="button grid-wizard-button-next">Clone Layout →</span>
+ </div>
+
+ </div><!-- #grid-wizard-tab-clone-page -->
+ <?php
+ }
+
+
+ if ( $templates_to_assign_select_options !== '' && strpos($current_layout, 'template-') === false ) {
+ ?>
+ <div id="grid-wizard-tab-assign-template" class="tab-content">
+
+ <h4>Choose a Shared Layout</h4>
+
+ <?php
+ echo '<div class="select-container"><select id="grid-wizard-assign-template">';
+
+ echo '<option value="" disabled="disabled">— Select a Shared Layout —</option>';
+
+ echo $templates_to_assign_select_options;
+
+ echo '</select></div><!-- .select-container -->';
+ ?>
+
+ <div class="grid-wizard-buttons">
+ <span class="grid-wizard-use-empty-grid">Use Empty Grid</span>
+
+ <span id="grid-wizard-button-assign-template" class="button grid-wizard-button-next">Assign Layout →</span>
+ </div>
+
+ </div><!-- #grid-wizard-tab-assign-template -->
+ <?php
+ }
+ ?>
+
+ <div id="grid-wizard-tab-import-export" class="tab-content">
+
+ <div id="grid-wizard-import" class="grid-wizard-buttons grid-wizard-import-export-group">
+ <h4>Import Layout</h4>
+ <p>Select the Headway Layout file you would like to import.<br /><br /><strong>Note:</strong> When you browse to and select a file below the imported layout's blocks will automatically be added to the current layout.</p>
+ <input type="file" />
+ <span class="button" id="grid-wizard-import-select-file">Select File & Import</span>
+ </div><!-- #grid-wizard-import -->
+
+ <div id="grid-wizard-export" class="grid-wizard-buttons grid-wizard-import-export-group">
+ <h4>Export Current Layout</h4>
+ <p>Clicking on the button below will package up the current layout and its blocks into a file to be saved and imported later.</p>
+ <span class="button" id="grid-wizard-export-download-file">Download Export File</span>
+ </div><!-- #grid-wizard-export -->
+
+ </div><!-- #grid-wizard-tab-import-export -->
+
+ <?php
+ }
+
+
+ static function get_blocks_select_options_for_mirroring($block_type) {
+
+ $return = '';
+
+ $blocks = HeadwayBlocksData::get_blocks_by_type($block_type);
+
+ //If there are no blocks, then just return the Do Not Mirror option.
+ if ( !isset($blocks) || !is_array($blocks) )
+ return $return;
+
+ foreach ( $blocks as $block_id => $block ) {
+
+ //Get the block instance
+ $block = HeadwayBlocksData::get_block($block_id);
+
+ //If the block is mirrored, skip it
+ if ( headway_get('mirror-block', $block['settings'], false) )
+ continue;
+
+ //If the block is in the same layout as the current block, then do not allow it to be used as a block to mirror.
+ if ( $block['layout'] == headway_post('layout') )
+ continue;
+
+ //Create the default name by using the block type and ID
+ $default_name = HeadwayBlocks::block_type_nice($block['type']);
+
+ //If we can't get a name for the layout, then things probably aren't looking good. Just skip this block.
+ if ( !($layout_name = HeadwayLayout::get_name($block['layout'])) )
+ continue;
+
+ //Get alias if it exists, otherwise use the default name
+ $return .= '<option value="' . $block['id'] . '">' . headway_get('alias', $block['settings'], $default_name) . ' – ' . $layout_name . '</option>';
+
+ }
+
+ return $return;
+
+ }
+
+
+ static function clone_pages_select_walker($pages, $depth = 0) {
+
+ $return = '';
+
+ foreach($pages as $id => $children) {
+
+ $layout_id_fragments = explode(HeadwayLayout::$sep, $id);
+
+ $status = HeadwayLayout::get_status($id);
+
+ /* Take care of layouts that are the front page or blog index */
+ if ( get_option('show_on_front') === 'page' && (isset($layout_id_fragments[1]) && $layout_id_fragments[1] == 'page') ) {
+
+ /* If the page is set as the static homepage or blog page, hide it if they don't have children. */
+ if ( end($layout_id_fragments) == get_option('page_on_front') || end($layout_id_fragments) == get_option('page_for_posts') ) {
+
+ /* Layout has children--add the no edit class and has children class. */
+ if ( is_array($children) && count($children) !== 0 )
+ $disabled = true;
+
+ /* If the layout doesn't have children, then just hide it. */
+ else
+ continue;
+
+ }
+
+ }
+
+ /* Handle layouts that aren't customized or have a template */
+ if ( headway_get('customized', $status, false) === false || headway_get('template', $status, false) !== false ) {
+
+ /* If there ARE customized children, add the no-edit class */
+ if ( is_array($children) && count($children) !== 0 ) {
+
+ /* Check if the children are customized. */
+ if ( HeadwayVisualEditorDisplay::is_any_layout_child_customized($children) ) {
+
+ $disabled = true;
+
+ } else
+ continue;
+
+ /* If there aren't any children, do not display the node at all */
+ } else
+ continue;
+
+ }
+
+ /* If the current layout is selected, then make it disabled. */
+ if ( headway_post('layout') == $id )
+ $disabled = true;
+
+ /* Output Stuff */
+ $depth_display = str_repeat(' ', $depth);
+
+ $disabled = ( isset($disabled) && $disabled === true ) ? ' disabled="disabled"' : null;
+
+ $return .= '<option value="' . $id . '"' . $disabled .'>' . $depth_display . HeadwayLayout::get_name($id) . '</option>';
+
+ if ( is_array($children) && count($children) !== 0 )
+ $return .= self::clone_pages_select_walker($children, $depth + 1);
+
+ }
+
+ return $return;
+
+ }
+
+
+ static function templates_to_assign_select_options() {
+
+ $templates = HeadwayLayout::get_templates();
+
+ $return = '';
+
+ foreach ( $templates as $id => $name) {
+
+ $return .= '<option value="template-' . $id . '">' . $name . '</option>';
+
+ }
+
+ return $return;
+
+ }
+
+
+}
\ No newline at end of file
--- /dev/null
+<?php
+headway_register_visual_editor_box('HeadwaySnapshotsBox');
+class HeadwaySnapshotsBox extends HeadwayVisualEditorBoxAPI {
+
+
+ /**
+ * Slug/ID of panel. Will be used for HTML IDs and whatnot.
+ **/
+ protected $id = 'snapshots';
+
+
+ /**
+ * Name of panel. This will be shown in the title.
+ **/
+ protected $title = 'Snapshots';
+
+ protected $description = 'Restore your work with snapshots.';
+
+
+ /**
+ * Which mode to put the panel on.
+ **/
+ protected $mode = 'all';
+
+ protected $center = true;
+
+ protected $width = 400;
+
+ protected $height = 500;
+
+ protected $min_width = 350;
+
+ protected $min_height = 200;
+
+ protected $closable = true;
+
+ protected $draggable = true;
+
+ protected $resizable = false;
+
+
+ public function content() {
+
+ echo '
+ <span class="button button-blue" data-bind="click: saveSnapshot">Save Snapshot</span>
+ <span class="spinner"></span>
+
+ <ul id="snapshots-list" data-bind="foreach: snapshots">
+ <li data-bind="attr: {id: \'snapshot-\' + id}">
+ <span class="snapshot-timestamp" data-bind="text: $parent.formatSnapshotDatetime(timestamp)"></span>
+ <span class="snapshot-delete" data-bind="click: $parent.deleteSnapshot" title="Delete Snapshot">Delete</span>
+
+ <span class="button button-small" data-bind="click: $parent.rollbackToSnapshot">Rollback</span>
+
+ <p class="snapshot-comments" data-bind="text:comments, visible: comments"></p>
+ </li>
+ </ul>
+ ';
+
+ }
+
+
+}
\ No newline at end of file
--- /dev/null
+@customized_element_color = #199ebf;
+
+/* Side Panel Structure */
+ body.visual-editor-mode-design {
+ div#panel {
+ right: 290px !important;
+ .transition('right 100ms linear');
+ }
+
+ div#iframe-container {
+ right: 290px !important;
+ .transition('right 100ms linear');
+ }
+ }
+
+ body.visual-editor-mode-design.side-panel-hidden {
+ div#panel {
+ right: 0 !important;
+ }
+
+ div#iframe-container {
+ right: 0 !important;
+ }
+
+ div#side-panel-container {
+ right: -290px;
+ }
+ }
+
+ div#side-panel-container {
+ position: fixed;
+ right: 0;
+ top: 36px;
+ z-index: 13;
+ bottom: 0;
+ border-left: 1px solid #ccc;
+ -moz-box-shadow: 0 0 1px 1px rgba(0,0,0,0.15),0 2px 12px 0 rgba(0,0,0,0.12);
+ -webkit-box-shadow: 0 0 1px 1px rgba(0,0,0,0.15),0 2px 12px 0 rgba(0,0,0,0.12);
+ box-shadow: 0 0 1px 1px rgba(0,0,0,0.15),0 2px 12px 0 rgba(0,0,0,0.12);
+ width: 290px;
+
+ .transition('right 100ms linear');
+
+ div#side-panel {
+ height: 100%;
+ width: 100%;
+ background: #ffffff;
+
+ div#side-panel-top {
+ width: 100%;
+ height: 100%;
+ position: relative;
+ }
+
+ div#side-panel-bottom {
+ display: none;
+ position: relative; /* For cog positioning */
+ background: #eee;
+ border-top: 1px solid #d8d8d8;
+ box-shadow: 8px -10px 15px rgba(255, 255, 255, 1);
+ width: 100%;
+ height: 55%;
+ padding-top: 80px;
+ .border-box();
+ }
+ }
+ }
+
+ /* Once element is selected, split the side panel */
+ body.design-editor-element-selected {
+ div#side-panel-container div#side-panel {
+ div#side-panel-top {
+ height: 45%;
+ }
+
+ div#side-panel-bottom {
+ display: block;
+ }
+ }
+ }
+/* End Side Panel Structure */
+
+
+/* Element Selector */
+ /* Element Selector Filters */
+ ul#element-selector-tabs {
+ width: 100%;
+ height: 35px;
+ background: #eee;
+ margin-bottom: 5px;
+
+ li {
+ display: block;
+ float: left;
+ color: #777;
+ padding: 0 10px;
+ height: 35px;
+ line-height: 35px;
+
+ a {
+ color: inherit;
+ text-decoration: none;
+ }
+
+ &:hover {
+ color: #2EA2CC;
+ }
+
+ &.ui-state-active {
+ background: #fff;
+ color: #555;
+ }
+ }
+
+ }
+ /* End Element Selector Filters */
+
+ /* Collapse arrow */
+ #side-panel-collapse-arrow {
+ position: fixed;
+ right: 6px;
+ top: 43px;
+ cursor: pointer;
+
+ width: 20px;
+ height: 20px;
+ display: block;
+
+ &::after {
+ -webkit-border-radius: 50%;
+ border-radius: 50%;
+ content: "\f148";
+ color: #777;
+ background: #eee;
+ font: normal 20px/1 'dashicons';
+ speak: none;
+ display: block;
+ padding: 0;
+ text-indent: 0;
+ text-align: center;
+ position: relative;
+ .antialias();
+ text-decoration: none !important;
+
+ -webkit-transform: rotate(180deg);
+ -ms-transform: rotate(180deg);
+ transform: rotate(180deg);
+
+ -webkit-transition: -webkit-transform 200ms;
+ transition: transform 200ms;
+ }
+
+ &:hover::after {
+ color: #0074a2;
+ }
+ }
+
+ body.side-panel-hidden #side-panel-collapse-arrow::after {
+ -webkit-transform: rotate(0);
+ -ms-transform: rotate(0);
+ transform: rotate(0);
+ }
+ /* End collapse arrow */
+
+ @element_selector_tree_x_width = 18px;
+ @element_selector_tree_x_padding = 5px;
+
+ @element_selector_group_padding = 15px;
+
+ @element_selector_breadcrumb_trail_color = #bbb;
+
+ div#design-editor-element-selector-container {
+ width: 100%;
+ position: absolute;
+ top: 35px;
+ bottom: 0;
+
+ overflow-y: auto;
+ overflow-x: hidden;
+
+ .antialias();
+
+ -webkit-mask: -webkit-linear-gradient(top, transparent, black 25px);
+ }
+
+ /* All Elements/Layout Elements Toggle */
+ div#design-editor-element-selector-container span.button {
+ margin: 20px 0 30px 20px; /* Bottom margin for scroll padding */
+ display: none;
+ }
+
+ div#design-editor-element-selector-container.show-only-layout-elements span#element-selector-show-all-elements {
+ display: inline-block;
+ }
+
+ div#design-editor-element-selector-container:not(.show-only-layout-elements) span#element-selector-show-current-layout-elements {
+ display: inline-block;
+ }
+ /* End all elements/layout elements toggle buttons */
+
+
+ ul#design-editor-element-selector {
+ position: relative;
+ list-style: none;
+ color: #333;
+
+ .cog-container {
+ margin-top: -10px !important;
+ }
+
+ ul {
+ display: none;
+ }
+
+ ul.group-elements {
+ margin-left: 15px !important;
+ }
+
+ ul.group-elements ul {
+ padding-left: @element_selector_tree_x_width + @element_selector_tree_x_padding;
+ border-left: 1px dotted @element_selector_breadcrumb_trail_color;
+
+ /* Offsets to get children ULs to line up with element expanders */
+ margin-left: -9px;
+ margin-top: -7px;
+ padding-top: 7px;
+ }
+
+ /* Show children when li.children-visible class is present */
+ li.children-visible > ul {
+ display: block;
+ }
+
+ li {
+ position: relative;
+ margin: 2px 0;
+
+ /* Element Groups */
+ &.element-group {
+ border-bottom: 1px solid #ededed;
+ padding: 20px;
+
+ > .description {
+ font-size: 12px;
+ font-style: italic;
+ margin: 10px 0 0;
+ color: #969696;
+ }
+
+ > span.element-group-name {
+ font-weight: 400;
+ color: #222;
+ font-size: 17px;
+ cursor: default;
+ margin-left: 0;
+ }
+
+ > ul {
+ margin: -2px 0 0 2px;
+ padding-top: 10px;
+ }
+ }
+
+ /* Element Names */
+ span.element-name {
+ min-height: 20px;
+ max-height: 40px;
+ line-height: 20px;
+ padding: 0 3px;
+ border-radius: 3px;
+ cursor: pointer;
+ display: inline-block;
+
+ small {
+ color: #4a4a4a;
+ font-size: 95%;
+ margin: 0 0 0 5px;
+ }
+ }
+
+ /* Element Name Buttons */
+ span.element-name-button {
+ margin: 0 7px 0 0;
+ height: 20px;
+ line-height: 20px;
+ display: none;
+ vertical-align: bottom;
+
+ &:after {
+ .icon-font();
+ width: 9px;
+ color: inherit;
+ display: inline-block;
+ text-align: center;
+ }
+
+ &:first-of-type {
+ border-left: 1px solid rgba(255, 255, 255, .15);
+ padding-left: 10px;
+ margin-left: 6px;
+ }
+
+ &.element-name-button-layout-specific {
+ &:after {
+ width: 13px;
+ content: "\e011";
+ }
+ }
+
+ &.element-name-button-live-css {
+ margin-right: 3px;
+
+ &:after {
+ width: 12px;
+ content: "\e003";
+ }
+ }
+ }
+
+ /* Hovered element names */
+ > span.element-name:hover,
+ &.element-just-selected > span.element-name {
+ background: #eee;
+
+ &:after {
+ left: 13px !important;
+ }
+
+ > span.element-name-button {
+ display: inline-block;
+
+ &:first-of-type {
+ border-left-color: rgba(0, 0, 0, .2);
+ }
+ }
+
+ > small {
+ display: none;
+ }
+ }
+
+ /* Selected element names */
+ &.ui-state-active {
+ > span.element-name {
+ background: #199ebf;
+ color: rgba(255, 255, 255, .9) !important;
+
+ &:after {
+ left: 13px !important;
+ }
+
+ > span.element-name-button {
+ display: inline-block;
+
+ &:first-of-type {
+ border-left: 1px solid rgba(255, 255, 255, .15) !important;
+ }
+ }
+ }
+ }
+
+ /* Instance/State Container Names */
+ &.element-instances-container, &.element-states-container {
+ > span.element-name {
+ color: #777 !important;
+ cursor: default;
+
+ &:hover {
+ background: inherit;
+ }
+ }
+
+ > span.element-expander {
+ opacity: .6;
+ }
+ }
+
+
+ /* Element Description */
+ .description {
+ display: block;
+ color: #777;
+ font-size: 11px;
+ margin: 0 3px 3px;
+ }
+
+ /* Element Flags */
+ &.customized-element {
+ > span.element-name:after {
+ content: '\2022';
+ .icon-font;
+ color: @customized_element_color;
+ line-height: 1px;
+ font-size: 20px;
+ height: 1px;
+ display: inline-block;
+ position: relative;
+ top: 2px;
+ left: 5px;
+ }
+
+ .element-name-button-live-css {
+ margin-right: 0 !important;
+ }
+ }
+ /* End element flags */
+
+ /* Element children expanders */
+ span.element-expander {
+ width: 11px;
+ height: 11px;
+ left: -14px;
+ top: 4px;
+ .rounded-corners(1px);
+ display: none;
+ position: absolute;
+ cursor: pointer;
+ color: #777;
+ background: #eee;
+
+ &::after {
+ content: "+";
+ color: inherit;
+ font-size: 11px;
+ font-family: monospace;
+ font-weight: 600;
+ line-height: 11px;
+ text-align: center;
+ width: 100%;
+ display: block;
+ }
+
+ &:hover {
+ background: #777;
+ color: #eee;
+ }
+ }
+
+ /* Flag will be in different place if expander is present */
+ &.has-children {
+ > span.element-expander {
+ display: block;
+ }
+ }
+
+ &.children-visible {
+ > span.element-expander::after {
+ content: "-";
+ line-height: 10px;
+ }
+ }
+
+ /* Different expander for element groups */
+ &.element-group {
+
+ > span.element-expander {
+ top: 0;
+ left: 0;
+ right: 0;
+ color: #aaa;
+ background: none !important;
+
+ width: 100%;
+ height: 55px;
+
+ &::after {
+ font-family: 'headway-ve';
+ content: "d";
+ font-size: 16px;
+ text-align: right;
+ position: relative;
+ top: 21px;
+ right: 20px;
+ }
+
+ &:hover {
+ background: none;
+ color: #444;
+ }
+ }
+
+ > small.description + span.element-expander {
+ height: 75px;
+ }
+
+ &.children-visible > span.element-expander::after {
+ content: "h";
+ }
+
+ }
+ /* End element expanders */
+
+ /* Tree Connectors */
+ ul.group-elements ul li::before {
+ display: block;
+ background: none;
+ width: @element_selector_tree_x_width;
+ height: 1px;
+ position: absolute;
+ left: -@element_selector_tree_x_width - @element_selector_tree_x_padding;
+ top: 10px;
+ border-top: 1px dotted @element_selector_breadcrumb_trail_color;
+ content: " ";
+ }
+
+ /* Put cover element on the span on the last li to cover up overflow border of the <ul> */
+ ul.group-elements ul li:not(.children-visible):last-child > span.element-name::before {
+ position: absolute;
+ background: #fff;
+ content: " ";
+ width: 5px;
+ height: 20px;
+ left: -@element_selector_tree_x_width - @element_selector_tree_x_padding - 3px;
+ top: 11px;
+ display: block;
+ }
+ /* End Tree connectors */
+ }
+
+ /* Filters */
+ /* Hide uncustomized elements */
+ &.hide-uncustomized-elements {
+ li.element:not(.customized-element):not(.has-customized-children) {
+ display: none;
+ }
+
+ li.element.has-customized-children:not(.customized-element) > span.element-name {
+ opacity: .4;
+ }
+ }
+
+ /* End Filters */
+ }
+
+
+ div#design-editor-styles-container {
+ position: absolute;
+ top: 35px;
+ bottom: 0;
+ width: 100%;
+
+ overflow-y: auto;
+ overflow-x: hidden;
+ }
+
+ div.design-editor-styles-message {
+ background-image: url(data:image/svg+xml;base64,PD94bWwgdmVyc2lvbj0iMS4wIiBlbmNvZGluZz0iVVRGLTgiIHN0YW5kYWxvbmU9Im5vIj8+Cjxzdmcgd2lkdGg9IjEzMHB4IiBoZWlnaHQ9IjEzMHB4IiB2aWV3Qm94PSIwIDAgMTMwIDEzMCIgdmVyc2lvbj0iMS4xIiB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHhtbG5zOnhsaW5rPSJodHRwOi8vd3d3LnczLm9yZy8xOTk5L3hsaW5rIiB4bWxuczpza2V0Y2g9Imh0dHA6Ly93d3cuYm9oZW1pYW5jb2RpbmcuY29tL3NrZXRjaC9ucyI+CiAgICA8dGl0bGU+aW5zcGVjdC1ub3RoaW5nLXNlbGVjdGVkPC90aXRsZT4KICAgIDxkZXNjcmlwdGlvbj5DcmVhdGVkIHdpdGggU2tldGNoIChodHRwOi8vd3d3LmJvaGVtaWFuY29kaW5nLmNvbS9za2V0Y2gpPC9kZXNjcmlwdGlvbj4KICAgIDxkZWZzPjwvZGVmcz4KICAgIDxnIGlkPSJQYWdlLTEiIHN0cm9rZT0ibm9uZSIgc3Ryb2tlLXdpZHRoPSIxIiBmaWxsPSJub25lIiBmaWxsLXJ1bGU9ImV2ZW5vZGQiIHNrZXRjaDp0eXBlPSJNU1BhZ2UiPgogICAgICAgIDxnIGlkPSJPdmFsLTM1LSstU2hhcGUiIHNrZXRjaDp0eXBlPSJNU0xheWVyR3JvdXAiPgogICAgICAgICAgICA8Y2lyY2xlIGlkPSJPdmFsLTM1IiBmaWxsPSIjRUVFRUVFIiBza2V0Y2g6dHlwZT0iTVNTaGFwZUdyb3VwIiBjeD0iNjUiIGN5PSI2NSIgcj0iNjUiPjwvY2lyY2xlPgogICAgICAgICAgICA8cGF0aCBkPSJNODksNjEuNzgyMDI0NCBMNDksMzAgTDQ5LDgyLjk2OTM0MjggTDYxLjQ4NDgwNjYsNzAuNDk2NDg0MyBMNzMuOTY5NjEzMSw5NyBMODQuNTc2ODU2Niw5MS4zODIyOTMyIEw3Mi4wOTIwNSw2NC44Nzg3Nzc1IEw4OSw2MS43ODIwMjQ0IFoiIGlkPSJTaGFwZSIgZmlsbC1vcGFjaXR5PSIwLjQ1Njc3Mjc0OCIgZmlsbD0iIzk5OTk5OSIgc2tldGNoOnR5cGU9Ik1TU2hhcGVHcm91cCI+PC9wYXRoPgogICAgICAgIDwvZz4KICAgIDwvZz4KPC9zdmc+);
+ background-repeat: no-repeat;
+ background-position: top center;
+
+ padding: 170px 20px 0;
+ margin: 30px 0 0;
+ text-align: center;
+
+ p {
+ font-size: 24px;
+ text-align: center;
+ color: #888;
+ font-weight: 300;
+ font-style: italic;
+ line-height: 30px;
+ margin-bottom: 30px;
+
+ strong {
+ font-weight: 500;
+ }
+ }
+
+ a {
+ font-size: 13px;
+ }
+ }
+
+ div#design-editor-styles-no-styles {
+ display: none;
+ }
+
+ ul#design-editor-styles {
+ position: relative;
+ list-style: none;
+ color: #333;
+ padding: 15px;
+ display: none;
+
+ h2 {
+ font-size: 18px;
+ margin-bottom: 10px;
+ font-weight: 300;
+ padding-bottom: 10px;
+ border-bottom: 1px solid #DDD;
+ }
+
+ /* Property value group names */
+ .property-value-group-name {
+ font-weight: 400;
+ color: #222;
+ padding: 8px 0 10px;
+ font-size: 14px;
+ position: relative;
+ }
+ /* End property value group names */
+
+
+ ul {
+ display: block !important;
+ padding: 0;
+ border: 1px solid #E5E5E5;
+ -webkit-box-shadow: 0 1px 1px rgba(0, 0, 0, 0.04);
+ box-shadow: 0 1px 1px rgba(0, 0, 0, 0.04);
+ .rounded-corners(2px);
+ overflow: hidden;
+ margin: 5px 0 15px;
+
+ /* Property value Groups */
+ ul[data-property-group-id] {
+ display: none;
+ padding: 0;
+ border: 0;
+ margin: 0;
+ }
+
+ li.property-value-group-name.property-value-group-visible + ul[data-property-group-id] {
+ display: block;
+ }
+ /* End property value groups */
+
+ li {
+ padding: 9px 10px;
+ border-bottom: 1px solid #eee;
+ margin: 0;
+
+ &:last-of-type {
+ border-bottom: none;
+ }
+
+ &:hover {
+ span.property-delete {
+ display: inline-block;
+ }
+ }
+
+ /* Special element properties */
+ &.property[data-special-element-type] {
+ strong {
+ font-weight: 300;
+ }
+
+ margin-left: 10px;
+ }
+
+ /* Special element type icons */
+ &.property[data-special-element-type] strong {
+ max-width: 50%;
+ text-overflow: ellipsis;
+ overflow: hidden;
+ display: inline-block;
+ white-space: nowrap;
+ }
+ /* End special element properties */
+
+ span.property-value {
+ color: #555;
+ display: inline-block;
+ float: right;
+ cursor: pointer;
+ overflow: hidden;
+ padding: 3px;
+ margin: -3px;
+ max-width: 50%;
+ white-space: nowrap;
+ text-overflow: ellipsis;
+
+ &:hover {
+ background: #eee;
+ outline: 1px solid #ddd;
+ }
+
+ span.unit {
+ color: #999;
+ margin-left: 2px;
+ font-size: 11px;
+ }
+ }
+
+ span.property-delete {
+ display: none;
+ color: #666;
+ cursor: pointer;
+ position: absolute;
+ margin-left: 5px;
+
+ &:after {
+ .icon-font;
+ content: "\70";
+ font-size: 12px;
+ }
+
+ &:hover {
+ color: #aaa;
+ }
+ }
+
+ strong {
+ font-weight: bold;
+ color: #222;
+ }
+
+ &:not([data-special-element-type]) strong {
+ max-width: 65%;
+ display: inline-block;
+ overflow: hidden;
+ white-space: nowrap;
+ text-overflow: ellipsis;
+ }
+
+ &::before {
+ display: none !important;
+ }
+
+ div.colorpicker-box-container {
+ width: 12px;
+ height: 12px;
+ float: none;
+ display: inline-block;
+ margin: 0 4px -2px 4px;
+ border: none;
+ border-radius: 0;
+
+ div.colorpicker-box {
+ cursor: default;
+ position: static;
+ width: 10px;
+ height:10px;
+ box-shadow: 0 0 0 1px rgba(255, 255, 255, 0.4) inset;
+ border: 1px solid #000;
+ }
+ }
+ }
+ }
+ /* End Element Properties */
+ }
+/* End Element Selector */
+
+
+/* Design Editor Info (Currently Editing, Instances, and States) */
+ div.design-editor-info {
+ .no-highlight();
+ float: left;
+ font-size: 13px;
+ background: #f7f7f7;
+ border-bottom: 1px solid #d7d7d7;
+ box-shadow: 0 3px 4px rgba(0, 0, 0, 0.02) inset;
+ padding: 15px;
+ display: block;
+ min-height: 80px;
+ margin-top: -80px;
+ width: 100% !important;
+ position: relative;
+
+ .border-box;
+
+ div.design-editor-selection {
+ float: left;
+ color: #777;
+ width: 100%;
+ font-size: 13px;
+
+ > strong {
+ color: #555;
+ font-weight: 300;
+ font-size: 16px;
+ }
+
+ span.design-editor-selection-details {
+ font-size: 13px;
+ color: #777;
+ line-height: 20px;
+ width: 100%;
+ margin: 12px 0 0;
+ position: relative;
+ display: block;
+
+ strong {
+ color: #444;
+ font-weight: 600;
+ }
+ }
+ }
+
+ em {
+ color: #414141;
+ }
+
+ span.design-editor-info-button {
+ margin: 10px 40px 0 0;
+ height: 26px;
+ line-height: 26px;
+ font-size: 12px;
+ }
+ }
+/* End Design Editor Info */
+
+
+/* Design Editor (Properties) */
+ /* Structure */
+ div.design-editor-options-container {
+ width: 100%;
+ height: 100%;
+ overflow-x: hidden;
+ overflow-y: auto;
+ position: relative;
+ .border-box;
+ float: left;
+ clear: both;
+ display: block;
+ padding-bottom: 10px;
+ }
+
+ div.design-editor-options {
+ width: 100%;
+ float: left;
+ position: relative;
+ margin-top: 1px; /* For box shadow on element details to show if property group is selected in first row */
+ }
+
+ /* Property Group Boxes */
+ /* Box Structure */
+ div.property-group-row {
+ display: block;
+ width: 100%;
+ float: left;
+ clear: both;
+ }
+
+ div.design-editor-box {
+ float: left;
+ display: block;
+ width: 33.3333%;
+ .border-box();
+
+ /* Box Titles */
+ span.design-editor-box-title {
+ display: block;
+ .border-box();
+
+ width: 100%;
+ height: 90px;
+ padding: 65px 0 0 0;
+
+ text-align: center;
+ font-size: 12px;
+ line-height: 10px;
+ color: #777;
+ font-weight: 400;
+ position: relative;
+ z-index: 2;
+
+ background-size: 40px;
+ background-position: 50% 15px;
+ background-repeat: no-repeat;
+
+ cursor: pointer;
+ .no-highlight();
+
+ &:hover {
+ color: #444;
+ }
+ }
+
+ &.design-editor-box-customized {
+ span.design-editor-box-title span {
+ &:after {
+ content: '\2022';
+ .icon-font();
+ color: @customized_element_color;
+ line-height: 1px;
+ font-size: 14px;
+ height: 1px;
+ display: inline-block;
+ position: relative;
+ top: 2px;
+ left: 3px;
+ }
+ }
+ }
+
+ &.design-editor-box-open {
+ span.design-editor-box-title {
+ background-color: #fff;
+ box-shadow: 0 1px 0 #fff;
+
+ color: #444;
+ }
+ }
+ }
+
+ /* Conditionals for a prettier box open for those in the top row */
+ div.property-group-row:first-of-type div.design-editor-box-open span.design-editor-box-title {
+ background-position: 50% 15px;
+ padding-top: 65px;
+ border-top: none;
+ }
+
+ /* Images for property groups */
+ div.design-editor-box-background span.design-editor-box-title {
+ background-image: url(data:image/svg+xml;base64,PD94bWwgdmVyc2lvbj0iMS4wIiBlbmNvZGluZz0iVVRGLTgiIHN0YW5kYWxvbmU9Im5vIj8+Cjxzdmcgd2lkdGg9IjM2cHgiIGhlaWdodD0iMzZweCIgdmlld0JveD0iMCAwIDM2IDM2IiB2ZXJzaW9uPSIxLjEiIHhtbG5zPSJodHRwOi8vd3d3LnczLm9yZy8yMDAwL3N2ZyIgeG1sbnM6eGxpbms9Imh0dHA6Ly93d3cudzMub3JnLzE5OTkveGxpbmsiIHhtbG5zOnNrZXRjaD0iaHR0cDovL3d3dy5ib2hlbWlhbmNvZGluZy5jb20vc2tldGNoL25zIj4KICAgIDx0aXRsZT5iYWNrZ3JvdW5kPC90aXRsZT4KICAgIDxkZXNjcmlwdGlvbj5DcmVhdGVkIHdpdGggU2tldGNoIChodHRwOi8vd3d3LmJvaGVtaWFuY29kaW5nLmNvbS9za2V0Y2gpPC9kZXNjcmlwdGlvbj4KICAgIDxkZWZzPjwvZGVmcz4KICAgIDxnIGlkPSJQYWdlLTEiIHN0cm9rZT0ibm9uZSIgc3Ryb2tlLXdpZHRoPSIxIiBmaWxsPSJub25lIiBmaWxsLXJ1bGU9ImV2ZW5vZGQiIHNrZXRjaDp0eXBlPSJNU1BhZ2UiPgogICAgICAgIDxnIGlkPSJFZGl0LUljb25zLUFsbC1DbG9zZWQiIHNrZXRjaDp0eXBlPSJNU0xheWVyR3JvdXAiIHRyYW5zZm9ybT0idHJhbnNsYXRlKC0xNC4wMDAwMDAsIDAuMDAwMDAwKSIgc3Ryb2tlLXdpZHRoPSIyIiBzdHJva2U9IiM5Mzk3OUIiPgogICAgICAgICAgICA8ZyBpZD0iUm93LTEiIHNrZXRjaDp0eXBlPSJNU1NoYXBlR3JvdXAiPgogICAgICAgICAgICAgICAgPGcgaWQ9IkJhY2tncm91bmQiIHRyYW5zZm9ybT0idHJhbnNsYXRlKDAuMDAwMDAwLCAyLjAwMDAwMCkiPgogICAgICAgICAgICAgICAgICAgIDxnIGlkPSJHcm91cCIgdHJhbnNmb3JtPSJ0cmFuc2xhdGUoMTYuMDAwMDAwLCAwLjAwMDAwMCkiPgogICAgICAgICAgICAgICAgICAgICAgICA8cmVjdCBpZD0iUmVjdGFuZ2xlLTUiIGZpbGw9IiNENEQ0RDQiIHg9IjEiIHk9IjEiIHdpZHRoPSIzMCIgaGVpZ2h0PSIzMCI+PC9yZWN0PgogICAgICAgICAgICAgICAgICAgICAgICA8cmVjdCBpZD0iUmVjdGFuZ2xlLTUiIGZpbGw9IiNGRkZGRkYiIHg9IjAiIHk9IjAiIHdpZHRoPSI0IiBoZWlnaHQ9IjQiPjwvcmVjdD4KICAgICAgICAgICAgICAgICAgICAgICAgPHJlY3QgaWQ9IlJlY3RhbmdsZS01IiBmaWxsPSIjRkZGRkZGIiB4PSIwIiB5PSIyOCIgd2lkdGg9IjQiIGhlaWdodD0iNCI+PC9yZWN0PgogICAgICAgICAgICAgICAgICAgICAgICA8cmVjdCBpZD0iUmVjdGFuZ2xlLTUiIGZpbGw9IiNGRkZGRkYiIHg9IjI4IiB5PSIwIiB3aWR0aD0iNCIgaGVpZ2h0PSI0Ij48L3JlY3Q+CiAgICAgICAgICAgICAgICAgICAgICAgIDxyZWN0IGlkPSJSZWN0YW5nbGUtNSIgZmlsbD0iI0ZGRkZGRiIgeD0iMjgiIHk9IjI4IiB3aWR0aD0iNCIgaGVpZ2h0PSI0Ij48L3JlY3Q+CiAgICAgICAgICAgICAgICAgICAgPC9nPgogICAgICAgICAgICAgICAgPC9nPgogICAgICAgICAgICA8L2c+CiAgICAgICAgPC9nPgogICAgPC9nPgo8L3N2Zz4=);
+ }
+
+ div.design-editor-box-borders span.design-editor-box-title {
+ background-image: url(data:image/svg+xml;base64,PD94bWwgdmVyc2lvbj0iMS4wIiBlbmNvZGluZz0iVVRGLTgiIHN0YW5kYWxvbmU9Im5vIj8+Cjxzdmcgd2lkdGg9IjM2cHgiIGhlaWdodD0iMzZweCIgdmlld0JveD0iMCAwIDM2IDM2IiB2ZXJzaW9uPSIxLjEiIHhtbG5zPSJodHRwOi8vd3d3LnczLm9yZy8yMDAwL3N2ZyIgeG1sbnM6eGxpbms9Imh0dHA6Ly93d3cudzMub3JnLzE5OTkveGxpbmsiIHhtbG5zOnNrZXRjaD0iaHR0cDovL3d3dy5ib2hlbWlhbmNvZGluZy5jb20vc2tldGNoL25zIj4KICAgIDx0aXRsZT5ib3JkZXJzPC90aXRsZT4KICAgIDxkZXNjcmlwdGlvbj5DcmVhdGVkIHdpdGggU2tldGNoIChodHRwOi8vd3d3LmJvaGVtaWFuY29kaW5nLmNvbS9za2V0Y2gpPC9kZXNjcmlwdGlvbj4KICAgIDxkZWZzPjwvZGVmcz4KICAgIDxnIGlkPSJQYWdlLTEiIHN0cm9rZT0ibm9uZSIgc3Ryb2tlLXdpZHRoPSIxIiBmaWxsPSJub25lIiBmaWxsLXJ1bGU9ImV2ZW5vZGQiIHNrZXRjaDp0eXBlPSJNU1BhZ2UiPgogICAgICAgIDxnIGlkPSJFZGl0LUljb25zLUFsbC1DbG9zZWQiIHNrZXRjaDp0eXBlPSJNU0xheWVyR3JvdXAiIHRyYW5zZm9ybT0idHJhbnNsYXRlKC0xMTAuMDAwMDAwLCAwLjAwMDAwMCkiIHN0cm9rZS13aWR0aD0iMiIgc3Ryb2tlPSIjOTM5NzlCIiBmaWxsPSIjRkZGRkZGIj4KICAgICAgICAgICAgPGcgaWQ9IlJvdy0xIiBza2V0Y2g6dHlwZT0iTVNTaGFwZUdyb3VwIj4KICAgICAgICAgICAgICAgIDxnIGlkPSJCb3JkZXJzIiB0cmFuc2Zvcm09InRyYW5zbGF0ZSgxMDguMDAwMDAwLCAyLjAwMDAwMCkiPgogICAgICAgICAgICAgICAgICAgIDxnIGlkPSJHcm91cCIgdHJhbnNmb3JtPSJ0cmFuc2xhdGUoNC4wMDAwMDAsIDAuMDAwMDAwKSI+CiAgICAgICAgICAgICAgICAgICAgICAgIDxyZWN0IGlkPSJSZWN0YW5nbGUtNSIgc3Ryb2tlLWRhc2hhcnJheT0iMiwyIiB4PSIxIiB5PSIxIiB3aWR0aD0iMzAiIGhlaWdodD0iMzAiPjwvcmVjdD4KICAgICAgICAgICAgICAgICAgICAgICAgPHJlY3QgaWQ9IlJlY3RhbmdsZS01IiB4PSIwIiB5PSIwIiB3aWR0aD0iNCIgaGVpZ2h0PSI0Ij48L3JlY3Q+CiAgICAgICAgICAgICAgICAgICAgICAgIDxyZWN0IGlkPSJSZWN0YW5nbGUtNSIgeD0iMCIgeT0iMjgiIHdpZHRoPSI0IiBoZWlnaHQ9IjQiPjwvcmVjdD4KICAgICAgICAgICAgICAgICAgICAgICAgPHJlY3QgaWQ9IlJlY3RhbmdsZS01IiB4PSIyOCIgeT0iMCIgd2lkdGg9IjQiIGhlaWdodD0iNCI+PC9yZWN0PgogICAgICAgICAgICAgICAgICAgICAgICA8cmVjdCBpZD0iUmVjdGFuZ2xlLTUiIHg9IjI4IiB5PSIyOCIgd2lkdGg9IjQiIGhlaWdodD0iNCI+PC9yZWN0PgogICAgICAgICAgICAgICAgICAgIDwvZz4KICAgICAgICAgICAgICAgIDwvZz4KICAgICAgICAgICAgPC9nPgogICAgICAgIDwvZz4KICAgIDwvZz4KPC9zdmc+);
+ }
+
+ div.design-editor-box-box-shadow span.design-editor-box-title {
+ background-image: url(data:image/svg+xml;base64,PD94bWwgdmVyc2lvbj0iMS4wIiBlbmNvZGluZz0iVVRGLTgiIHN0YW5kYWxvbmU9Im5vIj8+Cjxzdmcgd2lkdGg9IjQwcHgiIGhlaWdodD0iNDBweCIgdmlld0JveD0iMCAwIDQwIDQwIiB2ZXJzaW9uPSIxLjEiIHhtbG5zPSJodHRwOi8vd3d3LnczLm9yZy8yMDAwL3N2ZyIgeG1sbnM6eGxpbms9Imh0dHA6Ly93d3cudzMub3JnLzE5OTkveGxpbmsiIHhtbG5zOnNrZXRjaD0iaHR0cDovL3d3dy5ib2hlbWlhbmNvZGluZy5jb20vc2tldGNoL25zIj4KICAgIDx0aXRsZT5zaGFkb3c8L3RpdGxlPgogICAgPGRlc2NyaXB0aW9uPkNyZWF0ZWQgd2l0aCBTa2V0Y2ggKGh0dHA6Ly93d3cuYm9oZW1pYW5jb2RpbmcuY29tL3NrZXRjaCk8L2Rlc2NyaXB0aW9uPgogICAgPGRlZnM+CiAgICAgICAgPGZpbHRlciB4PSItNTAlIiB5PSItNTAlIiB3aWR0aD0iMjAwJSIgaGVpZ2h0PSIyMDAlIiBmaWx0ZXJVbml0cz0ib2JqZWN0Qm91bmRpbmdCb3giIGlkPSJmaWx0ZXItMSI+CiAgICAgICAgICAgIDxmZU9mZnNldCBkeD0iMCIgZHk9IjAiIGluPSJTb3VyY2VBbHBoYSIgcmVzdWx0PSJzaGFkb3dPZmZzZXRPdXRlcjEiPjwvZmVPZmZzZXQ+CiAgICAgICAgICAgIDxmZUdhdXNzaWFuQmx1ciBzdGREZXZpYXRpb249IjIuNSIgaW49InNoYWRvd09mZnNldE91dGVyMSIgcmVzdWx0PSJzaGFkb3dCbHVyT3V0ZXIxIj48L2ZlR2F1c3NpYW5CbHVyPgogICAgICAgICAgICA8ZmVDb2xvck1hdHJpeCB2YWx1ZXM9IjAgMCAwIDAgMCAgIDAgMCAwIDAgMCAgIDAgMCAwIDAgMCAgMCAwIDAgMC43IDAiIGluPSJzaGFkb3dCbHVyT3V0ZXIxIiB0eXBlPSJtYXRyaXgiIHJlc3VsdD0ic2hhZG93TWF0cml4T3V0ZXIxIj48L2ZlQ29sb3JNYXRyaXg+CiAgICAgICAgICAgIDxmZU1lcmdlPgogICAgICAgICAgICAgICAgPGZlTWVyZ2VOb2RlIGluPSJzaGFkb3dNYXRyaXhPdXRlcjEiPjwvZmVNZXJnZU5vZGU+CiAgICAgICAgICAgICAgICA8ZmVNZXJnZU5vZGUgaW49IlNvdXJjZUdyYXBoaWMiPjwvZmVNZXJnZU5vZGU+CiAgICAgICAgICAgIDwvZmVNZXJnZT4KICAgICAgICA8L2ZpbHRlcj4KICAgIDwvZGVmcz4KICAgIDxnIGlkPSJQYWdlLTEiIHN0cm9rZT0ibm9uZSIgc3Ryb2tlLXdpZHRoPSIxIiBmaWxsPSJub25lIiBmaWxsLXJ1bGU9ImV2ZW5vZGQiIHNrZXRjaDp0eXBlPSJNU1BhZ2UiPgogICAgICAgIDxnIGlkPSJFZGl0LUljb25zLUFsbC1DbG9zZWQiIHNrZXRjaDp0eXBlPSJNU0xheWVyR3JvdXAiIHRyYW5zZm9ybT0idHJhbnNsYXRlKC0xMi4wMDAwMDAsIC05My4wMDAwMDApIiBzdHJva2U9IiM5Mzk3OUIiIHN0cm9rZS13aWR0aD0iMiIgZmlsbD0iI0ZGRkZGRiI+CiAgICAgICAgICAgIDxnIGlkPSJSb3ctMiIgdHJhbnNmb3JtPSJ0cmFuc2xhdGUoMi4wMDAwMDAsIDk0LjAwMDAwMCkiIHNrZXRjaDp0eXBlPSJNU1NoYXBlR3JvdXAiPgogICAgICAgICAgICAgICAgPGcgaWQ9IkJveC1TaGFkb3ciIHRyYW5zZm9ybT0idHJhbnNsYXRlKDAuMDAwMDAwLCAzLjAwMDAwMCkiPgogICAgICAgICAgICAgICAgICAgIDxnIGlkPSJHcm91cCIgdHJhbnNmb3JtPSJ0cmFuc2xhdGUoMTQuMDAwMDAwLCAwLjAwMDAwMCkiPgogICAgICAgICAgICAgICAgICAgICAgICA8cmVjdCBpZD0iUmVjdGFuZ2xlLTUiIGZpbHRlcj0idXJsKCNmaWx0ZXItMSkiIHg9IjEiIHk9IjEiIHdpZHRoPSIzMCIgaGVpZ2h0PSIzMCI+PC9yZWN0PgogICAgICAgICAgICAgICAgICAgICAgICA8cmVjdCBpZD0iUmVjdGFuZ2xlLTUiIHg9IjAiIHk9IjAiIHdpZHRoPSI0IiBoZWlnaHQ9IjQiPjwvcmVjdD4KICAgICAgICAgICAgICAgICAgICAgICAgPHJlY3QgaWQ9IlJlY3RhbmdsZS01IiB4PSIwIiB5PSIyOCIgd2lkdGg9IjQiIGhlaWdodD0iNCI+PC9yZWN0PgogICAgICAgICAgICAgICAgICAgICAgICA8cmVjdCBpZD0iUmVjdGFuZ2xlLTUiIHg9IjI4IiB5PSIwIiB3aWR0aD0iNCIgaGVpZ2h0PSI0Ij48L3JlY3Q+CiAgICAgICAgICAgICAgICAgICAgICAgIDxyZWN0IGlkPSJSZWN0YW5nbGUtNSIgeD0iMjgiIHk9IjI4IiB3aWR0aD0iNCIgaGVpZ2h0PSI0Ij48L3JlY3Q+CiAgICAgICAgICAgICAgICAgICAgPC9nPgogICAgICAgICAgICAgICAgPC9nPgogICAgICAgICAgICA8L2c+CiAgICAgICAgPC9nPgogICAgPC9nPgo8L3N2Zz4=);
+ }
+
+ div.design-editor-box-corners span.design-editor-box-title {
+ background-image: url(data:image/svg+xml;base64,PD94bWwgdmVyc2lvbj0iMS4wIiBlbmNvZGluZz0iVVRGLTgiIHN0YW5kYWxvbmU9Im5vIj8+Cjxzdmcgd2lkdGg9IjM2cHgiIGhlaWdodD0iMzZweCIgdmlld0JveD0iMCAwIDM2IDM2IiB2ZXJzaW9uPSIxLjEiIHhtbG5zPSJodHRwOi8vd3d3LnczLm9yZy8yMDAwL3N2ZyIgeG1sbnM6eGxpbms9Imh0dHA6Ly93d3cudzMub3JnLzE5OTkveGxpbmsiIHhtbG5zOnNrZXRjaD0iaHR0cDovL3d3dy5ib2hlbWlhbmNvZGluZy5jb20vc2tldGNoL25zIj4KICAgIDx0aXRsZT5jb3JuZXJzPC90aXRsZT4KICAgIDxkZXNjcmlwdGlvbj5DcmVhdGVkIHdpdGggU2tldGNoIChodHRwOi8vd3d3LmJvaGVtaWFuY29kaW5nLmNvbS9za2V0Y2gpPC9kZXNjcmlwdGlvbj4KICAgIDxkZWZzPjwvZGVmcz4KICAgIDxnIGlkPSJQYWdlLTEiIHN0cm9rZT0ibm9uZSIgc3Ryb2tlLXdpZHRoPSIxIiBmaWxsPSJub25lIiBmaWxsLXJ1bGU9ImV2ZW5vZGQiIHNrZXRjaDp0eXBlPSJNU1BhZ2UiPgogICAgICAgIDxnIGlkPSJFZGl0LUljb25zLUFsbC1DbG9zZWQiIHNrZXRjaDp0eXBlPSJNU0xheWVyR3JvdXAiIHRyYW5zZm9ybT0idHJhbnNsYXRlKC0yMDUuMDAwMDAwLCAtMTkwLjAwMDAwMCkiIGZpbGw9IiNBMkEyQTIiPgogICAgICAgICAgICA8ZyBpZD0iUm93LTMiIHRyYW5zZm9ybT0idHJhbnNsYXRlKDEyLjAwMDAwMCwgMTkwLjAwMDAwMCkiIHNrZXRjaDp0eXBlPSJNU1NoYXBlR3JvdXAiPgogICAgICAgICAgICAgICAgPGcgaWQ9IlNoYXBlLSstQ09STkVSUyIgdHJhbnNmb3JtPSJ0cmFuc2xhdGUoMTkwLjAwMDAwMCwgMC4wMDAwMDApIj4KICAgICAgICAgICAgICAgICAgICA8cGF0aCBkPSJNOC40NTQ1NDU0NSwxNC4yNzIxODkzIEM4LjQ1NDU0NTQ1LDEzLjAxNzMwMTggNy4yMzM0OTQzMiwxMiA1LjcyNzI3MjczLDEyIEM0LjIyMTA1MTE0LDEyIDMsMTMuMDE3MzAxOCAzLDE0LjI3MjE4OTMgQzMsMTUuMTEzMTEyNCAzLjU0ODY5MzE4LDE1Ljg0Njc0NTYgNC4zNjM2MzYzNiwxNi4yMzk2MjEzIEw0LjM2MzYzNjM2LDM2IEw3LjA5MDkwOTA5LDM2IEw3LjA5MDkwOTA5LDE2LjIzOTYyMTMgQzcuOTA1ODUyMjcsMTUuODQ2NzQ1NiA4LjQ1NDU0NTQ1LDE1LjExMzExMjQgOC40NTQ1NDU0NSwxNC4yNzIxODkzIEM4LjQ1NDU0NTQ1LDE0LjI3MjE4OTMgOC40NTQ1NDU0NSwxNS4xMTMxMTI0IDguNDU0NTQ1NDUsMTQuMjcyMTg5MyBMOC40NTQ1NDU0NSwxNC4yNzIxODkzIEw4LjQ1NDU0NTQ1LDE0LjI3MjE4OTMgWiBNMTMuMjg1NzE0MywxMC4yODU3MTQzIEwxMy4yODU3MTQzLDE1Ljc1MzUwNjUgQzguODkzNjg1MDYsMjEuMzI0MDA5NyA2LjI3MjcyNzI3LDI4LjM1NTc3MTEgNi4yNzI3MjcyNywzNiBMOC42MTAzODk2MSwzNiBDOC42MTAzODk2MSwzMS44OTYzNzk5IDkuNDEzNTk1NzgsMjcuOTE2ODAxOSAxMC45OTc1ODEyLDI0LjE3MTcyMDggQzEyLjA0MzM5MjksMjEuNjk5MDU4NCAxMy4zOTg0MzM0LDE5LjM5ODY1MjYgMTUuMDQyMTc1MywxNy4yOTg3MDEzIEwyMC4yOTg3MDEzLDE3LjI5ODcwMTMgTDIwLjI5ODcwMTMsMTIuMDQyMTc1MyBDMjIuMzk4NjUyNiwxMC4zOTg0MzM0IDI0LjY5OTA1ODQsOS4wNDM0NjU5MSAyNy4xNzE3MjA4LDcuOTk3NTgxMTcgQzMwLjkxNjgwMTksNi40MTM1OTU3OCAzNC44OTYzNzk5LDUuNjEwMzg5NjEgMzksNS42MTAzODk2MSBMMzksMy4yNzI3MjcyNyBDMzEuMzU1NzcxMSwzLjI3MjcyNzI3IDI0LjMyMzkzNjcsNS44OTM2ODUwNiAxOC43NTM1MDY1LDEwLjI4NTcxNDMgTDEzLjI4NTcxNDMsMTAuMjg1NzE0MyBMMTMuMjg1NzE0MywxMC4yODU3MTQzIEwxMy4yODU3MTQzLDEwLjI4NTcxNDMgTDEzLjI4NTcxNDMsMTAuMjg1NzE0MyBaIE0xOS4yMzk2MjEzLDEuMzYzNjM2MzYgQzE4Ljg0NjY3NDYsMC41NDg2OTMxODIgMTguMTEzMDQxNCwwIDE3LjI3MjE4OTMsMCBDMTYuMDE3MzAxOCwwIDE1LDEuMjIwOTY1OTEgMTUsMi43MjcyNzI3MyBDMTUsNC4yMzM1Nzk1NSAxNi4wMTczMDE4LDUuNDU0NTQ1NDUgMTcuMjcyMTg5Myw1LjQ1NDU0NTQ1IEMxOC4xMTMxMTI0LDUuNDU0NTQ1NDUgMTguODQ2NzQ1Niw0LjkwNTg1MjI3IDE5LjIzOTYyMTMsNC4wOTA5MDkwOSBMMzksNC4wOTA5MDkwOSBMMzksMS4zNjM2MzYzNiBMMTkuMjM5NjIxMywxLjM2MzYzNjM2IEwxOS4yMzk2MjEzLDEuMzYzNjM2MzYgTDE5LjIzOTYyMTMsMS4zNjM2MzYzNiBMMTkuMjM5NjIxMywxLjM2MzYzNjM2IFogTTEyLjgxODE4MTgsMzMuODE4MTgxOCBMMTguMjcyNzI3MywzMy44MTgxODE4IEwxOC4yNzI3MjczLDM2IEwxMi44MTgxODE4LDM2IEwxMi44MTgxODE4LDM2IEwxMi44MTgxODE4LDMzLjgxODE4MTggTDEyLjgxODE4MTgsMzMuODE4MTgxOCBaIE0yMi42MzYzNjM2LDMzLjgxODE4MTggTDI4LjA5MDkwOTEsMzMuODE4MTgxOCBMMjguMDkwOTA5MSwzNiBMMjIuNjM2MzYzNiwzNiBMMjIuNjM2MzYzNiwzNiBMMjIuNjM2MzYzNiwzMy44MTgxODE4IEwyMi42MzYzNjM2LDMzLjgxODE4MTggWiBNMzYuODE4MTgxOCwyOS40NTQ1NDU1IEwzNi44MTgxODE4LDMzLjgxODE4MTggTDMyLjQ1NDU0NTUsMzMuODE4MTgxOCBMMzIuNDU0NTQ1NSwzNiBMMzksMzYgTDM5LDI5LjQ1NDU0NTUgTDM5LDI5LjQ1NDU0NTUgTDM2LjgxODE4MTgsMjkuNDU0NTQ1NSBMMzYuODE4MTgxOCwyOS40NTQ1NDU1IFogTTM2LjgxODE4MTgsOS44MTgxODE4MiBMMzksOS44MTgxODE4MiBMMzksMTUuMjcyNzI3MyBMMzYuODE4MTgxOCwxNS4yNzI3MjczIEwzNi44MTgxODE4LDE1LjI3MjcyNzMgTDM2LjgxODE4MTgsOS44MTgxODE4MiBMMzYuODE4MTgxOCw5LjgxODE4MTgyIFogTTM2LjgxODE4MTgsMTkuNjM2MzYzNiBMMzksMTkuNjM2MzYzNiBMMzksMjUuMDkwOTA5MSBMMzYuODE4MTgxOCwyNS4wOTA5MDkxIEwzNi44MTgxODE4LDI1LjA5MDkwOTEgTDM2LjgxODE4MTgsMTkuNjM2MzYzNiBMMzYuODE4MTgxOCwxOS42MzYzNjM2IFoiIGlkPSJTaGFwZSI+PC9wYXRoPgogICAgICAgICAgICAgICAgPC9nPgogICAgICAgICAgICA8L2c+CiAgICAgICAgPC9nPgogICAgPC9nPgo8L3N2Zz4=);
+ }
+
+ div.design-editor-box-fonts span.design-editor-box-title {
+ background-image: url(data:image/svg+xml;base64,PD94bWwgdmVyc2lvbj0iMS4wIiBlbmNvZGluZz0iVVRGLTgiIHN0YW5kYWxvbmU9Im5vIj8+Cjxzdmcgd2lkdGg9IjM2cHgiIGhlaWdodD0iMzZweCIgdmlld0JveD0iMCAwIDM2IDM2IiB2ZXJzaW9uPSIxLjEiIHhtbG5zPSJodHRwOi8vd3d3LnczLm9yZy8yMDAwL3N2ZyIgeG1sbnM6eGxpbms9Imh0dHA6Ly93d3cudzMub3JnLzE5OTkveGxpbmsiIHhtbG5zOnNrZXRjaD0iaHR0cDovL3d3dy5ib2hlbWlhbmNvZGluZy5jb20vc2tldGNoL25zIj4KICAgIDx0aXRsZT5mb250czwvdGl0bGU+CiAgICA8ZGVzY3JpcHRpb24+Q3JlYXRlZCB3aXRoIFNrZXRjaCAoaHR0cDovL3d3dy5ib2hlbWlhbmNvZGluZy5jb20vc2tldGNoKTwvZGVzY3JpcHRpb24+CiAgICA8ZGVmcz48L2RlZnM+CiAgICA8ZyBpZD0iUGFnZS0xIiBzdHJva2U9Im5vbmUiIHN0cm9rZS13aWR0aD0iMSIgZmlsbD0ibm9uZSIgZmlsbC1ydWxlPSJldmVub2RkIiBza2V0Y2g6dHlwZT0iTVNQYWdlIj4KICAgICAgICA8ZyBpZD0iRWRpdC1JY29ucy1BbGwtQ2xvc2VkIiBza2V0Y2g6dHlwZT0iTVNMYXllckdyb3VwIiB0cmFuc2Zvcm09InRyYW5zbGF0ZSgtMjA2LjAwMDAwMCwgMC4wMDAwMDApIiBmaWxsPSIjOUI5QjlCIj4KICAgICAgICAgICAgPGcgaWQ9IlJvdy0xIiBza2V0Y2g6dHlwZT0iTVNTaGFwZUdyb3VwIj4KICAgICAgICAgICAgICAgIDxnIGlkPSJ0eXBlIiB0cmFuc2Zvcm09InRyYW5zbGF0ZSgyMDguMDAwMDAwLCAwLjAwMDAwMCkiPgogICAgICAgICAgICAgICAgICAgIDxwYXRoIGQ9Ik0wLDExLjI1IEw0LjQyODU3MTQzLDQuNSBMMTMuMjg1NzE0Myw0LjUgTDEzLjI4NTcxNDMsMzMuNzUgTDguODU3MTQyODYsMzMuNzUgTDYuNjQyODU3MTQsMzYgTDE1LjUsMzYgTDI0LjM1NzE0MjksMzYgTDIyLjE0Mjg1NzEsMzMuNzUgTDE3LjcxNDI4NTcsMzMuNzUgTDE3LjcxNDI4NTcsNC41IEwyNi41NzE0Mjg2LDQuNSBMMzEsMTEuMjUgTDMxLDAgTDAsMCBMMCwxMS4yNSBaIiBpZD0iU2hhcGUiPjwvcGF0aD4KICAgICAgICAgICAgICAgIDwvZz4KICAgICAgICAgICAgPC9nPgogICAgICAgIDwvZz4KICAgIDwvZz4KPC9zdmc+);
+ }
+
+ div.design-editor-box-lists span.design-editor-box-title {
+ background-image: url(data:image/svg+xml;base64,PD94bWwgdmVyc2lvbj0iMS4wIiBlbmNvZGluZz0iVVRGLTgiIHN0YW5kYWxvbmU9Im5vIj8+Cjxzdmcgd2lkdGg9IjM2cHgiIGhlaWdodD0iMzZweCIgdmlld0JveD0iMCAwIDM2IDM2IiB2ZXJzaW9uPSIxLjEiIHhtbG5zPSJodHRwOi8vd3d3LnczLm9yZy8yMDAwL3N2ZyIgeG1sbnM6eGxpbms9Imh0dHA6Ly93d3cudzMub3JnLzE5OTkveGxpbmsiIHhtbG5zOnNrZXRjaD0iaHR0cDovL3d3dy5ib2hlbWlhbmNvZGluZy5jb20vc2tldGNoL25zIj4KICAgIDx0aXRsZT5TbGljZSAxPC90aXRsZT4KICAgIDxkZXNjcmlwdGlvbj5DcmVhdGVkIHdpdGggU2tldGNoIChodHRwOi8vd3d3LmJvaGVtaWFuY29kaW5nLmNvbS9za2V0Y2gpPC9kZXNjcmlwdGlvbj4KICAgIDxkZWZzPjwvZGVmcz4KICAgIDxnIGlkPSJQYWdlLTEiIHN0cm9rZT0ibm9uZSIgc3Ryb2tlLXdpZHRoPSIxIiBmaWxsPSJub25lIiBmaWxsLXJ1bGU9ImV2ZW5vZGQiIHNrZXRjaDp0eXBlPSJNU1BhZ2UiPgogICAgICAgIDxnIGlkPSJMaXN0cy1pY29uIiBza2V0Y2g6dHlwZT0iTVNMYXllckdyb3VwIj4KICAgICAgICAgICAgPHJlY3QgaWQ9IlJlY3RhbmdsZS01IiBzdHJva2U9IiM5Nzk3OTciIHN0cm9rZS13aWR0aD0iMiIgZmlsbC1vcGFjaXR5PSIwLjExMTk4ODc0MSIgZmlsbD0iI0Q4RDhEOCIgc2tldGNoOnR5cGU9Ik1TU2hhcGVHcm91cCIgeD0iMCIgeT0iMCIgd2lkdGg9IjM2IiBoZWlnaHQ9IjM2Ij48L3JlY3Q+CiAgICAgICAgICAgIDxwYXRoIGQ9Ik02LDYgTDEyLDYgTDEyLDEyIEw2LDEyIEw2LDYgWiBNMTUsNiBMMzAsNiBMMzAsMTIgTDE1LDEyIEwxNSw2IFogTTYsMTUgTDEyLDE1IEwxMiwyMSBMNiwyMSBMNiwxNSBaIE0xNSwxNSBMMzAsMTUgTDMwLDIxIEwxNSwyMSBMMTUsMTUgWiBNNiwyNCBMMTIsMjQgTDEyLDMwIEw2LDMwIEw2LDI0IFogTTE1LDI0IEwzMCwyNCBMMzAsMzAgTDE1LDMwIEwxNSwyNCBaIiBpZD0iU2hhcGUiIGZpbGw9IiM5Nzk3OTciIHNrZXRjaDp0eXBlPSJNU1NoYXBlR3JvdXAiPjwvcGF0aD4KICAgICAgICA8L2c+CiAgICA8L2c+Cjwvc3ZnPg==);
+ }
+
+ div.design-editor-box-margins span.design-editor-box-title {
+ background-image: url(data:image/svg+xml;base64,PD94bWwgdmVyc2lvbj0iMS4wIiBlbmNvZGluZz0iVVRGLTgiIHN0YW5kYWxvbmU9Im5vIj8+Cjxzdmcgd2lkdGg9IjQwcHgiIGhlaWdodD0iNDBweCIgdmlld0JveD0iMCAwIDQwIDQwIiB2ZXJzaW9uPSIxLjEiIHhtbG5zPSJodHRwOi8vd3d3LnczLm9yZy8yMDAwL3N2ZyIgeG1sbnM6eGxpbms9Imh0dHA6Ly93d3cudzMub3JnLzE5OTkveGxpbmsiIHhtbG5zOnNrZXRjaD0iaHR0cDovL3d3dy5ib2hlbWlhbmNvZGluZy5jb20vc2tldGNoL25zIj4KICAgIDx0aXRsZT5tYXJnaW48L3RpdGxlPgogICAgPGRlc2NyaXB0aW9uPkNyZWF0ZWQgd2l0aCBTa2V0Y2ggKGh0dHA6Ly93d3cuYm9oZW1pYW5jb2RpbmcuY29tL3NrZXRjaCk8L2Rlc2NyaXB0aW9uPgogICAgPGRlZnM+PC9kZWZzPgogICAgPGcgaWQ9IlBhZ2UtMSIgc3Ryb2tlPSJub25lIiBzdHJva2Utd2lkdGg9IjEiIGZpbGw9Im5vbmUiIGZpbGwtcnVsZT0iZXZlbm9kZCIgc2tldGNoOnR5cGU9Ik1TUGFnZSI+CiAgICAgICAgPGcgaWQ9IkVkaXQtSWNvbnMtQWxsLUNsb3NlZCIgc2tldGNoOnR5cGU9Ik1TTGF5ZXJHcm91cCIgdHJhbnNmb3JtPSJ0cmFuc2xhdGUoLTEwOS4wMDAwMDAsIC05NC4wMDAwMDApIiBmaWxsPSIjRkZGRkZGIj4KICAgICAgICAgICAgPGcgaWQ9IlJvdy0yIiB0cmFuc2Zvcm09InRyYW5zbGF0ZSgyLjAwMDAwMCwgOTQuMDAwMDAwKSIgc2tldGNoOnR5cGU9Ik1TU2hhcGVHcm91cCI+CiAgICAgICAgICAgICAgICA8ZyBpZD0iTWFyZ2luIiB0cmFuc2Zvcm09InRyYW5zbGF0ZSgxMDcuMDAwMDAwLCAwLjAwMDAwMCkiPgogICAgICAgICAgICAgICAgICAgIDxnIGlkPSJHcm91cCI+CiAgICAgICAgICAgICAgICAgICAgICAgIDxyZWN0IGlkPSJSZWN0YW5nbGUtMjEiIHN0cm9rZT0iI0Q5RDlEOSIgc3Ryb2tlLWRhc2hhcnJheT0iMSwxIiB4PSIwIiB5PSIwIiB3aWR0aD0iNDAiIGhlaWdodD0iNDAiPjwvcmVjdD4KICAgICAgICAgICAgICAgICAgICAgICAgPHJlY3QgaWQ9IlJlY3RhbmdsZS01IiBzdHJva2U9IiM5Mzk3OUIiIHN0cm9rZS13aWR0aD0iMiIgeD0iNSIgeT0iNSIgd2lkdGg9IjMwIiBoZWlnaHQ9IjMwIj48L3JlY3Q+CiAgICAgICAgICAgICAgICAgICAgICAgIDxyZWN0IGlkPSJSZWN0YW5nbGUtNSIgc3Ryb2tlPSIjOTM5NzlCIiBzdHJva2Utd2lkdGg9IjIiIHg9IjQiIHk9IjQiIHdpZHRoPSI0IiBoZWlnaHQ9IjQiPjwvcmVjdD4KICAgICAgICAgICAgICAgICAgICAgICAgPHJlY3QgaWQ9IlJlY3RhbmdsZS01IiBzdHJva2U9IiM5Mzk3OUIiIHN0cm9rZS13aWR0aD0iMiIgeD0iNCIgeT0iMzIiIHdpZHRoPSI0IiBoZWlnaHQ9IjQiPjwvcmVjdD4KICAgICAgICAgICAgICAgICAgICAgICAgPHJlY3QgaWQ9IlJlY3RhbmdsZS01IiBzdHJva2U9IiM5Mzk3OUIiIHN0cm9rZS13aWR0aD0iMiIgeD0iMzIiIHk9IjQiIHdpZHRoPSI0IiBoZWlnaHQ9IjQiPjwvcmVjdD4KICAgICAgICAgICAgICAgICAgICAgICAgPHJlY3QgaWQ9IlJlY3RhbmdsZS01IiBzdHJva2U9IiM5Mzk3OUIiIHN0cm9rZS13aWR0aD0iMiIgeD0iMzIiIHk9IjMyIiB3aWR0aD0iNCIgaGVpZ2h0PSI0Ij48L3JlY3Q+CiAgICAgICAgICAgICAgICAgICAgPC9nPgogICAgICAgICAgICAgICAgPC9nPgogICAgICAgICAgICA8L2c+CiAgICAgICAgPC9nPgogICAgPC9nPgo8L3N2Zz4=);
+ }
+
+ div.design-editor-box-nudging span.design-editor-box-title {
+ background-image: url(data:image/svg+xml;base64,PD94bWwgdmVyc2lvbj0iMS4wIiBlbmNvZGluZz0iVVRGLTgiIHN0YW5kYWxvbmU9Im5vIj8+Cjxzdmcgd2lkdGg9IjM2cHgiIGhlaWdodD0iMzZweCIgdmlld0JveD0iMCAwIDM2IDM2IiB2ZXJzaW9uPSIxLjEiIHhtbG5zPSJodHRwOi8vd3d3LnczLm9yZy8yMDAwL3N2ZyIgeG1sbnM6eGxpbms9Imh0dHA6Ly93d3cudzMub3JnLzE5OTkveGxpbmsiIHhtbG5zOnNrZXRjaD0iaHR0cDovL3d3dy5ib2hlbWlhbmNvZGluZy5jb20vc2tldGNoL25zIj4KICAgIDx0aXRsZT5OdWRnaW5nPC90aXRsZT4KICAgIDxkZXNjcmlwdGlvbj5DcmVhdGVkIHdpdGggU2tldGNoIChodHRwOi8vd3d3LmJvaGVtaWFuY29kaW5nLmNvbS9za2V0Y2gpPC9kZXNjcmlwdGlvbj4KICAgIDxkZWZzPjwvZGVmcz4KICAgIDxnIGlkPSJQYWdlLTEiIHN0cm9rZT0ibm9uZSIgc3Ryb2tlLXdpZHRoPSIxIiBmaWxsPSJub25lIiBmaWxsLXJ1bGU9ImV2ZW5vZGQiIHNrZXRjaDp0eXBlPSJNU1BhZ2UiPgogICAgICAgIDxnIGlkPSJFZGl0LUljb25zLUFsbC1DbG9zZWQiIHNrZXRjaDp0eXBlPSJNU0xheWVyR3JvdXAiIHRyYW5zZm9ybT0idHJhbnNsYXRlKC0xNS4wMDAwMDAsIC0xODkuMDAwMDAwKSI+CiAgICAgICAgICAgIDxnIGlkPSJSb3ctMyIgdHJhbnNmb3JtPSJ0cmFuc2xhdGUoMTIuMDAwMDAwLCAxOTAuMDAwMDAwKSIgc2tldGNoOnR5cGU9Ik1TU2hhcGVHcm91cCI+CiAgICAgICAgICAgICAgICA8ZyBpZD0iTnVkZ2luZyIgdHJhbnNmb3JtPSJ0cmFuc2xhdGUoNS4wMDAwMDAsIDEuMDAwMDAwKSI+CiAgICAgICAgICAgICAgICAgICAgPHJlY3QgaWQ9IlJlY3RhbmdsZS01IiBzdHJva2U9IiM5Mzk3OUIiIHN0cm9rZS13aWR0aD0iMiIgZmlsbD0iI0ZGRkZGRiIgeD0iMSIgeT0iMSIgd2lkdGg9IjMwIiBoZWlnaHQ9IjMwIj48L3JlY3Q+CiAgICAgICAgICAgICAgICAgICAgPHJlY3QgaWQ9IlJlY3RhbmdsZS01IiBzdHJva2U9IiM5Nzk3OTciIGZpbGw9IiNENEQ0RDQiIHg9IjEwIiB5PSIxMCIgd2lkdGg9IjEyIiBoZWlnaHQ9IjEyIj48L3JlY3Q+CiAgICAgICAgICAgICAgICAgICAgPHJlY3QgaWQ9IlJlY3RhbmdsZS01IiBzdHJva2U9IiM5Mzk3OUIiIHN0cm9rZS13aWR0aD0iMiIgZmlsbD0iI0ZGRkZGRiIgeD0iMCIgeT0iMCIgd2lkdGg9IjQiIGhlaWdodD0iNCI+PC9yZWN0PgogICAgICAgICAgICAgICAgICAgIDxyZWN0IGlkPSJSZWN0YW5nbGUtNSIgc3Ryb2tlPSIjOTM5NzlCIiBzdHJva2Utd2lkdGg9IjIiIGZpbGw9IiNGRkZGRkYiIHg9IjAiIHk9IjI4IiB3aWR0aD0iNCIgaGVpZ2h0PSI0Ij48L3JlY3Q+CiAgICAgICAgICAgICAgICAgICAgPHJlY3QgaWQ9IlJlY3RhbmdsZS01IiBzdHJva2U9IiM5Mzk3OUIiIHN0cm9rZS13aWR0aD0iMiIgZmlsbD0iI0ZGRkZGRiIgeD0iMjgiIHk9IjAiIHdpZHRoPSI0IiBoZWlnaHQ9IjQiPjwvcmVjdD4KICAgICAgICAgICAgICAgICAgICA8cmVjdCBpZD0iUmVjdGFuZ2xlLTUiIHN0cm9rZT0iIzkzOTc5QiIgc3Ryb2tlLXdpZHRoPSIyIiBmaWxsPSIjRkZGRkZGIiB4PSIyOCIgeT0iMjgiIHdpZHRoPSI0IiBoZWlnaHQ9IjQiPjwvcmVjdD4KICAgICAgICAgICAgICAgICAgICA8ZyBpZD0ic2NhbGUtdXAiIHRyYW5zZm9ybT0idHJhbnNsYXRlKDcuMDAwMDAwLCA3LjAwMDAwMCkiIGZpbGw9IiM5QjlCOUIiPgogICAgICAgICAgICAgICAgICAgICAgICA8cGF0aCBkPSJNMTIuMDg5Mjg1NywxLjgwMzU3MTQzIEwxNy44NzUsLTAuMTI1IEwxNS45NDY0Mjg2LDUuNjYwNzE0MjkgTDE1Ljk0NjQyODYsNS42NjA3MTQyOSBMMTIuMDg5Mjg1NywxLjgwMzU3MTQzIEwxMi4wODkyODU3LDEuODAzNTcxNDMgWiBNMS44MDM1NzE0Myw1LjY2MDcxNDI5IEwtMC4xMjUsLTAuMTI1IEw1LjY2MDcxNDI5LDEuODAzNTcxNDMgTDUuNjYwNzE0MjksMS44MDM1NzE0MyBMMS44MDM1NzE0Myw1LjY2MDcxNDI5IEwxLjgwMzU3MTQzLDUuNjYwNzE0MjkgWiBNNS42NjA3MTQyOSwxNS45NDY0Mjg2IEwtMC4xMjUsMTcuODc1IEwxLjgwMzU3MTQzLDEyLjA4OTI4NTcgTDEuODAzNTcxNDMsMTIuMDg5Mjg1NyBMNS42NjA3MTQyOSwxNS45NDY0Mjg2IEw1LjY2MDcxNDI5LDE1Ljk0NjQyODYgWiBNMTUuOTQ2NDI4NiwxMi4wODkyODU3IEwxNy44NzUsMTcuODc1IEwxMi4wODkyODU3LDE1Ljk0NjQyODYgTDEyLjA4OTI4NTcsMTUuOTQ2NDI4NiBMMTUuOTQ2NDI4NiwxMi4wODkyODU3IEwxNS45NDY0Mjg2LDEyLjA4OTI4NTcgWiIgaWQ9IlNoYXBlIj48L3BhdGg+CiAgICAgICAgICAgICAgICAgICAgPC9nPgogICAgICAgICAgICAgICAgPC9nPgogICAgICAgICAgICA8L2c+CiAgICAgICAgPC9nPgogICAgPC9nPgo8L3N2Zz4=);
+ }
+
+ div.design-editor-box-overflow span.design-editor-box-title {
+ background-image: url(data:image/svg+xml;base64,PD94bWwgdmVyc2lvbj0iMS4wIiBlbmNvZGluZz0iVVRGLTgiIHN0YW5kYWxvbmU9Im5vIj8+Cjxzdmcgd2lkdGg9IjM2cHgiIGhlaWdodD0iMzZweCIgdmlld0JveD0iMCAwIDM2IDM2IiB2ZXJzaW9uPSIxLjEiIHhtbG5zPSJodHRwOi8vd3d3LnczLm9yZy8yMDAwL3N2ZyIgeG1sbnM6eGxpbms9Imh0dHA6Ly93d3cudzMub3JnLzE5OTkveGxpbmsiIHhtbG5zOnNrZXRjaD0iaHR0cDovL3d3dy5ib2hlbWlhbmNvZGluZy5jb20vc2tldGNoL25zIj4KICAgIDx0aXRsZT5vdmVyZmxvdzwvdGl0bGU+CiAgICA8ZGVzY3JpcHRpb24+Q3JlYXRlZCB3aXRoIFNrZXRjaCAoaHR0cDovL3d3dy5ib2hlbWlhbmNvZGluZy5jb20vc2tldGNoKTwvZGVzY3JpcHRpb24+CiAgICA8ZGVmcz48L2RlZnM+CiAgICA8ZyBpZD0iUGFnZS0xIiBzdHJva2U9Im5vbmUiIHN0cm9rZS13aWR0aD0iMSIgZmlsbD0ibm9uZSIgZmlsbC1ydWxlPSJldmVub2RkIiBza2V0Y2g6dHlwZT0iTVNQYWdlIj4KICAgICAgICA8ZyBpZD0iRWRpdC1JY29ucy1BbGwtQ2xvc2VkIiBza2V0Y2g6dHlwZT0iTVNMYXllckdyb3VwIiB0cmFuc2Zvcm09InRyYW5zbGF0ZSgtMTExLjAwMDAwMCwgLTE5MC4wMDAwMDApIj4KICAgICAgICAgICAgPGcgaWQ9IlJvdy0zIiB0cmFuc2Zvcm09InRyYW5zbGF0ZSgxMi4wMDAwMDAsIDE5MC4wMDAwMDApIiBza2V0Y2g6dHlwZT0iTVNTaGFwZUdyb3VwIj4KICAgICAgICAgICAgICAgIDxnIGlkPSJHcm91cCIgdHJhbnNmb3JtPSJ0cmFuc2xhdGUoMTAxLjAwMDAwMCwgMi4wMDAwMDApIj4KICAgICAgICAgICAgICAgICAgICA8cmVjdCBpZD0iUmVjdGFuZ2xlLTUiIHN0cm9rZT0iIzk3OTc5NyIgc3Ryb2tlLXdpZHRoPSIyIiBmaWxsPSIjRkZGRkZGIiB4PSIxIiB5PSIxIiB3aWR0aD0iMzAiIGhlaWdodD0iMzAiPjwvcmVjdD4KICAgICAgICAgICAgICAgICAgICA8cmVjdCBpZD0iUmVjdGFuZ2xlLTUiIHN0cm9rZT0iIzk3OTc5NyIgc3Ryb2tlLXdpZHRoPSIyIiBmaWxsPSIjRDRENEQ0IiB4PSIxMCIgeT0iMTEiIHdpZHRoPSIxMiIgaGVpZ2h0PSIxMyI+PC9yZWN0PgogICAgICAgICAgICAgICAgICAgIDxyZWN0IGlkPSJSZWN0YW5nbGUtNSIgZmlsbD0iIzlCOUI5QiIgeD0iMiIgeT0iMTgiIHdpZHRoPSIyOCIgaGVpZ2h0PSIxMyI+PC9yZWN0PgogICAgICAgICAgICAgICAgICAgIDxyZWN0IGlkPSJSZWN0YW5nbGUtNSIgc3Ryb2tlPSIjOTc5Nzk3IiBzdHJva2Utd2lkdGg9IjIiIGZpbGw9IiNGRkZGRkYiIHg9IjAiIHk9IjAiIHdpZHRoPSI0IiBoZWlnaHQ9IjQiPjwvcmVjdD4KICAgICAgICAgICAgICAgICAgICA8cmVjdCBpZD0iUmVjdGFuZ2xlLTUiIHN0cm9rZT0iIzk3OTc5NyIgc3Ryb2tlLXdpZHRoPSIyIiBmaWxsPSIjRkZGRkZGIiB4PSIwIiB5PSIyOCIgd2lkdGg9IjQiIGhlaWdodD0iNCI+PC9yZWN0PgogICAgICAgICAgICAgICAgICAgIDxyZWN0IGlkPSJSZWN0YW5nbGUtNSIgc3Ryb2tlPSIjOTc5Nzk3IiBzdHJva2Utd2lkdGg9IjIiIGZpbGw9IiNGRkZGRkYiIHg9IjI4IiB5PSIwIiB3aWR0aD0iNCIgaGVpZ2h0PSI0Ij48L3JlY3Q+CiAgICAgICAgICAgICAgICAgICAgPHJlY3QgaWQ9IlJlY3RhbmdsZS01IiBzdHJva2U9IiM5Nzk3OTciIHN0cm9rZS13aWR0aD0iMiIgZmlsbD0iI0ZGRkZGRiIgeD0iMjgiIHk9IjI4IiB3aWR0aD0iNCIgaGVpZ2h0PSI0Ij48L3JlY3Q+CiAgICAgICAgICAgICAgICA8L2c+CiAgICAgICAgICAgIDwvZz4KICAgICAgICA8L2c+CiAgICA8L2c+Cjwvc3ZnPg==);
+ }
+
+ div.design-editor-box-padding span.design-editor-box-title {
+ background-image: url(data:image/svg+xml;base64,PD94bWwgdmVyc2lvbj0iMS4wIiBlbmNvZGluZz0iVVRGLTgiIHN0YW5kYWxvbmU9Im5vIj8+Cjxzdmcgd2lkdGg9IjM2cHgiIGhlaWdodD0iMzZweCIgdmlld0JveD0iMCAwIDM2IDM2IiB2ZXJzaW9uPSIxLjEiIHhtbG5zPSJodHRwOi8vd3d3LnczLm9yZy8yMDAwL3N2ZyIgeG1sbnM6eGxpbms9Imh0dHA6Ly93d3cudzMub3JnLzE5OTkveGxpbmsiIHhtbG5zOnNrZXRjaD0iaHR0cDovL3d3dy5ib2hlbWlhbmNvZGluZy5jb20vc2tldGNoL25zIj4KICAgIDx0aXRsZT5wYWRkaW5nPC90aXRsZT4KICAgIDxkZXNjcmlwdGlvbj5DcmVhdGVkIHdpdGggU2tldGNoIChodHRwOi8vd3d3LmJvaGVtaWFuY29kaW5nLmNvbS9za2V0Y2gpPC9kZXNjcmlwdGlvbj4KICAgIDxkZWZzPjwvZGVmcz4KICAgIDxnIGlkPSJQYWdlLTEiIHN0cm9rZT0ibm9uZSIgc3Ryb2tlLXdpZHRoPSIxIiBmaWxsPSJub25lIiBmaWxsLXJ1bGU9ImV2ZW5vZGQiIHNrZXRjaDp0eXBlPSJNU1BhZ2UiPgogICAgICAgIDxnIGlkPSJFZGl0LUljb25zLUFsbC1DbG9zZWQiIHNrZXRjaDp0eXBlPSJNU0xheWVyR3JvdXAiIHRyYW5zZm9ybT0idHJhbnNsYXRlKC0yMDUuMDAwMDAwLCAtOTYuMDAwMDAwKSIgc3Ryb2tlLXdpZHRoPSIyIj4KICAgICAgICAgICAgPGcgaWQ9IlJvdy0yIiB0cmFuc2Zvcm09InRyYW5zbGF0ZSgyLjAwMDAwMCwgOTQuMDAwMDAwKSIgc2tldGNoOnR5cGU9Ik1TU2hhcGVHcm91cCI+CiAgICAgICAgICAgICAgICA8ZyBpZD0iUGFkZGluZyIgdHJhbnNmb3JtPSJ0cmFuc2xhdGUoMjAxLjAwMDAwMCwgNC4wMDAwMDApIj4KICAgICAgICAgICAgICAgICAgICA8ZyBpZD0iR3JvdXAiIHRyYW5zZm9ybT0idHJhbnNsYXRlKDQuMDAwMDAwLCAwLjAwMDAwMCkiPgogICAgICAgICAgICAgICAgICAgICAgICA8cmVjdCBpZD0iUmVjdGFuZ2xlLTUiIHN0cm9rZT0iIzkzOTc5QiIgZmlsbD0iI0ZGRkZGRiIgeD0iMSIgeT0iMSIgd2lkdGg9IjMwIiBoZWlnaHQ9IjMwIj48L3JlY3Q+CiAgICAgICAgICAgICAgICAgICAgICAgIDxyZWN0IGlkPSJSZWN0YW5nbGUtNSIgc3Ryb2tlPSIjOTc5Nzk3IiBmaWxsPSIjRDRENEQ0IiB4PSI5IiB5PSI5IiB3aWR0aD0iMTQiIGhlaWdodD0iMTQiPjwvcmVjdD4KICAgICAgICAgICAgICAgICAgICAgICAgPHJlY3QgaWQ9IlJlY3RhbmdsZS01IiBzdHJva2U9IiM5Mzk3OUIiIGZpbGw9IiNGRkZGRkYiIHg9IjAiIHk9IjAiIHdpZHRoPSI0IiBoZWlnaHQ9IjQiPjwvcmVjdD4KICAgICAgICAgICAgICAgICAgICAgICAgPHJlY3QgaWQ9IlJlY3RhbmdsZS01IiBzdHJva2U9IiM5Mzk3OUIiIGZpbGw9IiNGRkZGRkYiIHg9IjAiIHk9IjI4IiB3aWR0aD0iNCIgaGVpZ2h0PSI0Ij48L3JlY3Q+CiAgICAgICAgICAgICAgICAgICAgICAgIDxyZWN0IGlkPSJSZWN0YW5nbGUtNSIgc3Ryb2tlPSIjOTM5NzlCIiBmaWxsPSIjRkZGRkZGIiB4PSIyOCIgeT0iMCIgd2lkdGg9IjQiIGhlaWdodD0iNCI+PC9yZWN0PgogICAgICAgICAgICAgICAgICAgICAgICA8cmVjdCBpZD0iUmVjdGFuZ2xlLTUiIHN0cm9rZT0iIzkzOTc5QiIgZmlsbD0iI0ZGRkZGRiIgeD0iMjgiIHk9IjI4IiB3aWR0aD0iNCIgaGVpZ2h0PSI0Ij48L3JlY3Q+CiAgICAgICAgICAgICAgICAgICAgPC9nPgogICAgICAgICAgICAgICAgPC9nPgogICAgICAgICAgICA8L2c+CiAgICAgICAgPC9nPgogICAgPC9nPgo8L3N2Zz4=);
+ }
+ /* End Box Structure */
+
+ /* Box Content */
+ ul.design-editor-box-content {
+ clear: both;
+ display: none;
+ float: left;
+ margin: 0;
+ padding: 15px;
+ width: 290px;
+ background-color: #fff;
+ border-top: 1px solid #eee;
+ border-bottom: 1px solid #eee;
+ .border-box();
+ overflow: hidden;
+
+ > li {
+ margin: 0;
+ background: #fff;
+ border-bottom: 1px solid #eee;
+ padding: 5px 10px;
+ font-size: 12px;
+ float: left;
+ display: block;
+ min-height: 36px;
+ width: 100%;
+ position: relative;
+ .border-box();
+
+ &:last-of-type {
+ border-bottom: none;
+ }
+
+ > strong {
+ color: #444;
+ font-weight: 600;
+ height: 26px;
+ line-height: 26px;
+ float: left;
+ .no-highlight();
+ cursor: default;
+ }
+
+ /* Customize and Uncustomize Buttons */
+ span.uncustomize-property {
+ text-indent: -9999px;
+ height: 10px;
+ width: 10px;
+ cursor: pointer;
+ display: none;
+ color: rgba(0, 0, 0, .25);
+ margin: 8px 0 0 7px;
+ float: right;
+ .no-highlight();
+ .transition('color 100ms linear');
+
+ &:hover {
+ color: rgba(0, 0, 0, .8);
+ }
+
+ &:before {
+ .icon-font;
+ content: '\78';
+ float: left;
+ font-size: 11px;
+ line-height: 11px;
+ }
+ }
+
+ /* Uncustomized Properties */
+ &.uncustomized-property {
+ div.property {
+ opacity: 0;
+ }
+
+ /* Hide the uncustomize button on uncustomized elements */
+ strong span.uncustomize-property {
+ display: none;
+ }
+
+ /* Show customize button on uncustomized properties */
+ div.customize-property {
+ display: block;
+ }
+ }
+ /* End Uncustomized Properties */
+
+ /* Only show the uncustomize button on hovered properties */
+ &:hover span.uncustomize-property {
+ display: block;
+ }
+
+ /* Customize Buttons */
+ div.customize-property {
+ /* Hide the customize button by default. It will only show on uncustomized properties. */
+ display: none;
+ position: absolute;
+ top: 50%;
+ right: 10px;
+ color: #666;
+ margin: -10px 0 0 0;
+ line-height: 20px;
+ .no-highlight();
+
+ span {
+ cursor: pointer;
+ color: #199ebf;
+ text-decoration: none;
+
+ &:hover {
+ text-decoration: underline;
+ }
+ }
+ }
+ /* End Customize and Uncustomize Buttons */
+
+ /* Dot Flags */
+ /* Customized property by user */
+ ul.design-editor-box-content li.customized-property-by-user strong span:after {
+ content: '\2022';
+ .icon-font;
+ color: @customized_element_color;
+ font-size: 20px;
+ line-height: 5px;
+ margin: 0 0 0 8px;
+ opacity: .5;
+ }
+ /* End Dot Flags */
+
+ /* Properties */
+ > div.property {
+ color: #555;
+ font-weight: 400;
+ float: right;
+ max-width: 110px;
+ }
+ /* End Properties */
+
+ } /* End > li */
+ } /* End ul.design-editor-box-content */
+
+ /* Open Boxes */
+ div.design-editor-box-open {
+ ul.design-editor-box-content {
+ display: block;
+ }
+
+ /* Box Content Position */
+ &:nth-child(2) ul.design-editor-box-content {
+ margin-left: -97px;
+ }
+
+ &:nth-child(3) ul.design-editor-box-content {
+ margin-left: -193px;
+ }
+ /* End Box Content Position */
+ }
+ /* End Open Boxes */
+ /* End Box Content */
+ /* End Property Group Boxes */
+/* End Properties */
+
+
+/* Box Modal Properties */
+ div.box-model-inputs-container {
+ float: left;
+ clear: both;
+ width: 100%;
+
+ strong.box-model-inputs-heading {
+ display: block;
+ font-size: 13px;
+ color: #444;
+ font-weight: 600;
+ padding: 0 8px;
+ margin: 17px 0 0;
+ }
+
+ div.box-model-inputs {
+ margin: 17px 8px 20px;
+ position: relative;
+ border: 1px solid #aaa;
+ height: 100px;
+ .border-box();
+
+ &.box-model-inputs-locked {
+ @locked_color = #199ebf;
+
+ &, input, span {
+ border-color: @locked_color !important;
+ color: @locked_color;
+ }
+ }
+
+ /* Lock Sides button */
+ .design-editor-lock-sides {
+ display: block;
+ text-decoration: underline;
+ cursor: pointer;
+ color: #444;
+ position: absolute;
+ top: 50%;
+ left: 50%;
+ margin-top: -17px;
+ margin-left: -17px;
+ z-index: 1;
+ background: #ddd;
+ .rounded-corners(30px);
+ padding: 10px;
+ border: 1px solid #aaa;
+ text-decoration: none;
+ width: 12px;
+ height: 12px;
+
+ &:hover:not(.locked) {
+ background: #ccc;
+ }
+
+ &.locked {
+ color: #78BBAC;
+ }
+
+ &:before {
+ .icon-font;
+ font-size: 16px;
+ line-height: .8;
+ content: "5";
+ }
+ }
+
+ > li {
+ width: 95px;
+ height: 18px;
+ position: absolute;
+
+ strong { display: none; }
+
+ div.property {
+ width: 95px;
+ position: relative;
+ display: block;
+
+ span.uncustomize-property {
+ text-indent: -9999px;
+ height: 10px;
+ width: 10px;
+ cursor: pointer;
+ position: absolute;
+ color: rgba(0, 0, 0, .25);
+ left: 4px;
+ top: 27px;
+ -webkit-transform: rotateY(180deg);
+ -moz-transform: rotateY(180deg);
+ transform: rotateY(180deg);
+ .no-highlight();
+ .transition('color 100ms linear');
+ z-index: 5;
+
+ &:hover {
+ color: rgba(0, 0, 0, .6);
+ }
+
+ &:before {
+ .icon-font;
+ content: '\78';
+ float: left;
+ font-size: 11px;
+ line-height: 11px;
+ }
+ }
+
+ input {
+ float: left;
+ margin: 0;
+ width: 39px !important;
+ }
+
+ .property-unit-select {
+ margin: 0;
+
+ select {
+ font-size: 9px;
+ float: right;
+ height: 25px;
+ width: 45px;
+ }
+ }
+
+ span.unit {
+ color: #626262;
+ display: block;
+ font-weight: 400;
+ font-size: 10px;
+ clear: both;
+ float: right;
+ margin: 1px 2px 0 0;
+ }
+
+ &:hover {
+ span.uncustomize-property {
+ display: block;
+ }
+ }
+ }
+
+ .customize-property {
+ display: none;
+ color: #199ebf;
+ text-decoration: none;
+ cursor: pointer;
+ font-size: 11px;
+ line-height: 18px;
+
+ &:hover {
+ text-decoration: underline;
+ }
+ }
+
+ &.uncustomized-property {
+ div.property,
+ .uncustomize-property {
+ display: none;
+ }
+
+ .customize-property {
+ display: block;
+ }
+ }
+ }
+
+ /* Positioning */
+ &.box-model-inputs-position-sides {
+ /* Top */
+ > li[data-property-id*="-top"] {
+ top: 0;
+ left: 50%;
+ margin-left: -47px;
+ text-align: center;
+
+ div.property {
+ margin-top: -9px;
+ margin-left: 0;
+ }
+ }
+
+ /* Right */
+ > li[data-property-id*="-right"] {
+ top: 50%;
+ right: 0;
+ text-align: right;
+ margin-top: -9px;
+
+ div.property {
+ margin-right: -18px;
+ float: right;
+ }
+
+ .customize-property {
+ margin-right: 5px;
+ float: right;
+ }
+ }
+
+ /* Bottom */
+ > li[data-property-id*="-bottom"] {
+ bottom: 0;
+ left: 50%;
+ margin-left: -47px;
+ text-align: center;
+
+ div.property {
+ margin-top: 9px;
+ margin-left: 0;
+ }
+ }
+
+ /* Left */
+ > li[data-property-id*="-left"] {
+ top: 50%;
+ left: 0;
+ text-align: center;
+ margin-top: -9px;
+
+ div.property {
+ margin-left: -18px;
+ }
+
+ .customize-property {
+ margin-left: 5px;
+ float: left;
+ }
+ }
+ }
+
+ &.box-model-inputs-position-corners {
+ /* Top Left */
+ > li[data-property-id*="top-left"] {
+ top: 0;
+ left: 0;
+
+ div.property {
+ margin: -9px 0 0 -18px;
+ }
+
+ .customize-property {
+ margin-left: 5px;
+ margin-top: 3px;
+ float: left;
+ }
+ }
+
+ /* Top Right */
+ > li[data-property-id*="top-right"] {
+ top: 0;
+ right: 0;
+ text-align: right;
+
+ div.property {
+ float: right;
+ margin: -9px -18px 0 0;
+ }
+
+ .customize-property {
+ margin-right: 5px;
+ margin-top: 5px;
+ float: right;
+ }
+ }
+
+ /* Bottom Right */
+ > li[data-property-id*="bottom-right"] {
+ bottom: 0;
+ right: 0;
+ text-align: right;
+
+ div.property {
+ float: right;
+ margin: 9px -18px 0 0;
+ }
+
+ .customize-property {
+ margin-right: 5px;
+ position: relative;
+ top: -2px;
+ float: right;
+ }
+ }
+
+ /* Bottom Left */
+ > li[data-property-id*="bottom-left"] {
+ bottom: 0;
+ left: 0;
+
+ div.property {
+ margin: 9px 0 0 -18px;
+ }
+
+ .customize-property {
+ margin-left: 4px;
+ position: relative;
+ top: -2px;
+ float: left;
+ }
+ }
+ }
+ /* End Positioning */
+ }
+ }
+/* End Box Modal Properties */
+
+
+/* Property Inputs */
+ /* Integer */
+ div.property-integer input {
+ width: 45px;
+ outline:none;
+ padding: 2px 0 2px 5px;
+ float: left;
+ margin: 2px 3px 0 0;
+ }
+
+ div.property-integer span.unit {
+ float: left;
+ margin: 5px 0 0 0;
+ .no-highlight();
+ }
+
+ /* Color */
+
+ /* Select */
+ div.property .select-container {
+ margin-top: 3px;
+ }
+
+ div.property .select-container select {
+ font-size: 13px;
+ width: 90px;
+ height: 22px;
+ }
+
+ /* Unit Select */
+ div.property .property-unit-select {
+ float: right;
+ }
+
+ div.property .property-unit-select select {
+ font-size: 11px;
+ width: 53px;
+ }
+
+ /* Image */
+ div.property-image span.button {
+ font-size: 11px;
+ height: 20px;
+ line-height: 20px;
+ margin: 3px 0 0;
+ float: right;
+ }
+
+ div.property-image div.image-input-controls-container {
+ width: 200px;
+ margin: 10px 0 10px -100px;
+ float: left;
+ }
+
+ div.property-image span.src {
+ font-size: 11px;
+ line-height: 13px;
+ color: #666;
+ margin: 0;
+ max-width: 170px;
+ }
+
+ div.property-image span.delete-image {
+ margin: 1px 0 0 10px;
+ float: left;
+ }
+/* End Property Inputs */
\ No newline at end of file
--- /dev/null
+body {
+ font-family: helvetica, sans-serif;
+ font-size: 13px;
+ background: url(%VISUALEDITOR%/images/grid-mode-bg.png) repeat top center #4C4C4C;
+}
+
+.block {
+ background: #fff;
+ box-shadow: 0 0 0 1px #000;
+ outline: none;
+
+ /* Force hardware acceleration */
+ -webkit-transform: translateZ(0);
+ -moz-transform: translateZ(0);
+ -ms-transform: translateZ(0);
+ transform: translateZ(0);
+}
+
+ .block:hover {
+ box-shadow: 0 0 0 1px #2ea2cc;
+
+ svg .x-line {
+ stroke: #2ea2cc;
+ }
+ }
+
+ .block-mirrored {
+ box-shadow: 0 0 0 1px #008FD5;
+ }
+
+ .block-error, .block-type-unknown {
+ box-shadow: 0 0 0 1px #f00;
+
+ &:hover {
+ box-shadow: 0 0 0 1px #c00;
+ }
+ }
+
+ div.ui-grid-helper {
+ box-shadow: 0 0 0 1px #2ea2cc;
+ }
+
+
+
+div#whitewrap {
+ background: #ddd;
+}
+
+.wrapper {
+ border: 1px solid #000;
+ background: #fff;
+ padding: 15px;
+ position: relative;
+}
+
+/* Give a background to block content cover to cover up content of all blocks */
+.block-content-cover {
+ background: #fff;
+}
+
+/* Block Type readout styling */
+ .block-content-cover svg .x-line {
+ stroke: #000;
+ stroke-width: 1;
+ }
+
+ .block-content-cover span.block-type-and-id {
+ display: block;
+ position: absolute;
+ top: 0;
+ right: 0;
+ background: #000;
+ color: #FFF;
+ font-size: 11px;
+ padding: 3px 5px;
+
+ span {
+ color: rgba(255, 255, 255, .6);
+ }
+ }
+
+ /* Mirrored Blocks */
+ .block-mirrored {
+
+ .block-content-cover {
+ span.block-type-and-id {
+ background: #008FD5;
+ }
+
+ svg .x-line {
+ stroke: #008FD5;
+ }
+ }
+
+ }
+
+ /* Erred Blocks */
+ .block-error, .block-type-unknown {
+
+ .block-content-cover {
+ span.block-type-and-id {
+ background: #f00;
+ }
+
+ svg .x-line {
+ stroke: #f00;
+ }
+ }
+
+ }
+
+/* Show SVG Cover for all blocks then hide it certain blocks */
+ .block-content-cover svg {
+ display: block;
+ width: 100%;
+ height: 100%;
+ }
+
+ .block:not(.hide-content-in-grid) {
+
+ .block-content-cover {
+ background: none;
+
+ svg {
+ display: none;
+ }
+ }
+
+ }
+
+/* All Hyperlink */
+.block-content-fade a {
+ color: #222;
+}
+
+/* Blocks */
+ /* Header */
+ .block-type-header span.banner a {
+ font-size: 32px;
+ text-decoration: none;
+ margin: 20px 10px 0;
+ display: block;
+ }
+
+ .block-type-header .tagline {
+ font-size: 14px;
+ color: #666;
+ margin: 10px 10px 20px;
+ display: block;
+ }
+
+
+ /* Navigation */
+ .block-type-navigation .nav-horizontal, .block-type-navigation ul {
+ height: 100%;
+ }
+
+ .block-type-navigation .nav-align-left ul { text-align: left; }
+ .block-type-navigation .nav-align-right ul { text-align: right; }
+ .block-type-navigation .nav-align-center ul { text-align: center; }
+
+ .block-type-navigation ul li {
+ height: 100%;
+ display: inline-block;
+ }
+
+ .block-type-navigation ul li a {
+ text-decoration: none;
+ display: table;
+ height: 100% !important;
+ line-height: normal !important;
+ padding: 0 15px;
+ }
+
+ .block-type-navigation .nav-vertical ul li a {
+ height: auto;
+ line-height: 40px !important;
+ }
+
+ .block-type-navigation .nav-horizontal ul li a {
+ border-right: 1px solid #888;
+ }
+
+ .block-type-navigation .nav-vertical ul li a {
+ width: 100%;
+ border-bottom: 1px solid #888;
+ }
+
+ .block-type-navigation a span {
+ display: table-cell;
+ vertical-align: middle;
+ }
+
+ .block-type-navigation ul li.current_page_item a {
+ background: #aaa;
+ }
+
+ .block-type-navigation ul li ul {
+ display: none;
+ }
+
+ .block-type-navigation .nav-search-active .nav-search {
+ height: 100% !important;
+ }
+
+ .block-type-navigation .nav-hide-home-link .menu-item-home {
+ display: none !important;
+ }
+
+ /* Footer */
+ .block-type-footer .footer-left {
+ margin-top: 10px;
+ margin-left: 10px;
+ float: left;
+ }
+
+ .block-type-footer .footer-right {
+ margin-top: 10px;
+ margin-right: 10px;
+ float: right;
+ }
+
+ .block-type-footer .footer-link {
+ margin-bottom: 10px;
+ }
+
+ .block-type-footer .copyright {
+ float: left;
+ width: 100%;
+ clear: both;
+ text-align: center;
+ margin: 10px 0;
+ }
+
+ .block-type-footer a {
+ color: inherit;
+ }
+
+ .block-type-footer p.footer-responsive-grid-link-container {
+ float: left;
+ width: 100%;
+ clear: both;
+ text-align: center;
+ margin: 10px 0;
+ display: none;
+ }
+
+ .block-type-footer p.footer-responsive-grid-link-enable-container {
+ display: block;
+ }
+/* END BLOCKS */
\ No newline at end of file
--- /dev/null
+/* Structure */
+html {
+ height: 100%;
+}
+
+body {
+ position: relative;
+ min-height: 100%;
+ height: auto;
+}
+
+ /* Hide Guides */
+ body.hide-guides {
+ .grid-guides {
+ opacity: 0 !important;
+ }
+
+ .block {
+ outline: none;
+ }
+ }
+
+ /* Wrapper Mirroring */
+ /* Hide these by default and only show them if the wrapper mirrored class is on the wrapper */
+ div.wrapper-mirror-notice,
+ div.wrapper-mirror-overlay {
+ display: none;
+ }
+
+ div.wrapper-mirrored {
+ height: 120px !important;
+ min-height: 0 !important;
+ padding: 10px !important;
+ }
+
+ div.wrapper-mirrored div.grid-container {
+ min-height: 0 !important;
+ height: 100% !important;
+ }
+
+ div.wrapper-mirrored .block,
+ div.wrapper-mirrored .grid-guides,
+ div.wrapper-mirrored .ui-resizable-handle {
+ display: none !important;
+ }
+
+ div.wrapper-mirrored div.wrapper-mirror-notice,
+ div.wrapper-mirrored div.wrapper-mirror-overlay {
+ display: block;
+ }
+
+
+ /* Wrapper Mirror Notice */
+ div.wrapper-mirrored div.wrapper-mirror-notice {
+ color: rgba(0, 0, 0, .8);
+ background: rgba(255, 112, 42, .25);
+ width: 100%;
+ text-align: center;
+ border-radius: 5px;
+ height: 100%;
+ border: 1px dashed rgba(255, 112, 42, .6);
+ .border-box;
+ position: relative;
+ }
+
+ div.wrapper-mirrored div.wrapper-mirror-notice div {
+ height: 54px;
+ position: absolute;
+ top: 50%;
+ width: 100%;
+ margin-top: -27px;
+ }
+
+ div.wrapper-mirrored div.wrapper-mirror-notice h2 {
+ font-size: 15px;
+ font-weight: 600;
+ margin: 0;
+ }
+
+ div.wrapper-mirrored div.wrapper-mirror-notice p {
+ margin: 10px 0 5px;
+ }
+
+ div.wrapper-mirrored div.wrapper-mirror-notice small {
+ font-style: italic;
+ font-size: 11px;
+ }
+
+ /* End Wrapper Mirroring */
+
+ /* Wrapper Buttons */
+ #wrapper-buttons-template {
+ display: none;
+ }
+
+ div.wrapper-buttons {
+ position: absolute;
+ top: 10px;
+ right: -27px;
+ z-index: 999;
+ display: none;
+ }
+
+ /* Put a buffer area for fixed wrappers that way the buttons don't sporadically disappear */
+ div.wrapper-fixed div.wrapper-buttons {
+ height: 95%;
+ min-height: 90px;
+ width: 27px;
+ }
+
+ /* Hover hiding and showing */
+ div.wrapper:hover div.wrapper-buttons,
+ div.wrapper.ui-sortable-helper div.wrapper-buttons,
+ div.wrapper.wrapper-handle-in-use div.wrapper-buttons,
+ body.ipad div.wrapper div.wrapper-buttons {
+ display: block !important;
+ }
+
+ div.wrapper-fluid div.wrapper-buttons {
+ right: 10px;
+ }
+
+ /* General handle styling */
+ div.wrapper-handle {
+ display: block;
+ width: 25px;
+ height: auto;
+ padding: 7px 0;
+ background: #000;
+ cursor: move;
+ }
+
+ /* Lines inside of wrapper handle */
+ div.wrapper-handle span {
+ width: 15px;
+ background: rgba(255, 255, 255, .3);
+ height: 1px;
+ display: block;
+ margin: 1px auto;
+ }
+
+ /* Ordering Handle */
+ div.wrapper-drag-handle {
+ border-top: none;
+ border-bottom: none;
+ border-radius: 0;
+ }
+
+ /* Margin Handles */
+ div.wrapper-top-margin-handle,
+ div.wrapper-bottom-margin-handle {
+ padding: 4px 0;
+ background: #333;
+ cursor: row-resize;
+ }
+
+ /* Hide the margin handles for mirrored wrappers */
+ div.wrapper-mirrored div.wrapper-margin-handle {
+ display: none;
+ }
+
+
+ /* Inside Lines */
+ div.wrapper-top-margin-handle span:first-child,
+ div.wrapper-bottom-margin-handle span:nth-child(3) {
+ width: 2px;
+ }
+
+ div.wrapper-top-margin-handle span:nth-child(2),
+ div.wrapper-bottom-margin-handle span:nth-child(2) {
+ width: 6px;
+ }
+
+ div.wrapper-top-margin-handle span:nth-child(3),
+ div.wrapper-bottom-margin-handle span:first-child {
+ width: 10px;
+ }
+
+ /* Wrapper Options Button */
+ div.wrapper-options {
+ display: block;
+ margin: 6px 0 0;
+ width: 25px;
+ height: 25px;
+ padding: 0;
+ background: #000;
+ cursor: pointer;
+ text-align: center;
+ line-height: 25px;
+ }
+
+ div.wrapper-options span:before {
+ content: '\33';
+ .icon-font;
+ color: #dedede;
+ font-size: 15px;
+ }
+ /* End Wrapper Buttons */
+
+ div.wrapper.wrapper-fluid {
+ width: 100% !important;
+ }
+
+ div.wrapper.wrapper-fluid:first-of-type {
+ margin-top: 0;
+ }
+
+div#whitewrap {
+ width: 100%;
+ float: left;
+ margin: 0;
+ /* padding: 36px 0 0; */
+ padding: 0;
+ .border-box;
+ min-height: 100%;
+ position: relative;
+}
+
+
+/* Grid and Blocks */
+div.grid-container {
+ width: 100%;
+ height: 100%;
+ min-height: 10px;
+ margin: 0 auto;
+ float: none;
+ position: relative;
+ z-index: 2;
+}
+
+ div.wrapper-fluid-grid div.grid-container {
+ width: 100% !important;
+ }
+
+ div.grid-container.ui-state-hover {
+ background: #ddd;
+ }
+
+.block {
+ position: absolute !important;
+ cursor: move;
+ overflow: hidden;
+ min-height: 0 !important;
+
+ box-sizing: content-box !important;
+ -moz-box-sizing: content-box !important;
+
+ margin: 0 !important;
+ outline: 1px dashed rgba(0, 0, 0, .25); /* DON'T GET RID OF THIS OUTLINE... IT WILL SCREW GRID BEHAVIOR UP IN FIREFOX */
+ border: none;
+}
+
+ .block-ghost {
+ opacity: .5 !important;
+ }
+
+ .block-content {
+ position: relative;
+ z-index: 1;
+ }
+
+ .block-content-cover {
+ position: absolute;
+ z-index: 2;
+ width: 100%;
+ height: 100%;
+ display: block;
+
+ > svg, > span {
+ display: none;
+ }
+ }
+
+/* Unknown Block Types */
+.block-type-unknown div.block-content {
+ padding: 10px;
+ .border-box;
+}
+
+ .block-type-unknown div.block-type-unknown-notice {
+ overflow: auto;
+ margin: 0;
+ height: 100%;
+ .border-box;
+ overflow: auto;
+ display: block;
+ }
+
+ .block-safe-mode {
+ overflow: auto;
+ margin: 10px;
+ .border-box;
+ overflow: auto;
+ display: block;
+ }
+
+/* Grouped Blocks */
+div.grouping-active .block {
+ opacity: .3 !important;
+}
+
+div.grouping-active .grouped-block {
+ box-shadow: 0 0 5px rgba(20, 192, 241, .6) !important;
+ opacity: 1 !important;
+}
+
+ body.firefox {
+ div.grouping-active .grouped-block {
+ outline-offset: -7px;
+ }
+ }
+
+/* Wrapper Stuff */
+ div.add-wrapper-buttons {
+ width: 36px;
+ height: 36px;
+
+ margin: 0;
+
+ position: absolute;
+ left: 0;
+ top: 20px;
+
+ z-index: 998;
+ .border-box;
+ display: block;
+
+ div.add-wrapper-button-fixed {
+ display: inline-block;
+ border-radius: 0;
+ cursor: pointer;
+ position: relative;
+ height: 30px;
+ width: 30px;
+ font-size: 22px;
+ color: #fff;
+ line-height: 28px;
+ text-align: left;
+ background: #000;
+ text-align: center;
+ opacity: .5;
+ .transition('opacity 100ms linear');
+
+ &:hover {
+ opacity: .9;
+ }
+ }
+
+
+ /* Top & Bottom Add Wrapper Button Positions */
+ &.add-wrapper-buttons-bottom {
+ left: 0;
+ top: auto;
+ bottom: 20px;
+ }
+
+ }
+
+/* Grid Guides */
+.grid-guides {
+ display: block;
+ z-index: 0;
+ position: absolute;
+ height: 100%;
+ .border-box;
+ top: 0;
+ bottom: 0;
+ width: 100%;
+}
+
+.grid-guides .grid-guide {
+ margin: 0 10px;
+ overflow: visible;
+ float: left;
+ display: inline;
+ height: 100%;
+ .border-box;
+}
+
+ .grid-guides-red .grid-guide {
+ background: rgba(255, 0, 0, .075);
+ border-left: 1px solid rgba(255, 0, 0, .1);
+ border-right: 1px solid rgba(255, 0, 0, .1);
+ }
+
+ .grid-guides-grey .grid-guide {
+ background: rgba(0, 0, 0, .035);
+ border-left: 1px solid rgba(0, 0, 0, .07);
+ border-right: 1px solid rgba(0, 0, 0, .07);
+ }
+
+ .grid-guides-blue .grid-guide {
+ background: rgba(0, 0, 255, .06);
+ border-left: 1px solid rgba(0, 0, 255, .075);
+ border-right: 1px solid rgba(0, 0, 255, .075);
+ }
+
+ .grid-guides .grid-guide:first-child {
+ margin-left: 0 !important;
+ border-left: none;
+ }
+
+ .grid-guides .grid-guide:last-child {
+ margin-right: 0 !important;
+ border-right: none;
+ }
+
+
+/* Touch Optimization */
+body.ipad .wrapper:hover > div.ui-resizable-handle {
+ background: rgba(0, 0, 0, .05);
+}
+
+body.ipad .block:hover > div.ui-resizable-handle {
+ background: rgba(0, 0, 0, .05);
+}
+
+
+/* Helper */
+div.ui-grid-helper {
+ z-index: 10000;
+ border: none;
+ display: block;
+ position: absolute;
+ margin: -1px 0 0 -1px;
+}
+
+div.wrapper-sortable-placeholder {
+ display: block;
+ background: rgba(0, 0, 0, .1);
+ margin: 0 auto;
+ border: 1px dashed rgba(205, 246, 244, 0.6);
+ box-shadow: inset 0 0 15px rgba(20, 192, 241, .7), 0 0 15px rgba(20, 192, 241, .7);
+ .border-box;
+}
+
+div.ui-sortable-helper.wrapper {
+ opacity: .65;
+}
\ No newline at end of file
--- /dev/null
+/* General */
+body {
+ float: left;
+ width: 100%;
+}
+
+* {
+ user-select: none !important;
+ -webkit-user-select: none !important;
+}
+
+
+/* Blocks */
+.block {
+ position: relative;
+}
+
+/* Design Editor */
+body:not(.inspector-disabled) .inspector-element-hover {
+ outline: 1px solid #0ea8c7 !important;
+ outline-offset: -1px;
+}
+
+body:not(.inspector-disabled) .inspector-element-selected {
+ outline: 1px solid #ee7248 !important;
+ outline-offset: -1px;
+}
+
+
+/* No Edit Notice */
+div#no-edit-notice {
+ background: rgba(0, 0, 0, 0.7);
+ display: block;
+ height: 100%;
+ position: fixed;
+ width: 105%;
+ z-index: 15000;
+ left: -50px;
+ font-family: helvetica, sans-serif;
+}
+
+ div#no-edit-notice div {
+ background: rgba(0, 0, 0, 0.5);
+ .rounded-corners(15px);
+ min-height: 20px;
+ left: 50%;
+ margin-left: -300px;
+ padding: 30px;
+ position: fixed;
+ text-align: center;
+ top: 150px;
+ width: 600px;
+ }
+
+ div#no-edit-notice h1 {
+ color: rgba(255, 255, 255, 0.75);
+ font-size: 18px;
+ line-height: 24px;
+ }
+
+ div#no-edit-notice h2 {
+ margin: 10px 0 0;
+ color: #6a6a6a;
+ }
+
+
+/* jQuery UI Staples */
+.ui-resizable {
+ position: relative; }
+
+.ui-resizable-handle {
+ display: block;
+ font-size: 0.1px;
+ position: absolute;
+ z-index: 10; }
+
+.ui-resizable-n {
+ cursor: ns-resize;
+ height: 15px;
+ left: 0;
+ top: -5px;
+ width: 100%; }
+
+.ui-resizable-s {
+ bottom: -5px;
+ cursor: ns-resize;
+ height: 15px;
+ left: 0;
+ width: 98%; }
+
+.ui-resizable-e {
+ cursor: ew-resize;
+ height: 98%;
+ right: -5px;
+ top: 0;
+ width: 15px; }
+
+.ui-resizable-w {
+ cursor: ew-resize;
+ height: 100%;
+ left: -5px;
+ top: 0;
+ width: 15px; }
+
+.ui-resizable-se {
+ bottom: -5px;
+ cursor: se-resize;
+ height: 15px;
+ right: -5px;
+ width: 15px; }
+
+.ui-resizable-sw {
+ bottom: -5px;
+ cursor: sw-resize;
+ height: 15px;
+ left: -5px;
+ width: 15px; }
+
+.ui-resizable-nw {
+ top: -5px;
+ cursor: nw-resize;
+ height: 15px;
+ left: -5px;
+ width: 15px; }
\ No newline at end of file
--- /dev/null
+/* All inputs */
+ textarea, input[type="text"], input[type="password"], input[type="email"], input[type="number"], input[type="search"], input[type="tel"], input[type="url"] {
+ color: #333;
+ background-color: #FFF;
+ border: 1px solid #DDD;
+ box-shadow: inset 0 1px 2px rgba(0, 0, 0, 0.07);
+ padding: 3px 5px;
+ font-size: 14px;
+ line-height: 15px;
+ }
+
+ textarea:focus, input[type="text"]:focus, input[type="password"]:focus, input[type="email"]:focus, input[type="number"]:focus, input[type="search"]:focus, input[type="tel"]:focus, input[type="url"]:focus, input[type="checkbox"]:focus, input[type="radio"]:focus, select:focus {
+ border-color: #5B9DD9;
+ -webkit-box-shadow: 0 0 2px rgba(30, 140, 190, 0.8);
+ box-shadow: 0 0 2px rgba(30, 140, 190, 0.8);
+ }
+
+ input:disabled, input.disabled, textarea:disabled, textarea.disabled {
+ -webkit-box-shadow: inset 0 1px 2px rgba(0, 0, 0, 0.04);
+ box-shadow: inset 0 1px 2px rgba(0, 0, 0, 0.04);
+ border-color: rgba(222, 222, 222, 0.75);
+ background: rgba(255, 255, 255, 0.5);
+ color: rgba(51, 51, 51, 0.5);
+ }
+
+ input[type="checkbox"], input[type="radio"] {
+ border-width: 1px;
+ border-style: solid;
+ clear: none;
+ cursor: pointer;
+ display: inline-block;
+ line-height: 0;
+ height: 16px;
+ margin: -4px 4px 0 0;
+ outline: 0;
+ padding: 0 !important;
+ text-align: center;
+ vertical-align: middle;
+ width: 16px;
+ min-width: 16px;
+ -webkit-appearance: none;
+ -webkit-box-sizing: border-box;
+ box-sizing: border-box;
+
+ background: #FFF;
+ border-color: #BBB;
+ color: #555;
+ -webkit-box-shadow: inset 0px 1px 2px rgba(0, 0, 0, 0.1);
+ box-shadow: inset 0px 1px 2px rgba(0, 0, 0, 0.1);
+ }
+
+ input[type=checkbox]:checked:before, input[type=radio]:checked:before {
+ float: left;
+ display: inline-block;
+ vertical-align: middle;
+ width: 16px;
+ font: normal 21px/1 'dashicons';
+ speak: none;
+ .antialias();
+ }
+
+ input[type=checkbox]:checked:before {
+ content: '\f147';
+ margin: -3px 0 0 -4px;
+ color: #1E8CBE;
+ }
+
+ input[type=radio]:checked:before {
+ content: '\2022';
+ text-indent: -9999px;
+ border-radius: 50px;
+ font-size: 24px;
+ width: 6px;
+ height: 6px;
+ margin: 4px;
+ line-height: 16px;
+ }
+
+/* Visual Editor Sub Tabs Content Inputs */
+div.sub-tabs-content div.input {
+ background: #fff;
+ float: left;
+ margin: 0 15px 15px 0;
+ height: 25px;
+ padding: 8px;
+ border: 1px solid #E5E5E5;
+ -webkit-box-shadow: 0 1px 1px rgba(0, 0, 0, 0.04);
+ box-shadow: 0 1px 1px rgba(0, 0, 0, 0.04);
+}
+
+ div.sub-tabs-content div.input label {
+ color: #444;
+ font-weight: bold;
+ line-height: 25px;
+ font-size: 14px;
+ margin: 0 5px;
+ float: left;
+ }
+
+ /* Global Text Inputs */
+ div.sub-tabs-content div.input input.text {
+ margin: 0 0 0 2px;
+ }
+
+ div.sub-tabs-content div.input input.text::-webkit-input-placeholder,
+ div.sub-tabs-content div.input input.text::-moz-placeholder {
+ color: #666;
+ }
+
+ div.sub-tabs-content div.input div.input-left {
+ float: left;
+ margin-right: 5px;
+ }
+
+ div.sub-tabs-content div.input div.input-right {
+ float: left;
+ }
+
+/* Integer Inputs */
+div.sub-tabs-content div.input-integer input {
+ width: 30px;
+}
+
+/* Heading Element */
+div.sub-tabs-content div.input-heading {
+ background: none;
+ border: none;
+ padding: 0;
+ float: left;
+ clear: both;
+ width: 100%;
+ margin: 11px 0;
+ height: 35px;
+ box-shadow: none;
+}
+
+ div.sub-tabs-content div.input-heading:first-child {
+ margin-top: 0;
+ }
+
+ div.sub-tabs-content .options-heading {
+ text-transform: none;
+ font-weight: bold;
+ color: #222;
+ width: 100%;
+ margin: 0 0 15px;
+ padding: 10px 0;
+ .border-box;
+ font-size: 18px;
+ }
+
+ div.sub-tabs-content div.input-heading .tooltip-button {
+ margin: 10px 6px 0 0;
+ }
+
+/* Notices */
+div.sub-tabs-content div.input-notice {
+ background: none;
+ border: 0;
+ box-shadow: none;
+ padding: 0;
+ float: left;
+ clear: both;
+ width: 100%;
+ margin: 15px 0 20px;
+ height: auto;
+}
+
+ div.sub-tabs-content div.input-notice:first-child {
+ margin-top: 0;
+ }
+
+ div.sub-tabs-content div.input-notice p {
+ margin: 0;
+ }
+
+/* Suffixes/units */
+div.sub-tabs-content div.input span.suffix {
+ color: #666;
+ margin: 0 5px 0 7px;
+ font-size: 11px;
+}
+
+/* Pencil Icon */
+ span.pencil-icon {
+ color: #555;
+ display: block;
+ width: 12px;
+ height: 14px;
+ cursor: pointer;
+ .transition('color 150ms linear');
+ margin: 5px 8px 0 2px;
+ }
+
+ span.pencil-icon:hover {
+ color: #999;
+ }
+
+ span.pencil-icon:before {
+ .icon-font;
+ font-size: 16px;
+ content: '\34';
+ }
+
+/* Textarea */
+div.sub-tabs-content div.input-textarea {
+ position: relative;
+}
+
+ div.sub-tabs-content div.input-textarea div.textarea-container {
+ display: none;
+ position: fixed;
+ background: #0d0d0d;
+ width: auto;
+ height: auto;
+ border: 1px solid rgba(255, 255, 255, 0.15);
+ .rounded-corners(5px);
+ padding: 5px;
+ opacity: .85;
+ box-shadow: 0 0 6px rgba(0, 0, 0, 0.3);
+ z-index: 11; /* Stay above panel resize handle */
+ margin: 0 0 10px;
+ }
+
+ div.sub-tabs-content div.input-textarea div.textarea-container textarea {
+ .rounded-corners(5px);
+ width: 450px;
+ height: 200px;
+ .border-box;
+ padding: 7px;
+ opacity: .9;
+ font-family: courier, monospace;
+ line-height: 16px;
+ }
+
+/* WYSIWYG */
+div.sub-tabs-content div.input-wysiwyg {
+ position: relative;
+}
+
+ div.sub-tabs-content div.input-wysiwyg .wysiwyg-container > textarea {
+ display: none;
+ }
+
+ div.sub-tabs-content div.input-wysiwyg div.wysiwyg-container {
+ display: none;
+ position: fixed;
+ background: #eee;
+ width: 660px;
+ height: 350px;
+ border: 1px solid rgba(255, 255, 255, 0.15);
+ border-radius: 5px;
+ padding: 5px;
+ opacity: .96;
+ box-shadow: 0 0 6px rgba(0, 0, 0, 0.3);
+ z-index: 11; /* Stay above panel resize handle */
+ margin: 0 0 10px;
+ }
+
+ div.sub-tabs-content div.input-wysiwyg div.wysiwyg-container textarea {
+ height: 318px !important;
+ }
+
+
+/* Checkbox */
+div.sub-tabs-content div.input-checkbox {
+ cursor: pointer;
+}
+
+ div.sub-tabs-content div.input-checkbox label {
+ cursor: pointer;
+
+ /* Make the label take up most of the box so it's clickable */
+ padding: 8px 17px 8px 0;
+ margin-top: -8px;
+ margin-right: -12px;
+ }
+
+/* Selects */
+.select-container select {
+ font-size: 14px;
+ padding: 2px;
+ line-height: 28px;
+ height: 28px;
+ font-family: 'Open Sans', sans-serif;
+ vertical-align: middle;
+ max-width: 270px;
+ -webkit-appearance: menulist-button;
+ border-color: #DDD;
+ box-shadow: inset 0 1px 2px rgba(0, 0, 0, 0.07);
+}
+
+ .select-container select:focus {
+ border-color: #999;
+ }
+
+ /* Repeaters */
+ div.sub-tabs-content .repeater {
+ float: left;
+ width: 100%;
+
+ .options-heading {
+ clear: none;
+ }
+
+ .repeater-group {
+ background: #fff;
+ float: left;
+ padding: 2px;
+ border-radius: 5px;
+ margin: 0 0 10px;
+ clear: both;
+ position: relative;
+ padding-left: 16px;
+ padding-right: 75px;
+
+ div.input {
+ margin: 5px;
+ }
+
+ .sortable-handle {
+ height: 26px;
+ display: block;
+ position: absolute;
+ left: 0;
+ top: 50%;
+ margin: -13px 1px 0 6px;
+ cursor: move;
+
+ span {
+ width: 1px;
+ height: 26px;
+ background: #dfdfdf;
+ margin: 0 1px;
+ display: inline-block;
+ }
+ }
+
+ .repeater-group-buttons {
+ float: left;
+ top: 15px;
+ right: 7px;
+ position: absolute;
+ }
+
+ .remove-group, .add-group {
+ float: left;
+ color: #555;
+ width: 26px;
+ background: #eee;
+ border-radius: 2px;
+ height: 26px;
+ margin: 0 4px;
+ text-align: center;
+ line-height: 26px;
+ cursor: pointer;
+
+ &:hover {
+ background: #ddd;
+ }
+ }
+
+ .remove-group::after {
+ .icon-font;
+ content: '\5f';
+ }
+
+ .add-group::after {
+ .icon-font;
+ content: '\3d';
+ }
+
+ &.repeater-group-single .remove-group {
+ display: none;
+ }
+
+ &.repeater-group-template {
+ display: none;
+ }
+
+ div.input-heading {
+ width: 99%;
+ height: auto;
+ float: none;
+ margin: 0;
+ }
+
+ .options-heading {
+ float: none;
+ margin: 0 0 2px 6px;
+ font-size: 12px;
+ padding: 10px 0 4px 4px;
+ font-weight: normal;
+ .border-box()
+ }
+ }
+
+ .ui-sortable-placeholder {
+ border: 2px dotted #bbb;
+ background: none;
+ visibility: visible !important;
+ }
+
+ &.limit-met {
+ .add-group {
+ display: none !important;
+ }
+ }
+ }
+
+/* Multi-select */
+div.sub-tabs-content div.input-multi-select {
+ position: relative;
+}
+
+ div.sub-tabs-content div.input-multi-select div.multi-select-container {
+ display: none;
+ position: fixed;
+ top: -180px;
+ left: 0;
+ background: #0d0d0d;
+ width: auto;
+ height: auto;
+ border: 1px solid rgba(255, 255, 255, 0.15);
+ .rounded-corners(5px);
+ padding: 5px;
+ opacity: .95;
+ box-shadow: 0 0 6px rgba(0, 0, 0, 0.3);
+ z-index: 11; /* Stay above panel resize handle */
+ margin: 0 0 10px;
+ }
+
+ div.sub-tabs-content div.input-multi-select div.multi-select-container select {
+ padding: 5px;
+ .border-box;
+ width: 170px;
+ height: 160px;
+ font-size: 12px;
+ }
+
+/* Colorpicker Buttons */
+div.sub-tabs-content div.input-colorpicker {
+ padding-right: 10px;
+}
+
+div.colorpicker-box-container {
+ display: block;
+ width: 15px;
+ height: 15px;
+ box-shadow: 0 0 0 1px rgba(255, 255, 255, .15);
+ border: 1px solid #ccc;
+ .rounded-corners(2px);
+ float: right;
+ margin: 3px 0 0 0;
+ padding: 1px;
+ text-indent: -9999px;
+ overflow: hidden;
+ position: relative;
+}
+
+ div.colorpicker-box-transparency {
+ background-image: url(%VISUALEDITOR%/images/transparent-bg.png);
+ background-repeat: no-repeat;
+ display: block;
+ width: 15px;
+ height: 15px;
+ position: absolute;
+ z-index: 0;
+ .rounded-corners(2px);
+ }
+
+ div.colorpicker-box {
+ display: block;
+ width: 15px;
+ height: 15px;
+ cursor: pointer;
+ position: absolute;
+ z-index: 1;
+ .rounded-corners(1px);
+ }
+
+div.colorpicker-color {
+ display: block;
+ width: 15px;
+ height: 15px;
+ background-color: #fff;
+}
+
+/* Slider */
+div.input-slider-bar {
+ .rounded-corners(3px);
+ width: 200px;
+ height: 10px;
+ border: 1px solid #dfdfdf;
+ display: block;
+ float: left;
+ margin: 6px 7px 0 8px;
+ position: relative;
+}
+
+ .input-slider-bar-input {
+ width: 40px;
+ margin: 0;
+ }
+
+ div.input-slider-bar div.ui-slider-range {
+ background: #eee;
+ height: 10px;
+ .rounded-corners(2px);
+ }
+
+ div.input-slider-bar a.ui-slider-handle {
+ background: #2ea2cc;
+ .rounded-corners(8px);
+ display: block;
+ height: 16px;
+ width: 16px;
+ margin: -13px 0 0 -8px;
+ position: absolute;
+ cursor: pointer;
+ }
+
+ div.input-slider-bar a.ui-slider-handle.ui-state-active { background: #1E8CBE; }
+
+div.input-slider-bar-text {
+ font-size: 11px;
+ float: left;
+ margin: 0 0 0 6px;
+}
+
+ div.input-slider-bar-text span {
+ margin: 0 0 0 5px;
+ }
+
+ div.input-slider-bar-text span.slider-value { color: #666; }
+
+ div.input-slider-bar-text span.slider-unit { color: #5a5a5a; }
+
+
+/* Fonts */
+ /* Font Tabs */
+ .font-browser ul.tabs {
+ margin: 0 0 0 10px;
+ padding: 0;
+ width: 100%;
+ height: 25px;
+ display: block;
+ background: none;
+ .rounded-corners(0 0 0 3px);
+ }
+
+ .font-browser ul.tabs li {
+ display: inline-block;
+ padding: 0;
+ .rounded-corners(0);
+ margin: 0 5px 0 0;
+ width: auto;
+ background: none;
+ }
+
+ .font-browser ul.tabs li a {
+ color: #ccc;
+ background: #666;
+ float: left;
+ padding: 7px 10px;
+ height: 25px;
+ font-size: 11px;
+ display: block;
+ text-decoration: none;
+ .rounded-corners(5px 5px 0 0);
+ .border-box;
+ }
+
+ .font-browser ul.tabs li.ui-tabs-active a {
+ color: #eee;
+ background: #444;
+ }
+
+
+ .font-browser ul.tabs li:not(.ui-tabs-active) a:hover {
+ color: #ddd;
+ }
+
+ /* Fonts Tab Content */
+ .font-browser .tab-content {
+ padding: 0;
+ float: left;
+ width: 100%;
+ height: 325px;
+ overflow: hidden;
+
+ background: #eee;
+ .rounded-corners(5px);
+ box-shadow: 0 0 6px rgba(0, 0, 0, 0.3);
+
+ position: absolute;
+
+ .border-box;
+ }
+
+ /* Loader */
+ .fonts-loading {
+ display: block;
+ position: absolute;
+ top: 33%;
+ font-size: 50px;
+ text-align: center;
+ width: 100%;
+ color: #CCC;
+
+ .cog-container {
+ opacity: 1;
+ }
+ }
+
+ /* fonts-search-input */
+ div.property-font-family-select form.fonts-search {
+ position: relative;
+ background: #444;
+ border-radius: 5px 5px 0 0;
+ padding: 7px 7px 0 7px;
+ height: 35px;
+ width: 100%;
+ float: left;
+ .border-box;
+
+ .fonts-filter {
+ width: 100%;
+ padding: 6px 110px 6px 6px;
+ background-color: #FFFFFF;
+ background-image: -moz-linear-gradient(center top , #EEEEEE 1%, #FFFFFF 15%);
+ border: 1px solid #222;
+ cursor: text;
+ height: auto !important;
+ margin: 0;
+ overflow: hidden;
+ position: relative;
+ float: right;
+ .border-box;
+ .rounded-corners(5px);
+ }
+
+ .select-container {
+ margin: 0;
+ position: absolute;
+ top: 10px;
+ right: 10px;
+ width: 100px;
+ }
+
+ select {
+ background-color: #777;
+ border-color: #666;
+ color: #EEE;
+ width: 100%;
+ }
+ }
+
+
+ /* Content */
+ .fonts-noresults {
+ display: block;
+ position: absolute;
+ top: 0;
+ font-size: 50px;
+ text-align: center;
+ width: 100%;
+ color: #CCC;
+ height: 100%;
+ line-height: 250px;
+ }
+
+ .font-browser .fonts-list {
+ position: relative;
+ clear: both;
+ border-radius: 5px;
+ height: 320px;
+ border-top: 5px solid #444;
+ overflow: hidden;
+ -webkit-mask-image: url(data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAIAAACQd1PeAAAAGXRFWHRTb2Z0d2FyZQBBZG9iZSBJbWFnZVJlYWR5ccllPAAAAA5JREFUeNpiYGBgAAgwAAAEAAGbA+oJAAAAAElFTkSuQmCC); /* Rounded corner overflow hidden fix */
+ }
+
+ .font-browser p.error {
+ margin: 20px;
+ padding: 12px 20px;
+ line-height: 20px;
+ color: #B94A48;
+ background-color: #F2DEDE;
+ border-color: #EED3D7;
+ border: 1px solid #EED3D7;
+ .rounded-corners(10px);
+ }
+
+ .font-browser form.fonts-search + .fonts-list {
+ height: 285px;
+ border-radius: 0 0 5px 5px;
+ }
+
+ .font-browser .fonts-list ul {
+ height: 100%;
+ overflow-y: scroll;
+ }
+
+ .font-browser .fonts-list ul li {
+ border-bottom: 1px solid #DDDDDD;
+ font-size: 16px;
+ height: 16px;
+ padding: 0 60px 10px 10px;
+ position: relative;
+ overflow: hidden;
+ width: 100%;
+ .border-box;
+ background: #fafafa;
+ height: 38px;
+ line-height: 2;
+ margin: 0;
+ border-radius: 0;
+ }
+
+ .font-browser .fonts-list ul li.selected-font {
+ border-left: 2px solid #57b196;
+ background: #f3f3f3;
+ }
+
+ .font-browser .webfonts-list ul li span {
+ opacity: 0.2;
+ .transition("opacity 100ms linear");
+ }
+
+ .font-browser .fonts-list ul li span.font-family {
+ font-family: inherit;
+ font-size: 19px;
+ }
+
+ .font-browser .fonts-list ul li span.font-preview-text {
+ font-family: inherit;
+ font-size: 19px;
+ margin-left: 10px;
+ padding-left: 10px;
+ border-left: 1px solid #DDD;
+ }
+
+ .font-browser .webfonts-list ul li span.font-preview-text {
+ display: none;
+ }
+
+ .font-browser .fonts-list ul li span.font-loading {
+ display: none;
+ }
+
+ .font-browser .webfonts-list ul li span.font-loading {
+ opacity: 1;
+ position: absolute;
+ right: 10px;
+ top: 11px;
+ width: 14px;
+ height: 15px;
+
+ .icon-font;
+ font-size: 16px;
+
+ line-height: 16px;
+ font-size: 17px;
+ color: #DDD;
+
+ .animation('spin 2000ms infinite linear');
+ }
+
+ .font-browser .fonts-list ul li:hover {
+ background: #eaeaea;
+ cursor: pointer;
+ }
+
+ .font-browser .fonts-list ul li span.action {
+ position: absolute;
+ top: 8px;
+ color: #fff;
+ text-decoration: none;
+ .rounded-corners(100px);
+ margin: 0 2px 0 0;
+ display: none;
+ opacity: 1;
+ cursor: pointer;
+
+ font-size: 12px;
+ width: 22px;
+ line-height: 22px;
+ height: 22px;
+ text-align: center;
+
+ &:hover {
+ background: #444;
+ color: #fff;
+ }
+
+ &::before {
+ .icon-font;
+ font-size: 12px;
+ }
+ }
+
+ .font-browser .fonts-list ul li span.font-loading ~ span.action {
+ display: none !important;
+ }
+
+ .font-browser .fonts-list ul li span.use-font {
+ right: 30px;
+ background: #57b196;
+ }
+
+ .font-browser .fonts-list ul li span.use-font::before {
+ content: '\32';
+ }
+
+ .font-browser .fonts-list ul li span.preview-font {
+ right: 3px;
+ background: #DD5A2A;
+ }
+
+ .font-browser .fonts-list ul li span.preview-font::before {
+ content: '\25be';
+ }
+
+ .font-browser .fonts-list ul li:hover span.action {
+ display: block;
+ }
+
+ /* Input for opening browser */
+ .property-font-family-select {
+ .open-font-browser {
+ position: absolute;
+ right: 3px;
+ }
+
+ .font-browser {
+ display: none;
+ position: fixed;
+ top: -180px;
+ left: 0;
+ width: 500px;
+ height: 350px;
+ z-index: 11; /* Stay above panel resize handle */
+ margin: 0 0 10px;
+ }
+
+ .property-fonts.property {
+ min-width: 70px;
+ padding-right: 18px;
+ }
+
+ .font-name {
+ color: #999;
+ float: right;
+ margin: 4px 26px 0 0;
+ line-height: 20px;
+ height: 20px;
+
+ max-width: 85px;
+ overflow: hidden;
+
+ white-space: nowrap;
+
+ &.font-name-webfont {
+ opacity: 0;
+ }
+ }
+ }
+
+ /* font preview overlay */
+ .font-preview-overlay {
+ padding: 20px;
+ background: #fafafa;
+ position: absolute;
+ top: 0;
+ left: 0;
+ z-index: 2;
+ width: 100%;
+ height: 100%;
+ .rounded-corners(5px);
+ }
+
+ .font-preview-overlay,
+ .font-preview-overlay * {
+ user-select: auto!important;
+ -webkit-user-select: auto!important;
+ .border-box;
+ }
+
+ .font-preview-overlay header,
+ .font-preview-overlay header h4,
+ .font-preview-overlay header h4 span {
+ font-size: 33px;
+ font-family: inherit !important;
+ }
+
+ .font-preview-overlay span {
+ color: #ccc;
+ }
+
+ .font-preview-overlay header,
+ .font-preview-overlay footer {
+ text-align: center;
+ color: #999;
+ }
+
+ .font-preview-overlay header {
+ border-bottom: 3px solid #ccc;
+ margin: 0;
+ padding: 0 0 10px;
+ }
+
+ .font-preview-overlay header p {
+ margin: 6px 0 0 -26px;
+ & strong { font-weight: bold }
+ }
+
+ .font-preview-overlay header p * {
+ font-size: 13px;
+ font-weight: bold;
+ }
+
+ .font-preview-overlay footer {
+ border-top: 3px solid #ccc;
+ padding: 7px 0 0;
+ position: absolute;
+ height: 45px;
+ bottom: 0;
+ left: 20px;
+ right: 20px;
+ }
+
+ .font-preview-overlay .close-preview {
+ width: 19px;
+ height: 19px;
+ float: right;
+ display: block;
+ cursor: pointer;
+ color: #ddd;
+ .transition('color 150ms linear');
+ }
+
+ .font-preview-overlay .close-preview:before {
+ .icon-font;
+ content: '\58';
+ font-size: 22px;
+ }
+
+ .font-preview-overlay .close-preview:hover {
+ color: #b3b3b3;
+ }
+
+ .font-preview-overlay .tools span {
+ color: #777;
+ text-decoration: none;
+ .rounded-corners(100px);
+ background: #ddd;
+ margin: 0 2px;
+
+ width: 22px;
+ height: 22px;
+ line-height: 22px;
+ font-size: 12px;
+ text-align: center;
+
+ cursor: pointer;
+ float: left;
+
+ &:hover {
+ background: #444;
+ color: #fff;
+ }
+
+ &:before {
+ .icon-font;
+ }
+ }
+
+ .font-preview-overlay .tools span.reset-preview:before {
+ content: '\72';
+ }
+
+ .font-preview-overlay .tools span.size-down:before {
+ content: '\5f';
+ }
+
+ .font-preview-overlay .tools span.size-up:before {
+ content: '\3d';
+ }
+
+ .font-preview-overlay .tools span.use-font {
+ float: right;
+ background: #57b196;
+ color: #fff;
+
+ &:before {
+ content: '\32';
+ }
+
+ &:hover {
+ background: #444;
+ }
+ }
+
+
+ .font-preview-overlay .editable {
+ font-size: 34px;
+ text-align: center;
+ line-height: 130%;
+ height: 195px;
+ overflow: scroll;
+ font-family: inherit;
+ padding: 10px 0;
+ }
+
+ .font-preview-overlay .editable:focus {
+ box-shadow: 0 0 4px #57b196;
+ }
+/* End font browser */
+
+
+/* Import Files */
+ div.input-import-file input[type="file"] {
+ visibility: hidden;
+ position: absolute;
+ top: -99999px;
+ left: -99999px;
+ }
+
+
+/* Buttons */
+ div.input div.input-right:first-child:last-child .button {
+ margin: 0;
+ }
+
+
+/* Redactor */
+ .redactor_box {
+ height: 100% !important;
+ }
+
+ .redactor_box * {
+ user-select: auto!important;
+ -webkit-user-select: auto!important;
+ }
+
+ .redactor_editor {
+ height: 318px !important;
+ box-sizing: border-box !important;
+ -moz-box-sizing: border-box !important;
+ }
+
+/* Colorpicker */
+input.color {
+ display: inline-block;
+ vertical-align: middle;
+ width: 3em;
+ height: 1.5em;
+ margin: 0.1em;
+ border-radius: 2px;
+
+ width: 4em;
+ border: 0 none;
+ padding: 0.2em;
+}
+input.color.alphaHex {
+ width: 5.25em;
+}
+input.color.selected {
+ outline: none;
+}
+input.color.error {
+ box-shadow: 0 0 3px 3px #d00;
+}
+.colorContainer {
+ width: auto;
+ height: auto;
+ overflow: visible;
+ box-shadow: none;
+ background: url(%VISUALEDITOR%/images/transparent.png) repeat;
+}
+.colorContainer > .color {
+ margin: 0;
+ display: block;
+}
+.colorContainer.color-null {
+ background: none;
+}
+.colorContainer.color-null .color {
+ box-shadow: inset 0 1px 1px rgba(0,0,0,0.3), 0 1px 1px rgba(255,255,255,0.7);
+ background-color: transparent !important;
+ background: -moz-linear-gradient(top, rgba(255,255,255,0.5) 0%, rgba(255,255,255,0) 50%, rgba(0,0,0,0) 50%, rgba(0,0,0,0.35) 100%),
+ -moz-linear-gradient(left, rgba(255,0,0,0.25) 0%, rgba(255,255,0,0.25) 16.67%, rgba(0,255,0,0.25) 33.33%, rgba(0,255,255,0.25) 50%, rgba(0,0,255,0.25) 66.67%, rgba(255,0,255,0.25) 83.33%, rgba(255,0,0,0.25) 100%);
+ background: -webkit-gradient(linear, left top, left bottom, color-stop(0%,rgba(255,255,255,0.5)), color-stop(50%,rgba(255,255,255,0)), color-stop(50%,rgba(0,0,0,0)), color-stop(100%,rgba(0,0,0,0.35))),
+ -webkit-gradient(linear, left top, right top, color-stop(0%,rgba(255,0,0,0.25)), color-stop(16.67%,rgba(255,255,0,0.25)), color-stop(33.33%,rgba(0,255,0,0.25)), color-stop(50%,rgba(0,255,255,0.25)), color-stop(66.67%,rgba(0,0,255,0.25)), color-stop(83.33%,rgba(255,0,255,0.25)), color-stop(100%,rgba(255,0,0,0.25)));
+ background: -webkit-linear-gradient(top, rgba(255,255,255,0.5) 0%,rgba(255,255,255,0) 50%,rgba(0,0,0,0) 50%,rgba(0,0,0,0.35) 100%),
+ -webkit-linear-gradient(left, rgba(255,0,0,0.25) 0%,rgba(255,255,0,0.25) 16.67%,rgba(0,255,0,0.25) 33.33%,rgba(0,255,255,0.25) 50%,rgba(0,0,255,0.25) 66.67%,rgba(255,0,255,0.25) 83.33%,rgba(255,0,0,0.25) 100%);
+ background: -o-linear-gradient(top, rgba(255,255,255,0.5) 0%,rgba(255,255,255,0) 50%,rgba(0,0,0,0) 50%,rgba(0,0,0,0.35) 100%),
+ -o-linear-gradient(left, rgba(255,0,0,0.25) 0%,rgba(255,255,0,0.25) 16.67%,rgba(0,255,0,0.25) 33.33%,rgba(0,255,255,0.25) 50%,rgba(0,0,255,0.25) 66.67%,rgba(255,0,255,0.25) 83.33%,rgba(255,0,0,0.25) 100%);
+ background: -ms-linear-gradient(top, rgba(255,255,255,0.5) 0%,rgba(255,255,255,0) 50%,rgba(0,0,0,0) 50%,rgba(0,0,0,0.35) 100%),
+ -ms-linear-gradient(left, rgba(255,0,0,0.25) 0%,rgba(255,255,0,0.25) 16.67%,rgba(0,255,0,0.25) 33.33%,rgba(0,255,255,0.25) 50%,rgba(0,0,255,0.25) 66.67%,rgba(255,0,255,0.25) 83.33%,rgba(255,0,0,0.25) 100%);
+ background: linear-gradient(top, rgba(255,255,255,0.5) 0%,rgba(255,255,255,0) 50%,rgba(0,0,0,0) 50%,rgba(0,0,0,0.35) 100%),
+ linear-gradient(left, rgba(255,0,0,0.25) 0%,rgba(255,255,0,0.25) 16.67%,rgba(0,255,0,0.25) 33.33%,rgba(0,255,255,0.25) 50%,rgba(0,0,255,0.25) 66.67%,rgba(255,0,255,0.25) 83.33%,rgba(255,0,0,0.25) 100%);
+}
+.colorContainer.color-null .color.selected {
+ box-shadow: 0 0 1px rgba(0,0,0,0.8), inset 0 1px 1px rgba(255,255,255,0.8);
+}
+
+#css3colorpicker-div {
+ z-index: 1000;
+ display: block;
+ padding: 10px;
+ position: absolute;
+ box-shadow: 0 0 0 3px rgba(0, 0, 0, .2);
+ border-radius: 5px;
+ background: #121212;
+ border: 1px solid #393939;
+}
+#css3colorpicker-div-container {
+ width: 378px;
+ height: 256px;
+ position: relative;
+}
+#css3colorpicker-div.alphaOn #css3colorpicker-div-container {
+ height: 282px;
+}
+#css3colorpicker-div-swatchContainer {
+ width: 378px;
+ height: auto;
+ display: none;
+ position: relative;
+}
+ #css3colorpicker-div.swatchesOn #css3colorpicker-div-swatchContainer {
+ display: block;
+ }
+ #css3colorpicker-div-swatches {
+ width: 378px;
+ height: 28px;
+ position: relative;
+ margin-top: 10px;
+ background: #222;
+ border: 1px solid #444;
+ border-radius: 2px;
+ overflow: hidden;
+ }
+
+ #css3colorpicker-div-add-swatch-button {
+ position: absolute;
+ background: #414141;
+ display: block;
+ width: 20px;
+ height: 20px;
+ text-align: center;
+ line-height: 20px;
+ right: 4px;
+ top: 5px;
+ border-radius: 10px;
+ cursor: pointer;
+ }
+
+ #css3colorpicker-div-add-swatch-button:hover {
+ background: #3a3a3a;
+ }
+
+ #css3colorpicker-div-add-swatch-button:before {
+ .icon-font;
+ color: #ccc;
+ content: '\2b';
+ }
+
+ #css3colorpicker-div-swatches .swatch {
+ display: inline-block;
+ vertical-align: middle;
+ float: left;
+ width: 20px;
+ height: 20px;
+ margin: 4px 5px;
+ margin-right: 0;
+ border-radius: 2px;
+ position: relative;
+ cursor: pointer;
+ }
+ #css3colorpicker-div.alphaOn #css3colorpicker-div-swatches .swatch {
+ background: url(%VISUALEDITOR%/images/transparent.png) repeat;
+ }
+ #css3colorpicker-div-swatches .swatch > div {
+ position: absolute;
+ top: 0;
+ bottom: 0;
+ left: 0;
+ right: 0;
+ border-radius: 2px;
+ }
+ #css3colorpicker-div-swatches .swatch:first-child {
+ margin-left: 4px;
+ }
+#css3colorpicker-div-colorContainer {
+ width: 85px;
+ height: 50px;
+ position: absolute;
+ top: 0;
+ right: 0;
+ cursor: pointer;
+ border-radius: 2px;
+ overflow: hidden;
+ background: url(%VISUALEDITOR%/images/transparent.png) repeat;
+}
+#css3colorpicker-div-color {
+ width: 50px;
+ position: absolute;
+ top: 0;
+ bottom: 0;
+ left: 0;
+ border-radius: 2px 0 0 2px;
+}
+#css3colorpicker-div-colorOld {
+ width: 35px;
+ position: absolute;
+ right: 0;
+ top: 0;
+ bottom: 0;
+ border-radius: 0 2px 2px 0;
+}
+.css3colorpicker-inputContainer {
+ width: 85px;
+ height: auto;
+ padding: 1px 0;
+ display: block;
+ position: absolute;
+ right: 0;
+ margin: 0;
+ overflow: hidden;
+ background: #222;
+ border: 1px solid #444;
+ border-radius: 2px;
+}
+#css3colorpicker-div-inputContainer-hsv {
+ top: 53px;
+}
+#css3colorpicker-div-inputContainer-rgba {
+ top: 141px;
+}
+#css3colorpicker-div-inputContainer-hex {
+ top: 256px;
+}
+.css3colorpicker-inputContainer li {
+ list-style: none;
+ display: block;
+ font-family: arial;
+ font-weight: normal;
+ font-size: 10px;
+ padding: 3px 5px;
+ background: transparent;
+ position: relative;
+ height: 20px;
+ line-height: 20px;
+ margin: 0;
+ cursor: default;
+ overflow: hidden;
+ text-shadow: 0px 1px 0 rgba(0,0,0,0.45);
+ color: #bfbfbf;
+ border-bottom: 1px solid #333;
+}
+.css3colorpicker-inputContainer li:last-child {
+ border-bottom: none;
+}
+.css3colorpicker-inputContainer li.selected {
+ background: rgba(0, 0, 0, 0.5);
+}
+.css3colorpicker-inputContainer input {
+ width: 45px;
+ height: 14px;
+ margin: 0;
+ border: 0 none;
+ padding: 2px 0 2px 4px;
+ font-size: 10px;
+ position: absolute;
+ right: 17px;
+ border-radius: 2px;
+ background: #121212;
+ border: 1px solid #2e2e2e;
+ color: #898989;
+}
+.css3colorpicker-inputContainer input#css3colorpicker-div-hex {
+ width: 56px;
+ right: 5px;
+}
+.css3colorpicker-inputContainer li span {
+ position: absolute;
+ right: 5px;
+ font-size: 10px;
+}
+#css3colorpicker-div-1d,
+#css3colorpicker-div-2d,
+#css3colorpicker-div-alpha {
+ position: absolute;
+ overflow: visible;
+ box-shadow: 0 1px 5px rgba(0,0,0,0.75);
+}
+#css3colorpicker-div-1d,
+#css3colorpicker-div-2d {
+ height: 256px;
+ background: #fff;
+}
+#css3colorpicker-div-1d {
+ cursor: n-resize;
+ width: 20px;
+ top: 0;
+ left: 265px;
+}
+#css3colorpicker-div-2d {
+ cursor: crosshair;
+ width: 256px;
+ top: 0;
+ left: 0;
+}
+#css3colorpicker-div-alpha {
+ cursor: e-resize;
+ width: 256px;
+ height: 0;
+ bottom: 0;
+ overflow: hidden;
+}
+#css3colorpicker-div.alphaOn #css3colorpicker-div-alpha {
+ height: 20px;
+}
+#css3colorpicker-div-alpha:after {
+ content: '';
+ display: block;
+ position: absolute;
+ top: 0;
+ bottom: 0;
+ left: 0;
+ right: 0;
+ background: url(%VISUALEDITOR%/images/transparentGrad.png) left top repeat-y;
+}
+
+#css3colorpicker-div-1dControl,
+#css3colorpicker-div-2dControl,
+#css3colorpicker-div-alphaControl {
+ position: absolute;
+ top: 0;
+ left: 0;
+ z-index: 2;
+}
+#css3colorpicker-div-1dControl {
+ width: auto;
+ height: 1px;
+ right: 0;
+}
+#css3colorpicker-div-2dControl {
+ width: 11px;
+ height: 11px;
+ margin-left: -5px;
+ margin-top: -5px;
+ border-radius: 6px;
+}
+#css3colorpicker-div-alphaControl {
+ width: 1px;
+ height: auto;
+ bottom: 0;
+ display: none;
+}
+#css3colorpicker-div.alphaOn #css3colorpicker-div-alphaControl {
+ display: block;
+}
+
+#css3colorpicker-div-1dColor,
+#css3colorpicker-div-1dColor:after,
+#css3colorpicker-div-1dGradient,
+#css3colorpicker-div-2dColor,
+#css3colorpicker-div-2dColor:after,
+#css3colorpicker-div-2dGradient,
+#css3colorpicker-div-2dGradient:after {
+ position: absolute;
+ top: 0;
+ bottom: 0;
+ left: 0;
+ right: 0;
+}
+#css3colorpicker-div-1dColor:after,
+#css3colorpicker-div-2dColor:after,
+#css3colorpicker-div-2dGradient:after {
+ content: '';
+ display: block;
+}
+
+
+/* Gradients */
+
+#css3colorpicker-div.mode-h #css3colorpicker-div-1dGradient {
+ background: #000;
+}
+#css3colorpicker-div.mode-h #css3colorpicker-div-1dColor {
+ background: -moz-linear-gradient(top, #ff0000 0%, #ff00ff 16.67%, #0000ff 33.33%, #00ffff 50%, #00ff00 66.67%, #ffff00 83.33%, #ff0000 100%);
+ background: -webkit-gradient(linear, left top, left bottom, color-stop(0%,#ff0000), color-stop(16.67%,#ff00ff), color-stop(33.33%,#0000ff), color-stop(50%,#00ffff), color-stop(66.67%,#00ff00), color-stop(83.33%,#ffff00), color-stop(100%,#ff0000));
+ background: -webkit-linear-gradient(top, #ff0000 0%,#ff00ff 16.67%,#0000ff 33.33%,#00ffff 50%,#00ff00 66.67%,#ffff00 83.33%,#ff0000 100%);
+ background: -o-linear-gradient(top, #ff0000 0%,#ff00ff 16.67%,#0000ff 33.33%,#00ffff 50%,#00ff00 66.67%,#ffff00 83.33%,#ff0000 100%);
+ background: -ms-linear-gradient(top, #ff0000 0%,#ff00ff 16.67%,#0000ff 33.33%,#00ffff 50%,#00ff00 66.67%,#ffff00 83.33%,#ff0000 100%);
+ background: linear-gradient(top, #ff0000 0%,#ff00ff 16.67%,#0000ff 33.33%,#00ffff 50%,#00ff00 66.67%,#ffff00 83.33%,#ff0000 100%);
+}
+#css3colorpicker-div.mode-h #css3colorpicker-div-2dGradient:after,
+#css3colorpicker-div.mode-s #css3colorpicker-div-2dGradient,
+#css3colorpicker-div.mode-v #css3colorpicker-div-1dGradient {
+ background: -moz-linear-gradient(top, rgba(0,0,0,0) 0%, rgba(0,0,0,1) 100%);
+ background: -webkit-gradient(linear, left top, left bottom, color-stop(0%,rgba(0,0,0,0)), color-stop(100%,rgba(0,0,0,1)));
+ background: -webkit-linear-gradient(top, rgba(0,0,0,0) 0%,rgba(0,0,0,1) 100%);
+ background: -o-linear-gradient(top, rgba(0,0,0,0) 0%,rgba(0,0,0,1) 100%);
+ background: -ms-linear-gradient(top, rgba(0,0,0,0) 0%,rgba(0,0,0,1) 100%);
+ background: linear-gradient(top, rgba(0,0,0,0) 0%,rgba(0,0,0,1) 100%);
+}
+#css3colorpicker-div.mode-v #css3colorpicker-div-2dColor:after,
+#css3colorpicker-div.mode-s #css3colorpicker-div-1dColor:after {
+ background: -moz-linear-gradient(top, rgba(255,255,255,0) 0%, rgba(255,255,255,1) 100%);
+ background: -webkit-gradient(linear, left top, left bottom, color-stop(0%,rgba(255,255,255,0)), color-stop(100%,rgba(255,255,255,1)));
+ background: -webkit-linear-gradient(top, rgba(255,255,255,0) 0%,rgba(255,255,255,1) 100%);
+ background: -o-linear-gradient(top, rgba(255,255,255,0) 0%,rgba(255,255,255,1) 100%);
+ background: -ms-linear-gradient(top, rgba(255,255,255,0) 0%,rgba(255,255,255,1) 100%);
+ background: linear-gradient(top, rgba(255,255,255,0) 0%,rgba(255,255,255,1) 100%);
+}
+#css3colorpicker-div.mode-h #css3colorpicker-div-2dGradient {
+ background: -moz-linear-gradient(left, rgba(255,255,255,1) 0%, rgba(255,255,255,0) 100%);
+ background: -webkit-gradient(linear, left top, right top, color-stop(0%,rgba(255,255,255,1)), color-stop(100%,rgba(255,255,255,0)));
+ background: -webkit-linear-gradient(left, rgba(255,255,255,1) 0%,rgba(255,255,255,0) 100%);
+ background: -o-linear-gradient(left, rgba(255,255,255,1) 0%,rgba(255,255,255,0) 100%);
+ background: -ms-linear-gradient(left, rgba(255,255,255,1) 0%,rgba(255,255,255,0) 100%);
+ background: linear-gradient(left, rgba(255,255,255,1) 0%,rgba(255,255,255,0) 100%);
+}
+#css3colorpicker-div.mode-s #css3colorpicker-div-2dColor,
+#css3colorpicker-div.mode-v #css3colorpicker-div-2dColor {
+ background: -moz-linear-gradient(left, #ff0000 0%, #ffff00 16.67%, #00ff00 33.33%, #00ffff 50%, #0000ff 66.67%, #ff00ff 83.33%, #ff0000 100%);
+ background: -webkit-gradient(linear, left top, right top, color-stop(0%,#ff0000), color-stop(16.67%,#ffff00), color-stop(33.33%,#00ff00), color-stop(50%,#00ffff), color-stop(66.67%,#0000ff), color-stop(83.33%,#ff00ff), color-stop(100%,#ff0000));
+ background: -webkit-linear-gradient(left, #ff0000 0%,#ffff00 16.67%,#00ff00 33.33%,#00ffff 50%,#0000ff 66.67%,#ff00ff 83.33%,#ff0000 100%);
+ background: -o-linear-gradient(left, #ff0000 0%,#ffff00 16.67%,#00ff00 33.33%,#00ffff 50%,#0000ff 66.67%,#ff00ff 83.33%,#ff0000 100%);
+ background: -ms-linear-gradient(left, #ff0000 0%,#ffff00 16.67%,#00ff00 33.33%,#00ffff 50%,#0000ff 66.67%,#ff00ff 83.33%,#ff0000 100%);
+ background: linear-gradient(left, #ff0000 0%,#ffff00 16.67%,#00ff00 33.33%,#00ffff 50%,#0000ff 66.67%,#ff00ff 83.33%,#ff0000 100%);
+}
+#css3colorpicker-div.mode-v #css3colorpicker-div-2dGradient,
+#css3colorpicker-div.mode-s #css3colorpicker-div-1dGradient {
+ background: #000;
+}
+
+
+/* Control Themes */
+
+#css3colorpicker-div.controls-inset #css3colorpicker-div-1d,
+#css3colorpicker-div.controls-raised #css3colorpicker-div-1d,
+#css3colorpicker-div.controls-inset #css3colorpicker-div-2d,
+#css3colorpicker-div.controls-inset #css3colorpicker-div-alpha,
+#css3colorpicker-div.controls-raised #css3colorpicker-div-alpha {
+ overflow: hidden;
+}
+#css3colorpicker-div.controls-raised #css3colorpicker-div-2d,
+#css3colorpicker-div.controls-simple #css3colorpicker-div-1d,
+#css3colorpicker-div.controls-simple #css3colorpicker-div-2d,
+#css3colorpicker-div.controls-simple #css3colorpicker-div-alpha {
+ overflow: visible;
+}
+
+
+#css3colorpicker-div.controls-simple #css3colorpicker-div-1dControl,
+#css3colorpicker-div.controls-simple #css3colorpicker-div-alphaControl {
+ border: 1px solid #000;
+ box-shadow: 0 0 3px 1px rgba(255,255,255,0.65);
+}
+#css3colorpicker-div.controls-simple #css3colorpicker-div-1dControl {
+ margin-top: -1px;
+}
+#css3colorpicker-div.controls-simple #css3colorpicker-div-alphaControl {
+ margin-left: -1px;
+}
+#css3colorpicker-div.controls-simple.controls-invert #css3colorpicker-div-1dControl,
+#css3colorpicker-div.controls-simple.controls-invert #css3colorpicker-div-alphaControl {
+ border: 1px solid #fff;
+ box-shadow: 0 0 3px 1px rgba(0,0,0,0.65);
+}
+#css3colorpicker-div.controls-simple #css3colorpicker-div-2dControl {
+ border: 1px solid #000;
+ width: 9px;
+ height: 9px;
+ box-shadow: 0 0 3px 1px rgba(255,255,255,0.65);
+}
+#css3colorpicker-div.controls-simple.controls-invert #css3colorpicker-div-2dControl {
+ width: 9px;
+ height: 9px;
+ border: 1px solid #fff;
+ box-shadow: 0 0 3px 1px rgba(0,0,0,0.65);
+}
+
+
+#css3colorpicker-div.controls-inset.controls-invert #css3colorpicker-div-1dControl,
+#css3colorpicker-div.controls-raised #css3colorpicker-div-1dControl {
+ box-shadow: 0 -1px 1px rgba(255,255,255,0.65), 0 1px 1px rgba(0,0,0,0.65);
+}
+#css3colorpicker-div.controls-inset.controls-invert #css3colorpicker-div-alphaControl,
+#css3colorpicker-div.controls-raised #css3colorpicker-div-alphaControl {
+ box-shadow: -1px 0 1px rgba(255,255,255,0.65), 1px 0 1px rgba(0,0,0,0.65);
+}
+#css3colorpicker-div.controls-inset #css3colorpicker-div-1dControl,
+#css3colorpicker-div.controls-raised.controls-invert #css3colorpicker-div-1dControl {
+ box-shadow: 0 -1px 1px rgba(0,0,0,0.65), 0 1px 1px rgba(255,255,255,0.65);
+}
+#css3colorpicker-div.controls-inset #css3colorpicker-div-alphaControl,
+#css3colorpicker-div.controls-raised.controls-invert #css3colorpicker-div-alphaControl {
+ box-shadow: -1px 0 1px rgba(0,0,0,0.65), 1px 0 1px rgba(255,255,255,0.65);
+}
+#css3colorpicker-div.controls-inset.controls-invert #css3colorpicker-div-2dControl,
+#css3colorpicker-div.controls-raised #css3colorpicker-div-2dControl {
+ box-shadow: inset 0 1px 1px rgba(255,255,255,0.65), 0 1px 3px rgba(0,0,0,0.65);
+}
+#css3colorpicker-div.controls-inset #css3colorpicker-div-2dControl,
+#css3colorpicker-div.controls-raised.controls-invert #css3colorpicker-div-2dControl {
+ box-shadow: inset 0 1px 3px rgba(0,0,0,0.65), 0 1px 1px rgba(255,255,255,0.65);
+}
\ No newline at end of file
--- /dev/null
+/* Layout Selector */
+ div#layout-selector-select.layout-selector-visible div#layout-selector {
+ display: block;
+ }
+
+ div#layout-selector-select-content {
+ width: 320px;
+ float: left;
+ color: rgba(255, 255, 255, 0.65);
+ margin: 0;
+ height: @menu_height;
+ background: rgba(255, 255, 255, 0.1);
+ line-height: @menu_height;
+ padding: 0 0 0 10px;
+ border-right: rgba(0, 0, 0, 0.4) 1px solid;
+ cursor: pointer;
+ white-space: nowrap;
+ position: relative;
+
+ &:hover {
+ span#layout-selector-select-content-arrow {
+ color: rgba(255, 255, 255, 0.95);
+ }
+ }
+ }
+
+ div#layout-selector-select-content span#currently-editing {
+ color: rgba(255, 255, 255, .5);
+ margin: 0 5px 0 0;
+ float: left;
+ }
+
+ div#layout-selector-select-content span#current-layout {
+ max-width: 180px;
+ text-overflow: ellipsis;
+ overflow: hidden;
+ white-space: nowrap;
+ display: inline-block;
+ }
+
+ span#layout-selector-select-content-arrow {
+ position: absolute;
+ top: 0;
+ right: 0;
+ width: 35px;
+ height: @menu_height;
+ text-align: center;
+ margin-left: 10px;
+ background: rgba(255, 255, 255, 0.15);
+ display: block;
+ border-left: 1px solid rgba(0, 0, 0, 0.5);
+ }
+
+ span#layout-selector-select-content-arrow:after {
+ .icon-font;
+ content: 'g';
+ font-size: 13px;
+ }
+
+ div#layout-selector-select.layout-selector-visible span#layout-selector-select-content-arrow {
+ background: rgba(255, 255, 255, 0.3);
+ }
+
+ div#layout-selector {
+ width: 330px;
+ padding: 0;
+ background: #fff;
+ height: 75%;
+ max-height: 550px;
+ position: fixed;
+ border: 1px solid #E5E5E5;
+ border-top: 0;
+ display: none;
+ box-shadow: 0 1px 1px rgba(0, 0, 0, 0.04);
+
+ top: @menu_height;
+ left: 0;
+ }
+
+ div.layout-selector-content {
+ float: left;
+ clear: both;
+ width: 100%;
+ height: auto;
+ position: absolute;
+ top: 31px;
+ bottom: 0;
+ padding: 0;
+ .border-box;
+ margin: 0;
+ overflow-y: auto;
+ overflow-x: hidden;
+ }
+
+ div.layout-selector-content ul li {
+ display: block;
+ float: left;
+ width: 100%;
+ }
+
+ div.layout-selector-content ul ul {
+ display: none;
+ }
+
+ div.layout-selector-content ul ul > li.layout-item span.layout {
+ padding-left: 45px;
+ }
+
+ div.layout-selector-content ul ul ul > li.layout-item span.layout {
+ padding-left: 70px;
+ }
+
+ div.layout-selector-content ul ul ul ul > li.layout-item span.layout {
+ padding-left: 95px;
+ }
+
+ div.layout-selector-content ul ul ul ul ul > li.layout-item span.layout {
+ padding-left: 120px;
+ }
+
+ div.layout-selector-content ul ul ul ul ul ul > li.layout-item span.layout {
+ padding-left: 145px;
+ }
+
+ /* Style big boy layout */
+ div.layout-selector-content ul > li.layout-item:nth-child(even) > span.layout {
+ background: #F9F9F9;
+ }
+
+ div.layout-selector-content li.layout-item span.layout {
+ padding: 10px 20px;
+ cursor: pointer;
+ display: block;
+ position: relative;
+ float: left;
+ width: 100%;
+ min-height: 18px;
+ line-height: 18px;
+ .border-box;
+
+ clear: both;
+ }
+
+ div.layout-selector-content li.layout-item span.layout strong {
+ float: left;
+ color: #0074A2;
+ }
+
+ div.layout-selector-content li.layout-item span.layout strong:hover {
+ color: #2EA2CC;
+ }
+
+ div.layout-selector-content li.layout-item span.layout span.status {
+ color: #555;
+ float: left;
+ margin: 0 0 0 10px;
+ /* Hide all statuses by default */
+ display: none;
+ }
+
+ div.layout-selector-content li.layout-item span.layout span.status-post-status {
+ display: block !important;
+ }
+ /* Change position of buttons for pages vs templates */
+ div.layout-selector-content li.layout-item span.layout-page span.layout-selector-button {
+ right: 10px;
+ }
+
+ div.layout-selector-content li.layout-item span.layout-template { }
+
+ div.layout-selector-content li.layout-item span.layout-template span.assign-template {
+ right: 60px;
+ }
+
+ div.layout-selector-content li.layout-item span.layout-template span.delete-template {
+ text-indent: -9999px;
+ /* Hide the delete template button by default */
+ display: none;
+ cursor: pointer;
+ width: 15px;
+ height: 14px;
+ margin: 1px 0 -3px 6px;
+ color: rgba(0, 0, 0, .35);
+ float: left;
+ .transition('color 100ms linear');
+ }
+
+ div.layout-selector-content li.layout-item span.layout-template span.delete-template:before {
+ .icon-font;
+ content: '\58';
+ line-height: 16px;
+ float: left;
+ }
+
+ div.layout-selector-content li.layout-item span.layout-template span.delete-template:hover {
+ color: rgba(0, 0, 0, .85);
+ }
+
+
+ /* Style buttons and hide them */
+ span.layout-selector-button {
+ display: none;
+ position: absolute;
+ cursor: pointer;
+ top: 10px;
+ right: 10px;
+ height: 20px;
+ line-height: 20px;
+ font-size: 11px;
+ }
+
+
+ /* Hide the revert button in the design mode. */
+ body.visual-editor-mode-design span.revert {
+ display: none !important;
+ }
+
+ /* Conditionals */
+ /* Hierarchial indicators */
+ div.layout-selector-content li.has-children > span.layout:before {
+ .icon-font;
+ font-size: 18px;
+ content: 'i';
+ float: left;
+ color: #BBB;
+ margin: 0 0 0 -15px;
+ }
+
+ div.layout-selector-content li.has-children > span.layout-open:before {
+ content: 'd';
+ margin-left: -16px;
+ }
+
+ /* Show edit button on all layouts (including templates) except for layouts that have a template assigned to them and selected layouts */
+ div.layout-selector-content li.layout-item:not(.layout-item-template-used):not(.layout-selected) > span.layout:hover span.edit {
+ display: block;
+ }
+
+ /* Show the template-specific assign template button for templates that are not selected */
+ div.layout-selector-content li.layout-item:not(.layout-selected) > span.layout-template:hover span.assign-template {
+ display: block;
+ }
+
+ /* Customized layouts: show the customized status flag */
+ div.layout-selector-content li.layout-item-customized > span.layout span.status-customized {
+ display: block;
+ }
+
+ /* Layouts using a template: show status template flag, hide edit button, hide revert button, and show the remove template button */
+ div.layout-selector-content li.layout-item-template-used > span.layout span.edit {
+ display: none;
+ }
+
+ div.layout-selector-content li.layout-item-template-used > span.layout span.revert {
+ display: none;
+ }
+
+ div.layout-selector-content li.layout-item-template-used > span.layout span.status-template {
+ display: block;
+ }
+
+ /* Hide it on hover too */
+ div.layout-selector-content li.layout-item-template-used > span.layout:hover span.edit {
+ display: none;
+ }
+
+ div.layout-selector-content li.layout-item-template-used > span.layout:hover span.revert {
+ display: none;
+ }
+
+ div.layout-selector-content li.layout-item-template-used > span.layout:hover span.remove-template {
+ display: block;
+ }
+
+ /* Selected layout:
+ * hide customized or template flag,
+ * lighten the template name to show that it's selected,
+ * add the currently editing flag,
+ * hide all buttons */
+ div.layout-selector-content li.layout-selected > span.layout strong {
+ color: #222 !important;
+ font-weight: bold;
+ }
+
+ div.layout-selector-content li.layout-selected > span.layout span.status {
+ display: none;
+ }
+
+ div.layout-selector-content li.layout-selected > span.layout span.status-currently-editing {
+ display: block;
+ }
+
+ /* Hide the buttons */
+ div.layout-selector-content li.layout-selected > span.layout span.layout-selector-button {
+ display: none;
+ }
+
+ div.layout-selector-content li.layout-selected > span.layout:hover span.layout-selector-button {
+ display: none;
+ }
+ /* End hiding buttons */
+
+ /* Selected layout that's customized: show revert button */
+ div.layout-selector-content li.layout-selected.layout-item-customized > span.layout span.revert {
+ display: block;
+ }
+
+ /* Selected layout that's using a template: show remove template button */
+ div.layout-selector-content li.layout-selected.layout-item-template-used > span.layout span.remove-template {
+ display: block;
+ }
+
+ /* Selected and hovered template: show delete button */
+ div.layout-selector-content li.layout-selected > span.layout-template span.delete-template,
+ div.layout-selector-content li.layout-item > span.layout-template:hover span.delete-template {
+ display: block;
+ }
+
+ /* Rename */
+ div.layout-selector-content li.layout-selected > span.layout-template span.rename-template,
+ div.layout-selector-content li.layout-selected > span.layout-template:hover span.rename-template {
+ display: block;
+ }
+
+ /* Layout No Edit */
+ div.layout-selector-content li.layout-item-no-edit > span.layout strong {
+ color: #555;
+ }
+
+ div.layout-selector-content li.layout-item-no-edit > span.layout span.layout-selector-button {
+ display: none !important;
+ }
+
+ div.layout-selector-content li.layout-item-no-edit.has-children > span.layout:before {
+ color: #555;
+ }
+
+ /* Layout With Customized Children */
+ div.layout-selector-content li.layout-item.has-customized-children {
+ position: relative;
+ clear: both;
+ }
+
+ div.layout-selector-content li.layout-item > span.layout-has-customized-children {
+ display: none;
+ font-size: 8px;
+ margin: 0;
+ font-weight: 200;
+ top: 12px;
+ left: 9px;
+ position: absolute;
+ color: #0EA8C7;
+ z-index: 2;
+ cursor: help;
+ }
+
+ div.layout-selector-content li.layout-item.has-customized-children > span.layout-has-customized-children {
+ display: inline;
+ }
+ /* End Conditionals */
+
+ /* Info Layout Item */
+ div.layout-selector-content li.info-layout-item span.layout strong, div.layout-selector-content li.info-layout-item span.layout strong:hover {
+ color: #888;
+ cursor: default;
+ }
+ /* End Info Layout Item */
+
+ div.layout-selector-content > ul {
+ width: 100%;
+ margin: 0;
+ height: 100%;
+ float: left;
+ }
+
+ /* Template Input */
+ div#layout-selector-templates {
+ bottom: 35px;
+ }
+
+ div#template-name-input-container {
+ float: left;
+ position: absolute;
+ bottom: 0;
+
+ background: #fff;
+ border-top: 1px solid #E1E1E1;
+
+ width: 100%;
+ padding: 8px 9px 6px;
+ .border-box;
+ }
+
+ div#template-name-input-container input {
+ float: left;
+ padding: 4px 5px;
+ margin: 0 0 0 2px;
+ width: 150px;
+ }
+
+ div#template-name-input-container input::-webkit-input-placeholder { opacity: .6; }
+ div#template-name-input-container input::-moz-placeholder { opacity: .6; }
+
+ div#template-name-input-container span.add-template {
+ display: block;
+ position: static;
+ top: auto;
+ left: auto;
+
+ margin: 0 0 0 8px;
+
+ float: right;
+ }
+
+ /* Hide the add template button in the design mode. */
+ body.visual-editor-mode-design div#template-name-input-container {
+ display: none !important;
+ }
+ /* End Template Inputs */
+
+ div#layout-selector-tabs {
+ z-index: 5;
+ width: 100%;
+ height: 30px;
+ border-bottom: 1px solid #E1E1E1;
+ }
+
+ div#layout-selector-tabs ul.tabs {
+ float: left;
+ display: block;
+ height: 30px;
+ list-style: none;
+ margin: 0;
+ }
+
+ div#layout-selector-tabs li {
+ float: left;
+ }
+
+ div#layout-selector-tabs a {
+ color: #666;
+ height: 30px;
+ line-height: 30px;
+ padding: 0 10px;
+ display: block;
+ text-decoration: none;
+ font-weight: bold;
+ }
+
+ div#layout-selector-tabs a:hover {
+ color: #0074A2;
+ }
+
+ div#layout-selector-tabs li.ui-tabs-active a {
+ color: #222;
+ }
\ No newline at end of file
--- /dev/null
+/* Body Overlay */
+div#ve-loading-overlay {
+ position: fixed;
+ background: #eee;
+ width: 100%;
+ height: 100%;
+ display: block;
+ z-index: 999;
+ opacity: 1;
+ -webkit-transition: opacity 150ms linear;
+ transition: opacity 150ms linear;
+}
+
+/* Loading */
+ @-webkit-keyframes spin {
+ from { -webkit-transform: rotate(0deg); }
+ to { -webkit-transform: rotate(360deg); }
+ }
+
+ @-moz-keyframes spin {
+ from { -moz-transform: rotate(0deg); }
+ to { -moz-transform: rotate(360deg); }
+ }
+
+ @-ms-keyframes spin {
+ from { -ms-transform: rotate(0deg); }
+ to { -ms-transform: rotate(360deg); }
+ }
+
+ @-webkit-keyframes spinReverse {
+ from { -webkit-transform: rotate(0deg); }
+ to { -webkit-transform: rotate(-360deg); }
+ }
+
+ @-moz-keyframes spinReverse {
+ from { -moz-transform: rotate(0deg); }
+ to { -moz-transform: rotate(-360deg); }
+ }
+
+ @-ms-keyframes spinReverse {
+ from { -ms-transform: rotate(0deg); }
+ to { -ms-transform: rotate(-360deg); }
+ }
+
+ div.cog-container {
+ position: absolute;
+ opacity: .8;
+ top: 50%;
+ left: 50%;
+ width: 1px; /* Width and height keep jQuery :visible from return false */
+ height: 1px;
+ margin: -10px 0 0 -25px;
+ -webkit-filter: brightness(80%);
+ filter: brightness(80%);
+ overflow: visible !important;
+ }
+
+ div.panel div.cog-container {
+ margin-top: 15px;
+ }
+
+ div.cog-container div {
+ background-image: url(data:image/svg+xml;base64,PHN2ZyB2ZXJzaW9uPSIxLjEiIHhtbG5zPSJodHRwOi8vd3d3LnczLm9yZy8yMDAwL3N2ZyIgZGF0YS1pY29uPSJjb2ciIHdpZHRoPSIxMjgiIGhlaWdodD0iMTI4IiBjbGFzcz0iaWNvbmljIGljb25pYy1jb2cgaWNvbmljLW9yaWVudGF0aW9uLXNxdWFyZSIgdmlld0JveD0iMCAwIDEyOCAxMjgiPgogIDxnIGRhdGEtd2lkdGg9IjEyOCIgZGF0YS1oZWlnaHQ9IjEyOCIgY2xhc3M9Imljb25pYy1sZyIgZGlzcGxheT0iaW5saW5lIj4KICAgIDxwYXRoIGQ9Ik0xMjggNzMuOXYtMTkuOWwtMTQuMy0zLjZjLTEuMi00LjItMi44LTguMy01LTEybDcuNS0xMi43LTE0LjEtMTQuMS0xMi43IDcuNmMtMy43LTIuMS03LjgtMy44LTEyLTVsLTMuNS0xNC4yaC0xOS45bC0zLjYgMTQuM2MtNC4yIDEuMi04LjMgMi44LTEyIDVsLTEyLjctNy41LTE0IDE0IDcuNiAxMi43Yy0yLjEgMy43LTMuOCA3LjgtNSAxMmwtMTQuMyAzLjZ2MTkuOWwxNC4zIDMuNmMxLjIgNC4yIDIuOCA4LjMgNSAxMmwtNy41IDEyLjcgMTQuMSAxNC4xIDEyLjctNy42YzMuNyAyLjEgNy44IDMuOCAxMiA1bDMuNyAxNC4zaDE5LjdsMy42LTE0LjNjNC4yLTEuMiA4LjMtMi44IDEyLTVsMTIuNyA3LjUgMTQuMS0xNC4xLTcuNi0xMi43YzIuMS0zLjcgMy44LTcuOCA1LTEybDE0LjItMy42em0tNjQgMjQuMWMtMTguOCAwLTM0LTE1LjItMzQtMzRzMTUuMi0zNCAzNC0zNCAzNCAxNS4yIDM0IDM0LTE1LjIgMzQtMzQgMzR6IgogICAgY2xhc3M9Imljb25pYy1jb2ctYm9keSBpY29uaWMtZWxlbWVudC1maWxsIiAvPgogIDwvZz4KPC9zdmc+);
+ }
+
+ div.cog-container div.cog-bottom-left {
+ position: absolute;
+ top: 0;
+ left: 0;
+ width: 36px;
+ height: 36px;
+ display: block;
+ -webkit-animation: spin 3000ms infinite linear;
+ -moz-animation: spin 3000ms infinite linear;
+ animation: spin 3000ms infinite linear;
+ background-size: 36px;
+ background-repeat: none;
+ }
+
+ div.cog-container div.cog-top-right {
+ position: absolute;
+ top: -21px;
+ left: 21px;
+ width: 28px;
+ height: 28px;
+ display: block;
+ -webkit-animation: spinReverse 3000ms infinite linear;
+ -moz-animation: spinReverse 3000ms infinite linear;
+ animation: spinReverse 3000ms infinite linear;
+ background-size: 28px;
+
+ background-image: url(data:image/svg+xml;base64,PHN2ZyB2ZXJzaW9uPSIxLjEiIHhtbG5zPSJodHRwOi8vd3d3LnczLm9yZy8yMDAwL3N2ZyIgZGF0YS1pY29uPSJjb2ciIHdpZHRoPSIxNiIgaGVpZ2h0PSIxNiIgY2xhc3M9Imljb25pYyBpY29uaWMtY29nIGljb25pYy1vcmllbnRhdGlvbi1zcXVhcmUiIHZpZXdCb3g9IjAgMCAxNiAxNiI+CiAgPHRpdGxlPkNvZzwvdGl0bGU+CiAgPGcgZGF0YS13aWR0aD0iMTYiIGRhdGEtaGVpZ2h0PSIxNiIgY2xhc3M9Imljb25pYy1zbSI+CiAgICA8cGF0aCBkPSJNMTYgOXYtMmwtMi0xYy0uMS0uMy0uMi0uNi0uNC0uOWwuOS0yLjEtMS41LTEuNS0yLjEuOC0uOS0uMy0xLTJoLTJsLTEgMi0uOS4zLTIuMS0uOC0xLjUgMS41LjggMi4xLS4zLjktMiAxdjJsMiAxYy4xLjMuMi42LjQuOWwtLjkgMi4xIDEuNSAxLjUgMi4xLS44LjkuMyAxIDJoMmwxLTJjLjMtLjEuNi0uMi45LS40bDIuMS44IDEuNS0xLjUtLjgtMi4xLjQtLjkgMS45LS45em0tOCAyYy0xLjcgMC0zLTEuMy0zLTNzMS4zLTMgMy0zIDMgMS4zIDMgMy0xLjMgMy0zIDN6IgogICAgY2xhc3M9Imljb25pYy1jb2ctYm9keSBpY29uaWMtZWxlbWVudC1maWxsIiAvPgogIDwvZz4KPC9zdmc+);
+ }
+
+/* iframe sizing */
+ div#iframe-container {
+ width: auto;
+ height: auto;
+ top: 35px;
+ bottom: 260px;
+ left: 0;
+ right: 0;
+ padding: 0;
+ margin: 0;
+ position: fixed;
+ opacity: 0;
+ }
+
+ iframe.content {
+ width: 100%;
+ height: 100%;
+ }
+
+
+ body.visual-editor-mode-design:not(.side-panel-hidden) div#iframe-container {
+ right: 290px !important;
+ }
--- /dev/null
+.rounded-corners(@radius) {
+ -webkit-border-radius: @radius;
+ -moz-border-radius: @radius;
+ border-radius: @radius;
+}
+
+/* Icon Font */
+ @font-face {
+ font-family: 'headway-ve';
+ src: local('☺'),
+ url('%VISUALEDITOR%/font/headway-ve.woff'),
+ url('%VISUALEDITOR%/font/headway-ve.ttf') format('truetype');
+ font-weight: normal;
+ font-style: normal;
+ }
+
+ .icon-plus:before { content: '\3d'; } /* '=' */
+ .icon-minus:before { content: '\5f'; } /* '_' */
+ .icon-up-dir:before { content: '\68'; } /* 'h' */
+ .icon-right-dir:before { content: '\69'; } /* 'i' */
+ .icon-down-dir:before { content: '\64'; } /* 'd' */
+ .icon-left-dir:before { content: '\65'; } /* 'e' */
+ .icon-list:before { content: '\45'; } /* 'E' */
+ .icon-cog:before { content: '\33'; } /* '3' */
+ .icon-cogs:before { content: '\30'; } /* '0' */
+ .icon-edit:before { content: '\34'; } /* '4' */
+ .icon-checkmark:before { content: '\32'; } /* '2' */
+ .icon-plus-circle:before { content: '\2b'; } /* '+' */
+ .icon-minus-solid-circle:before { content: '\2d'; } /* '-' */
+ .icon-x-circle:before { content: '\58'; } /* 'X' */
+ .icon-help-solid-circle:before { content: '\3f'; } /* '?' */
+ .icon-grid:before { content: '\31'; } /* '1' */
+ .icon-eye:before { content: '\25be'; } /* '▾' */
+ .icon-down-open:before { content: '\67'; } /* 'g' */
+ .icon-left-open:before { content: '\62'; } /* 'b' */
+ .icon-right-open:before { content: '\3e'; } /* '>' */
+ .icon-up-open:before { content: '\5e'; } /* '^' */
+ .icon-arrows-cw:before { content: '\72'; } /* 'r' */
+ .icon-equalizer:before { content: '\61'; } /* 'a' */
+ .icon-brush:before { content: '\63'; } /* 'c' */
+ .icon-cancel-alt:before { content: '\78'; } /* 'x' */
+ .icon-pictures:before { content: '\66'; } /* 'f' */
+ .icon-attach:before { content: '\36'; } /* '6' */
+ .icon-link:before { content: '\35'; } /* '5' */
+ .icon-checkmark-sharp:before { content: "\74"; } /* 't' */
+ .icon-copy:before { content: "\6c"; } /* 'l' */
+ .icon-loop:before { content: "\a8"; } /* '¨' */
+ .icon-remove:before { content: "\70"; } /* 'p' */
+ .icon-plus-sharp:before { content: "\a7"; } /* '§' */
+ .icon-insert-template:before { content: "\37"; } /* '7' */
+ .icon-cloud-download:before { content: "\38"; } /* '8' */
+
+ .icon-font() {
+ font-family: 'headway-ve';
+ font-style: normal;
+ font-weight: normal;
+ speak: none;
+ display: inline-block;
+ text-decoration: inherit;
+ width: auto;
+ text-indent: 0;
+ color: inherit;
+ font-size: 13px;
+ -webkit-font-smoothing: antialiased;
+ -moz-osx-font-smoothing: grayscale;
+ }
+
+/* Highlighting */
+ .no-highlight() {
+ -webkit-user-select: none;
+ user-select: none;
+ }
+
+ .allow-highlight() {
+ -webkit-user-select: text !important;
+ user-select: text !important;
+ }
+
+/* Box Sizing */
+ .border-box() {
+ -moz-box-sizing: border-box;
+ -webkit-box-sizing: border-box;
+ box-sizing: border-box;
+ }
+
+/* Anti-aliasing */
+ .antialias() {
+ -webkit-font-smoothing: antialiased;
+ -moz-osx-font-smoothing: grayscale;
+ }
+
+/* Transition */
+ .transition(@transition) {
+ -webkit-transition: e(@transition);
+ -moz-transition: e(@transition);
+ transition: e(@transition);
+ }
+
+ .animation(@animation) {
+ -webkit-animation: e(@animation);
+ -moz-animation: e(@animation);
+ animation: e(@animation);
+ }
+
+ .disable-transitions {
+ -webkit-transition: none !important;
+ -moz-transition: none !important;
+ transition: none !important;
+ }
\ No newline at end of file
--- /dev/null
+/* Tooltips */
+.qtip{
+ position: absolute;
+ left: -28000px;
+ top: -28000px;
+ display: none;
+
+ max-width: 400px;
+ min-width: 50px;
+
+ font-size: 10.5px;
+ line-height: 12px;
+
+ z-index: 15000;
+ font-family: "Open Sans", sans-serif;
+}
+
+ /* Hide disabled tooltips */
+ .qtip[aria-disabled="true"] {
+ display: none !important;
+ }
+
+ .qtip-content{
+ position: relative;
+ padding: 5px 9px;
+ overflow: hidden;
+
+ border-width: 1px;
+ border-style: solid;
+
+ text-align: left;
+ word-wrap: break-word;
+ overflow: hidden;
+ }
+
+ .qtip-content strong {
+ font-weight: bold;
+ }
+
+ .qtip-content em {
+ font-style: italic;
+ }
+
+ .qtip-content ul {
+ margin: 5px 0;
+ padding: 0 5px 0 30px;
+ list-style: disc;
+ }
+
+ .qtip-titlebar{
+ position: relative;
+ min-height: 14px;
+ padding: 5px 35px 5px 10px;
+ overflow: hidden;
+
+ border-width: 1px 1px 0;
+ border-style: solid;
+
+ font-weight: bold;
+ }
+
+ .qtip-titlebar + .qtip-content{ border-top-width: 0px !important; }
+
+ /*! Default close button class */
+ .qtip-titlebar .ui-state-default{
+ position: absolute;
+ right: 4px;
+ top: 50%;
+ margin-top: -9px;
+
+ cursor: pointer;
+ outline: medium none;
+
+ border-width: 1px;
+ border-style: solid;
+ }
+
+ * html .qtip-titlebar .ui-state-default{ top: 16px; } /* IE fix */
+
+ .qtip-titlebar .ui-icon,
+ .qtip-icon .ui-icon{
+ display: block;
+ text-indent: -1000em;
+ }
+
+ .qtip-icon, .qtip-icon .ui-icon{
+ .rounded-corners(3px);
+ }
+
+ .qtip-icon .ui-icon{
+ width: 18px;
+ height: 14px;
+
+ text-align: center;
+
+ color: inherit;
+ background: transparent none no-repeat -100em -100em;
+ }
+
+
+/* Tips plugin */
+.qtip .qtip-tip{
+ margin: 0 auto;
+ overflow: hidden;
+
+ background: transparent;
+ border: 0px dashed transparent !important;
+ z-index: 10;
+}
+
+ .qtip .qtip-tip,
+ .qtip .qtip-tip *{
+ position: absolute;
+
+ line-height: 0.1px !important;
+ font-size: 0.1px !important;
+ color: #123456;
+
+ background: transparent;
+ border: 0px dashed transparent;
+ }
+
+ .qtip .qtip-tip canvas{ top: 0; left: 0; }
+
+
+/* Headway Tooltips */
+div.qtip-headway div.qtip-content {
+ background: #313131;
+ color: #ddd;
+ border: none;
+ .rounded-corners(2px);
+ padding: 8px 12px;
+ font-size: 13px;
+ line-height: 20px;
+}
+
+/* Element Selector */
+div.qtip-headway-element-selector div.qtip-content {
+ background: #57595A;
+ padding: 3px 6px;
+}
+
+
+/* Inspector */
+div.qtip-inspector-tooltip {
+ opacity: .8 !important;
+ pointer-events: none;
+}
+
+div.qtip-inspector-tooltip span.inspector-tooltip-instance {
+ display: block;
+ text-align: center;
+ font-size: 11px;
+ height: 14px;
+ line-height: 14px;
+}
+
+div.qtip-inspector-tooltip small.right-click-message {
+ display: block;
+ text-align: center;
+ opacity: .7;
+ margin-top: 3px;
+ font-size: 11px;
+ line-height: 11px;
+}
+
+
+
+/* Block Dimensions */
+div.qtip-block-dimensions {
+ opacity: .8 !important;
+}
+
+div.qtip-block-dimensions div.qtip-content, div.qtip-block-dimensions div.qtip-content * {
+ font-size: 11px;
+ line-height: 17px;
+}
+
+ div.qtip-block-dimensions div.qtip-content div.block-info {
+ text-align: center;
+ font-size: 12px;
+ font-weight: 500;
+ display: block;
+ margin: 0 0 3px;
+ }
+
+ div.qtip-block-dimensions div.qtip-content span.block-info-type {
+ background-image: url(%VISUALEDITOR%/images/default-block-icon.png);
+ background-position: 50%;
+ background-size: 65%;
+ background-repeat: no-repeat;
+ width: 20px;
+ height: 20px;
+ display: inline-block;
+ margin: 0 4px -5px 0;
+ }
+
+ div.qtip-block-dimensions div.qtip-content span.main-block-info-mirrored {
+ opacity: .5;
+ }
+
+ div.qtip-block-dimensions div.qtip-content span.block-info-mirroring {
+ display: inline-block;
+ background: rgba(255, 255, 255, .2);
+ box-shadow: 0 0 1px rgba(0, 0, 0, .6);
+ border-radius: 3px;
+ padding: 1px 6px;
+ margin: 0 0 0 4px;
+ clear: both;
+ }
+
+ div.qtip-block-dimensions div.qtip-content span.block-dimensions-separator {
+ font-size: 13px;
+ opacity: .8;
+ }
+
+ div.qtip-block-dimensions div.qtip-content small {
+ font-size: 10px;
+ }
+
+ div.qtip-block-dimensions span.block-fluid-height-message,
+ div.qtip-block-dimensions span.right-click-message {
+ display: block;
+ text-align: center;
+ opacity: .7;
+ }
\ No newline at end of file
--- /dev/null
+body {
+ overflow: hidden;
+ font-size: 12px;
+ font-family: "Open Sans", sans-serif;
+}
+
+a {
+ color: #0074A2;
+}
+
+input, textarea {
+ font-family: "Open Sans",sans-serif;
+}
+
+body * {
+ outline: none;
+ .no-highlight;
+}
+
+input, textarea {
+ .allow-highlight;
+}
+
+/* For some reason these two selection declarations cannot be grouped using a comma, so they are separate. */
+::selection {
+ background: #0781a3;
+}
+
+::-moz-selection {
+ background: #0781a3;
+}
+
+
+/* Loading */
+ body.show-ve div#ve-loading-overlay {
+ opacity: 0;
+ pointer-events: none;
+ }
+
+/* jQuery UI */
+
+ /* Tabs */
+ div.ui-tabs-hide {
+ position: absolute;
+ top: -9999px;
+ left: -9999px;
+ }
+
+ /* Autocomplete */
+ .ui-autocomplete {
+ position: absolute;
+ cursor: default;
+ }
+
+ /* Menu */
+ .ui-menu {
+ list-style:none;
+ padding: 2px;
+ margin: 0;
+ display:block;
+ float: left;
+ }
+
+ .ui-menu .ui-menu { margin-top: -3px; }
+
+ .ui-menu-item {
+ margin:0;
+ padding: 0;
+ zoom: 1;
+ float: left;
+ clear: left;
+ width: 100%;
+ }
+
+ .ui-menu-item a {
+ text-decoration:none;
+ display:block;
+ padding:0;
+ line-height:100%;
+ zoom:1;
+ }
+
+ .ui-menu-item a.ui-state-hover, .ui-menu-item a.ui-state-active { font-weight: normal; }
+
+ /* Resizable */
+ .ui-resizable {
+ position: relative; }
+
+ .ui-resizable-handle {
+ display: block;
+ font-size: 0.1px;
+ position: absolute;
+ z-index: 10; }
+
+ .ui-resizable-n {
+ cursor: n-resize;
+ height: 15px;
+ left: 0;
+ top: -5px;
+ width: 100%; }
+
+ .ui-resizable-s {
+ bottom: -5px;
+ cursor: s-resize;
+ height: 15px;
+ left: 0;
+ width: 98%; }
+
+ .ui-resizable-e {
+ cursor: e-resize;
+ height: 98%;
+ right: -5px;
+ top: 0;
+ width: 15px; }
+
+ .ui-resizable-w {
+ cursor: w-resize;
+ height: 100%;
+ left: -5px;
+ top: 0;
+ width: 15px; }
+
+ .ui-resizable-se {
+ bottom: -5px;
+ cursor: se-resize;
+ height: 15px;
+ right: -5px;
+ width: 15px; }
+
+ .ui-resizable-sw {
+ bottom: -5px;
+ cursor: sw-resize;
+ height: 15px;
+ left: -5px;
+ width: 15px; }
+
+ .ui-resizable-nw {
+ top: -5px;
+ cursor: nw-resize;
+ height: 15px;
+ left: -5px;
+ width: 15px; }
+
+
+/* Random */
+ span.button {
+ display: inline-block;
+ text-decoration: none;
+ font-size: 13px;
+ line-height: 24px;
+ height: 26px;
+ margin: 0;
+ padding: 0 10px 1px;
+ cursor: pointer;
+ border-width: 1px;
+ border-style: solid;
+ -webkit-border-radius: 3px;
+ -webkit-appearance: none;
+ border-radius: 3px;
+ white-space: nowrap;
+ -webkit-box-sizing: border-box;
+ -moz-box-sizing: border-box;
+ box-sizing: border-box;
+
+ color: #555;
+ border-color: #CCC;
+ background: #F7F7F7;
+ -webkit-box-shadow: inset 0 1px 0 #FFF, 0 1px 0 rgba(0, 0, 0, 0.08);
+ box-shadow: inset 0 1px 0 #FFF, 0 1px 0 rgba(0, 0, 0, 0.08);
+ vertical-align: top;
+
+ }
+
+ span.button:hover, span.button:active, span.button-depressed {
+ background: #FAFAFA;
+ border-color: #999;
+ color: #222;
+ }
+
+ span.button:active, span.button-depressed {
+ background: #EEE;
+ border-color: #999;
+ color: #333;
+ -webkit-box-shadow: inset 0 2px 5px -3px rgba(0, 0, 0, 0.5);
+ box-shadow: inset 0 2px 5px -3px rgba(0, 0, 0, 0.5);
+ padding-top: 1px;
+ }
+
+ span.button.button-small {
+ font-size: 11px;
+ height: 20px;
+ line-height: 20px;
+ }
+
+ span.button.button-blue {
+ background: #2EA2CC;
+ border-color: #0074A2;
+ -webkit-box-shadow: inset 0 1px 0 rgba(120, 200, 230, 0.5),0 1px 0 rgba(0, 0, 0, 0.15);
+ box-shadow: inset 0 1px 0 rgba(120, 200, 230, 0.5),0 1px 0 rgba(0, 0, 0, 0.15);
+ color: #FFF;
+
+ &[disabled], &:disabled, &.button-disabled {
+ color: #94CDE7 !important;
+ background: #298CBA !important;
+ border-color: #1B607F !important;
+ -webkit-box-shadow: none !important;
+ box-shadow: none !important;
+ text-shadow: 0 -1px 0 rgba(0, 0, 0, 0.1) !important;
+ cursor: default;
+ }
+ }
+
+ span.button.button-blue:hover {
+ background: #1E8CBE;
+ border-color: #0074A2;
+ -webkit-box-shadow: inset 0 1px 0 rgba(120, 200, 230, 0.6);
+ box-shadow: inset 0 1px 0 rgba(120, 200, 230, 0.6);
+ color: #FFF;
+ }
+
+ span.button.button-blue:active {
+ background: #1E8CBE;
+ border-color: #005684;
+ color: rgba(255, 255, 255, 0.95);
+ -webkit-box-shadow: inset 0 1px 0 rgba(0, 0, 0, 0.1);
+ box-shadow: inset 0 1px 0 rgba(0, 0, 0, 0.1);
+ vertical-align: top;
+ }
+
+/* Image Uploader */
+ .input-image span.button::before {
+ content: "\f128";
+ font-family: 'dashicons';
+ font-size: 16px;
+ .antialias();
+ color: #888;
+ margin-right: 6px;
+ }
+
+ span.src {
+ float: left;
+ margin: 0 10px;
+ line-height: 25px;
+ color: #222;
+ word-wrap: break-word;
+ user-select: none;
+ -webkit-user-select: none;
+ }
+
+ span.delete-image, span.delete-file {
+ display: block;
+ float: left;
+ height: 14px;
+ margin: 6px 5px 0 -4px;
+ opacity: 0.3;
+ text-indent: -9999px;
+ width: 15px;
+ cursor: pointer;
+ color: rgba(0, 0, 0, .6);
+ .transition('color 100ms linear');
+ }
+
+ span.delete-image:before, span.delete-file:before {
+ .icon-font;
+ content: '\58';
+ float: left;
+ font-size: 16px;
+ line-height: 14px;
+ }
+
+ span.delete-image:hover, span.delete-file:hover {
+ color: rgba(0, 0, 0, 1);
+ }
+
+/* Spinner */
+ .spinner {
+ background: url(%SITE_URL%/wp-admin/images/spinner.gif) no-repeat;
+ background-size: 20px 20px;
+ display: none;
+ float: right;
+ opacity: 0.7;
+ filter: alpha(opacity=70);
+ width: 20px;
+ height: 20px;
+ margin: 2px 5px 0;
+ }
+
+/* Menu */
+@menu_height = 35px;
+
+div#menu {
+ width: 100%;
+ min-width: 870px;
+ height: @menu_height;
+ position: fixed;
+ z-index: 15;
+ background: #222222;
+}
+
+ span#logo {
+ width: 18px;
+ height: 22px;
+ background: url(%VISUALEDITOR%/images/logo-white.png) no-repeat 0;
+ display: block;
+ margin: 6px 8px 0;
+ float: left;
+ background-size: 18px 22px;
+ text-indent: -9999px;
+ opacity: .3;
+ }
+
+ /* Top Menu Navigation (Modes and Skins Button) */
+ @top_menu_nav_border_left = ~"1px solid rgba(255, 255, 255, .1)";
+ @top_menu_nav_border_right = ~"1px solid rgba(0, 0, 0, .65)";
+
+ ul.top-menu-nav {
+ float: left;
+ margin: 0;
+
+ border-left: @top_menu_nav_border_left;
+ border-right: @top_menu_nav_border_right;
+
+ > li {
+ float: left;
+ height: @menu_height;
+ color: #8c8c8c;
+
+ border-left: @top_menu_nav_border_right;
+ border-right: @top_menu_nav_border_left;
+
+ > a, > span {
+ cursor: pointer;
+ text-decoration: none;
+ height: @menu_height;
+ line-height: @menu_height;
+ padding: 0 15px;
+ display: block;
+ font-size: 13px;
+ color: #eee;
+
+ &:before {
+ margin: 0 10px 0 0;
+ .icon-font;
+ color: #999;
+ float: left;
+ font-size: 14px;
+ }
+ }
+
+ &:not(.active):hover > a,
+ &:not(.active):hover > span {
+ background-color: #333;
+ color: #2EA2CC;
+
+ &:before {
+ color: #2EA2CC;
+ }
+ }
+
+ &.active {
+ background: #2e2e2e;
+ }
+
+ &:not(.has-submenu):active {
+ background: #2e2e2e;
+ }
+
+ /* Sub Menus */
+ &.has-submenu {
+ > a::after, > span::after {
+ .icon-font;
+ content: 'd';
+ margin: 0 0 0 7px;
+ color: #8C8C8C;
+ }
+ }
+
+ &:hover ul {
+ display: block;
+ }
+
+ ul {
+ display: none;
+ width: auto;
+ margin: -1px 0 0 -1px;
+ padding: 10px 0;
+ .border-box;
+ position: absolute;
+
+ -webkit-box-shadow: 0 3px 5px rgba(0, 0, 0, 0.2);
+ box-shadow: 0 3px 5px rgba(0, 0, 0, 0.2);
+ background: #333;
+ border: 0;
+
+ li {
+ clear: both;
+ width: 100%;
+
+ a, span {
+ text-decoration: none;
+ color: #8c8c8c;
+ font-size: 13px;
+ padding: 7px 15px;
+ display: block;
+ cursor: pointer;
+
+ &:hover {
+ color: #ccc;
+ }
+
+ small {
+ font-size: 10px;
+ margin: 0 0 0 5px;
+ color: #5a5a5a;
+ line-height: 12px;
+ }
+ }
+ }
+ }
+ }
+
+ }
+
+ /* Mode Icons */
+ ul#modes {
+ li {
+ width: 50px;
+
+ a {
+ color: #999;
+ padding: 0;
+ text-align: center;
+
+ > span {
+ display: none;
+ }
+
+ &::before {
+ font-size: 22px;
+ display: block;
+ color: inherit;
+ font-family: 'dashicons';
+ width: 100% !important;
+ height: 100%;
+ margin: 0;
+ }
+ }
+
+
+ &.active a {
+ color: #fff;
+ }
+
+ &#mode-grid {
+ a:before {
+ content: "\f135";
+ }
+ }
+
+ &#mode-design {
+ a:before {
+ content: "\f100";
+ }
+ }
+ }
+ }
+
+ /* Menu Button Icons */
+ #menu-right ul.top-menu-nav {
+
+ li#snapshots-button > span::before {
+ font-family: 'dashicons';
+ content: "\f321";
+ }
+
+ li#menu-link-tools > span::before {
+ content: "\22";
+ }
+
+ li#menu-link-admin > span::before {
+ font-family: 'dashicons';
+ content: '\f120';
+ }
+
+ li#menu-link-view-site a::before {
+ font-family: 'dashicons';
+ content: "\f102";
+ }
+
+ }
+
+ /* End Top Menu Navigation */
+
+ /* Top Menu Mode Buttons */
+ .menu-mode-buttons {
+ float: left;
+ margin: 0;
+ border-left: 1px solid rgba(255, 255, 255, 0.1);
+
+ .menu-mode-button {
+ border-left: 1px solid rgba(0, 0, 0, 0.65);
+ border-right: 1px solid rgba(255, 255, 255, 0.1);
+ display: inline-block;
+ width: 30px;
+ height: 35px;
+ vertical-align: top;
+ text-align: center;
+ line-height: 35px;
+ cursor: pointer;
+ color: #a3a3a3;
+ position: relative;
+
+ &:hover {
+ background-color: #333;
+ }
+
+ &:last-child {
+ border-right: 0;
+ }
+
+ &::after {
+ .icon-font;
+ font-size: 14px;
+ }
+
+ &#toggle-inspector {
+ &::after {
+ content: "\e001";
+ width: 7px;
+ }
+
+ &::before {
+ content: "*";
+ font-size: 25px;
+ display: block;
+ position: absolute;
+ color: #7DD1E2;
+ top: -2px;
+ left: 6px;
+ width: 1px;
+ height: 1px;
+ .antialias();
+ }
+
+ &.inspector-disabled {
+ color: #a3a3a3;
+
+ &::before {
+ color: #888;
+ }
+ }
+ }
+
+ &#open-live-css {
+ &::after {
+ content: "\e003";
+ width: 14px;
+ }
+ }
+ }
+ }
+
+ /* Menu Right */
+ div#menu-right { float: right; }
+
+ /* Save Buttons */
+ .save-button-container {
+ position: relative;
+ float: right;
+ display: block;
+ width: 76px;
+ margin-right: -76px;
+ .transition('margin-right 300ms');
+ }
+
+ body.allow-saving .save-button-container {
+ margin-right: 0 !important;
+ }
+
+ span.save-button {
+ display: block;
+ font-size: 12px;
+ padding: 0;
+ height: @menu_height;
+ width: 76px;
+ line-height: @menu_height;
+ text-align: center;
+ text-decoration: none;
+ cursor: pointer;
+
+ box-sizing: border-box;
+
+ background: #2EA2CC;
+ color: #FFF;
+ font-size: 13px;
+ }
+
+ /* Save Button */
+ span#save-button {
+ z-index: 2;
+ .transition('box-shadow 300ms linear');
+ }
+
+ span#save-button:not(.active):hover {
+ background: #1E8CBE;
+ border-color: #0074A2;
+ -webkit-box-shadow: inset 0 1px 0 rgba(120, 200, 230, 0.6);
+ box-shadow: inset 0 1px 0 rgba(120, 200, 230, 0.6);
+ }
+
+ span#save-button:active, span#save-button.active {
+ .animation('saveButtonGlow 1250ms infinite linear');
+ }
+
+
+ @-webkit-keyframes saveButtonGlow {
+ from {
+ -webkit-box-shadow: inset 0 0 0 #7dd1e2;
+ }
+
+ 50% {
+ -webkit-box-shadow: inset 0 0 15px #7dd1e2;
+ }
+
+ to {
+ -webkit-box-shadow: inset 0 0 0 #7dd1e2;
+ }
+ }
+
+ @-moz-keyframes saveButtonGlow {
+ from {
+ -moz-box-shadow: inset 0 0 0 #7dd1e2;
+ }
+
+ 50% {
+ -moz-box-shadow: inset 0 0 15px #7dd1e2;
+ }
+
+ to {
+ -moz-box-shadow: inset 0 0 0 #7dd1e2;
+ }
+ }
+
+ @keyframes saveButtonGlow {
+ from {
+ box-shadow: inset 0 0 0 #7dd1e2;
+ }
+
+ 50% {
+ box-shadow: inset 0 0 15px #7dd1e2;
+ }
+
+ to {
+ box-shadow: inset 0 0 0 #7dd1e2;
+ }
+ }
+
+/* End Save Buttons */
+
+
+/* iframe */
+div#iframe-container {
+ width: auto;
+ height: auto;
+ top: @menu_height;
+ bottom: 260px;
+ left: 0;
+ right: 0;
+ padding: 0;
+ margin: 0;
+ overflow: hidden;
+ position: fixed;
+ z-index: 4;
+ opacity: 1;
+ background: url(%VISUALEDITOR%/images/grid-mode-bg.png) repeat top center #4c4c4c;
+}
+
+ body.ipad div#iframe-container {
+ -webkit-overflow-scrolling: touch;
+ overflow: auto;
+ }
+
+iframe.content {
+ /* Force hardware accelerated scrolling */
+ -webkit-transform: translateZ(0);
+ -moz-transform: translateZ(0);
+ -ms-transform: translateZ(0);
+ transform: translateZ(0);
+
+ width: 100%;
+ height: 100%;
+ margin: 0 0 -5px; /* Used to fix mysterious margin at bottom of wrapper inside iframe container */
+}
+
+ body.ipad iframe.content {
+ overflow: hidden;
+ }
+
+ div#iframe-overlay {
+ display: none;
+ position: absolute;
+ width: 100%;
+ height: 100%;
+ z-index: 4;
+ top: 0;
+ left: 0;
+ }
+
+ div#iframe-loading-overlay {
+ position: absolute;
+ z-index: 4;
+ background: url(%VISUALEDITOR%/images/grid-mode-bg.png) repeat top center #4c4c4c;
+ width: 100%;
+ height: 100%;
+ top: 0;
+ display: block;
+ }
+
+ div#iframe-loading-overlay div.cog-container {
+ margin: 0;
+ }
+
+/* Panel */
+ div#panel {
+ width: auto;
+ min-width: 800px;
+ height: 220px;
+ padding: 40px 0 0;
+ position: fixed;
+ left: 0;
+ right: 0;
+ bottom: 0;
+ background: #eeeeee;
+ z-index: 7;
+ }
+
+ body.panel-empty {
+ div#panel {
+ display: none !important;
+ }
+
+ div#iframe-container {
+ bottom: 0 !important;
+ }
+ }
+
+ div#panel div.panel {
+ height: 100%;
+ width: 100%;
+ padding: 40px 0 0;
+ margin: -40px 0 0;
+ .border-box;
+ position: absolute;
+ }
+
+ /* Panel Top */
+ div#panel-top-container {
+ width: 100%;
+ height: 40px;
+ margin: -40px 0 0 0;
+ background: #222222;
+ float: left;
+ display: block;
+ position: relative;
+ overflow: hidden;
+ z-index: 2;
+ padding: 0;
+ .border-box;
+ }
+
+ ul#panel-top {
+ float: left;
+ }
+
+ /* Panel Top Resize Handle */
+ div#panel .ui-resizable-n {
+ top: -8px;
+ cursor: row-resize;
+ z-index: 10 !important;
+ }
+
+ body.panel-hidden .ui-resizable-n {
+ display: none !important;
+ }
+
+ /* Panel Top Tabs */
+ ul#panel-top li {
+ margin: 0;
+ float: left;
+
+ &:first-child a {
+ border-left: 0;
+ }
+ }
+
+ ul#panel-top li a {
+ text-decoration: none;
+ color: #fff;
+ font-size: 14px;
+ padding: 0 15px;
+ height: 40px;
+ line-height: 40px;
+ display: block;
+ margin: 0;
+ }
+
+ ul#panel-top li a:hover {
+ color: #ddd;
+ }
+
+ ul#panel-top li span.block-type-icon {
+ text-indent: -9999px;
+ width: 16px;
+ height: 100%;
+ opacity: .7;
+ background-image: url(%VISUALEDITOR%/images/default-block-icon.png);
+ background-repeat: no-repeat;
+ background-position: 0 50%;
+ margin: 0 7px 0 -3px;
+ float: left;
+ }
+
+ ul#panel-top li span.close {
+ display: none;
+ position: absolute;
+ top: 5px;
+ right: 5px;
+ text-indent: -9999px;
+ width: 10px;
+ height: 10px;
+ cursor: pointer;
+ color: rgba(255, 255, 255, .5);
+ .transition('color 100ms linear');
+ }
+
+ ul#panel-top li span.close:before {
+ .icon-font;
+ content: 'X';
+ font-size: 11px;
+ float: left;
+ }
+
+ ul#panel-top li span.close:hover { color: rgba(255, 255, 255, .95); }
+
+ ul#panel-top li:hover span.close {
+ display: block;
+ }
+
+ ul#panel-top li:hover a {
+ color: #ddd;
+ }
+
+ ul#panel-top li.ui-corner-top {
+ position: relative;
+ }
+
+ ul#panel-top li.ui-state-active a {
+ background: #0074a2;
+ }
+
+ ul#panel-top li.ui-state-active span.close {
+ display: block;
+ }
+
+ /* Minimize */
+ ul#panel-top-right li#minimize {
+ float: right;
+ cursor: pointer;
+ padding: 0 15px;
+ }
+
+ ul#panel-top-right li#minimize span {
+ font-family: "headway-ve";
+ color: #777;
+ font-size: 18px;
+ line-height: 40px;
+ text-align: center;
+
+ &:hover {
+ color: #999;
+ }
+ }
+
+ ul#panel-top-right li#minimize:hover span {
+ color: #999;
+ }
+
+ /* Visual Editor Panel Sub Tabs */
+ div.sub-tabs-content-container {
+ overflow-x: hidden;
+ overflow-y: auto;
+ height: 100%;
+ }
+
+ ul.sub-tabs {
+ background: #e0e0e0;
+ box-shadow: -1px 0 0 0 #ccc inset;
+ float: left;
+ width: 220px;
+ height: 100%;
+ position: relative;
+ overflow-y: auto;
+ overflow-x: hidden;
+ }
+
+ ul.sub-tabs li {
+ text-decoration: none;
+ color: #555;
+ display: block;
+ font-size: 13px;
+ line-height: 16px;
+ cursor: pointer;
+ border-bottom: 1px solid #ccc;
+ }
+
+ ul.sub-tabs li > a, ul.sub-tabs li > span {
+ text-decoration: inherit;
+ color: inherit;
+ display: block;
+ font-size: inherit;
+ line-height: inherit;
+ padding: 10px 12px;
+ position: relative;
+ z-index: 2;
+ }
+
+ ul.sub-tabs li:hover:not(.ui-state-active) {
+ color: #2EA2CC;
+ }
+
+ ul.sub-tabs li.ui-state-active {
+ background: #EEE;
+ border-right: none;
+ }
+
+ /* Visual Editor Sub Tab Notice */
+ div.sub-tab-notice {
+ margin-bottom: 20px;
+ padding: 9px 10px;
+ width: 100%;
+ font-size: 13px;
+ line-height: 18px;
+ .border-box;
+
+ background-color: #FFF;
+ border-left: 4px solid #FFBA00;
+ -webkit-box-shadow: 0px 1px 1px 0px rgba(0, 0, 0, 0.1);
+ box-shadow: 0px 1px 1px 0px rgba(0, 0, 0, 0.1);
+
+ p {
+ margin: 9px 0;
+
+ &:first-child {
+ margin-top: 0;
+ }
+
+ &:last-child {
+ margin-bottom: 0;
+ }
+ }
+
+ strong {
+ font-weight: bold;
+ }
+
+ em {
+ font-style: italic;
+ }
+
+ a {
+ color: #171717;
+
+ &:hover {
+ text-decoration: none;
+ }
+ }
+ }
+
+ /* Visual Editor Panel Sub Tabs Content */
+ div.sub-tabs-content {
+ padding: 20px;
+ margin: 0;
+ height: 100%;
+ .border-box;
+ }
+
+ /* Visual Editor Sub Tabs Content Input Tooltips */
+ div.sub-tabs-content div.tooltip-button {
+ width: 17px;
+ height: 16px;
+ display: block;
+ cursor: pointer;
+ float: left;
+ margin: 4px 2px 0 4px;
+ color: #383838;
+ .transition('color 150ms linear');
+ }
+
+ div.sub-tabs-content div.tooltip-button:before {
+ .icon-font;
+ font-size: 18px;
+ font-family: 'dashicons';
+ content: "\f223";
+ }
+
+ div.sub-tabs-content div.tooltip-button:hover {
+ color: #555;
+ }
+
+
+/* Block Type Selector */
+ div.block-type-selector {
+ padding: 7px;
+ overflow: scroll;
+ height: 100%;
+ .border-box;
+
+ div.block-type {
+ cursor: pointer;
+ float: left;
+ width: 220px;
+ padding: 12px;
+ margin: 7px;
+ overflow-x: hidden;
+ overflow-y: hidden;
+ .rounded-corners(3px);
+
+ color: #555;
+ border: 1px solid #CCC;
+ background: #F7F7F7;
+ -webkit-box-shadow: inset 0 1px 0 #FFF, 0 1px 0 rgba(0, 0, 0, 0.08);
+ box-shadow: inset 0 1px 0 #FFF, 0 1px 0 rgba(0, 0, 0, 0.08);
+
+ &:hover {
+ background: #FAFAFA;
+ border-color: #999;
+ color: #222;
+ }
+
+ &:active {
+ background: #EEE;
+ border-color: #999;
+ color: #333;
+ -webkit-box-shadow: inset 0 2px 5px -3px rgba(0, 0, 0, 0.5);
+ box-shadow: inset 0 2px 5px -3px rgba(0, 0, 0, 0.5);
+ padding-top: 13px;
+ padding-bottom: 11px;
+ }
+
+ &.block-type-hidden {
+ display: none;
+ }
+
+ h4 {
+ padding: 0 0 0 24px;
+ height: 18px;
+ line-height: 19px;
+ display: block;
+ background-repeat: no-repeat;
+ font-weight: 500;
+ background-position: 0 50%;
+ font-size: 14px;
+ }
+
+ .block-type-description {
+ margin: 15px 0 0;
+ display: none;
+ line-height: 16px;
+ font-size: 11px;
+
+ p {
+ font-size: inherit;
+ }
+ }
+
+ }
+ }
+/* End Block Type Selector */
+
+
+/* Boxes */
+div.box {
+ border: 1px solid #E5E5E5;
+ box-shadow: 0 1px 5px rgba(0, 0, 0, 0.25);
+ background: #fff;
+ position: fixed !important;
+ display: none;
+ z-index: 16;
+ overflow: hidden;
+}
+
+ /* Loading Cog */
+ div.box div.cog-container {
+ margin-top: 15px;
+ }
+
+ /* Titles */
+ div.box-top {
+ border-bottom: 1px solid #EEE;
+ height: 40px;
+ line-height: 40px;
+ padding: 0 20px;
+ width: 100%;
+ display: block;
+ position: relative;
+ z-index: 2;
+ float: left;
+ font-size: 14px;
+ .border-box;
+ }
+
+ div.box-top > strong {
+ font-weight: bold;
+ color: #222;
+ float: left;
+ }
+
+ div.box-top > span {
+ font-style: italic;
+ color: #777;
+ float: left;
+ margin-left: 10px;
+ }
+
+ div.box-top > span strong {
+ font-weight: bold;
+ }
+
+ div.box-top span.box-close {
+ float: right;
+ display: block;
+ cursor: pointer;
+ opacity: .35;
+ .transition('color 150ms linear');
+ margin: 0 -10px 0 0;
+
+ color: #555;
+ font-family: "headway-ve";
+ font-size: 22px;
+ font-style: normal;
+ }
+
+ div.box-top span.box-close:hover { opacity: .7; }
+
+ /* Content */
+ div.box-content {
+ padding: 55px 15px 15px;
+ .border-box;
+ width: 100%;
+ height: 100%;
+ }
+
+ div.box-content-with-iframe {
+ padding: 40px 0 0;
+ }
+
+ div.box-content iframe {
+ width: 100%;
+ height: 100%;
+ }
+
+ div.box-content-bg {
+ height: 100%;
+ }
+
+ /* Tabs */
+ div.box ul.tabs {
+ margin: -15px 20px 0 -15px;
+ background: #eee;
+ padding: 0 0 30px;
+ width: 150px;
+ height: 100%;
+ display: block;
+ float: left;
+ }
+
+ div.box ul.tabs li a {
+ padding: 12px;
+ font-size: 12px;
+ display: block;
+ text-decoration: none;
+ color: #555;
+ }
+
+ div.box ul.tabs li:not(.ui-tabs-active) a:hover {
+ color: #2EA2CC;
+ }
+
+ div.box ul.tabs li.ui-tabs-active a {
+ background: #fff;
+ }
+
+
+/* Live CSS Box */
+textarea#live-css {
+ .border-box;
+ width: 100%;
+ height: 100%;
+ padding: 10px;
+ font-family: monospace;
+ border: 2px solid #BBB;
+ resize: none;
+ font-size: 13px;
+ line-height: 16px;
+}
+
+/* Snapshots */
+div#box-snapshots {
+ span.button-blue, .spinner {
+ float: left;
+ }
+
+ #snapshots-list {
+ clear: both;
+ float: left;
+ width: 100%;
+ height: 385px;
+ overflow-y: scroll;
+
+ margin: 10px -15px 0;
+ padding: 10px 15px 15px;
+
+ -webkit-mask: -webkit-linear-gradient(top, transparent, black 25px);
+ }
+
+ #snapshots-list > li {
+ border-top: 1px solid #EEE;
+ width: 100%;
+ float: left;
+
+ .snapshot-timestamp {
+ height: 30px;
+ line-height: 30px;
+ display: inline-block;
+ float: left;
+ }
+
+ .snapshot-comments {
+ margin: 0 0 7px;
+ color: #999;
+ clear: both;
+ }
+
+ .button {
+ display: none;
+ float: right;
+ margin-top: 5px;
+ margin-right: 4px;
+ }
+
+ .snapshot-delete {
+ text-indent: -9999px;
+ display: none;
+ cursor: pointer;
+ width: 15px;
+ height: 14px;
+ margin: 7px 0 -3px 6px;
+ color: rgba(0, 0, 0, .35);
+ float: left;
+
+ &:before {
+ .icon-font;
+ content: '\58';
+ line-height: 16px;
+ float: left;
+ }
+
+ &:hover {
+ color: rgba(0, 0, 0, .85);
+ }
+ }
+
+ &:hover {
+ .button, .snapshot-delete {
+ display: block;
+ }
+ }
+ }
+}
+
+/* Grid Wizard */
+div#box-grid-wizard {
+ margin: -220px 0 0 -300px;
+ top: 50%;
+ left: 50%;
+}
+
+ div#box-grid-wizard div.tab-content {
+ float: left;
+ width: 415px;
+ height: 350px;
+ position: absolute;
+ left: 170px;
+ }
+
+ div.grid-wizard-buttons {
+ display: block;
+ clear: both;
+ float: left;
+ margin: 10px 0 0;
+ width: 410px;
+ height: 39px;
+ padding: 6px 8px;
+ .border-box;
+
+ border: 1px solid #E5E5E5;
+ -webkit-box-shadow: 0 1px 1px rgba(0, 0, 0, 0.04);
+ box-shadow: 0 1px 1px rgba(0, 0, 0, 0.04);
+ background: #fff;
+
+ position: absolute;
+ bottom: 2px;
+ }
+
+ div.grid-wizard-buttons span.grid-wizard-use-empty-grid {
+ color: #888;
+ text-decoration: underline;
+ line-height: 25px;
+ display: block;
+ width: auto;
+ float: left;
+ margin: 0 0 0 3px;
+ cursor: pointer;
+ }
+
+ div.grid-wizard-buttons span.grid-wizard-use-empty-grid:hover {
+ text-decoration: none;
+ }
+
+ div.grid-wizard-buttons span.grid-wizard-button-next {
+ float: right;
+ }
+
+ div.grid-wizard-buttons span.grid-wizard-button-previous {
+ float: right;
+ margin: 0 5px 0 0;
+ }
+
+ div.grid-wizard-buttons span.grid-wizard-button-clone-page {
+ width: 80px;
+ }
+
+ div#box-grid-wizard div.box-content h4 {
+ font-size: 14px;
+ font-weight: 500;
+ color: #222;
+ margin: 0 0 10px;
+ }
+
+ div#box-grid-wizard .grid-wizard-info {
+ margin: 10px 0 0;
+ padding: 9px 10px;
+ width: 100%;
+ font-size: 12px;
+ line-height: 16px;
+ .border-box;
+
+ background-color: #FFF;
+ border-left: 4px solid #FFBA00;
+ -webkit-box-shadow: 0 0 1px 1px rgba(0, 0, 0, 0.1);
+ box-shadow: 0 0 1px 1px rgba(0, 0, 0, 0.1);
+
+ float: left;
+ clear: both;
+ }
+
+
+ /* Import/Export */
+ div#box-grid-wizard div.box-content .grid-wizard-import-export-group {
+ position: static;
+ padding: 15px;
+ height: auto;
+ margin: 6px 0 15px;
+
+ .button {
+ margin: 0;
+ }
+
+ input[type="file"] {
+ position: absolute;
+ opacity: 0;
+ }
+
+ p {
+ color: #555;
+ margin: 11px 0;
+ line-height: 150%;
+ font-size: 12px;
+ border-top: 1px solid #eee;
+ padding: 11px 0 0;
+
+ strong {
+ font-weight: bold;
+ }
+ }
+ }
+ /* End Import/Export */
+
+
+ /* Cloning */
+ #grid-wizard-tab-clone-page h4 {
+ clear: both;
+ }
+ /* End Cloning */
+
+ /* Grid Wizard Presets */
+ div#box-grid-wizard span.layout-preset {
+ margin: 7px 14px 15px 7px;
+ float: left;
+ background: #fff;
+ padding: 5px 5px 4px;
+ .rounded-corners(4px);
+ border: 1px solid #BBB;
+ opacity: .3;
+ cursor: pointer;
+
+ width: 105px;
+ height: 105px;
+
+ .transition('opacity 0.075s linear');
+ }
+
+ div#box-grid-wizard span.layout-preset-selected, div#box-grid-wizard span.layout-preset:hover {
+ opacity: .9;
+ }
+
+ div#box-grid-wizard span.layout-preset img {
+ opacity: .8;
+ width: 105px;
+ height: 105px;
+ }
+
+ /* Step 2 */
+ div#grid-wizard-presets-step-2 {
+ display: none;
+ }
+
+ div#grid-wizard-presets-step-2 h5 {
+ font-size: 13px;
+ font-weight: 300;
+ color: #444;
+ margin: 0 0 4px 1px;
+ }
+
+ div#grid-wizard-presets-step-2 div.select-container select {
+ width: 180px;
+ }
+
+ div.grid-wizard-presets-mirroring-column {
+ margin: 20px 0 0 0;
+ width: 195px;
+ float: left;
+ }
+
+ div.grid-wizard-presets-mirroring-column div {
+ margin: 0 0 15px 0;
+ }
+
+ div#grid-wizard-presets-mirroring-column-1 {
+ margin-right: 20px;
+ }
+ /* End Grid Wizard Presets */
+
+/* End Grid Wizard */
+
+
+
+/* Black Overlay */
+div.black-overlay {
+ position: fixed;
+ width: 100%;
+ height: 100%;
+ display: none;
+ z-index: 14;
+ background: rgba(0, 0, 0, .6);
+}
+
+/* Notifications */
+div#notification-center {
+ position: fixed;
+ top: 70px;
+ right: 20px;
+ z-index: 14;
+}
+
+div.notification {
+ float: right;
+ clear: right;
+ color: #444;
+ min-height: 20px;
+ line-height: 20px;
+ font-size: 13px;
+
+ background-color: #FFF;
+ border-left: 4px solid #ffba00;
+
+ -moz-box-shadow: 0px 2px 8px 0px rgba(0, 0, 0, 0.12), 0px 0px 1px 1px rgba(0, 0, 0, 0.15);
+ -webkit-box-shadow: 0px 2px 8px 0px rgba(0, 0, 0, 0.12), 0px 0px 1px 1px rgba(0, 0, 0, 0.15);
+ box-shadow: 0px 2px 8px 0px rgba(0, 0, 0, 0.12), 0px 0px 1px 1px rgba(0, 0, 0, 0.15);
+
+ width: auto;
+ display: block;
+ padding: 9px 17px;
+ max-width: 280px;
+ .border-box;
+ margin: 0 0 10px;
+ position: relative;
+}
+
+ div.notification ul {
+ display: block;
+ list-style: disc;
+ float: left;
+ clear: both;
+ padding: 0 0 0 20px;
+ }
+
+ div.notification ul li {
+ margin: 5px 0 0;
+ }
+
+ div.notification-closable {
+ padding: 9px 35px 9px 17px;
+ }
+
+ div.notification p {
+ display: inline-block;
+ float: left;
+ }
+
+ div.notification strong {
+ font-weight: bold;
+ }
+
+ div.notification em {
+ font-style: italic;
+ }
+
+ div.notification a {
+ color: inherit;
+ }
+
+ div.notification span.close {
+ display: block;
+ width: 15px;
+ height: 14px;
+ text-indent: -9999px;
+ cursor: pointer;
+ color: #d8d8d8;
+ position: absolute;
+ top: 11px;
+ right: 10px;
+ .transition('color 50ms linear');
+ }
+
+ div.notification span.close:before {
+ .icon-font;
+ content: '\58';
+ font-size: 17px;
+ line-height: 17px;
+ float: left;
+ }
+
+ div.notification span.close:hover {
+ color: #707070;
+ }
+
+div.notification-error {
+ border-left: 4px solid #DD3D36;
+}
+
+div.notification-success {
+ border-left: 4px solid #7AD03A;
+}
+
+
+/* Tour */
+ /* Tour Tooltips */
+ .qtip-tour {
+ box-shadow: 0 3px 10px rgba(0, 0, 0, 0.3);
+ .rounded-corners(2px);
+ max-width: 350px;
+ }
+
+ .qtip-tour .qtip-content {
+ padding: 15px 15px 60px; /* Bottom padding for button container */
+ position: relative;
+ font-size: 13px;
+ background: #FFF;
+ border: 1px solid #DFDFDF;
+ -webkit-box-shadow: 0 3px 6px rgba(0, 0, 0, 0.075);
+ box-shadow: 0 3px 6px rgba(0, 0, 0, 0.075);
+ }
+
+ .qtip-tour .qtip-content * {
+ font-size: inherit;
+ }
+
+ .qtip-tour .qtip-content p,
+ .qtip-tour .qtip-content ul {
+ line-height: 18px;
+ font-size: 13px;
+ margin: 0 0 13px;
+ color: #555;
+ .antialias();
+ }
+
+ .qtip-tour .qtip-content ul li {
+ margin: 0 0 4px;
+ }
+
+ .qtip-tour .qtip-content a {
+ color: #DC511E;
+ }
+
+ .qtip-tour .qtip-content a:hover {
+ text-decoration: none;
+ }
+
+ .qtip-tour .qtip-titlebar {
+ position: relative;
+ margin: -1px -1px 0;
+ padding: 15px 18px 14px 20px;
+ border: 1px solid #3592B6;
+ border-bottom: none;
+ line-height: 19px;
+ font-size: 14px;
+ color: #FFF;
+ background: #2EA2CC;
+ }
+
+ .qtip-tour .qtip-tip {
+ background-color: #2ea2cc;
+ }
+
+ .qtip-tour .qtip-titlebar .qtip-icon {
+ border: none;
+ right: 11px;
+ width: 18px;
+ top: 15px;
+ position: absolute;
+ height: 14px;
+ display: block;
+ cursor: pointer;
+ }
+
+ .qtip-tour .qtip-titlebar .qtip-icon .ui-icon-close {
+ color: rgba(255, 255, 255, .6);
+ text-indent: -9999px;
+ .transition('color 150ms linear');
+ }
+
+
+ .qtip-tour .qtip-titlebar .qtip-icon .ui-icon-close:before {
+ .icon-font;
+ float: left;
+ font-size: 18px;
+
+ content: '\58';
+ }
+
+ .qtip-tour .qtip-titlebar .qtip-icon .ui-icon-close:hover {
+ color: rgba(255, 255, 255, .85);
+ }
+
+ .qtip-tour .qtip-titlebar .ui-state-hover {
+ border-color: #AAA;
+ color: #111;
+ }
+
+ /* Tour Button */
+ div#tour-next-container {
+ width: 100%;
+ height: 45px;
+ position: absolute;
+ bottom: 0;
+ left: 0;
+ background: #eee;
+ border-top: 1px solid #ddd;
+ .rounded-corners(0 0 3px 3px);
+ .border-box();
+ padding: 9px;
+
+ span.tour-button {
+ position: relative;
+ padding-right: 24px;
+ float: right;
+
+ span.arrow {
+ display: inline-block;
+ margin: 0;
+ position: absolute;
+ top: -1px;
+ right: 10px;
+ font-size: 20px;
+ font-weight: 300;
+ color: rgba(255, 255, 255, .5);
+ }
+ }
+
+ p {
+ font-style: italic;
+ color: #888;
+ line-height: 25px;
+ text-align: center;
+ font-size: 11px;
+ margin: 0 10px;
+ }
+ }
+
+/* Context Menu */
+ ul.context-menu {
+ position: absolute;
+ top: -99999px;
+ left: -99999px;
+ z-index: 99999;
+ background: #333;
+ width: 200px;
+ font-size: 13px;
+ color: #fff;
+ box-shadow: 0 0 10px 0 rgba(0, 0, 0, .35);
+ }
+
+ ul.context-menu h3 {
+ padding: 8px;
+ background: #222;
+ border-radius: 5px 5px 0 0;
+ font-weight: 300;
+ color: #eee;
+ font-size: 12px;
+ overflow: hidden;
+ white-space: nowrap;
+ height: 14px;
+ line-height: 14px;
+ border-bottom: 1px solid #2e2e2e;
+ box-shadow: 0 -2px 4px rgba(0,0,0,0.1) inset;
+ }
+
+ ul.context-menu li {
+ position: relative;
+ }
+
+ ul.context-menu li span, ul.context-menu span.group-title {
+ padding: 8px 12px;
+ .border-box;
+
+ height: 30px;
+ line-height: 14px;
+ font-size: 13px;
+
+ display: inline-block;
+ width: 100%;
+ cursor: pointer;
+ }
+
+ ul.context-menu li span small {
+ display: block;
+ margin: 2px 0 0;
+ font-size: 85%;
+ color: #888;
+ }
+
+ ul.context-menu li:hover > span {
+ background-color: #0074a2;
+ color: #fff;
+ }
+
+ ul.context-menu span.group-title {
+ cursor: default;
+ color: #aaa;
+ height: auto;
+
+ &.group-title-clickable {
+ cursor: pointer;
+ }
+ }
+
+ ul.context-menu span.group-title:not(.group-title-no-dropdown)::after {
+ height: 8px;
+ font-family: 'headway-ve';
+ font-style: normal;
+ font-weight: normal;
+ speak: none;
+ display: inline-block;
+ text-decoration: inherit;
+ width: auto;
+ text-indent: 0;
+ font-size: 13px;
+ content: '\69';
+ color: #767676;
+ line-height: 12px;
+ position: absolute;
+ right: 12px;
+ top: 50%;
+ margin: -6px 0 0;
+ }
+
+ /* No dropdown groups */
+ ul.context-menu li.indent span {
+ padding-left: 24px;
+ }
+
+ ul.context-menu li:hover > span.group-title-no-dropdown {
+ background: inherit;
+ }
+
+ ul.context-menu ul {
+ display: none;
+ }
+
+ ul.context-menu li:hover > ul {
+ display: block;
+ position: absolute;
+ left: 200px;
+ top: 0;
+ background: #444;
+ box-shadow: 0 0 10px 0 rgba(0, 0, 0, .35);
+ width: 200px;
+ }
+
+ /* Design Editor Inspector */
+ #qtip-inspector {
+ white-space: nowrap;
+ }
+
+
+ /* Icons */
+ #context-menu-block li span:before,
+ #context-menu-wrapper li span:before,
+ li.inspector-context-menu-block-options span:before {
+ font-size: 15px;
+ .icon-font;
+ opacity: .35;
+ margin: 0 4px 0 -4px;
+ width: 20px;
+ text-align: center;
+ }
+
+ /* Set Alias */
+ #context-menu-block, #context-menu-wrapper {
+ li.context-menu-set-alias span:before {
+ font-family: 'dashicons';
+ content: "\f348";
+ }
+ }
+
+ /* Block Context Menu */
+ /* Heading */
+ #context-menu-block span.type {
+ height: 22px;
+ width: 20px;
+ display: inline-block;
+ background-image: url(%VISUALEDITOR%/images/default-block-icon.png);
+ background-repeat: no-repeat;
+ background-position: 0 50%;
+ float: left;
+ margin: -4px 3px 0 0;
+ }
+ /* Block Options */
+ li.context-menu-block-options span:before,
+ li.inspector-context-menu-block-options span:before {
+ content: '0';
+ }
+
+ /* Switch Type */
+ #context-menu-block li.context-menu-block-switch-type span:before {
+ content: '\72';
+ }
+
+
+ /* Unmirror Block */
+ #context-menu-block li.context-menu-block-unmirror span:before {
+ font-family: 'dashicons';
+ content: "\f225";
+ }
+
+ /* Delete Block */
+ #context-menu-block li.context-menu-block-delete span:before {
+ content: "\70";
+ }
+
+ /* Wrapper Context Menu */
+ /* Wrapper Options */
+ #context-menu-wrapper li.context-menu-wrapper-options span:before {
+ content: '0';
+ }
+
+
+ /* Wrapper Fluid/Fixed */
+ #context-menu-wrapper li.context-menu-wrapper-to-fixed span:before,
+ #context-menu-wrapper li.context-menu-wrapper-to-fluid span:before {
+ font-family: 'dashicons';
+ content: "\f169";
+ }
+
+ /* Grid Fluid/Fixed */
+ #context-menu-wrapper li.context-menu-wrapper-grid-to-fixed span:before,
+ #context-menu-wrapper li.context-menu-wrapper-grid-to-fluid span:before {
+ font-family: 'dashicons';
+ content: "\f180";
+ }
+
+
+ /* Delete Wrapper */
+ #context-menu-wrapper li.context-menu-wrapper-delete span:before {
+ content: "\70";
+ }
\ No newline at end of file
--- /dev/null
+<?php
+class HeadwayVisualEditorDisplay {
+
+
+ public static function init() {
+
+ //Load boxes
+ Headway::load('api/api-box');
+
+ require_once HEADWAY_LIBRARY_DIR . '/visual-editor/boxes/grid-wizard.php';
+ require_once HEADWAY_LIBRARY_DIR . '/visual-editor/boxes/snapshots.php';
+
+ //Load panels
+ if ( current_theme_supports('headway-grid') ) {
+ require_once HEADWAY_LIBRARY_DIR . '/visual-editor/panels/grid/setup.php';
+ }
+
+ if ( current_theme_supports('headway-design-editor') ) {
+ Headway::load('visual-editor/panels/design/side-panel-design-editor', 'SidePanelDesignEditor');
+ }
+
+ //Put in action so we can run top level functions
+ do_action('headway_visual_editor_display_init');
+
+ //System for scripts/styles
+ add_action('headway_visual_editor_head', array(__CLASS__, 'print_scripts'), 12);
+ add_action('headway_visual_editor_head', array(__CLASS__, 'print_styles'), 12);
+
+ //Enqueue Styles
+ remove_all_actions('wp_print_styles'); /* Removes bad plugin CSS */
+ add_action('headway_visual_editor_styles', array(__CLASS__, 'enqueue_styles'));
+ add_action('headway_visual_editor_head', array(__CLASS__, 'output_inline_loading_css'), 10);
+
+ //Enqueue Scripts
+ remove_all_actions('wp_print_scripts'); /* Removes bad plugin JS */
+
+ add_filter('clean_url', array(__CLASS__, 'require_js_attr' ), 10, 3 );
+ add_action('headway_visual_editor_scripts', array(__CLASS__, 'require_js'));
+
+ //Localize Scripts
+ add_action('headway_visual_editor_scripts', array(__CLASS__, 'add_visual_editor_js_vars'));
+
+ //Content
+ add_action('headway_visual_editor_menu', array(__CLASS__, 'layout_selector'));
+ add_action('headway_visual_editor_modes', array(__CLASS__, 'mode_navigation'));
+ add_action('headway_visual_editor_menu_links', array(__CLASS__, 'menu_links'));
+ add_action('headway_visual_editor_footer', array(__CLASS__, 'block_type_selector'));
+
+ add_action('headway_visual_editor_panel_top_right', array(__CLASS__, 'panel_top_right'), 12);
+ add_action('headway_visual_editor_menu_mode_buttons', array(__CLASS__, 'menu_mode_buttons'));
+
+ //Prevent any type of caching on this page
+ if ( !defined('DONOTCACHEPAGE') ) {
+ define('DONOTCACHEPAGE', true);
+ }
+
+ if ( !defined('DONOTMINIFY') ) {
+ define('DONOTMINIFY', true);
+ }
+
+ }
+
+
+ public static function display() {
+
+ do_action('headway_visual_editor_display');
+
+ require_once HEADWAY_LIBRARY_DIR . '/visual-editor/template.php';
+
+ }
+
+
+ public static function require_js() {
+
+ $script_folder = (defined('SCRIPT_DEBUG') && SCRIPT_DEBUG) ? 'scripts' : 'scripts-min';
+
+ wp_enqueue_script('headway-editor', headway_url() . '/library/visual-editor/' . $script_folder . '/deps/require-and-jquery.js');
+
+ }
+
+
+ public static function require_js_attr($good_protocol_url, $original_url, $_context) {
+
+ $script_folder = ( defined( 'SCRIPT_DEBUG' ) && SCRIPT_DEBUG ) ? 'scripts' : 'scripts-min';
+
+ if ( false !== strpos( $original_url, 'require-and-jquery.js' ) ) {
+
+ return $good_protocol_url . "' id='headway-editor' data-main='" . headway_url() . "/library/visual-editor/" . $script_folder . "/app.js";
+
+ } else if ( false !== strpos( $original_url, 'js' ) ) {
+
+ return $good_protocol_url . "' async='true";
+
+ }
+
+ return $good_protocol_url;
+
+ }
+
+
+ public static function enqueue_styles() {
+
+ HeadwayCompiler::register_file(array(
+ 'name' => 've',
+ 'format' => 'less',
+ 'fragments' => apply_filters('headway_visual_editor_css', array(
+ HEADWAY_LIBRARY_DIR . '/visual-editor/css/editor-mixins.less',
+ HEADWAY_LIBRARY_DIR . '/visual-editor/css/editor-tooltips.less',
+ HEADWAY_LIBRARY_DIR . '/visual-editor/css/editor.less',
+ HEADWAY_LIBRARY_DIR . '/visual-editor/css/editor-layout-selector.less',
+ HEADWAY_LIBRARY_DIR . '/visual-editor/css/editor-inputs.less',
+ HEADWAY_LIBRARY_DIR . '/visual-editor/css/editor-design.less'
+ )),
+ 'require-hard-flush' => true,
+ 'enqueue' => false
+ ));
+
+ $styles = array(
+ 'reset' => headway_url() . '/library/media/css/reset.css',
+ 'open-sans',
+ 'dashicons',
+ 'headway_visual_editor' => HeadwayCompiler::get_url('ve')
+ );
+
+ wp_enqueue_multiple_styles($styles);
+
+ }
+
+
+ public static function output_inline_loading_css() {
+
+ $css = '';
+ $path = HEADWAY_LIBRARY_DIR . '/visual-editor/css/editor-loading.css';
+
+ /* Insure file exists */
+ if ( !file_exists($path) )
+ return false;
+
+ /* Load in editor-loading.css */
+ $temp_handler = fopen($path, 'r');
+ $css .= fread($temp_handler, filesize($path));
+ fclose($temp_handler);
+
+ /* Echo content */
+ echo "\n" . '<style type="text/css">' . HeadwayCompiler::strip_whitespace($css) . '</style>' . "\n\n";
+
+ }
+
+
+ public static function print_scripts() {
+
+ /* Remove all other enqueued scripts from plugins that don't use 'headway_visual_editor_scripts' to reduce conflicts */
+ global $wp_scripts;
+ $wp_scripts = null;
+ remove_all_actions('wp_print_scripts');
+
+ echo "\n<!-- Scripts -->\n";
+
+ do_action('headway_visual_editor_scripts');
+
+ wp_print_scripts();
+
+ echo "\n<!-- End Scripts -->\n";
+
+ }
+
+
+ public static function print_styles() {
+
+ /* Remove all other enqueued styles from plugins that don't use 'headway_visual_editor_styles' to reduce conflicts */
+ global $wp_styles;
+ $wp_styles = null;
+ remove_all_actions('wp_print_styles');
+
+ echo "\n<!-- Styles -->\n";
+
+ do_action('headway_visual_editor_styles');
+
+ wp_print_styles();
+
+ echo "\n<!-- End Styles -->\n";
+
+ }
+
+
+ public static function add_visual_editor_js_vars() {
+
+ global $wp_scripts;
+
+ //Gather the URLs for the block types
+ $block_types = HeadwayBlocks::get_block_types();
+ $block_type_urls = array();
+
+ foreach ( $block_types as $block_type => $block_type_options )
+ $block_type_urls[$block_type] = $block_type_options['url'];
+
+ $current_layout_status = HeadwayLayout::get_status(HeadwayLayout::get_current());
+
+ wp_localize_script('headway-editor', 'Headway', array(
+ 'ajaxURL' => admin_url('admin-ajax.php'),
+ 'security' => wp_create_nonce('headway-visual-editor-ajax'),
+
+ 'currentLayout' => HeadwayLayout::get_current(),
+ 'currentLayoutName' => HeadwayLayout::get_name(HeadwayLayout::get_current()),
+ 'currentLayoutCustomized' => $current_layout_status['customized'],
+ 'currentLayoutTemplate' => $current_layout_status['template'],
+ 'currentLayoutTemplateName' => HeadwayLayout::get_name('template-' . $current_layout_status['template']),
+
+ 'siteName' => get_bloginfo('name'),
+ 'siteDescription' => get_bloginfo('description'),
+ 'headwayURL' => get_template_directory_uri(),
+ 'scriptFolder' => ( defined( 'SCRIPT_DEBUG' ) && SCRIPT_DEBUG ) ? 'scripts' : 'scripts-min',
+ 'siteURL' => site_url(),
+ 'homeURL' => home_url(),
+ 'adminURL' => admin_url(),
+ 'frontPage' => get_option('show_on_front', 'posts'),
+
+ 'mode' => HeadwayVisualEditor::get_current_mode(),
+ 'designEditorSupport' => current_theme_supports('headway-design-editor'),
+ 'gridSupported' => current_theme_supports('headway-grid'),
+
+ 'disableCodeMirror' => HeadwayOption::get('disable-codemirror', false, false),
+ 'disableTooltips' => HeadwayOption::get('disable-visual-editor-tooltips', false, false),
+
+ 'designEditorProperties' => HeadwayVisualEditor::is_mode('design') ? json_encode(HeadwayElementProperties::get_properties()) : json_encode(array()),
+ 'colorpickerSwatches' => HeadwaySkinOption::get('colorpicker-swatches', false, array()),
+ 'gridSafeMode' => HeadwayOption::get('grid-safe-mode', false, false),
+
+ 'ranTour' => json_encode(array(
+ 'legacy' => HeadwayOption::get('ran-tour', false, false),
+ 'grid' => HeadwayOption::get('ran-tour-grid', false, false),
+ 'design' => HeadwayOption::get('ran-tour-design', false, false)
+ )),
+
+ 'blockTypeURLs' => json_encode($block_type_urls),
+ 'allBlockTypes' => json_encode($block_types),
+
+ 'defaultGridColumnCount' => HeadwayWrappers::$default_columns,
+ 'globalGridColumnWidth' => HeadwayWrappers::$global_grid_column_width,
+ 'globalGridGutterWidth' => HeadwayWrappers::$global_grid_gutter_width,
+
+ 'responsiveGrid' => HeadwayResponsiveGrid::is_enabled(),
+
+ 'touch' => (stripos($_SERVER['HTTP_USER_AGENT'], 'iPad') !== false) ? true : false,
+
+ 'templates' => HeadwayTemplates::get_all(),
+ 'templateActive' => HeadwayTemplates::get_active(),
+
+ 'snapshots' => HeadwayDataSnapshots::list_snapshots(),
+
+ 'viewModels' => array()
+ ));
+
+ }
+
+
+ ////////////////// Content ///////////////////////
+
+
+ public static function panel_top_right() {
+
+ echo '<li id="minimize">
+ <span title="Minimize Panel <strong>Shortcut: Ctrl + P</strong>" class="tooltip-bottom-right">g</span>
+ </li>';
+
+ }
+
+
+ public static function menu_mode_buttons() {
+
+ switch ( HeadwayVisualEditor::get_current_mode() ) {
+
+ case 'design':
+
+ if ( current_theme_supports('headway-design-editor') ) {
+
+ $tooltip = '
+ <strong>Toggle Inspector</strong><br />
+ <em>Shortcut:</em> Ctrl + I<br /><br />
+ <strong>How to use:</strong> <em>Right-click</em> highlighted elements to style them. Once an element is selected, you may nudge it using your arrow keys.<br /><br />
+ The faded orange and purple are the margins and padding. These colors are only visible when the inspector is active.';
+
+ echo '<div class="menu-mode-buttons">';
+ echo '<span class="menu-mode-button tooltip-bottom-right" id="toggle-inspector" title="' . esc_attr($tooltip) . '"></span>';
+ echo '<span class="menu-mode-button tooltip-bottom-right" id="open-live-css" title="Open Live CSS Editor"></span>';
+ echo '</div><!-- .menu-mode-buttons -->';
+
+ }
+
+ break;
+
+ }
+
+ }
+
+
+ public static function block_type_selector() {
+
+ $block_types = HeadwayBlocks::get_block_types();
+
+ echo "\n". '<div class="block-type-selector block-type-selector-original" style="display: none;">' . "\n";
+
+ foreach ( $block_types as $block_type_id => $block_type ) {
+
+ echo '
+ <div id="block-type-' . $block_type_id . '" class="block-type" title="' . $block_type['description'] . '">
+ <h4 style="background-image: url(' . $block_type['url'] . '/icon.png);">' . $block_type['name'] . '</h4>
+
+ <div class="block-type-description">
+ <p>' . $block_type['description'] . '</p>
+ </div>
+ </div>
+ ';
+
+ }
+
+ echo '</div><!-- div.block-type-selector -->' . "\n\n";
+
+ }
+
+
+ public static function layout_selector() {
+
+ echo "\n" . '<div id="layout-selector-select">' . "\n";
+
+ echo '<div id="layout-selector-select-content"><span id="currently-editing">Currently Editing:</span><span id="current-layout">' . HeadwayLayout::get_current_name() . '</span> <span id="layout-selector-select-content-arrow"></span></div>' . "\n";
+
+ echo '<div id="layout-selector">' . "\n";
+
+ echo '<div id="layout-selector-tabs"><ul class="tabs">' . "\n";
+
+ echo '<li><a href="#layout-selector-pages-container">Pages</a></li>' . "\n";
+ echo '<li><a href="#layout-selector-templates-container">Shared Layouts</a></li>' . "\n";
+
+ echo '</ul></div><!-- #layout-selector-tabs -->' . "\n";
+
+
+ echo '<div id="layout-selector-pages-container">' . "\n";
+
+ echo '<div id="layout-selector-pages" class="layout-selector-content">' . "\n";
+ echo '</div><!-- div#layout-selector-pages -->' . "\n";
+
+ echo '</div><!-- #layout-selector-pages -->' . "\n";
+
+
+ echo '<div id="layout-selector-templates-container">' . "\n";
+
+ echo '<div id="layout-selector-templates" class="layout-selector-content">' . "\n";
+ echo '</div><!-- div#layout-selector-templates -->' . "\n";
+
+ echo '<div id="template-name-input-container">
+ <input type="text" placeholder="Shared Layout Name" value="" id="template-name-input" />
+ <span class="button add-template" id="add-template">Add Shared Layout</span>
+ </div>';
+
+ echo '</div><!-- #layout-selector-templates -->' . "\n";
+
+ echo '</div><!-- #layout-selector-container -->' . "\n";
+
+ echo '</div><!-- #layout-selector-select -->' . "\n";
+
+ }
+
+
+ public static function list_pages($pages = null) {
+
+ //Since this function is recursive, we must designate the default like this
+ if ( $pages === null ) {
+
+ $pages = HeadwayLayout::get_pages();
+ $root_pages = true;
+
+ }
+
+ $return = '';
+
+ $return .= '<ul>' . "\n";
+
+ /**
+ * Only show the message the function is being called for the first time (not showing children) and that the
+ * mode is NOT the grid and the grid is supported still.
+ **/
+ if ( isset($root_pages) && HeadwayVisualEditor::get_current_mode() !== 'grid' && current_theme_supports('headway-grid') ) {
+
+ $return .= '<li class="layout-item info-layout-item"><span class="layout"><strong>To add blocks to a new layout, please switch to the Grid mode.</strong></span></li>';
+
+ }
+
+ foreach ( $pages as $id => $children ) {
+
+ $layout_id_fragments = explode(HeadwayLayout::$sep, $id);
+
+ $status = HeadwayLayout::get_status($id, true);
+
+ $class = array('layout-item');
+
+ if ( is_array($children) && count($children) !== 0 )
+ $class[] = 'has-children';
+
+ if ( $status['customized'] === true && !$status['template'] && count(HeadwayBlocksData::get_blocks_by_layout($id)) > 0 )
+ $class[] = 'layout-item-customized';
+
+ if ( $status['template'] )
+ $class[] = 'layout-item-template-used';
+
+ if ( $id === headway_post('currentLayout') )
+ $class[] = 'layout-selected';
+
+ $template_id = ( $status['template'] ) ? 'template-' . $status['template'] : 'none';
+ $template_name = ( $status['template'] ) ? HeadwayLayout::get_name('template-' . $status['template']) : null;
+
+ /* Take care of layouts that are the front page or blog index */
+ if ( (get_option('show_on_front') === 'page' && (isset($layout_id_fragments[1]) && $layout_id_fragments[1] == 'page')) || apply_filters('headway_layout_selector_no_edit_item_' . $id, false) ) {
+
+ /* If the page is set as the static homepage or blog page, hide it if they don't have children. The Blog Index and Front Page layouts will override them. */
+ if ( end($layout_id_fragments) == get_option('page_on_front') || end($layout_id_fragments) == get_option('page_for_posts') || apply_filters('headway_layout_selector_no_edit_item_' . $id, false) ) {
+
+ /* Layout has children--add the no edit class and has children class. */
+ if ( is_array($children) && count($children) !== 0 ) {
+
+ $class[] = 'layout-item-no-edit';
+
+ /* If the layout doesn't have children, then just hide it. */
+ } else {
+
+ continue;
+
+ }
+
+ }
+
+ }
+
+ /* Add other classes */
+ if ( is_array($children) && count($children) && self::is_any_layout_child_customized($children) ) {
+ $class[] = 'has-children';
+ $class[] = 'has-customized-children';
+ }
+
+ /* Get post status */
+ $post_status = headway_get('post_status', $status);
+ $formatted_post_status = ($post_status && $post_status != 'Published') ? '<span class="status status-post-status">(' . $post_status . ')</span>' : null;
+
+ /* Output Stuff */
+ $return .= '<li class="' . implode(' ', array_filter($class)) . '">';
+
+ $return .= '<span class="layout-has-customized-children tooltip" title="This layout has customized children.">•</span>';
+
+ $return .= '<span data-layout-id="' . $id . '" data-layout-url="' . HeadwayLayout::get_url($id) . '" class="layout layout-page">';
+ $return .= '<strong>' . esc_html(HeadwayLayout::get_name($id)) . '</strong>';
+
+ $return .= $formatted_post_status;
+
+ $return .= '<span class="status status-template" data-template-id="' . $template_id . '">' . $template_name . '</span>';
+ $return .= '<span class="status status-customized">Customized</span>';
+ $return .= '<span class="status status-currently-editing">Currently Editing</span>';
+
+ $return .= '<span class="remove-template button layout-selector-button">Remove Shared Layout</span>';
+
+ if ( HeadwayVisualEditor::get_current_mode() !== 'design' )
+ $return .= '<span class="edit button button-blue layout-selector-button">Edit</span>';
+ else
+ $return .= '<span class="edit button button-blue layout-selector-button">View</span>';
+
+ $return .= '<span class="revert button layout-selector-button tooltip" title="Resetting a layout will remove all of its blocks<br />so it inherits the blocks of a parent layout.">Reset</span>';
+
+ $return .= '</span>' . "\n";
+
+ if ( is_array($children) && count($children) !== 0 )
+ $return .= self::list_pages($children);
+
+ $return .= '</li>' . "\n";
+
+ }
+
+ $return .= '</ul>' . "\n";
+
+ return $return;
+
+ }
+
+
+ public static function list_templates() {
+
+ $templates = HeadwayLayout::get_templates();
+
+ $return = '';
+
+ $return .= '<ul>' . "\n";
+
+ $no_templates_display = ( count($templates) === 0 ) ? null : ' style="display:none;"';
+
+ $return .= '<li class="layout-item info-layout-item" id="no-templates"' . $no_templates_display . '><span class="layout"><strong>There are no shared layouts to display. Add one!</strong></span></li>';
+
+ foreach($templates as $id => $name) {
+
+ $class = array('layout-item');
+
+ $class[] = ( 'template-' . $id === headway_post('currentLayout') ) ? 'layout-selected' : null;
+
+ //Output stuff
+ $return .= "\n" . '<li class="' . implode(' ', array_filter($class)) . '">' . "\n";
+
+ $return .= "\n". '
+ <span data-layout-id="template-' . $id . '" class="layout layout-template">
+ <strong class="template-name">' . HeadwayLayout::get_name('template-' . $id) . '</strong>
+
+ <span class="delete-template" title="Delete Shared Layout">Delete</span>
+
+ <span class="status status-currently-editing">Currently Editing</span>
+
+ <span class="rename-template button layout-selector-button">Rename</span>
+ <span class="assign-template button layout-selector-button">Use Layout</span>
+ <span class="edit button button-blue layout-selector-button">Edit</span>
+ </span>' . "\n";
+
+ $return .= '</li>' . "\n";
+
+ }
+
+ $return .= '</ul>' . "\n";
+
+ return $return;
+
+ }
+
+
+ public static function is_any_layout_child_customized($children) {
+
+ if ( !is_array($children) || count($children) == 0 )
+ return false;
+
+ foreach ( $children as $id => $grand_children ) {
+
+ $status = HeadwayLayout::get_status($id);
+
+ if ( headway_get('customized', $status) || headway_get('template', $status) )
+ return true;
+
+ if ( is_array($grand_children) && count($grand_children) > 0 && self::is_any_layout_child_customized($grand_children) === true )
+ return true;
+
+ }
+
+ return false;
+
+ }
+
+
+ public static function mode_navigation() {
+
+ foreach ( HeadwayVisualEditor::get_modes() as $mode => $tooltip ) {
+
+ $current = ( HeadwayVisualEditor::is_mode($mode) ) ? ' class="active"' : null;
+
+ $mode_id = strtolower($mode);
+
+ echo '
+ <li' . $current . ' id="mode-'. $mode_id . '">
+ <a href="' . home_url() . '/?visual-editor=true&visual-editor-mode=' . $mode_id . '" title="' . esc_attr($tooltip) . '" class="tooltip-top-left">
+ <span>' . ucwords($mode) . '</span>
+ </a>
+ </li>
+ ';
+
+ }
+
+ }
+
+
+ public static function menu_links() {
+
+ echo '<li id="menu-link-tools" class="has-submenu">
+ <span>Tools</span>
+
+ <ul>';
+
+ // echo '<li id="tools-undo"><span>Undo <small>Ctrl + Z</small></span></li>
+ // <li id="tools-redo"><span>Redo <small>Ctrl + Y</small></span></li>';
+
+ if ( HeadwayVisualEditor::is_mode('grid') )
+ echo '<li id="tools-grid-wizard"><span>Grid Wizard</span></li>';
+
+ if ( HeadwayCompiler::can_cache() )
+ echo '<li id="tools-clear-cache"><span>Clear Cache' . (!HeadwayCompiler::caching_enabled() ? ' (Disabled)' : '') . '</span></li>';
+
+ echo '<li id="tools-tour"><span>Tour</span></li>
+ </ul>
+
+ </li>';
+
+
+ echo '<li id="menu-link-admin" class="has-submenu">
+ <span>Admin</span>
+
+ <ul>
+ <li><a href="' . admin_url() . '" target="_blank">Dashboard</a></li>
+ <li><a href="' . admin_url('widgets.php') . '" target="_blank">Widgets</a></li>
+ <li><a href="' . admin_url('nav-menus.php') . '" target="_blank">Menus</a></li>
+ <li><a href="' . admin_url('admin.php?page=headway-options') . '" target="_blank">Headway Options</a></li>
+ <li><a href="http://docs.headwaythemes.com" target="_blank">Documentation</a></li>
+ <li><a href="http://support.headwaythemes.com" target="_blank">Support</a></li>
+ </ul>
+
+ </li>';
+
+
+ echo '<li id="menu-link-view-site"><a href="' . home_url() . '" target="_blank">View Site</a></li>';
+
+ }
+
+
+}
\ No newline at end of file
--- /dev/null
+<?php
+class HeadwayVisualEditorIframeGrid {
+
+
+ public static function display_grid_blocks($blocks, $wrapper) {
+
+ echo '<div class="grid-container">';
+
+ if ( is_array($blocks) ) {
+
+ foreach ($blocks as $block_id => $block) {
+
+ HeadwayBlocks::display_block($block, 'grid');
+
+ }
+
+ }
+
+ /* Mirrored wrapper notice */
+ $mirror_wrapper = HeadwayWrappersData::get_wrapper_mirror($wrapper);
+ $mirror_wrapper_layout = $mirror_wrapper ? HeadwayLayout::get_name(headway_get('layout', $mirror_wrapper)) : null;
+ $mirror_wrapper_alias = headway_get('alias', $mirror_wrapper) ? '(' . headway_get('alias', $mirror_wrapper) . ')' : null;
+
+ echo '<div class="wrapper-mirror-notice">
+ <div>
+ <h2>Wrapper Mirrored</h2>
+ <p>This wrapper is mirroring the blocks from a wrapper <span class="wrapper-mirror-notice-alias">' . $mirror_wrapper_alias . '</span> <span class="wrapper-mirror-notice-layout">from "' . $mirror_wrapper_layout . '" layout</span></p>
+ <small>Mirroring can be disabled via Wrapper Options in the right-click menu</small>
+ </div>
+ </div><!-- .wrapper-mirror-notice -->';
+ /* End mirrored wrapper notice */
+
+ echo '</div><!-- .grid-container -->';
+
+ }
+
+
+ public static function display_canvas() {
+
+ echo '<!DOCTYPE HTML>
+ <html lang="en">
+
+ <head>
+
+ <meta charset="' . get_bloginfo('charset') . '" />
+ <link rel="profile" href="http://gmpg.org/xfn/11" />
+
+ <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1" />
+ <meta http-equiv="cache-control" content="no-cache" />
+
+ <title>Visual Editor Grid: ' . wp_title(false, false) . '</title>';
+
+ do_action('headway_grid_iframe_head');
+
+ echo '</head><!-- /head -->
+
+ <body class="visual-editor-iframe-grid ' . join(' ', get_body_class()) . '">';
+
+ $wrappers = HeadwayWrappersData::get_wrappers_by_layout(HeadwayLayout::get_current_in_use());
+ $blocks = HeadwayBlocksData::get_blocks_by_layout(HeadwayLayout::get_current_in_use());
+
+ echo '<div id="whitewrap">';
+
+ foreach ( $wrappers as $wrapper_id => $wrapper ) {
+
+ /* Setup wrapper classes */
+ $wrapper_settings = headway_get('settings', $wrapper, array());
+ $wrapper_classes = array('wrapper');
+
+ $wrapper_classes[] = HeadwayWrappers::is_independent_grid($wrapper) ? 'independent-grid' : null;
+ $wrapper_classes[] = HeadwayWrappers::is_fluid($wrapper) ? 'wrapper-fluid' : 'wrapper-fixed';
+ $wrapper_classes[] = HeadwayWrappers::is_grid_fluid($wrapper) ? 'wrapper-fluid-grid' : 'wrapper-fixed-grid';
+
+ if ( HeadwayWrappersData::is_wrapper_mirrored($wrapper) )
+ $wrapper_classes[] = 'wrapper-mirrored';
+
+ /* Populate wrapper with its blocks */
+ $wrapper_blocks = array();
+
+ foreach ( $blocks as $block_id => $block ) {
+
+ /* Grab blocks belonging to this wrapper */
+ if ( headway_get('wrapper_id', $block, HeadwayWrappers::$default_wrapper_id) == $wrapper_id )
+ $wrapper_blocks[$block_id] = $block;
+
+ /* If last wrapper, grab all blocks on this layout with invalid wrapper IDs to make sure they're editable somewhere */
+ $last_wrapper_id = array_slice(array_keys($wrappers), -1, 1);
+ $last_wrapper_id = $last_wrapper_id[0];
+
+ if ( $last_wrapper_id == $wrapper_id && !headway_get(headway_get('wrapper_id', $block, HeadwayWrappers::$default_wrapper_id), $wrappers) )
+ $wrapper_blocks[$block_id] = $block;
+
+ }
+
+ /* Output the wrapper */
+ echo '<div id="wrapper-' . HeadwayWrappers::format_wrapper_id($wrapper_id) . '" class="' . implode(' ', array_filter($wrapper_classes)) . '" data-wrapper-settings="' . esc_attr(json_encode($wrapper_settings)) . '" data-id="' . HeadwayWrappers::format_wrapper_id($wrapper_id) . '" data-alias="' . esc_attr(headway_get('alias', $wrapper_settings)) . '">';
+
+ echo '<div class="wrapper-mirror-overlay"></div><!-- .wrapper-mirror-overlay -->';
+
+ self::display_grid_blocks($wrapper_blocks, $wrapper);
+
+ echo '</div><!-- #wrapper-' . $wrapper_id . ' -->';
+
+ }
+
+ echo '<div id="wrapper-buttons-template">';
+ echo '<div class="wrapper-top-margin-handle wrapper-handle wrapper-margin-handle" title="Drag to change wrapper top margin"><span></span><span></span><span></span></div>';
+ echo '<div class="wrapper-drag-handle wrapper-handle tooltip tooltip-right" title="Drag to change wrapper order"><span></span><span></span><span></span></div>';
+ echo '<div class="wrapper-bottom-margin-handle wrapper-handle wrapper-margin-handle" title="Drag to change wrapper bottom margin"><span></span><span></span><span></span></div>';
+
+ echo '<div class="wrapper-options tooltip tooltip-right" title="Click to open wrapper options"><span></span></div>';
+ echo '</div><!-- .wrapper-buttons -->';
+
+
+ do_action('headway_grid_iframe_footer');
+
+ echo '</div><!-- #whitewrap -->
+ </body>
+ </html>';
+
+ }
+
+
+ public static function show() {
+
+ //Prevent any type of caching on this page
+ if ( !defined('DONOTCACHEPAGE') ) {
+ define('DONOTCACHEPAGE', true);
+ }
+
+ if ( !defined('DONOTMINIFY') ) {
+ define('DONOTMINIFY', true);
+ }
+
+ add_action('headway_grid_iframe_head', array(__CLASS__, 'print_styles'), 12);
+ add_action('headway_grid_iframe_styles', array(__CLASS__, 'enqueue_canvas_assets'));
+
+ self::display_canvas();
+
+ }
+
+
+ public static function enqueue_canvas_assets() {
+
+ HeadwayCompiler::register_file(array(
+ 'name' => 've-iframe-grid',
+ 'format' => 'less',
+ 'fragments' => array(
+ HEADWAY_LIBRARY_DIR . '/media/css/reset.css',
+ HEADWAY_LIBRARY_DIR . '/media/css/grid.css',
+ HEADWAY_LIBRARY_DIR . '/media/css/alerts.css',
+ HEADWAY_LIBRARY_DIR . '/visual-editor/css/editor-loading.css',
+ HEADWAY_LIBRARY_DIR . '/visual-editor/css/editor-mixins.less',
+ HEADWAY_LIBRARY_DIR . '/visual-editor/css/editor-iframe.less',
+ HEADWAY_LIBRARY_DIR . '/visual-editor/css/editor-tooltips.less',
+ HEADWAY_LIBRARY_DIR . '/visual-editor/css/editor-iframe-grid.less',
+ HEADWAY_LIBRARY_DIR . '/visual-editor/css/editor-iframe-grid-wireframe.less'
+ ),
+ 'require-hard-flush' => true,
+ 'iframe-cache' => true
+ ));
+
+ HeadwayCompiler::register_file(array(
+ 'name' => 've-iframe-grid-dynamic',
+ 'format' => 'css',
+ 'fragments' => array(
+ array('HeadwayDynamicStyle', 'wrapper')
+ ),
+ 'dependencies' => array(
+ HEADWAY_LIBRARY_DIR . '/media/dynamic/style.php'
+ )
+ ));
+
+ }
+
+
+ public static function print_styles() {
+
+ global $wp_styles;
+ $wp_styles = null;
+
+ do_action('headway_grid_iframe_styles');
+
+ wp_print_styles();
+
+ }
+
+
+}
\ No newline at end of file
--- /dev/null
+<!DOCTYPE HTML>
+<html <?php language_attributes(); ?>>
+
+<head>
+
+<meta charset="<?php echo get_bloginfo('charset'); ?>" />
+<link rel="profile" href="http://gmpg.org/xfn/11" />
+
+
+<?php
+$GLOBALS['wp_media_view_strings'] = array();
+$GLOBALS['wp_media_view_settings'] = array();
+
+/* Begin kludge to fix issue with WP string localize in some cases. See: https://core.trac.wordpress.org/ticket/24724 */
+function headway_media_view_settings_grabber( $settings ) {
+
+ $GLOBALS['wp_media_view_settings'] = $settings;
+
+ return $settings;
+
+}
+
+add_filter( 'media_view_settings', 'headway_media_view_settings_grabber' );
+
+function headway_media_view_strings_grabber($strings) {
+
+ $GLOBALS['wp_media_view_strings'] = $strings;
+
+ return $strings;
+
+}
+add_filter('media_view_strings', 'headway_media_view_strings_grabber');
+
+wp_enqueue_media();
+
+$GLOBALS['wp_media_view_strings']['settings'] = $GLOBALS['wp_media_view_settings'];
+
+wp_localize_script( 'media-editor', '_wpMediaViewsL10n', $GLOBALS['wp_media_view_strings'] );
+wp_localize_script( 'media-views', '_wpMediaViewsL10n', $GLOBALS['wp_media_view_strings'] );
+/* End Kludge */
+
+wp_enqueue_style('open-sans');
+
+wp_print_scripts();
+wp_print_styles();
+?>
+
+<style type="text/css">
+ .media-modal {
+ top: 0;
+ left: 0;
+ right: 0;
+ bottom: 0;
+ }
+
+ .media-modal-close {
+ display: none;
+ }
+
+ .media-frame-router {
+ top: 5px;
+ }
+
+ .media-frame-content {
+ top: 39px;
+ }
+</style>
+
+
+</head>
+
+<body>
+
+<?php
+wp_print_media_templates();
+?>
+
+</body>
+</html>
\ No newline at end of file
--- /dev/null
+<?php
+class HeadwayPropertyInputs {
+
+
+ public static function display($element, $special_element_type = false, $special_element_meta = false, $data, $data_without_defaults) {
+
+ if ( !is_array($element) || empty($element['properties']) )
+ return null;
+
+ $default_box_args = array(
+ 'group' => false,
+ 'element' => $element,
+ 'special_element_type' => $special_element_type,
+ 'special_element_meta' => $special_element_meta,
+ 'selective_properties' => false,
+ 'property_values' => $data,
+ 'property_values_excluding_defaults' => $data_without_defaults
+ );
+
+ /* Format $element['properties'] into an easier array to work with and then make it alphabetical */
+ $property_groups = array();
+
+ foreach ( $element['properties'] as $key => $value ) {
+
+ if ( is_numeric($key) ) {
+ $property_groups[$value] = false;
+ } else {
+ $property_groups[$key] = $value;
+ }
+
+ }
+
+ /* Include nudging and margin for all elements except for Body */
+ if ( !(!empty($element['disallow-nudging']) && headway_fix_data_type($element['disallow-nudging']) === true) && !in_array('nudging', $element['properties']) ) {
+
+ $property_groups['nudging'] = false;
+ $property_groups['margins'] = false;
+
+ }
+
+ /* Change 'rounded-corners' to 'corners' if it exists */
+ if ( isset($property_groups['rounded-corners']) ) {
+
+ $property_groups['corners'] = $property_groups['rounded-corners'];
+ unset($property_groups['rounded-corners']);
+
+ }
+
+ /* Sort property groups */
+ ksort($property_groups);
+
+ /* Display the property groups registered to the element. */
+ $property_group_row_i = 0;
+
+ foreach ( $property_groups as $group => $selective_properties ) {
+
+ /* Possibly open property group row */
+ if ( $property_group_row_i % 3 === 0 ) {
+ echo '<div class="property-group-row">';
+ $property_group_row_open = true;
+ }
+
+ $property_group_row_i++;
+
+ /* Display the box */
+ self::box(array_merge($default_box_args, array(
+ 'group' => $group,
+ 'selective_properties' => $selective_properties
+ )));
+
+ /* Close property group row if necessary */
+ if ( $property_group_row_i % 3 === 0 || ($property_group_row_open && key(array_slice($property_groups, -1, 1, true)) == $group ) ) {
+ echo '</div><!-- .property-group-row -->';
+ unset($property_group_row_open);
+ }
+
+ }
+
+ }
+
+
+ public static function box($args) {
+
+ $defaults = array(
+ 'group' => null,
+ 'element' => null,
+ 'special_element_type' => false,
+ 'special_element_meta' => false,
+ 'selective_properties' => false,
+ 'property_values' => false,
+ 'property_values_excluding_defaults' => false,
+ 'unsaved_values' => false
+ );
+
+ $args = array_merge($defaults, $args);
+ $args['group_nice'] = ucwords(str_replace('-', ' ', $args['group']));
+
+ //If the group doesn't exist, don't attempt to display it
+ if ( !($properties = HeadwayElementProperties::get_properties_by_group($args['group_nice'])) )
+ return false;
+
+ $args['selector'] = isset($args['element']['selector']) ? $args['element']['selector'] : null;
+
+ /* Custom behaviors for special element types */
+ switch ( $args['special_element_type'] ) {
+
+ case 'instance':
+
+ $instances = headway_get('instances', $args['element']);
+ $instance = $instances[$args['special_element_meta']];
+
+ $args['selector'] = $instance['selector'];
+
+ break;
+
+ case 'state':
+
+ $states = headway_get('states', $args['element']);
+ $state = $states[$args['special_element_meta']];
+
+ $args['selector'] = $state['selector'];
+
+ break;
+
+
+ case 'layout':
+
+ if ( isset($args['element']['selector']) && isset($args['special_element_meta']) ) {
+
+ $args['selector'] = 'body.layout-using-' . $args['special_element_meta'] . ' ' . $args['element']['selector'];
+
+ if ( $args['element']['selector'] == 'body' )
+ $args['selector'] = str_replace(' body', '', $args['selector']);
+
+ }
+
+ break;
+
+ }
+
+ /* Set customized box class flag */
+ $customized_box_class = '';
+ $property_box_title = '';
+
+ foreach ( $args['property_values_excluding_defaults'] as $property_id => $property_value ) {
+
+ if ( !isset($properties[$property_id]) )
+ continue;
+
+ $customized_box_class = ' design-editor-box-customized';
+ $property_box_title = ' title="' . __('You have customized a property in this property group.', 'headway') . '"';
+
+ break;
+
+ }
+
+ /* Create the box */
+ echo '<div class="design-editor-box design-editor-box-' . $args['group'] . $customized_box_class . '">';
+ echo '<span class="design-editor-box-title"' . $property_box_title . '><span>' . $args['group_nice'] . '</span></span>';
+
+ echo '<ul class="design-editor-box-content">';
+
+ foreach ( $properties as $property_id => $property_options ) {
+
+ //If the $selective_properties variable is set, then make sure we're only showing those properties.
+ if ( is_array($args['selective_properties']) )
+ if ( !in_array($property_id, $args['selective_properties']) )
+ continue;
+
+ if ( !headway_get('display', $property_options, true) )
+ continue;
+
+ if ( $property_options['type'] != 'box-model' ) {
+
+ self::build_property_input($property_id, $property_options, $args);
+
+ continue;
+
+ }
+
+ /* Handle box model inputs differently from the rest of the property inputs */
+ echo '<div class="box-model-inputs-container">';
+
+ if ( headway_get('name', $property_options) )
+ echo '<strong class="box-model-inputs-heading">' . $property_options['name'] . '</strong>';
+
+ echo '<div class="box-model-inputs box-model-inputs-position-' . headway_get('position', $property_options, 'sides') . '">';
+
+ foreach ( $property_options['box-model-inputs'] as $box_modal_input_id ) {
+
+ /* Do not show wrapper-left and wrapper-right if it's a block or wrapper */
+ if ( ((strpos($args['element']['selector'], '.block-type') === 0 && strpos($args['element']['selector'], ' ') === false) || $args['element']['id'] == 'wrapper') && in_array($box_modal_input_id, array('margin-left', 'margin-right')) )
+ continue;
+
+ $box_modal_input_options['lockable'] = true;
+ self::build_property_input($box_modal_input_id, $properties[$box_modal_input_id], $args);
+
+ }
+
+ echo '<span class="design-editor-lock-sides" data-locked="false"></span>';
+
+ echo '</div><!-- .box-model-inputs -->';
+
+ echo '</div><!-- .box-model-inputs-container -->';
+ /* End box model input handling */
+
+ }
+
+ echo '</ul><!-- .design-editor-box-content -->';
+
+ echo '</div><!-- .design-editor-box -->';
+ /* End box creation */
+
+ }
+
+
+ public static function build_property_input($property_id, $property_options, $element_args) {
+
+ //Make sure the input type for the property really exists
+ if ( !is_callable(array(__CLASS__, 'input_' . str_replace('-', '_', $property_options['type']))) )
+ return false;
+
+ /* Get the value of the property */
+ $original_property_value = headway_fix_data_type(headway_get($property_id, $element_args['property_values']));
+
+ if ( ($original_property_value || $original_property_value === 0) && strtolower($original_property_value) !== 'delete' ) {
+
+ $property_options['value'] = $element_args['property_values'][$property_id];
+ $property_options['customized'] = true;
+
+ //Fall back to default
+ } else {
+
+ $property_default = isset($property_options['default']) ? $property_options['default'] : null;
+
+ $property_options['value'] = $property_default;
+ $property_options['customized'] = false;
+
+ }
+
+ /* Set up elements and attributes */
+ $uncustomize_button = $element_args['special_element_type'] != 'default' ? '<span class="uncustomize-property tooltip" title="Delete this customization."></span>' : null;
+ $customize_button = $element_args['special_element_type'] != 'default' ? '<div class="customize-property"><span class="tooltip" title="Click to change the value for this property. If left uncustomized, the property will automatically inherit to the default set for this element type in the defaults tab or the parent element if editing a state, instance, or layout-specific element.">Customize</span></div>' : null;
+
+ $hidden_input_attributes_array = array(
+ 'type' => 'hidden',
+ 'class' => 'property-hidden-input',
+ 'value' => $property_options['value'],
+ 'element' => $element_args['element']['id'],
+ 'property' => $property_id,
+ 'special_element_type' => $element_args['special_element_type'],
+ 'special_element_meta' => $element_args['special_element_meta'],
+ 'element_selector' => esc_attr(stripslashes($element_args['selector'])),
+ 'callback' => esc_attr('(function(params){' . $property_options['js-callback'] . '})')
+ );
+
+
+ /* Turn attributes array into a string for HTML */
+ $hidden_input_attributes = '';
+
+ foreach ( $hidden_input_attributes_array as $attribute => $attribute_value )
+ $hidden_input_attributes .= $attribute . '="' . $attribute_value . '" ';
+
+ $hidden_input_attributes = trim($hidden_input_attributes);
+
+ /* Set up attributes */
+ $property_title = '';
+ $property_classes = array(
+ 'design-editor-property-' . $property_id
+ );;
+
+ if ( $property_options['customized'] ) {
+
+ $property_classes[] = 'customized-property-by-user';
+ $property_title = ' title="' . __('You have customized this property.', 'headway') . '"';
+
+ } else if ( $element_args['special_element_type'] !== 'default' ) {
+
+ $property_classes[] = 'uncustomized-property';
+
+ }
+
+ /* add a locked class if it's a lockable element only */
+ if ( headway_get('lockable', $property_options) )
+ $property_classes[] = 'lockable-property';
+
+ /* set the customizable defaults and class */
+ if ( is_array( headway_get( 'unit', $property_options ) ) ) {
+
+ $unit_defaults = array(
+ 'default' => 'px',
+ 'options' => array(
+ 'px' => 'px',
+ '%' => '%',
+ 'em' => 'em',
+ 'rem' => 'rem',
+ )
+ );
+
+ $property_options['unit'] = array_merge( $unit_defaults, $property_options['unit'] );
+
+ /* add a unit class if necessary */
+ $property_classes[] = 'customizable-unit';
+
+ }
+
+ echo '<li data-property-id="' . $property_id . '" class="' . implode(' ', array_filter($property_classes)) . '"' . $property_title . '>';
+
+ echo '<strong><span class="property-label">' . $property_options['name'] . '</span>' . (!headway_get('lockable', $property_options) ? $uncustomize_button : null) . '</strong>';
+ echo '<div class="property-' . $property_options['type'] . ' property">';
+
+ echo (headway_get('lockable', $property_options)) ? $uncustomize_button : null; /* Uncustomize button needs to be in different location for box model input s*/
+
+ call_user_func(array(__CLASS__, 'input_' . str_replace('-', '_', $property_options['type'])), $property_options, $property_id);
+
+ /* Unit select */
+ if ( is_array( headway_get( 'unit', $property_options ) ) ) {
+
+ $unit_value = trim(str_replace( array_merge( range( 0, 9 ), array( '.', '-' ) ), '', $property_options['value'] ));
+
+ self::input_select(array(
+ 'options' => $property_options['unit']['options'],
+ 'value' => $unit_value ? $unit_value : $property_options['unit']['default'],
+ 'unit-select' => true
+ ));
+
+ }
+
+ echo '<input ' . $hidden_input_attributes . ' />';
+
+ echo '</div>';
+
+ echo $customize_button;
+
+ echo '</li>';
+
+
+ }
+
+
+ public static function input_integer($options, $id) {
+
+ $unit = is_string(headway_get('unit', $options)) ? '<span class="unit">' . headway_get('unit', $options) . '</span>' : null;
+
+ /* Remove unit from value */
+ if ( is_array( headway_get( 'unit', $options ) ) ) {
+
+ $value_unit = trim( str_replace( array_merge( range( 0, 9 ), array( '.', '-' ) ), '', $options['value'] ) );
+ $options['value'] = str_replace( $value_unit, '', $options['value']);
+
+ }
+
+
+ echo '<input type="number" value="' . $options['value'] . '" />' . $unit;
+
+ }
+
+
+ public static function input_color($options, $id) {
+
+ echo '
+ <div class="colorpicker-box-container">
+ <div class="colorpicker-box-transparency"></div>
+ <div class="colorpicker-box" style="background-color:' . headway_format_color($options['value']) . ';"></div>
+ </div><!-- .colorpicker-box-container -->
+ ';
+
+ }
+
+
+ public static function input_select($options, $id = null) {
+
+ $unit_select_class = headway_get('unit-select', $options) ? ' property-unit-select' : '';
+
+ echo '<div class="select-container' . $unit_select_class . '"><select>';
+
+ //If 'options' is a function, then call it and replace $options['options']
+ if ( is_string($options['options']) && strpos($options['options'], '()') !== false ) {
+
+ $sanitized_function = str_replace('()', '', $options['options']);
+
+ //If is a method rather than function, the method must be declared as static otherwise it'll return false on PHP 5.2
+ if ( !is_callable($sanitized_function) ) {
+ echo '</select></div><!-- .select-container -->';
+ return;
+ }
+
+ $options['options'] = call_user_func($sanitized_function);
+
+ }
+
+ if ( is_array($options['options']) ) {
+
+ foreach ( $options['options'] as $value => $content ) {
+
+ //If it's an optgroup, handle it.
+ if ( is_array($content) ) {
+
+ echo '<optgroup label="' . $value . '">';
+
+ foreach ( $content as $value => $text ) {
+
+ //If the current option is the value in the DB, then mark it as selected
+ $selected_option = ( $value == $options['value'] ) ? ' selected="selected"' : null;
+
+ echo '<option value="' . $value . '"' . $selected_option . '>' . $text . '</option>';
+
+ }
+
+ echo '</optgroup>';
+
+ //Otherwise it's just a normal option
+ } else {
+
+ //If the current option is the value in the DB, then mark it as selected
+ $selected_option = ( $value == $options['value'] ) ? ' selected="selected"' : null;
+
+ echo '<option value="' . $value . '"' . $selected_option . '>' . $content . '</option>';
+
+ }
+
+ }
+
+ }
+
+
+ echo '</select></div><!-- .select-container -->';
+
+ }
+
+
+ public static function input_image($options, $id) {
+
+ $src_visibility = ( is_string($options['value']) && strlen($options['value']) > 0 && $options['value'] != 'none' ) ? '' : ' style="display:none;"';
+
+ $filename_parts = explode('/', $options['value']);
+ $filename = end($filename_parts);
+
+ echo '
+ <span class="button">Choose</span>
+
+ <div class="image-input-controls-container"' . $src_visibility . '>
+ <span class="src">' . $filename . '</span>
+ <span class="delete-image">Delete</span>
+ </div>
+ ';
+
+ }
+
+
+ public static function input_checkbox($options, $id) {
+
+ }
+
+
+ public static function input_font_family_select($options, $id) {
+
+ /* Output input */
+ $font_fragments = explode('|', $options['value']);
+
+ /* Web Font */
+ if ( count($font_fragments) >= 2 ) {
+
+ $font_stack = $font_fragments[1];
+ $font_name = $font_fragments[1];
+
+ $webfont_class = ' font-name-webfont';
+
+ /* Traditional Font */
+ } else {
+
+ $font_stack = HeadwayFonts::get_stack($options['value']);
+ $font_name = ucwords($options['value']);
+
+ $webfont_class = null;
+
+ }
+
+ echo '<span class="font-name' . $webfont_class . '" style="font-family: ' . $font_stack . ';" data-webfont-value="' . $options['value'] . '">' . $font_name . '</span>';
+
+ echo '<span class="open-font-browser pencil-icon"></span>';
+
+ /* Font Browser */
+ echo '<div class="font-browser">';
+
+ echo '<ul class="tabs">';
+ do_action('headway_fonts_browser_tabs');
+ echo '</ul>';
+
+ do_action('headway_fonts_browser_content');
+
+ echo '</div><!-- .font-browser -->';
+
+ }
+}
\ No newline at end of file
--- /dev/null
+<?php
+class HeadwaySidePanelDesignEditor {
+
+
+ public static function init() {
+
+ if ( HeadwayVisualEditor::get_current_mode() != 'design' )
+ return false;
+
+ add_action('headway_visual_editor_side_panel', array(__CLASS__, 'template'));
+
+ add_action('headway_visual_editor_footer', array(__CLASS__, 'live_css_textarea'));
+
+ }
+
+
+ public static function live_css_textarea() {
+
+ echo '<textarea id="live-css" name="live-css" data-group="general" style="display:none;">' . esc_textarea(HeadwaySkinOption::get('live-css')) . '</textarea>';
+
+ }
+
+
+ public static function template() {
+
+ echo '<div id="side-panel-top">';
+ self::element_selector();
+ echo '</div><!-- #side-panel-top -->';
+
+ echo '<div id="side-panel-bottom">';
+ self::editor();
+ echo '</div><!-- #side-panel-bottom -->';
+
+ }
+
+
+ public static function element_selector() {
+
+ echo '
+ <ul id="element-selector-tabs">
+ <li><a href="#design-editor-element-selector-container">Navigator</a></li>
+ <li><a href="#design-editor-styles-container">Styles</a></li>
+
+ <span id="side-panel-collapse-arrow" title="Toggle Design Editor" class="tooltip-top-right"></span>
+ </ul>
+ ';
+
+ echo '<div id="design-editor-element-selector-container">';
+
+ echo '<ul id="design-editor-element-selector">';
+
+ echo '</ul><!-- #design-editor-element-selector -->';
+
+ echo '<span class="button button-blue" id="element-selector-show-all-elements">Show All Elements</span>';
+ echo '<span class="button" id="element-selector-show-current-layout-elements">Show Current Layout Elements</span>';
+
+ echo '</div><!-- #design-editor-element-selector-container -->';
+
+
+ echo '<div id="design-editor-styles-container">';
+
+
+ echo '<div id="design-editor-styles-nothing-selected" class="design-editor-styles-message">';
+
+ echo '<p>You <strong>have not selected an element</strong> to edit.</p>';
+ echo '<p>Use the inspector to inspect an element you want to edit.</p>';
+
+ echo '<a href="http://docs.headwaythemes.com/article/49-the-inspector" target="_blank">Learn more about the inspector</a>';
+
+ echo '</div><!-- #design-editor-styles-nothing-selected -->';
+
+
+ echo '<div id="design-editor-styles-no-styles" class="design-editor-styles-message">';
+
+ echo '<p>This element does not have any customized properties or instances.</p>';
+
+ echo '</div><!-- #design-editor-styles-nothing-selected -->';
+
+
+ echo '<ul id="design-editor-styles">';
+
+ echo '</ul><!-- #design-editor-styles -->';
+
+ echo '</div><!-- #design-editor-styles-container -->';
+
+ }
+
+
+ public static function editor() {
+
+ echo '
+ <div class="design-editor-info" style="display: none;">
+ <div class="design-editor-selection">
+ <strong>Editing:</strong>
+
+ <span class="design-editor-selection-details">
+ <strong class="design-editor-selected-element"></strong>
+ for <strong class="design-editor-selection-details-layout">all layouts</strong>
+ <span class="design-editor-selection-details-state-container"><span class="design-editor-selection-details-state-before"></span> <strong class="design-editor-selection-details-state"></strong></span>
+ </span>
+
+ <span class="button button-small design-editor-info-button customize-element-for-layout">Customize For Current Layout</span>
+ <span class="button button-small design-editor-info-button customize-for-regular-element">Customize Regular Element</span>
+ </div>
+ </div><!-- .design-editor-info -->
+
+ <div class="design-editor-options-container">
+
+ <div class="design-editor-options" style="display:none;"></div><!-- .design-editor-options -->
+
+ </div><!-- .design-editor-options-container -->
+ ';
+
+ }
+
+}
\ No newline at end of file
--- /dev/null
+<?php
+class GridSetupPanel extends HeadwayVisualEditorPanelAPI {
+
+ public $id = 'setup';
+ public $name = 'Setup';
+ public $mode = 'grid';
+
+ public $tabs = array(
+ 'grid' => 'Grid',
+ 'responsive-grid' => 'Responsive Grid'
+ );
+
+ public $tab_notices = array(
+ 'grid' => '<strong>Note:</strong> the content in the grid above will not reflect how your site actually looks. The content inside the blocks is to give you a general reference while you wireframe and build the layout to your site.<br /><br />The settings below are <strong>global</strong> and are not customized on a per-layout basis.',
+ 'responsive-grid' => 'The Headway Responsive Grid allows the powerful grid in Headway Base to be custom-tailored depending on the device that the visitor is viewing the site from. Please note: some sites may benefit from having the responsive grid enabled while other will not. As the designer of the website, it is up to you to decide. The responsive grid can be enabled or disabled at any time.'
+ );
+
+ public $inputs = array(
+ 'grid' => array(
+ 'columns' => array(
+ 'type' => 'slider',
+ 'name' => 'columns',
+ 'label' => 'Default Column Count', /* Column count is default only because you can't change it on the fly */
+ 'default' => 24,
+ 'tooltip' => 'The column count is the number of columns in the grid. This is represented by the grey regions on the grid.<br /><br /><strong>This will NOT affect wrappers that are already created. It only affects wrappers that are created after this setting is changed.</strong>',
+ 'slider-min' => 6,
+ 'slider-max' => 24,
+ 'slider-interval' => 1,
+ 'callback' => 'Headway.defaultGridColumnCount = value.toString();updateGridWidthInput($(input).parents(".sub-tabs-content"));'
+ ),
+
+ 'column-width' => array(
+ 'type' => 'slider',
+ 'name' => 'column-width',
+ 'label' => 'Global Column Width',
+ 'default' => 20,
+ 'tooltip' => 'The column width is the amount of space inside of each column. This is represented by the grey regions on the grid.',
+ 'unit' => 'px',
+ 'slider-min' => 10,
+ 'slider-max' => 80,
+ 'slider-interval' => 1,
+ 'callback' => 'Headway.globalGridColumnWidth = value.toString();$i("div.wrapper:not(.independent-grid)").each(function() { $(this).headwayGrid("updateGridCSS"); });updateGridWidthInput($(input).parents(".sub-tabs-content"));'
+ ),
+
+ 'gutter-width' => array(
+ 'type' => 'slider',
+ 'name' => 'gutter-width',
+ 'label' => 'Global Gutter Width',
+ 'default' => 20,
+ 'tooltip' => 'The gutter width is the amount of space between each column. This is the space between each of the grey regions on the grid.',
+ 'unit' => 'px',
+ 'slider-min' => 0,
+ 'slider-max' => 40,
+ 'slider-interval' => 1,
+ 'callback' => 'Headway.globalGridGutterWidth = value.toString();$i("div.wrapper:not(.independent-grid)").each(function() { $(this).headwayGrid("updateGridCSS"); });updateGridWidthInput($(input).parents(".sub-tabs-content"));'
+ ),
+
+ 'grid-width' => array(
+ 'type' => 'integer',
+ 'unit' => 'px',
+ 'default' => 940,
+ 'name' => 'grid-width',
+ 'label' => 'Global Grid Width',
+ 'readonly' => true
+ )
+ ),
+
+ 'responsive-grid' => array(
+ 'enable-responsive-grid' => array(
+ 'type' => 'checkbox',
+ 'name' => 'enable-responsive-grid',
+ 'label' => 'Enable Responsive Grid',
+ 'default' => false,
+ 'tooltip' => 'If Headway\'s responsive grid is enabled, the grid will automatically adjust depending on the visitor\'s device (computer, iPhone, iPad, etc). Enabling the responsive grid can be extremely beneficial for some websites, but may not be worthwhile for other websites. If the responsive grid is enabled, the user will always have the option to disable the responsive grid via a link in the footer block.<br /><br /><strong>Please Note:</strong> with the responsive grid enabled, the exact pixel widths of blocks may differ very slightly from when it is <em>disabled</em>.'
+ ),
+
+ 'responsive-video-resizing' => array(
+ 'type' => 'checkbox',
+ 'name' => 'responsive-video-resizing',
+ 'label' => 'Responsive Video Resizing',
+ 'default' => true,
+ 'tooltip' => 'If the Responsive Grid is enabled and the user visits the site when there are YouTube, Vimeo, or any other videos, then the videos will not resize properly unless then is checked.'
+ )
+ )
+ );
+
+}
+headway_register_visual_editor_panel('GridSetupPanel');
\ No newline at end of file
--- /dev/null
+<?php
+class HeadwayVisualEditorPreview {
+
+
+public static function remove_preview_options() {
+
+ if ( !HeadwayCapabilities::can_user_visually_edit() )
+ return;
+
+ //Fetch all options in wp_options and remove the preview-specific options
+ foreach ( wp_load_alloptions() as $option => $option_value ) {
+
+ //This if statement is incredibly important and must not be tampered with and needs to be triple-checked if changed.
+ if ( preg_match('/^headway_(.*)?_preview$/', $option) && strpos($option, 'headway_') === 0 && strpos($option, '_preview') !== false ) {
+ delete_option($option);
+ }
+
+ }
+
+ }
+
+
+
+}
\ No newline at end of file
--- /dev/null
+function ITStylesheet(e,t){return"undefined"!=typeof e.document&&(this.document=e.document,delete e.document),this.property_dom_names={},this.property_standard_names={},this.converted_rgb_values={},this.args="undefined"!=typeof e?e:{},this.action="undefined"!=typeof t?t:"load",this.init=function(){"find"===this.action?this._find_stylesheet():this._load_stylesheet()},this._load_stylesheet=function(){e=this.args;var t;"undefined"!=typeof e.href?(t=this.document.createElement("link"),t.href=e.href,this.type="link"):(t=this.document.createElement("style"),this.type="style"),t.type="text/css","undefined"!=typeof e.title&&(t.title=e.title),"undefined"!=typeof e.rel&&(t.rel=e.rel),"undefined"!=typeof e.media&&(t.media=e.media),"undefined"!=typeof e.href&&"undefined"==typeof e.rel&&(t.rel="stylesheet");var n="";"undefined"!=typeof e.content&&(n=e.content,delete e.content);var r=Math.floor(Math.random()*1e3)+1;this.$stylesheet_node=jQuery(t).insertBefore($i("style#live-css-holder")).addClass("ITStylesheet").attr("id","itstylesheet-"+r),this.stylesheet_node=this.$stylesheet_node[0];var i=this;jQuery.each(this.document.styleSheets,function(e,t){if(typeof t.ownerNode.id=="undefined"||!t.ownerNode.id||t.ownerNode.id!="itstylesheet-"+r)return;return i.stylesheet=t,!1}),this._find_rules(),""!==n&&this.set_rules(n)},this._find_stylesheet=function(){e=this.args;for(var t=0;t<this.document.styleSheets.length;t++){if("undefined"!=typeof e.href&&typeof this.document.styleSheets[t].href=="string"&&this.document.styleSheets[t].href.indexOf(e.href)===-1)continue;if("undefined"!=typeof e.title&&e.title!==this.document.styleSheets[t].title)continue;if("undefined"!=typeof e.rel&&e.rel!==this.document.styleSheets[t].rel)continue;if("undefined"!=typeof e.media&&e.media!==this.document.styleSheets[t].media)continue;if("undefined"!=typeof e.type&&e.type!==this.document.styleSheets[t].type)continue;if("undefined"!=typeof e.disabled&&e.disabled!==this.document.styleSheets[t].disabled)continue;this.type="link",this.stylesheet=this.document.styleSheets[t],this._find_rules();break}},this._find_rules=function(){if("undefined"==typeof this.stylesheet)return;this.stylesheet.cssRules?this.rules=this.stylesheet.cssRules:this.rules=this.stylesheet.rules},this._get_style_from_declarations=function(e){var t="";for(property in e)t+=property+":"+e[property]+"; ";return t},this._get_rules_obj_from_string=function(e){var t={},n=e.match(/\s*[^{;]+\s*{\s*[^{}]+\s*}/g);if(-1===n)return t;for(var r=0;r<n.length;r++){var i=n[r].match(/\s*([^{;]+)\s*{\s*([^{}]+)\s*}/);t[i[1]]=i[2]}return t},this._get_property_dom_name=function(e){if("undefined"!=typeof this.property_dom_names[e])return this.property_dom_names[e];var t=e.split("-"),n=t.shift();while(t.length>0){var r=t.shift();r=r.charAt(0).toUpperCase()+r.substr(1),n+=r}return this.property_dom_names[e]=n,n},this._get_property_standard_name=function(e){if("undefined"!=typeof this.property_standard_names[e])return this.property_standard_names[e];var t=e;return"padding-right-value"===e?t="padding-right":"padding-left-value"===e?t="padding-left":"margin-right-value"===e?t="margin-right":"margin-left-value"===e&&(t="margin-left"),this.property_standard_names[e]=t,t},this._delete_rule_at_index=function(e){this.stylesheet.deleteRule?this.stylesheet.deleteRule(e):this.stylesheet.removeRule(e)},this._get_stylesheet_rules=function(e){return e.cssRules?e.cssRules:e.rules},this._get_stylesheet_rules_object=function(e){var t=this._get_stylesheet_rules(e),n={},r=[];for(var i=0;i<t.length;i++)n[t[i].selectorText]=this._get_rule_declarations_object(t[i]),r.push(t[i].selectorText);r.sort();var s={};for(var i=0;i<r.length;i++)s[r[i]]=n[r[i]];return s},this._get_rule_declarations_object=function(e){var t={},n;e.style?n=e.style:n=e;var r=[];for(var i=0;i<n.length;i++)r.push(n[i]);r.sort();for(var i=0;i<r.length;i++){var s=this._get_property_standard_name(r[i]);"undefined"!=typeof n[s]?t[s]=n[s]:t[s]=n[this._get_property_dom_name(s)]}return t},this.get_rule_index=function(e){if("undefined"==typeof e)return!1;indexes=new Array,this.rules||this._find_rules();if(!this.rules)return!1;if("undefined"!=typeof this.rules[e])return e;for(var t=0;t<this.rules.length;t++)typeof this.rules[t].selectorText=="string"&&this.rules[t].selectorText.toLowerCase()==e.toLowerCase()&&indexes.push(t);return indexes.length!==0?indexes[indexes.length-1]:!1},this.get_rule=function(e){if("undefined"==typeof e)return!1;var t=this.get_rule_index(e);return!1===t||"undefined"==typeof this.rules[t]?!1:this.rules[t]},this.add_rule=function(e,t){return this.update_rule(e,t)},this.update_rule=function(e,t,n){if("undefined"==typeof this.rules||"undefined"==typeof e)return!1;"undefined"==typeof t&&(t={}),"undefined"==typeof n&&(n=!1);if(n)var r=e.split(",");else var r=new Array(e);var i=[];for(var s=0;s<r.length;s++){var o=r[s];if("undefined"==typeof o)continue;var u=this.get_rule(o);try{if(!1===u){var a=this.rules.length;string_declarations="string"==typeof t?t:this._get_style_from_declarations(t),this.stylesheet.addRule?this.stylesheet.addRule(o,string_declarations,a):this.stylesheet.insertRule(o+" {"+string_declarations+"}",a),u=this.rules[a]}else for(property in t)u.style.setAttribute?u.style.setAttribute(property,t[property]):u.style.setProperty(property,t[property],null);i.push(u)}catch(f){}}return i},this.delete_all_rules=function(){while(this.rules.length>0)this._delete_rule_at_index(0)},this.delete_rule=function(e){var t=this.get_rule_index(e);return!1===t?!1:(this._delete_rule_at_index(t),!0)},this.delete_rule_property=function(e,t){var n={};n[t]=null,this.update_rule(e,n)},this._convert_rgb_to_hex=function(e){if("undefined"!=typeof this.converted_rgb_values[e])return this.converted_rgb_values[e];var t=/rgb\(\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)\s*\)/.exec(e),n=parseInt(t[1]),r=parseInt(t[2]),i=parseInt(t[3]),s=i|r<<8|n<<16;hex=s.toString(16).toUpperCase();while(hex.length<6)hex="0"+hex;return this.converted_rgb_values[e]="#"+hex,"#"+hex},this.get_stylesheet_text=function(){var e=this._get_stylesheet_rules_object(this.stylesheet),t="",n=/^rgb\(\s*\d+\s*,\s*\d+\s*,\s*\d+\s*\)/;for(selector in e){var r="";for(property in e[selector]){var i=e[selector][property];if("undefined"==typeof i)continue;n.test(i)&&(i=this._convert_rgb_to_hex(i)),r+=" "+property+": "+i+";\n"}if(""===r)continue;""!==t&&(t+="\n"),t+=selector+" {\n"+r+"}"}return t},this.get_computed_style=function(e){return window.getComputedStyle?window.getComputedStyle(e,""):e.currentStyle},this.set_rules=function(e){this.delete_all_rules(),"string"==typeof e&&(e=this._get_rules_obj_from_string(e));for(selector in e)this.update_rule(selector,e[selector])},this.init(),!0}define("util.misc",["jquery"],function(e){updateQueryStringParameter=function(e,t,n){var r=new RegExp("([?|&])"+t+"=.*?(&|$)","i"),i=e.indexOf("?")!==-1?"&":"?";return e.match(r)?e.replace(r,"$1"+t+"="+n+"$2"):e+i+t+"="+n},jQuery.fn.reverse=[].reverse,Number.prototype.toNearest=function(e){return Math.round(this/e)*e},Math._round=Math.round,Math.round=function(e,t){t=Math.abs(parseInt(t))||0;var n=Math.pow(10,t);return Math._round(e*n)/n},String.prototype.repeatStr=function(e){return e<=0?"":Array.prototype.join.call({length:e+1},this)},String.prototype.capitalize=function(){return this.replace(/(^|\s)([a-z])/g,function(e,t,n){return t+n.toUpperCase()})},hwBoolean=function(e){if(typeof e=="boolean")return e;if(typeof e=="undefined")return!1;if(typeof e=="number")return e===1?!0:e===0?!1:null;if(e===null)return!1;if(typeof e=="string"){var t=e.split(/\b/g);return t[0]==="1"||t[0]==="true"?!0:t[0]==="0"||t[0]==="false"?!1:null}return null},Number.prototype.toBool=function(){return this===1?!0:this===0?!1:null},String.prototype.toBool=function(){var e=this.split(/\b/g);return e[0]==="1"||e[0]==="true"?!0:e[0]==="0"||e[0]==="false"?!1:null},String.prototype.escapeHTML=function(){return this.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""").replace(/'/g,"'")}}),define("util.loader",["jquery","util.misc"],function(e){createCog=function(t,n,r,i,s){if(e(t).length===0||e(t).find(".cog-container:visible").length)return!1;var r=typeof r=="undefined"?!1:r,o='<div class="cog-container"><div class="cog-bottom-left"></div><div class="cog-top-right"></div></div>';return r?t.append(o):t.html(o),typeof s!="undefined"&&t.find(".cog-container").css({opacity:s}),!0},changeTitle=function(t){return e("title").text(t)},startTitleActivityIndicator=function(){return typeof titleActivityIndicatorInstance=="number"?!1:(titleActivityIndicatorInstance=window.setInterval(titleActivityIndicator,500),titleActivityIndicatorSavedTitle=e("title").text(),!0)},stopTitleActivityIndicator=function(){return typeof titleActivityIndicatorInstance!="number"?!1:(window.clearInterval(titleActivityIndicatorInstance),changeTitle(titleActivityIndicatorSavedTitle),delete titleActivityIndicatorCounter,delete titleActivityIndicatorSavedTitle,delete titleActivityIndicatorInstance,!0)},titleActivityIndicator=function(){typeof titleActivityIndicatorCounter=="undefined"&&(titleActivityIndicatorCounter=0,titleActivityIndicatorCounterPos=!0),titleActivityIndicatorCounterPos===!0?++titleActivityIndicatorCounter:--titleActivityIndicatorCounter,titleActivityIndicatorCounter===3?titleActivityIndicatorCounterPos=!1:titleActivityIndicatorCounter===0&&(titleActivityIndicatorCounterPos=!0);var e=titleActivityIndicatorSavedTitle+".".repeatStr(titleActivityIndicatorCounter);changeTitle(e)}}),function(){var DEBUG=!0;(function(undefined){var window=this||(0,eval)("this"),document=window.document,navigator=window.navigator,jQuery=window.jQuery,JSON=window.JSON;(function(e){if(typeof require=="function"&&typeof exports=="object"&&typeof module=="object"){var t=module.exports||exports;e(t)}else typeof define=="function"&&define.amd?define("ko",["exports"],e):e(window.ko={})})(function(e){function r(e,t){var r=e===null||typeof e in n;return r?e===t:!1}function i(e,t){var n;return function(){n||(n=setTimeout(function(){n=undefined,e()},t))}}function s(e,t){var n;return function(){clearTimeout(n),n=setTimeout(e,t)}}function o(e){var n=this;return e&&t.utils.objectForEach(e,function(e,r){var i=t.extenders[e];typeof i=="function"&&(n=i(n,r)||n)}),n}function d(e){t.bindingHandlers[e]={init:function(n,r,i,s,o){var u=function(){var t={};return t[e]=r(),t};return t.bindingHandlers.event.init.call(this,n,u,i,s,o)}}}function g(e,n,r,i){t.bindingHandlers[e]={init:function(e,s,o,u,a){var f,l;return t.computed(function(){var o=t.utils.unwrapObservable(s()),u=!r!=!o,c=!l,h=c||n||u!==f;h&&(c&&t.computedContext.getDependenciesCount()&&(l=t.utils.cloneNodes(t.virtualElements.childNodes(e),!0)),u?(c||t.virtualElements.setDomNodeChildren(e,t.utils.cloneNodes(l)),t.applyBindingsToDescendants(i?i(a,o):a,e)):t.virtualElements.emptyNode(e),f=u)},null,{disposeWhenNodeIsRemoved:e}),{controlsDescendantBindings:!0}}},t.expressionRewriting.bindingRewriteValidators[e]=!1,t.virtualElements.allowedBindings[e]=!0}var t=typeof e!="undefined"?e:{};t.exportSymbol=function(e,n){var r=e.split("."),i=t;for(var s=0;s<r.length-1;s++)i=i[r[s]];i[r[r.length-1]]=n},t.exportProperty=function(e,t,n){e[t]=n},t.version="3.1.0",t.exportSymbol("version",t.version),t.utils=function(){function e(e,t){for(var n in e)e.hasOwnProperty(n)&&t(n,e[n])}function n(e,t){if(t)for(var n in t)t.hasOwnProperty(n)&&(e[n]=t[n]);return e}function r(e,t){return e.__proto__=t,e}function h(e,n){if(t.utils.tagNameLower(e)!=="input"||!e.type)return!1;if(n.toLowerCase()!="click")return!1;var r=e.type;return r=="checkbox"||r=="radio"}var i={__proto__:[]}instanceof Array,s={},o={},u=navigator&&/Firefox\/2/i.test(navigator.userAgent)?"KeyboardEvent":"UIEvents";s[u]=["keyup","keydown","keypress"],s.MouseEvents=["click","dblclick","mousedown","mouseup","mousemove","mouseover","mouseout","mouseenter","mouseleave"],e(s,function(e,t){if(t.length)for(var n=0,r=t.length;n<r;n++)o[t[n]]=e});var a={propertychange:!0},f=document&&function(){var e=3,t=document.createElement("div"),n=t.getElementsByTagName("i");while(t.innerHTML="<!--[if gt IE "+ ++e+"]><i></i><![endif]-->",n[0]);return e>4?e:undefined}(),l=f===6,c=f===7;return{fieldsIncludedWithJsonPost:["authenticity_token",/^__RequestVerificationToken(_.*)?$/],arrayForEach:function(e,t){for(var n=0,r=e.length;n<r;n++)t(e[n],n)},arrayIndexOf:function(e,t){if(typeof Array.prototype.indexOf=="function")return Array.prototype.indexOf.call(e,t);for(var n=0,r=e.length;n<r;n++)if(e[n]===t)return n;return-1},arrayFirst:function(e,t,n){for(var r=0,i=e.length;r<i;r++)if(t.call(n,e[r],r))return e[r];return null},arrayRemoveItem:function(e,n){var r=t.utils.arrayIndexOf(e,n);r>0?e.splice(r,1):r===0&&e.shift()},arrayGetDistinctValues:function(e){e=e||[];var n=[];for(var r=0,i=e.length;r<i;r++)t.utils.arrayIndexOf(n,e[r])<0&&n.push(e[r]);return n},arrayMap:function(e,t){e=e||[];var n=[];for(var r=0,i=e.length;r<i;r++)n.push(t(e[r],r));return n},arrayFilter:function(e,t){e=e||[];var n=[];for(var r=0,i=e.length;r<i;r++)t(e[r],r)&&n.push(e[r]);return n},arrayPushAll:function(e,t){if(t instanceof Array)e.push.apply(e,t);else for(var n=0,r=t.length;n<r;n++)e.push(t[n]);return e},addOrRemoveItem:function(e,n,r){var i=t.utils.arrayIndexOf(t.utils.peekObservable(e),n);i<0?r&&e.push(n):r||e.splice(i,1)},canSetPrototype:i,extend:n,setPrototypeOf:r,setPrototypeOfOrExtend:i?r:n,objectForEach:e,objectMap:function(e,t){if(!e)return e;var n={};for(var r in e)e.hasOwnProperty(r)&&(n[r]=t(e[r],r,e));return n},emptyDomNode:function(e){while(e.firstChild)t.removeNode(e.firstChild)},moveCleanedNodesToContainerElement:function(e){var n=t.utils.makeArray(e),r=document.createElement("div");for(var i=0,s=n.length;i<s;i++)r.appendChild(t.cleanNode(n[i]));return r},cloneNodes:function(e,n){for(var r=0,i=e.length,s=[];r<i;r++){var o=e[r].cloneNode(!0);s.push(n?t.cleanNode(o):o)}return s},setDomNodeChildren:function(e,n){t.utils.emptyDomNode(e);if(n)for(var r=0,i=n.length;r<i;r++)e.appendChild(n[r])},replaceDomNodes:function(e,n){var r=e.nodeType?[e]:e;if(r.length>0){var i=r[0],s=i.parentNode;for(var o=0,u=n.length;o<u;o++)s.insertBefore(n[o],i);for(var o=0,u=r.length;o<u;o++)t.removeNode(r[o])}},fixUpContinuousNodeArray:function(e,t){if(e.length){t=t.nodeType===8&&t.parentNode||t;while(e.length&&e[0].parentNode!==t)e.shift();if(e.length>1){var n=e[0],r=e[e.length-1];e.length=0;while(n!==r){e.push(n),n=n.nextSibling;if(!n)return}e.push(r)}}return e},setOptionNodeSelectionState:function(e,t){f<7?e.setAttribute("selected",t):e.selected=t},stringTrim:function(e){return e===null||e===undefined?"":e.trim?e.trim():e.toString().replace(/^[\s\xa0]+|[\s\xa0]+$/g,"")},stringTokenize:function(e,n){var r=[],i=(e||"").split(n);for(var s=0,o=i.length;s<o;s++){var u=t.utils.stringTrim(i[s]);u!==""&&r.push(u)}return r},stringStartsWith:function(e,t){return e=e||"",t.length>e.length?!1:e.substring(0,t.length)===t},domNodeIsContainedBy:function(e,t){if(e===t)return!0;if(e.nodeType===11)return!1;if(t.contains)return t.contains(e.nodeType===3?e.parentNode:e);if(t.compareDocumentPosition)return(t.compareDocumentPosition(e)&16)==16;while(e&&e!=t)e=e.parentNode;return!!e},domNodeIsAttachedToDocument:function(e){return t.utils.domNodeIsContainedBy(e,e.ownerDocument.documentElement)},anyDomNodeIsAttachedToDocument:function(e){return!!t.utils.arrayFirst(e,t.utils.domNodeIsAttachedToDocument)},tagNameLower:function(e){return e&&e.tagName&&e.tagName.toLowerCase()},registerEventHandler:function(e,n,r){var i=f&&a[n];if(!i&&jQuery)jQuery(e).bind(n,r);else if(!i&&typeof e.addEventListener=="function")e.addEventListener(n,r,!1);else{if(typeof e.attachEvent=="undefined")throw new Error("Browser doesn't support addEventListener or attachEvent");var s=function(t){r.call(e,t)},o="on"+n;e.attachEvent(o,s),t.utils.domNodeDisposal.addDisposeCallback(e,function(){e.detachEvent(o,s)})}},triggerEvent:function(e,t){if(!e||!e.nodeType)throw new Error("element must be a DOM node when calling triggerEvent");var n=h(e,t);if(jQuery&&!n)jQuery(e).trigger(t);else if(typeof document.createEvent=="function"){if(typeof e.dispatchEvent!="function")throw new Error("The supplied element doesn't support dispatchEvent");var r=o[t]||"HTMLEvents",i=document.createEvent(r);i.initEvent(t,!0,!0,window,0,0,0,0,0,!1,!1,!1,!1,0,e),e.dispatchEvent(i)}else if(n&&e.click)e.click();else{if(typeof e.fireEvent=="undefined")throw new Error("Browser doesn't support triggering events");e.fireEvent("on"+t)}},unwrapObservable:function(e){return t.isObservable(e)?e():e},peekObservable:function(e){return t.isObservable(e)?e.peek():e},toggleDomNodeCssClass:function(e,n,r){if(n){var i=/\S+/g,s=e.className.match(i)||[];t.utils.arrayForEach(n.match(i),function(e){t.utils.addOrRemoveItem(s,e,r)}),e.className=s.join(" ")}},setTextContent:function(e,n){var r=t.utils.unwrapObservable(n);if(r===null||r===undefined)r="";var i=t.virtualElements.firstChild(e);!i||i.nodeType!=3||t.virtualElements.nextSibling(i)?t.virtualElements.setDomNodeChildren(e,[e.ownerDocument.createTextNode(r)]):i.data=r,t.utils.forceRefresh(e)},setElementName:function(e,t){e.name=t;if(f<=7)try{e.mergeAttributes(document.createElement("<input name='"+e.name+"'/>"),!1)}catch(n){}},forceRefresh:function(e){if(f>=9){var t=e.nodeType==1?e:e.parentNode;t.style&&(t.style.zoom=t.style.zoom)}},ensureSelectElementIsRenderedCorrectly:function(e){if(f){var t=e.style.width;e.style.width=0,e.style.width=t}},range:function(e,n){e=t.utils.unwrapObservable(e),n=t.utils.unwrapObservable(n);var r=[];for(var i=e;i<=n;i++)r.push(i);return r},makeArray:function(e){var t=[];for(var n=0,r=e.length;n<r;n++)t.push(e[n]);return t},isIe6:l,isIe7:c,ieVersion:f,getFormFields:function(e,n){var r=t.utils.makeArray(e.getElementsByTagName("input")).concat(t.utils.makeArray(e.getElementsByTagName("textarea"))),i=typeof n=="string"?function(e){return e.name===n}:function(e){return n.test(e.name)},s=[];for(var o=r.length-1;o>=0;o--)i(r[o])&&s.push(r[o]);return s},parseJson:function(e){if(typeof e=="string"){e=t.utils.stringTrim(e);if(e)return JSON&&JSON.parse?JSON.parse(e):(new Function("return "+e))()}return null},stringifyJson:function(e,n,r){if(!JSON||!JSON.stringify)throw new Error("Cannot find JSON.stringify(). Some browsers (e.g., IE < 8) don't support it natively, but you can overcome this by adding a script reference to json2.js, downloadable from http://www.json.org/json2.js");return JSON.stringify(t.utils.unwrapObservable(e),n,r)},postJson:function(n,r,i){i=i||{};var s=i.params||{},o=i.includeFields||this.fieldsIncludedWithJsonPost,u=n;if(typeof n=="object"&&t.utils.tagNameLower(n)==="form"){var a=n;u=a.action;for(var f=o.length-1;f>=0;f--){var l=t.utils.getFormFields(a,o[f]);for(var c=l.length-1;c>=0;c--)s[l[c].name]=l[c].value}}r=t.utils.unwrapObservable(r);var h=document.createElement("form");h.style.display="none",h.action=u,h.method="post";for(var p in r){var d=document.createElement("input");d.name=p,d.value=t.utils.stringifyJson(t.utils.unwrapObservable(r[p])),h.appendChild(d)}e(s,function(e,t){var n=document.createElement("input");n.name=e,n.value=t,h.appendChild(n)}),document.body.appendChild(h),i.submitter?i.submitter(h):h.submit(),setTimeout(function(){h.parentNode.removeChild(h)},0)}}}(),t.exportSymbol("utils",t.utils),t.exportSymbol("utils.arrayForEach",t.utils.arrayForEach),t.exportSymbol("utils.arrayFirst",t.utils.arrayFirst),t.exportSymbol("utils.arrayFilter",t.utils.arrayFilter),t.exportSymbol("utils.arrayGetDistinctValues",t.utils.arrayGetDistinctValues),t.exportSymbol("utils.arrayIndexOf",t.utils.arrayIndexOf),t.exportSymbol("utils.arrayMap",t.utils.arrayMap),t.exportSymbol("utils.arrayPushAll",t.utils.arrayPushAll),t.exportSymbol("utils.arrayRemoveItem",t.utils.arrayRemoveItem),t.exportSymbol("utils.extend",t.utils.extend),t.exportSymbol("utils.fieldsIncludedWithJsonPost",t.utils.fieldsIncludedWithJsonPost),t.exportSymbol("utils.getFormFields",t.utils.getFormFields),t.exportSymbol("utils.peekObservable",t.utils.peekObservable),t.exportSymbol("utils.postJson",t.utils.postJson),t.exportSymbol("utils.parseJson",t.utils.parseJson),t.exportSymbol("utils.registerEventHandler",t.utils.registerEventHandler),t.exportSymbol("utils.stringifyJson",t.utils.stringifyJson),t.exportSymbol("utils.range",t.utils.range),t.exportSymbol("utils.toggleDomNodeCssClass",t.utils.toggleDomNodeCssClass),t.exportSymbol("utils.triggerEvent",t.utils.triggerEvent),t.exportSymbol("utils.unwrapObservable",t.utils.unwrapObservable),t.exportSymbol("utils.objectForEach",t.utils.objectForEach),t.exportSymbol("utils.addOrRemoveItem",t.utils.addOrRemoveItem),t.exportSymbol("unwrap",t.utils.unwrapObservable),Function.prototype.bind||(Function.prototype.bind=function(e){var t=this,n=Array.prototype.slice.call(arguments),e=n.shift();return function(){return t.apply(e,n.concat(Array.prototype.slice.call(arguments)))}}),t.utils.domData=new function(){function r(r,i){var s=r[t],o=s&&s!=="null"&&n[s];if(!o){if(!i)return undefined;s=r[t]="ko"+e++,n[s]={}}return n[s]}var e=0,t="__ko__"+(new Date).getTime(),n={};return{get:function(e,t){var n=r(e,!1);return n===undefined?undefined:n[t]},set:function(e,t,n){if(n===undefined&&r(e,!1)===undefined)return;var i=r(e,!0);i[t]=n},clear:function(e){var r=e[t];return r?(delete n[r],e[t]=null,!0):!1},nextKey:function(){return e++ +t}}},t.exportSymbol("utils.domData",t.utils.domData),t.exportSymbol("utils.domData.clear",t.utils.domData.clear),t.utils.domNodeDisposal=new function(){function i(n,r){var i=t.utils.domData.get(n,e);return i===undefined&&r&&(i=[],t.utils.domData.set(n,e,i)),i}function s(n){t.utils.domData.set(n,e,undefined)}function o(e){var n=i(e,!1);if(n){n=n.slice(0);for(var s=0;s<n.length;s++)n[s](e)}t.utils.domData.clear(e),t.utils.domNodeDisposal.cleanExternalData(e),r[e.nodeType]&&u(e)}function u(e){var t,n=e.firstChild;while(t=n)n=t.nextSibling,t.nodeType===8&&o(t)}var e=t.utils.domData.nextKey(),n={1:!0,8:!0,9:!0},r={1:!0,9:!0};return{addDisposeCallback:function(e,t){if(typeof t!="function")throw new Error("Callback must be a function");i(e,!0).push(t)},removeDisposeCallback:function(e,n){var r=i(e,!1);r&&(t.utils.arrayRemoveItem(r,n),r.length==0&&s(e))},cleanNode:function(e){if(n[e.nodeType]){o(e);if(r[e.nodeType]){var i=[];t.utils.arrayPushAll(i,e.getElementsByTagName("*"));for(var s=0,u=i.length;s<u;s++)o(i[s])}}return e},removeNode:function(e){t.cleanNode(e),e.parentNode&&e.parentNode.removeChild(e)},cleanExternalData:function(e){jQuery&&typeof jQuery["cleanData"]=="function"&&jQuery.cleanData([e])}}},t.cleanNode=t.utils.domNodeDisposal.cleanNode,t.removeNode=t.utils.domNodeDisposal.removeNode,t.exportSymbol("cleanNode",t.cleanNode),t.exportSymbol("removeNode",t.removeNode),t.exportSymbol("utils.domNodeDisposal",t.utils.domNodeDisposal),t.exportSymbol("utils.domNodeDisposal.addDisposeCallback",t.utils.domNodeDisposal.addDisposeCallback),t.exportSymbol("utils.domNodeDisposal.removeDisposeCallback",t.utils.domNodeDisposal.removeDisposeCallback),function(){function n(e){var n=t.utils.stringTrim(e).toLowerCase(),r=document.createElement("div"),i=n.match(/^<(thead|tbody|tfoot)/)&&[1,"<table>","</table>"]||!n.indexOf("<tr")&&[2,"<table><tbody>","</tbody></table>"]||(!n.indexOf("<td")||!n.indexOf("<th"))&&[3,"<table><tbody><tr>","</tr></tbody></table>"]||[0,"",""],s="ignored<div>"+i[1]+e+i[2]+"</div>";typeof window["innerShiv"]=="function"?r.appendChild(window.innerShiv(s)):r.innerHTML=s;while(i[0]--)r=r.lastChild;return t.utils.makeArray(r.lastChild.childNodes)}function r(e){if(jQuery.parseHTML)return jQuery.parseHTML(e)||[];var t=jQuery.clean([e]);if(t&&t[0]){var n=t[0];while(n.parentNode&&n.parentNode.nodeType!==11)n=n.parentNode;n.parentNode&&n.parentNode.removeChild(n)}return t}var e=/^(\s*)<!--(.*?)-->/;t.utils.parseHtmlFragment=function(e){return jQuery?r(e):n(e)},t.utils.setHtml=function(e,n){t.utils.emptyDomNode(e),n=t.utils.unwrapObservable(n);if(n!==null&&n!==undefined){typeof n!="string"&&(n=n.toString());if(jQuery)jQuery(e).html(n);else{var r=t.utils.parseHtmlFragment(n);for(var i=0;i<r.length;i++)e.appendChild(r[i])}}}}(),t.exportSymbol("utils.parseHtmlFragment",t.utils.parseHtmlFragment),t.exportSymbol("utils.setHtml",t.utils.setHtml),t.memoization=function(){function n(){return((1+Math.random())*4294967296|0).toString(16).substring(1)}function r(){return n()+n()}function i(e,n){if(!e)return;if(e.nodeType==8){var r=t.memoization.parseMemoText(e.nodeValue);r!=null&&n.push({domNode:e,memoId:r})}else if(e.nodeType==1)for(var s=0,o=e.childNodes,u=o.length;s<u;s++)i(o[s],n)}var e={};return{memoize:function(t){if(typeof t!="function")throw new Error("You can only pass a function to ko.memoization.memoize()");var n=r();return e[n]=t,"<!--[ko_memo:"+n+"]-->"},unmemoize:function(t,n){var r=e[t];if(r===undefined)throw new Error("Couldn't find any memo with ID "+t+". Perhaps it's already been unmemoized.");try{return r.apply(null,n||[]),!0}finally{delete e[t]}},unmemoizeDomNodeAndDescendants:function(e,n){var r=[];i(e,r);for(var s=0,o=r.length;s<o;s++){var u=r[s].domNode,a=[u];n&&t.utils.arrayPushAll(a,n),t.memoization.unmemoize(r[s].memoId,a),u.nodeValue="",u.parentNode&&u.parentNode.removeChild(u)}},parseMemoText:function(e){var t=e.match(/^\[ko_memo\:(.*?)\]$/);return t?t[1]:null}}}(),t.exportSymbol("memoization",t.memoization),t.exportSymbol("memoization.memoize",t.memoization.memoize),t.exportSymbol("memoization.unmemoize",t.memoization.unmemoize),t.exportSymbol("memoization.parseMemoText",t.memoization.parseMemoText),t.exportSymbol("memoization.unmemoizeDomNodeAndDescendants",t.memoization.unmemoizeDomNodeAndDescendants),t.extenders={throttle:function(e,n){e.throttleEvaluation=n;var r=null;return t.dependentObservable({read:e,write:function(t){clearTimeout(r),r=setTimeout(function(){e(t)},n)}})},rateLimit:function(e,t){var n,r,o;typeof t=="number"?n=t:(n=t.timeout,r=t.method),o=r=="notifyWhenChangesStop"?s:i,e.limit(function(e){return o(e,n)})},notify:function(e,t){e.equalityComparer=t=="always"?null:r}};var n={"undefined":1,"boolean":1,number:1,string:1};t.exportSymbol("extenders",t.extenders),t.subscription=function(e,n,r){this.target=e,this.callback=n,this.disposeCallback=r,this.isDisposed=!1,t.exportProperty(this,"dispose",this.dispose)},t.subscription.prototype.dispose=function(){this.isDisposed=!0,this.disposeCallback()},t.subscribable=function(){t.utils.setPrototypeOfOrExtend(this,t.subscribable.fn),this._subscriptions={}};var u="change",a={subscribe:function(e,n,r){var i=this;r=r||u;var s=n?e.bind(n):e,o=new t.subscription(i,s,function(){t.utils.arrayRemoveItem(i._subscriptions[r],o)});return i.peek&&i.peek(),i._subscriptions[r]||(i._subscriptions[r]=[]),i._subscriptions[r].push(o),o},notifySubscribers:function(e,n){n=n||u;if(this.hasSubscriptionsForEvent(n))try{t.dependencyDetection.begin();for(var r=this._subscriptions[n].slice(0),i=0,s;s=r[i];++i)s.isDisposed||s.callback(e)}finally{t.dependencyDetection.end()}},limit:function(e){var n=this,r=t.isObservable(n),i,s,o,a="beforeChange";n._origNotifySubscribers||(n._origNotifySubscribers=n.notifySubscribers,n.notifySubscribers=function(e,t){!t||t===u?n._rateLimitedChange(e):t===a?n._rateLimitedBeforeChange(e):n._origNotifySubscribers(e,t)});var f=e(function(){r&&o===n&&(o=n()),i=!1,n.isDifferent(s,o)&&n._origNotifySubscribers(s=o)});n._rateLimitedChange=function(e){i=!0,o=e,f()},n._rateLimitedBeforeChange=function(e){i||(s=e,n._origNotifySubscribers(e,a))}},hasSubscriptionsForEvent:function(e){return this._subscriptions[e]&&this._subscriptions[e].length},getSubscriptionsCount:function(){var e=0;return t.utils.objectForEach(this._subscriptions,function(t,n){e+=n.length}),e},isDifferent:function(e,t){return!this.equalityComparer||!this.equalityComparer(e,t)},extend:o};t.exportProperty(a,"subscribe",a.subscribe),t.exportProperty(a,"extend",a.extend),t.exportProperty(a,"getSubscriptionsCount",a.getSubscriptionsCount),t.utils.canSetPrototype&&t.utils.setPrototypeOf(a,Function.prototype),t.subscribable.fn=a,t.isSubscribable=function(e){return e!=null&&typeof e.subscribe=="function"&&typeof e["notifySubscribers"]=="function"},t.exportSymbol("subscribable",t.subscribable),t.exportSymbol("isSubscribable",t.isSubscribable),t.computedContext=t.dependencyDetection=function(){function i(){return++r}function s(t){e.push(n),n=t}function o(){n=e.pop()}var e=[],n,r=0;return{begin:s,end:o,registerDependency:function(e){if(n){if(!t.isSubscribable(e))throw new Error("Only subscribable things can act as dependencies");n.callback(e,e._id||(e._id=i()))}},ignore:function(e,t,n){try{return s(),e.apply(t,n||[])}finally{o()}},getDependenciesCount:function(){if(n)return n.computed.getDependenciesCount()},isInitial:function(){if(n)return n.isInitial}}}(),t.exportSymbol("computedContext",t.computedContext),t.exportSymbol("computedContext.getDependenciesCount",t.computedContext.getDependenciesCount),t.exportSymbol("computedContext.isInitial",t.computedContext.isInitial),t.observable=function(e){function r(){return arguments.length>0?(r.isDifferent(n,arguments[0])&&(r.valueWillMutate(),n=arguments[0],DEBUG&&(r._latestValue=n),r.valueHasMutated()),this):(t.dependencyDetection.registerDependency(r),n)}var n=e;return t.subscribable.call(r),t.utils.setPrototypeOfOrExtend(r,t.observable.fn),DEBUG&&(r._latestValue=n),r.peek=function(){return n},r.valueHasMutated=function(){r.notifySubscribers(n)},r.valueWillMutate=function(){r.notifySubscribers(n,"beforeChange")},t.exportProperty(r,"peek",r.peek),t.exportProperty(r,"valueHasMutated",r.valueHasMutated),t.exportProperty(r,"valueWillMutate",r.valueWillMutate),r},t.observable.fn={equalityComparer:r};var f=t.observable.protoProperty="__ko_proto__";t.observable.fn[f]=t.observable,t.utils.canSetPrototype&&t.utils.setPrototypeOf(t.observable.fn,t.subscribable.fn),t.hasPrototype=function(e,n){return e===null||e===undefined||e[f]===undefined?!1:e[f]===n?!0:t.hasPrototype(e[f],n)},t.isObservable=function(e){return t.hasPrototype(e,t.observable)},t.isWriteableObservable=function(e){return typeof e=="function"&&e[f]===t.observable?!0:typeof e=="function"&&e[f]===t.dependentObservable&&e.hasWriteFunction?!0:!1},t.exportSymbol("observable",t.observable),t.exportSymbol("isObservable",t.isObservable),t.exportSymbol("isWriteableObservable",t.isWriteableObservable),t.observableArray=function(e){e=e||[];if(typeof e=="object"&&"length"in e){var n=t.observable(e);return t.utils.setPrototypeOfOrExtend(n,t.observableArray.fn),n.extend({trackArrayChanges:!0})}throw new Error("The argument passed when initializing an observable array must be an array, or null, or undefined.")},t.observableArray.fn={remove:function(e){var n=this.peek(),r=[],i=typeof e=="function"&&!t.isObservable(e)?e:function(t){return t===e};for(var s=0;s<n.length;s++){var o=n[s];i(o)&&(r.length===0&&this.valueWillMutate(),r.push(o),n.splice(s,1),s--)}return r.length&&this.valueHasMutated(),r},removeAll:function(e){if(e===undefined){var n=this.peek(),r=n.slice(0);return this.valueWillMutate(),n.splice(0,n.length),this.valueHasMutated(),r}return e?this.remove(function(n){return t.utils.arrayIndexOf(e,n)>=0}):[]},destroy:function(e){var n=this.peek(),r=typeof e=="function"&&!t.isObservable(e)?e:function(t){return t===e};this.valueWillMutate();for(var i=n.length-1;i>=0;i--){var s=n[i];r(s)&&(n[i]._destroy=!0)}this.valueHasMutated()},destroyAll:function(e){return e===undefined?this.destroy(function(){return!0}):e?this.destroy(function(n){return t.utils.arrayIndexOf(e,n)>=0}):[]},indexOf:function(e){var n=this();return t.utils.arrayIndexOf(n,e)},replace:function(e,t){var n=this.indexOf(e);n>=0&&(this.valueWillMutate(),this.peek()[n]=t,this.valueHasMutated())}},t.utils.arrayForEach(["pop","push","reverse","shift","sort","splice","unshift"],function(e){t.observableArray.fn[e]=function(){var t=this.peek();this.valueWillMutate(),this.cacheDiffForKnownOperation(t,e,arguments);var n=t[e].apply(t,arguments);return this.valueHasMutated(),n}}),t.utils.arrayForEach(["slice"],function(e){t.observableArray.fn[e]=function(){var t=this();return t[e].apply(t,arguments)}}),t.utils.canSetPrototype&&t.utils.setPrototypeOf(t.observableArray.fn,t.observable.fn),t.exportSymbol("observableArray",t.observableArray);var l="arrayChange";t.extenders.trackArrayChanges=function(e){function o(){if(n)return;n=!0;var t=e.notifySubscribers;e.notifySubscribers=function(e,n){return(!n||n===u)&&++i,t.apply(this,arguments)};var s=[].concat(e.peek()||[]);r=null,e.subscribe(function(t){t=[].concat(t||[]);if(e.hasSubscriptionsForEvent(l)){var n=a(s,t);n.length&&e.notifySubscribers(n,l)}s=t,r=null,i=0})}function a(e,n){if(!r||i>1)r=t.utils.compareArrays(e,n,{sparse:!0});return r}if(e.cacheDiffForKnownOperation)return;var n=!1,r=null,i=0,s=e.subscribe;e.subscribe=e.subscribe=function(e,t,n){return n===l&&o(),s.apply(this,arguments)},e.cacheDiffForKnownOperation=function(e,s,o){function c(e,t,n){return u[u.length]={status:e,value:t,index:n}}if(!n||i)return;var u=[],a=e.length,f=o.length,l=0;switch(s){case"push":l=a;case"unshift":for(var h=0;h<f;h++)c("added",o[h],l+h);break;case"pop":l=a-1;case"shift":a&&c("deleted",e[l],l);break;case"splice":var p=Math.min(Math.max(0,o[0]<0?a+o[0]:o[0]),a),d=f===1?a:Math.min(p+(o[1]||0),a),v=p+f-2,m=Math.max(d,v),g=[],y=[];for(var h=p,b=2;h<m;++h,++b)h<d&&y.push(c("deleted",e[h],h)),h<v&&g.push(c("added",o[b],h));t.utils.findMovesInArrayComparison(y,g);break;default:return}r=u}},t.computed=t.dependentObservable=function(e,n,r){function l(e,t){S[t]||(S[t]=e.subscribe(h),++x)}function c(){a=!0,t.utils.objectForEach(S,function(e,t){t.dispose()}),S={},x=0,s=!1}function h(){var e=d.throttleEvaluation;e&&e>=0?(clearTimeout(T),T=setTimeout(p,e)):d._evalRateLimited?d._evalRateLimited():p()}function p(){if(o)return;if(a)return;if(w&&w()){if(!u){E();return}}else u=!1;o=!0;try{var e=S,r=x;t.dependencyDetection.begin({callback:function(t,n){a||(r&&e[n]?(S[n]=e[n],++x,delete e[n],--r):l(t,n))},computed:d,isInitial:!x}),S={},x=0;try{var c=n?f.call(n):f()}finally{t.dependencyDetection.end(),r&&t.utils.objectForEach(e,function(e,t){t.dispose()}),s=!1}d.isDifferent(i,c)&&(d.notifySubscribers(i,"beforeChange"),i=c,DEBUG&&(d._latestValue=i),(!d._evalRateLimited||d.throttleEvaluation)&&d.notifySubscribers(i))}finally{o=!1}x||E()}function d(){if(arguments.length>0){if(typeof g!="function")throw new Error("Cannot write a value to a ko.computed unless you specify a 'write' option. If you wish to read the current value, don't pass any parameters.");return g.apply(n,arguments),this}return s&&p(),t.dependencyDetection.registerDependency(d),i}function v(){return s&&!x&&p(),i}function m(){return s||x>0}var i,s=!0,o=!1,u=!1,a=!1,f=e;f&&typeof f=="object"?(r=f,f=r.read):(r=r||{},f||(f=r.read));if(typeof f!="function")throw new Error("Pass a function that returns the value of the ko.computed");var g=r.write,y=r.disposeWhenNodeIsRemoved||r.disposeWhenNodeIsRemoved||null,b=r.disposeWhen||r.disposeWhen,w=b,E=c,S={},x=0,T=null;n||(n=r.owner),t.subscribable.call(d),t.utils.setPrototypeOfOrExtend(d,t.dependentObservable.fn),d.peek=v,d.getDependenciesCount=function(){return x},d.hasWriteFunction=typeof r.write=="function",d.dispose=function(){E()},d.isActive=m;var N=d.limit;return d.limit=function(e){N.call(d,e),d._evalRateLimited=function(){d._rateLimitedBeforeChange(i),s=!0,d._rateLimitedChange(d)}},t.exportProperty(d,"peek",d.peek),t.exportProperty(d,"dispose",d.dispose),t.exportProperty(d,"isActive",d.isActive),t.exportProperty(d,"getDependenciesCount",d.getDependenciesCount),y&&(u=!0,y.nodeType&&(w=function(){return!t.utils.domNodeIsAttachedToDocument(y)||b&&b()})),r.deferEvaluation!==!0&&p(),y&&m()&&y.nodeType&&(E=function(){t.utils.domNodeDisposal.removeDisposeCallback(y,E),c()},t.utils.domNodeDisposal.addDisposeCallback(y,E)),d},t.isComputed=function(e){return t.hasPrototype(e,t.dependentObservable)};var c=t.observable.protoProperty;t.dependentObservable[c]=t.observable,t.dependentObservable.fn={equalityComparer:r},t.dependentObservable.fn[c]=t.dependentObservable,t.utils.canSetPrototype&&t.utils.setPrototypeOf(t.dependentObservable.fn,t.subscribable.fn),t.exportSymbol("dependentObservable",t.dependentObservable),t.exportSymbol("computed",t.dependentObservable),t.exportSymbol("isComputed",t.isComputed),function(){function n(e,t,s){s=s||new i,e=t(e);var o=typeof e=="object"&&e!==null&&e!==undefined&&!(e instanceof Date)&&!(e instanceof String)&&!(e instanceof Number)&&!(e instanceof Boolean);if(!o)return e;var u=e instanceof Array?[]:{};return s.save(e,u),r(e,function(r){var i=t(e[r]);switch(typeof i){case"boolean":case"number":case"string":case"function":u[r]=i;break;case"object":case"undefined":var o=s.get(i);u[r]=o!==undefined?o:n(i,t,s)}}),u}function r(e,t){if(e instanceof Array){for(var n=0;n<e.length;n++)t(n);typeof e["toJSON"]=="function"&&t("toJSON")}else for(var r in e)t(r)}function i(){this.keys=[],this.values=[]}var e=10;t.toJS=function(r){if(arguments.length==0)throw new Error("When calling ko.toJS, pass the object you want to convert.");return n(r,function(n){for(var r=0;t.isObservable(n)&&r<e;r++)n=n();return n})},t.toJSON=function(e,n,r){var i=t.toJS(e);return t.utils.stringifyJson(i,n,r)},i.prototype={constructor:i,save:function(e,n){var r=t.utils.arrayIndexOf(this.keys,e);r>=0?this.values[r]=n:(this.keys.push(e),this.values.push(n))},get:function(e){var n=t.utils.arrayIndexOf(this.keys,e);return n>=0?this.values[n]:undefined}}}(),t.exportSymbol("toJS",t.toJS),t.exportSymbol("toJSON",t.toJSON),function(){var e="__ko__hasDomDataOptionValue__";t.selectExtensions={readValue:function(n){switch(t.utils.tagNameLower(n)){case"option":if(n[e]===!0)return t.utils.domData.get(n,t.bindingHandlers.options.optionValueDomDataKey);return t.utils.ieVersion<=7?n.getAttributeNode("value")&&n.getAttributeNode("value").specified?n.value:n.text:n.value;case"select":return n.selectedIndex>=0?t.selectExtensions.readValue(n.options[n.selectedIndex]):undefined;default:return n.value}},writeValue:function(n,r,i){switch(t.utils.tagNameLower(n)){case"option":switch(typeof r){case"string":t.utils.domData.set(n,t.bindingHandlers.options.optionValueDomDataKey,undefined),e in n&&delete n[e],n.value=r;break;default:t.utils.domData.set(n,t.bindingHandlers.options.optionValueDomDataKey,r),n[e]=!0,n.value=typeof r=="number"?r:""}break;case"select":if(r===""||r===null)r=undefined;var s=-1;for(var o=0,u=n.options.length,a;o<u;++o){a=t.selectExtensions.readValue(n.options[o]);if(a==r||a==""&&r===undefined){s=o;break}}if(i||s>=0||r===undefined&&n.size>1)n.selectedIndex=s;break;default:if(r===null||r===undefined)r="";n.value=r}}}}(),t.exportSymbol("selectExtensions",t.selectExtensions),t.exportSymbol("selectExtensions.readValue",t.selectExtensions.readValue),t.exportSymbol("selectExtensions.writeValue",t.selectExtensions.writeValue),t.expressionRewriting=function(){function r(r){if(t.utils.arrayIndexOf(e,r)>=0)return!1;var i=r.match(n);return i===null?!1:i[1]?"Object("+i[1]+")"+i[2]:r}function p(e){var n=t.utils.stringTrim(e);n.charCodeAt(0)===123&&(n=n.slice(1,-1));var r=[],i=n.match(l),s,o,u=0;if(i){i.push(",");for(var a=0,f;f=i[a];++a){var p=f.charCodeAt(0);if(p===44){if(u<=0){s&&r.push(o?{key:s,value:o.join("")}:{unknown:s}),s=o=u=0;continue}}else if(p===58){if(!o)continue}else if(p===47&&a&&f.length>1){var d=i[a-1].match(c);d&&!h[d[0]]&&(n=n.substr(n.indexOf(f)+1),i=n.match(l),i.push(","),a=-1,f="/")}else if(p===40||p===123||p===91)++u;else if(p===41||p===125||p===93)--u;else if(!s&&!o){s=p===34||p===39?f.slice(1,-1):f;continue}o?o.push(f):o=[f]}}return r}function v(e,n){function i(e,n){function f(t){return t&&t.preprocess?n=t.preprocess(n,e,i):!0}var a;if(!f(t.getBindingHandler(e)))return;d[e]&&(a=r(n))&&o.push("'"+e+"':function(_z){"+a+"=_z}"),u&&(n="function(){return "+n+" }"),s.push("'"+e+"':"+n)}n=n||{};var s=[],o=[],u=n.valueAccessors,a=typeof e=="string"?p(e):e;return t.utils.arrayForEach(a,function(e){i(e.key||e.unknown,e.value)}),o.length&&i("_ko_property_writers","{"+o.join(",")+" }"),s.join(",")}var e=["true","false","null","undefined"],n=/^(?:[$_a-z][$\w]*|(.+)(\.\s*[$_a-z][$\w]*|\[.+\]))$/i,i='"(?:[^"\\\\]|\\\\.)*"',s="'(?:[^'\\\\]|\\\\.)*'",o="/(?:[^/\\\\]|\\\\.)*/w*",u=",\"'{}()/:[\\]",a="[^\\s:,/][^"+u+"]*[^\\s"+u+"]",f="[^\\s]",l=RegExp(i+"|"+s+"|"+o+"|"+a+"|"+f,"g"),c=/[\])"'A-Za-z0-9_$]+$/,h={"in":1,"return":1,"typeof":1},d={};return{bindingRewriteValidators:[],twoWayBindings:d,parseObjectLiteral:p,preProcessBindings:v,keyValueArrayContainsKey:function(e,t){for(var n=0;n<e.length;n++)if(e[n]["key"]==t)return!0;return!1},writeValueToProperty:function(e,n,r,i,s){if(!e||!t.isObservable(e)){var o=n.get("_ko_property_writers");o&&o[r]&&o[r](i)}else t.isWriteableObservable(e)&&(!s||e.peek()!==i)&&e(i)}}}(),t.exportSymbol("expressionRewriting",t.expressionRewriting),t.exportSymbol("expressionRewriting.bindingRewriteValidators",t.expressionRewriting.bindingRewriteValidators),t.exportSymbol("expressionRewriting.parseObjectLiteral",t.expressionRewriting.parseObjectLiteral),t.exportSymbol("expressionRewriting.preProcessBindings",t.expressionRewriting.preProcessBindings),t.exportSymbol("expressionRewriting._twoWayBindings",t.expressionRewriting.twoWayBindings),t.exportSymbol("jsonExpressionRewriting",t.expressionRewriting),t.exportSymbol("jsonExpressionRewriting.insertPropertyAccessorsIntoJson",t.expressionRewriting.preProcessBindings),function(){function s(t){return t.nodeType==8&&n.test(e?t.text:t.nodeValue)}function o(t){return t.nodeType==8&&r.test(e?t.text:t.nodeValue)}function u(e,t){var n=e,r=1,i=[];while(n=n.nextSibling){if(o(n)){r--;if(r===0)return i}i.push(n),s(n)&&r++}if(!t)throw new Error("Cannot find closing comment tag to match: "+e.nodeValue);return null}function a(e,t){var n=u(e,t);return n?n.length>0?n[n.length-1].nextSibling:e.nextSibling:null}function f(e){var t=e.firstChild,n=null;if(t)do if(n)n.push(t);else if(s(t)){var r=a(t,!0);r?t=r:n=[t]}else o(t)&&(n=[t]);while(t=t.nextSibling);return n}var e=document&&document.createComment("test").text==="<!--test-->",n=e?/^<!--\s*ko(?:\s+([\s\S]+))?\s*-->$/:/^\s*ko(?:\s+([\s\S]+))?\s*$/,r=e?/^<!--\s*\/ko\s*-->$/:/^\s*\/ko\s*$/,i={ul:!0,ol:!0};t.virtualElements={allowedBindings:{},childNodes:function(e){return s(e)?u(e):e.childNodes},emptyNode:function(e){if(!s(e))t.utils.emptyDomNode(e);else{var n=t.virtualElements.childNodes(e);for(var r=0,i=n.length;r<i;r++)t.removeNode(n[r])}},setDomNodeChildren:function(e,n){if(!s(e))t.utils.setDomNodeChildren(e,n);else{t.virtualElements.emptyNode(e);var r=e.nextSibling;for(var i=0,o=n.length;i<o;i++)r.parentNode.insertBefore(n[i],r)}},prepend:function(e,t){s(e)?e.parentNode.insertBefore(t,e.nextSibling):e.firstChild?e.insertBefore(t,e.firstChild):e.appendChild(t)},insertAfter:function(e,n,r){r?s(e)?e.parentNode.insertBefore(n,r.nextSibling):r.nextSibling?e.insertBefore(n,r.nextSibling):e.appendChild(n):t.virtualElements.prepend(e,n)},firstChild:function(e){return s(e)?!e.nextSibling||o(e.nextSibling)?null:e.nextSibling:e.firstChild},nextSibling:function(e){return s(e)&&(e=a(e)),e.nextSibling&&o(e.nextSibling)?null:e.nextSibling},hasBindingValue:s,virtualNodeBindingValue:function(t){var r=(e?t.text:t.nodeValue).match(n);return r?r[1]:null},normaliseVirtualElementDomStructure:function(e){if(!i[t.utils.tagNameLower(e)])return;var n=e.firstChild;if(n)do if(n.nodeType===1){var r=f(n);if(r){var s=n.nextSibling;for(var o=0;o<r.length;o++)s?e.insertBefore(r[o],s):e.appendChild(r[o])}}while(n=n.nextSibling)}}}(),t.exportSymbol("virtualElements",t.virtualElements),t.exportSymbol("virtualElements.allowedBindings",t.virtualElements.allowedBindings),t.exportSymbol("virtualElements.emptyNode",t.virtualElements.emptyNode),t.exportSymbol("virtualElements.insertAfter",t.virtualElements.insertAfter),t.exportSymbol("virtualElements.prepend",t.virtualElements.prepend),t.exportSymbol("virtualElements.setDomNodeChildren",t.virtualElements.setDomNodeChildren),function(){function n(e,t,n){var i=e+(n&&n.valueAccessors||"");return t[i]||(t[i]=r(e,n))}function r(e,n){var r=t.expressionRewriting.preProcessBindings(e,n),i="with($context){with($data||{}){return{"+r+"}}}";return new Function("$context","$element",i)}var e="data-bind";t.bindingProvider=function(){this.bindingCache={}},t.utils.extend(t.bindingProvider.prototype,{nodeHasBindings:function(n){switch(n.nodeType){case 1:return n.getAttribute(e)!=null;case 8:return t.virtualElements.hasBindingValue(n);default:return!1}},getBindings:function(e,t){var n=this.getBindingsString(e,t);return n?this.parseBindingsString(n,t,e):null},getBindingAccessors:function(e,t){var n=this.getBindingsString(e,t);return n?this.parseBindingsString(n,t,e,{valueAccessors:!0}):null},getBindingsString:function(n,r){switch(n.nodeType){case 1:return n.getAttribute(e);case 8:return t.virtualElements.virtualNodeBindingValue(n);default:return null}},parseBindingsString:function(e,t,r,i){try{var s=n(e,this.bindingCache,i);return s(t,r)}catch(o){throw o.message="Unable to parse bindings.\nBindings value: "+e+"\nMessage: "+o.message,o}}}),t.bindingProvider.instance=new t.bindingProvider}(),t.exportSymbol("bindingProvider",t.bindingProvider),function(){function n(e){return function(){return e}}function r(e){return e()}function i(e){return t.utils.objectMap(t.dependencyDetection.ignore(e),function(t,n){return function(){return e()[n]}})}function s(e,r,s){return typeof e=="function"?i(e.bind(null,r,s)):t.utils.objectMap(e,n)}function o(e,t){return i(this.getBindings.bind(this,e,t))}function u(e){var n=t.virtualElements.allowedBindings[e];if(!n)throw new Error("The binding '"+e+"' cannot be used with virtual elements")}function a(e,n,r){var i,s=t.virtualElements.firstChild(n),o=t.bindingProvider.instance,u=o.preprocessNode;if(u){while(i=s)s=t.virtualElements.nextSibling(i),u.call(o,i);s=t.virtualElements.firstChild(n)}while(i=s)s=t.virtualElements.nextSibling(i),f(e,i,r)}function f(n,r,i){var s=!0,o=r.nodeType===1;o&&t.virtualElements.normaliseVirtualElementDomStructure(r);var u=o&&i||t.bindingProvider.instance.nodeHasBindings(r);u&&(s=h(r,null,n,i).shouldBindDescendants),s&&!e[t.utils.tagNameLower(r)]&&a(n,r,!o)}function c(e){var n=[],r={},i=[];return t.utils.objectForEach(e,function s(o){if(!r[o]){var u=t.getBindingHandler(o);u&&(u.after&&(i.push(o),t.utils.arrayForEach(u.after,function(n){if(e[n]){if(t.utils.arrayIndexOf(i,n)!==-1)throw Error("Cannot combine the following bindings, because they have a cyclic dependency: "+i.join(", "));s(n)}}),i.length--),n.push({key:o,handler:u})),r[o]=!0}}),n}function h(e,n,i,s){var a=t.utils.domData.get(e,l);if(!n){if(a)throw Error("You cannot apply bindings multiple times to the same element.");t.utils.domData.set(e,l,!0)}!a&&s&&t.storedBindingContextForNode(e,i);var f;if(n&&typeof n!="function")f=n;else{var h=t.bindingProvider.instance,p=h.getBindingAccessors||o,d=t.dependentObservable(function(){return f=n?n(i,e):p.call(h,e,i),f&&i._subscribable&&i._subscribable(),f},null,{disposeWhenNodeIsRemoved:e});if(!f||!d.isActive())d=null}var v;if(f){var m=d?function(e){return function(){return r(d()[e])}}:function(e){return f[e]};function g(){return t.utils.objectMap(d?d():f,r)}g.get=function(e){return f[e]&&r(m(e))},g.has=function(e){return e in f};var y=c(f);t.utils.arrayForEach(y,function(n){var r=n.handler.init,s=n.handler.update,o=n.key;e.nodeType===8&&u(o);try{typeof r=="function"&&t.dependencyDetection.ignore(function(){var t=r(e,m(o),g,i.$data,i);if(t&&t.controlsDescendantBindings){if(v!==undefined)throw new Error("Multiple bindings ("+v+" and "+o+") are trying to control descendant bindings of the same element. You cannot use these bindings together on the same element.");v=o}}),typeof s=="function"&&t.dependentObservable(function(){s(e,m(o),g,i.$data,i)},null,{disposeWhenNodeIsRemoved:e})}catch(a){throw a.message='Unable to process binding "'+o+": "+f[o]+'"\nMessage: '+a.message,a}})}return{shouldBindDescendants:v===undefined}}function d(e){return e&&e instanceof t.bindingContext?e:new t.bindingContext(e)}t.bindingHandlers={};var e={script:!0};t.getBindingHandler=function(e){return t.bindingHandlers[e]},t.bindingContext=function(e,n,r,i){function s(){var s=a?e():e,o=t.utils.unwrapObservable(s);return n?(n._subscribable&&n._subscribable(),t.utils.extend(u,n),l&&(u._subscribable=l)):(u.$parents=[],u.$root=o,u.ko=t),u.$rawData=s,u.$data=o,r&&(u[r]=o),i&&i(u,n,o),u.$data}function o(){return f&&!t.utils.anyDomNodeIsAttachedToDocument(f)}var u=this,a=typeof e=="function"&&!t.isObservable(e),f,l=t.dependentObservable(s,null,{disposeWhen:o,disposeWhenNodeIsRemoved:!0});l.isActive()&&(u._subscribable=l,l.equalityComparer=null,f=[],l._addNode=function(e){f.push(e),t.utils.domNodeDisposal.addDisposeCallback(e,function(e){t.utils.arrayRemoveItem(f,e),f.length||(l.dispose(),u._subscribable=l=undefined)})})},t.bindingContext.prototype.createChildContext=function(e,n,r){return new t.bindingContext(e,this,n,function(e,t){e.$parentContext=t,e.$parent=t.$data,e.$parents=(t.$parents||[]).slice(0),e.$parents.unshift(e.$parent),r&&r(e)})},t.bindingContext.prototype.extend=function(e){return new t.bindingContext(this._subscribable||this.$data,this,null,function(n,r){n.$rawData=r.$rawData,t.utils.extend(n,typeof e=="function"?e():e)})};var l=t.utils.domData.nextKey(),p=t.utils.domData.nextKey();t.storedBindingContextForNode=function(e,n){if(arguments.length!=2)return t.utils.domData.get(e,p);t.utils.domData.set(e,p,n),n._subscribable&&n._subscribable._addNode(e)},t.applyBindingAccessorsToNode=function(e,n,r){return e.nodeType===1&&t.virtualElements.normaliseVirtualElementDomStructure(e),h(e,n,d(r),!0)},t.applyBindingsToNode=function(e,n,r){var i=d(r);return t.applyBindingAccessorsToNode(e,s(n,i,e),i)},t.applyBindingsToDescendants=function(e,t){(t.nodeType===1||t.nodeType===8)&&a(d(e),t,!0)},t.applyBindings=function(e,t){!jQuery&&window.jQuery&&(jQuery=window.jQuery);if(t&&t.nodeType!==1&&t.nodeType!==8)throw new Error("ko.applyBindings: first parameter should be your view model; second parameter should be a DOM node");t=t||window.document.body,f(d(e),t,!0)},t.contextFor=function(e){switch(e.nodeType){case 1:case 8:var n=t.storedBindingContextForNode(e);if(n)return n;if(e.parentNode)return t.contextFor(e.parentNode)}return undefined},t.dataFor=function(e){var n=t.contextFor(e);return n?n.$data:undefined},t.exportSymbol("bindingHandlers",t.bindingHandlers),t.exportSymbol("applyBindings",t.applyBindings),t.exportSymbol("applyBindingsToDescendants",t.applyBindingsToDescendants),t.exportSymbol("applyBindingAccessorsToNode",t.applyBindingAccessorsToNode),t.exportSymbol("applyBindingsToNode",t.applyBindingsToNode),t.exportSymbol("contextFor",t.contextFor),t.exportSymbol("dataFor",t.dataFor)}();var h={"class":"className","for":"htmlFor"};t.bindingHandlers.attr={update:function(e,n,r){var i=t.utils.unwrapObservable(n())||{};t.utils.objectForEach(i,function(n,r){r=t.utils.unwrapObservable(r);var i=r===!1||r===null||r===undefined;i&&e.removeAttribute(n),t.utils.ieVersion<=8&&n in h?(n=h[n],i?e.removeAttribute(n):e[n]=r):i||e.setAttribute(n,r.toString()),n==="name"&&t.utils.setElementName(e,i?"":r.toString())})}},function(){t.bindingHandlers.checked={after:["value","attr"],init:function(e,n,r){function i(){return r.has("checkedValue")?t.utils.unwrapObservable(r.get("checkedValue")):e.value}function s(){var s=e.checked,o=c?i():s;if(t.computedContext.isInitial())return;if(a&&!s)return;var u=t.dependencyDetection.ignore(n);f?l!==o?(s&&(t.utils.addOrRemoveItem(u,o,!0),t.utils.addOrRemoveItem(u,l,!1)),l=o):t.utils.addOrRemoveItem(u,o,s):t.expressionRewriting.writeValueToProperty(u,r,"checked",o,!0)}function o(){var r=t.utils.unwrapObservable(n());f?e.checked=t.utils.arrayIndexOf(r,i())>=0:u?e.checked=r:e.checked=i()===r}var u=e.type=="checkbox",a=e.type=="radio";if(!u&&!a)return;var f=u&&t.utils.unwrapObservable(n())instanceof Array,l=f?i():undefined,c=a||f;a&&!e.name&&t.bindingHandlers.uniqueName.init(e,function(){return!0}),t.computed(s,null,{disposeWhenNodeIsRemoved:e}),t.utils.registerEventHandler(e,"click",s),t.computed(o,null,{disposeWhenNodeIsRemoved:e})}},t.expressionRewriting.twoWayBindings.checked=!0,t.bindingHandlers.checkedValue={update:function(e,n){e.value=t.utils.unwrapObservable(n())}}}();var p="__ko__cssValue";t.bindingHandlers.css={update:function(e,n){var r=t.utils.unwrapObservable(n());typeof r=="object"?t.utils.objectForEach(r,function(n,r){r=t.utils.unwrapObservable(r),t.utils.toggleDomNodeCssClass(e,n,r)}):(r=String(r||""),t.utils.toggleDomNodeCssClass(e,e[p],!1),e[p]=r,t.utils.toggleDomNodeCssClass(e,r,!0))}},t.bindingHandlers.enable={update:function(e,n){var r=t.utils.unwrapObservable(n());r&&e.disabled?e.removeAttribute("disabled"):!r&&!e.disabled&&(e.disabled=!0)}},t.bindingHandlers.disable={update:function(e,n){t.bindingHandlers.enable.update(e,function(){return!t.utils.unwrapObservable(n())})}},t.bindingHandlers.event={init:function(e,n,r,i,s){var o=n()||{};t.utils.objectForEach(o,function(o){typeof o=="string"&&t.utils.registerEventHandler(e,o,function(e){var u,a=n()[o];if(!a)return;try{var f=t.utils.makeArray(arguments);i=s.$data,f.unshift(i),u=a.apply(i,f)}finally{u!==!0&&(e.preventDefault?e.preventDefault():e.returnValue=!1)}var l=r.get(o+"Bubble")!==!1;l||(e.cancelBubble=!0,e.stopPropagation&&e.stopPropagation())})})}},t.bindingHandlers.foreach={makeTemplateValueAccessor:function(e){return function(){var n=e(),r=t.utils.peekObservable(n);return!r||typeof r.length=="number"?{foreach:n,templateEngine:t.nativeTemplateEngine.instance}:(t.utils.unwrapObservable(n),{foreach:r.data,as:r.as,includeDestroyed:r.includeDestroyed,afterAdd:r.afterAdd,beforeRemove:r.beforeRemove,afterRender:r.afterRender,beforeMove:r.beforeMove,afterMove:r.afterMove,templateEngine:t.nativeTemplateEngine.instance})}},init:function(e,n,r,i,s){return t.bindingHandlers.template.init(e,t.bindingHandlers.foreach.makeTemplateValueAccessor(n))},update:function(e,n,r,i,s){return t.bindingHandlers.template.update(e,t.bindingHandlers.foreach.makeTemplateValueAccessor(n),r,i,s)}},t.expressionRewriting.bindingRewriteValidators.foreach=!1,t.virtualElements.allowedBindings.foreach=!0;var v="__ko_hasfocusUpdating",m="__ko_hasfocusLastValue";t.bindingHandlers.hasfocus={init:function(e,n,r){var i=function(i){e[v]=!0;var s=e.ownerDocument;if("activeElement"in s){var o;try{o=s.activeElement}catch(u){o=s.body}i=o===e}var a=n();t.expressionRewriting.writeValueToProperty(a,r,"hasfocus",i,!0),e[m]=i,e[v]=!1},s=i.bind(null,!0),o=i.bind(null,!1);t.utils.registerEventHandler(e,"focus",s),t.utils.registerEventHandler(e,"focusin",s),t.utils.registerEventHandler(e,"blur",o),t.utils.registerEventHandler(e,"focusout",o)},update:function(e,n){var r=!!t.utils.unwrapObservable(n());!e[v]&&e[m]!==r&&(r?e.focus():e.blur(),t.dependencyDetection.ignore(t.utils.triggerEvent,null,[e,r?"focusin":"focusout"]))}},t.expressionRewriting.twoWayBindings.hasfocus=!0,t.bindingHandlers.hasFocus=t.bindingHandlers.hasfocus,t.expressionRewriting.twoWayBindings.hasFocus=!0,t.bindingHandlers.html={init:function(){return{controlsDescendantBindings:!0}},update:function(e,n){t.utils.setHtml(e,n())}},g("if"),g("ifnot",!1,!0),g("with",!0,!1,function(e,t){return e.createChildContext(t)});var y={};t.bindingHandlers.options={init:function(e){if(t.utils.tagNameLower(e)!=="select")throw new Error("options binding applies only to SELECT elements");while(e.length>0)e.remove(0);return{controlsDescendantBindings:!0}},update:function(e,n,r){function i(){return t.utils.arrayFilter(e.options,function(e){return e.selected})}function p(e,t,n){var r=typeof t;return r=="function"?t(e):r=="string"?e[t]:n}function v(n,i,s){s.length&&(h=s[0].selected?[t.selectExtensions.readValue(s[0])]:[],d=!0);var o=e.ownerDocument.createElement("option");if(n===y)t.utils.setTextContent(o,r.get("optionsCaption")),t.selectExtensions.writeValue(o,undefined);else{var u=p(n,r.get("optionsValue"),n);t.selectExtensions.writeValue(o,t.utils.unwrapObservable(u));var a=p(n,r.get("optionsText"),u);t.utils.setTextContent(o,a)}return[o]}function m(n,r){if(h.length){var i=t.utils.arrayIndexOf(h,t.selectExtensions.readValue(r[0]))>=0;t.utils.setOptionNodeSelectionState(r[0],i),d&&!i&&t.dependencyDetection.ignore(t.utils.triggerEvent,null,[e,"change"])}}var s=e.length==0,o=!s&&e.multiple?e.scrollTop:null,u=t.utils.unwrapObservable(n()),a=r.get("optionsIncludeDestroyed"),f={},l,c,h;e.multiple?h=t.utils.arrayMap(i(),t.selectExtensions.readValue):h=e.selectedIndex>=0?[t.selectExtensions.readValue(e.options[e.selectedIndex])]:[],u&&(typeof u.length=="undefined"&&(u=[u]),c=t.utils.arrayFilter(u,function(e){return a||e===undefined||e===null||!t.utils.unwrapObservable(e._destroy)}),r.has("optionsCaption")&&(l=t.utils.unwrapObservable(r.get("optionsCaption")),l!==null&&l!==undefined&&c.unshift(y)));var d=!1;f.beforeRemove=function(t){e.removeChild(t)};var g=m;r.has("optionsAfterRender")&&(g=function(e,n){m(e,n),t.dependencyDetection.ignore(r.get("optionsAfterRender"),null,[n[0],e!==y?e:undefined])}),t.utils.setDomNodeChildrenFromArrayMapping(e,c,v,f,g),t.dependencyDetection.ignore(function(){if(r.get("valueAllowUnset")&&r.has("value"))t.selectExtensions.writeValue(e,t.utils.unwrapObservable(r.get("value")),!0);else{var n;e.multiple?n=h.length&&i().length<h.length:n=h.length&&e.selectedIndex>=0?t.selectExtensions.readValue(e.options[e.selectedIndex])!==h[0]:h.length||e.selectedIndex>=0,n&&t.utils.triggerEvent(e,"change")}}),t.utils.ensureSelectElementIsRenderedCorrectly(e),o&&Math.abs(o-e.scrollTop)>20&&(e.scrollTop=o)}},t.bindingHandlers.options.optionValueDomDataKey=t.utils.domData.nextKey(),t.bindingHandlers.selectedOptions={after:["options","foreach"],init:function(e,n,r){t.utils.registerEventHandler(e,"change",function(){var i=n(),s=[];t.utils.arrayForEach(e.getElementsByTagName("option"),function(e){e.selected&&s.push(t.selectExtensions.readValue(e))}),t.expressionRewriting.writeValueToProperty(i,r,"selectedOptions",s)})},update:function(e,n){if(t.utils.tagNameLower(e)!="select")throw new Error("values binding applies only to SELECT elements");var r=t.utils.unwrapObservable(n());r&&typeof r.length=="number"&&t.utils.arrayForEach(e.getElementsByTagName("option"),function(e){var n=t.utils.arrayIndexOf(r,t.selectExtensions.readValue(e))>=0;t.utils.setOptionNodeSelectionState(e,n)})}},t.expressionRewriting.twoWayBindings.selectedOptions=!0,t.bindingHandlers.style={update:function(e,n){var r=t.utils.unwrapObservable(n()||{});t.utils.objectForEach(r,function(n,r){r=t.utils.unwrapObservable(r),e.style[n]=r||""})}},t.bindingHandlers.submit={init:function(e,n,r,i,s){if(typeof n()!="function")throw new Error("The value for a submit binding must be a function");t.utils.registerEventHandler(e,"submit",function(t){var r,i=n();try{r=i.call(s.$data,e)}finally{r!==!0&&(t.preventDefault?t.preventDefault():t.returnValue=!1)}})}},t.bindingHandlers.text={init:function(){return{controlsDescendantBindings:!0}},update:function(e,n){t.utils.setTextContent(e,n())}},t.virtualElements.allowedBindings.text=!0,t.bindingHandlers.uniqueName={init:function(e,n){if(n()){var r="ko_unique_"+ ++t.bindingHandlers.uniqueName.currentIndex;t.utils.setElementName(e,r)}}},t.bindingHandlers.uniqueName.currentIndex=0,t.bindingHandlers.value={after:["options","foreach"],init:function(e,n,r){var i=["change"],s=r.get("valueUpdate"),o=!1;s&&(typeof s=="string"&&(s=[s]),t.utils.arrayPushAll(i,s),i=t.utils.arrayGetDistinctValues(i));var u=function(){o=!1;var i=n(),s=t.selectExtensions.readValue(e);t.expressionRewriting.writeValueToProperty(i,r,"value",s)},a=t.utils.ieVersion&&e.tagName.toLowerCase()=="input"&&e.type=="text"&&e.autocomplete!="off"&&(!e.form||e.form.autocomplete!="off");a&&t.utils.arrayIndexOf(i,"propertychange")==-1&&(t.utils.registerEventHandler(e,"propertychange",function(){o=!0}),t.utils.registerEventHandler(e,"focus",function(){o=!1}),t.utils.registerEventHandler(e,"blur",function(){o&&u()})),t.utils.arrayForEach(i,function(n){var r=u;t.utils.stringStartsWith(n,"after")&&(r=function(){setTimeout(u,0)},n=n.substring("after".length)),t.utils.registerEventHandler(e,n,r)})},update:function(e,n,r){var i=t.utils.unwrapObservable(n()),s=t.selectExtensions.readValue(e),o=i!==s;if(o)if(t.utils.tagNameLower(e)==="select"){var u=r.get("valueAllowUnset"),a=function(){t.selectExtensions.writeValue(e,i,u)};a(),!u&&i!==t.selectExtensions.readValue(e)?t.dependencyDetection.ignore(t.utils.triggerEvent,null,[e,"change"]):setTimeout(a,0)}else t.selectExtensions.writeValue(e,i)}},t.expressionRewriting.twoWayBindings.value=!0,t.bindingHandlers.visible={update:function(e,n){var r=t.utils.unwrapObservable(n()),i=e.style.display!="none";r&&!i?e.style.display="":!r&&i&&(e.style.display="none")}},d("click"),t.templateEngine=function(){},t.templateEngine.prototype.renderTemplateSource=function(e,t,n){throw new Error("Override renderTemplateSource")},t.templateEngine.prototype.createJavaScriptEvaluatorBlock=function(e){throw new Error("Override createJavaScriptEvaluatorBlock")},t.templateEngine.prototype.makeTemplateSource=function(e,n){if(typeof e=="string"){n=n||document;var r=n.getElementById(e);if(!r)throw new Error("Cannot find template with ID "+e);return new t.templateSources.domElement(r)}if(e.nodeType==1||e.nodeType==8)return new t.templateSources.anonymousTemplate(e);throw new Error("Unknown template type: "+e)},t.templateEngine.prototype.renderTemplate=function(e,t,n,r){var i=this.makeTemplateSource(e,r);return this.renderTemplateSource(i,t,n)},t.templateEngine.prototype.isTemplateRewritten=function(e,t){return this.allowTemplateRewriting===!1?!0:this.makeTemplateSource(e,t).data("isRewritten")},t.templateEngine.prototype.rewriteTemplate=function(e,t,n){var r=this.makeTemplateSource(e,n),i=t(r.text());r.text(i),r.data("isRewritten",!0)},t.exportSymbol("templateEngine",t.templateEngine),t.templateRewriting=function(){function r(e){var n=t.expressionRewriting.bindingRewriteValidators;for(var r=0;r<e.length;r++){var i=e[r].key;if(n.hasOwnProperty(i)){var s=n[i];if(typeof s=="function"){var o=s(e[r].value);if(o)throw new Error(o)}else if(!s)throw new Error("This template engine does not support the '"+i+"' binding within its templates")}}}function i(e,n,i,s){var o=t.expressionRewriting.parseObjectLiteral(e);r(o);var u=t.expressionRewriting.preProcessBindings(o,{valueAccessors:!0}),a="ko.__tr_ambtns(function($context,$element){return(function(){return{ "+u+" } })()},'"+i.toLowerCase()+"')";return s.createJavaScriptEvaluatorBlock(a)+n}var e=/(<([a-z]+\d*)(?:\s+(?!data-bind\s*=\s*)[a-z0-9\-]+(?:=(?:\"[^\"]*\"|\'[^\']*\'))?)*\s+)data-bind\s*=\s*(["'])([\s\S]*?)\3/gi,n=/<!--\s*ko\b\s*([\s\S]*?)\s*-->/g;return{ensureTemplateIsRewritten:function(e,n,r){n.isTemplateRewritten(e,r)||n.rewriteTemplate(e,function(e){return t.templateRewriting.memoizeBindingAttributeSyntax(e,n)},r)},memoizeBindingAttributeSyntax:function(t,r){return t.replace(e,function(){return i(arguments[4],arguments[1],arguments[2],r)}).replace(n,function(){return i(arguments[1],"<!-- ko -->","#comment",r)})},applyMemoizedBindingsToNextSibling:function(e,n){return t.memoization.memoize(function(r,i){var s=r.nextSibling;s&&s.nodeName.toLowerCase()===n&&t.applyBindingAccessorsToNode(s,e,i)})}}}(),t.exportSymbol("__tr_ambtns",t.templateRewriting.applyMemoizedBindingsToNextSibling),function(){t.templateSources={},t.templateSources.domElement=function(e){this.domElement=e},t.templateSources.domElement.prototype.text=function(){var e=t.utils.tagNameLower(this.domElement),n=e==="script"?"text":e==="textarea"?"value":"innerHTML";if(arguments.length==0)return this.domElement[n];var r=arguments[0];n==="innerHTML"?t.utils.setHtml(this.domElement,r):this.domElement[n]=r};var e=t.utils.domData.nextKey()+"_";t.templateSources.domElement.prototype.data=function(n){if(arguments.length===1)return t.utils.domData.get(this.domElement,e+n);t.utils.domData.set(this.domElement,e+n,arguments[1])};var n=t.utils.domData.nextKey();t.templateSources.anonymousTemplate=function(e){this.domElement=e},t.templateSources.anonymousTemplate.prototype=new t.templateSources.domElement,t.templateSources.anonymousTemplate.prototype.constructor=t.templateSources.anonymousTemplate,t.templateSources.anonymousTemplate.prototype.text=function(){if(arguments.length==0){var e=t.utils.domData.get(this.domElement,n)||{};return e.textData===undefined&&e.containerData&&(e.textData=e.containerData.innerHTML),e.textData}var r=arguments[0];t.utils.domData.set(this.domElement,n,{textData:r})},t.templateSources.domElement.prototype.nodes=function(){if(arguments.length==0){var e=t.utils.domData.get(this.domElement,n)||{};return e.containerData}var r=arguments[0];t.utils.domData.set(this.domElement,n,{containerData:r})},t.exportSymbol("templateSources",t.templateSources),t.exportSymbol("templateSources.domElement",t.templateSources.domElement),t.exportSymbol("templateSources.anonymousTemplate",t.templateSources.anonymousTemplate)}(),function(){function n(e,n,r){var i,s=e,o=t.virtualElements.nextSibling(n);while(s&&(i=s)!==o)s=t.virtualElements.nextSibling(i),r(i,s)}function r(e,r){if(e.length){var i=e[0],s=e[e.length-1],o=i.parentNode,u=t.bindingProvider.instance,a=u.preprocessNode;if(a){n(i,s,function(e,t){var n=e.previousSibling,r=a.call(u,e);r&&(e===i&&(i=r[0]||t),e===s&&(s=r[r.length-1]||n))}),e.length=0;if(!i)return;i===s?e.push(i):(e.push(i,s),t.utils.fixUpContinuousNodeArray(e,o))}n(i,s,function(e){(e.nodeType===1||e.nodeType===8)&&t.applyBindings(r,e)}),n(i,s,function(e){(e.nodeType===1||e.nodeType===8)&&t.memoization.unmemoizeDomNodeAndDescendants(e,[r])}),t.utils.fixUpContinuousNodeArray(e,o)}}function i(e){return e.nodeType?e:e.length>0?e[0]:null}function s(n,s,o,u,a){a=a||{};var f=n&&i(n),l=f&&f.ownerDocument,c=a.templateEngine||e;t.templateRewriting.ensureTemplateIsRewritten(o,c,l);var h=c.renderTemplate(o,u,a,l);if(typeof h.length!="number"||h.length>0&&typeof h[0].nodeType!="number")throw new Error("Template engine must return an array of DOM nodes");var p=!1;switch(s){case"replaceChildren":t.virtualElements.setDomNodeChildren(n,h),p=!0;break;case"replaceNode":t.utils.replaceDomNodes(n,h),p=!0;break;case"ignoreTargetNode":break;default:throw new Error("Unknown renderMode: "+s)}return p&&(r(h,u),a.afterRender&&t.dependencyDetection.ignore(a.afterRender,null,[h,u.$data])),h}function u(e,n){var r=t.utils.domData.get(e,o);r&&typeof r.dispose=="function"&&r.dispose(),t.utils.domData.set(e,o,n&&n.isActive()?n:undefined)}var e;t.setTemplateEngine=function(n){if(!(n==undefined||n instanceof t.templateEngine))throw new Error("templateEngine must inherit from ko.templateEngine");e=n},t.renderTemplate=function(n,r,o,u,a){o=o||{};if((o["templateEngine"]||e)==undefined)throw new Error("Set a template engine before calling renderTemplate");a=a||"replaceChildren";if(u){var f=i(u),l=function(){return!f||!t.utils.domNodeIsAttachedToDocument(f)},c=f&&a=="replaceNode"?f.parentNode:f;return t.dependentObservable(function(){var e=r&&r instanceof t.bindingContext?r:new t.bindingContext(t.utils.unwrapObservable(r)),l=t.isObservable(n)?n():typeof n=="function"?n(e.$data,e):n,c=s(u,a,l,e,o);a=="replaceNode"&&(u=c,f=i(u))},null,{disposeWhen:l,disposeWhenNodeIsRemoved:c})}return t.memoization.memoize(function(e){t.renderTemplate(n,r,o,e,"replaceNode")})},t.renderTemplateForEach=function(e,n,i,o,u){var a,f=function(t,n){a=u.createChildContext(t,i.as,function(e){e.$index=n});var r=typeof e=="function"?e(t,a):e;return s(null,"ignoreTargetNode",r,a,i)},l=function(e,t,n){r(t,a),i.afterRender&&i.afterRender(t,e)};return t.dependentObservable(function(){var e=t.utils.unwrapObservable(n)||[];typeof e.length=="undefined"&&(e=[e]);var r=t.utils.arrayFilter(e,function(e){return i.includeDestroyed||e===undefined||e===null||!t.utils.unwrapObservable(e._destroy)});t.dependencyDetection.ignore(t.utils.setDomNodeChildrenFromArrayMapping,null,[o,r,f,i,l])},null,{disposeWhenNodeIsRemoved:o})};var o=t.utils.domData.nextKey();t.bindingHandlers.template={init:function(e,n){var r=t.utils.unwrapObservable(n());if(typeof r=="string"||r.name)t.virtualElements.emptyNode(e);else{var i=t.virtualElements.childNodes(e),s=t.utils.moveCleanedNodesToContainerElement(i);(new t.templateSources.anonymousTemplate(e)).nodes(s)}return{controlsDescendantBindings:!0}},update:function(e,n,r,i,s){var o=n(),a,f=t.utils.unwrapObservable(o),l=!0,c=null,h;typeof f=="string"?(h=o,f={}):(h=f.name,"if"in f&&(l=t.utils.unwrapObservable(f["if"])),l&&"ifnot"in f&&(l=!t.utils.unwrapObservable(f.ifnot)),a=t.utils.unwrapObservable(f.data));if("foreach"in f){var p=l&&f.foreach||[];c=t.renderTemplateForEach(h||e,p,f,e,s)}else if(!l)t.virtualElements.emptyNode(e);else{var d="data"in f?s.createChildContext(a,f.as):s;c=t.renderTemplate(h||e,d,f,e)}u(e,c)}},t.expressionRewriting.bindingRewriteValidators.template=function(e){var n=t.expressionRewriting.parseObjectLiteral(e);return n.length==1&&n[0].unknown?null:t.expressionRewriting.keyValueArrayContainsKey(n,"name")?null:"This template engine does not support anonymous templates nested within its templates"},t.virtualElements.allowedBindings.template=!0}(),t.exportSymbol("setTemplateEngine",t.setTemplateEngine),t.exportSymbol("renderTemplate",t.renderTemplate),t.utils.findMovesInArrayComparison=function(e,t,n){if(e.length&&t.length){var r,i,s,o,u;for(r=i=0;(!n||r<n)&&(o=e[i]);++i){for(s=0;u=t[s];++s)if(o.value===u.value){o.moved=u.index,u.moved=o.index,t.splice(s,1),r=s=0;break}r+=s}}},t.utils.compareArrays=function(){function r(t,r,s){return s=typeof s=="boolean"?{dontLimitMoves:s}:s||{},t=t||[],r=r||[],t.length<=r.length?i(t,r,e,n,s):i(r,t,n,e,s)}function i(e,n,r,i,s){var o=Math.min,u=Math.max,a=[],f,l=e.length,c,h=n.length,p=h-l||1,d=l+h+1,v,m,g,y;for(f=0;f<=l;f++){m=v,a.push(v=[]),g=o(h,f+p),y=u(0,f-1);for(c=y;c<=g;c++)if(!c)v[c]=f+1;else if(!f)v[c]=c+1;else if(e[f-1]===n[c-1])v[c]=m[c-1];else{var b=m[c]||d,w=v[c-1]||d;v[c]=o(b,w)+1}}var E=[],S,x=[],T=[];for(f=l,c=h;f||c;)S=a[f][c]-1,c&&S===a[f][c-1]?x.push(E[E.length]={status:r,value:n[--c],index:c}):f&&S===a[f-1][c]?T.push(E[E.length]={status:i,value:e[--f],index:f}):(--c,--f,s.sparse||E.push({status:"retained",value:n[c]}));return t.utils.findMovesInArrayComparison(x,T,l*10),E.reverse()}var e="added",n="deleted";return r}(),t.exportSymbol("utils.compareArrays",t.utils.compareArrays),function(){function e(e,n,r,i,s){var o=[],u=t.dependentObservable(function(){var u=n(r,s,t.utils.fixUpContinuousNodeArray(o,e))||[];o.length>0&&(t.utils.replaceDomNodes(o,u),i&&t.dependencyDetection.ignore(i,null,[r,u,s])),o.length=0,t.utils.arrayPushAll(o,u)},null,{disposeWhenNodeIsRemoved:e,disposeWhen:function(){return!t.utils.anyDomNodeIsAttachedToDocument(o)}});return{mappedNodes:o,dependentObservable:u.isActive()?u:undefined}}var n=t.utils.domData.nextKey();t.utils.setDomNodeChildrenFromArrayMapping=function(r,i,s,o,u){function E(e,n){w=f[n],d!==n&&(y[e]=w),w.indexObservable(d++),t.utils.fixUpContinuousNodeArray(w.mappedNodes,r),h.push(w),m.push(w)}function S(e,n){if(e)for(var r=0,i=n.length;r<i;r++)n[r]&&t.utils.arrayForEach(n[r].mappedNodes,function(t){e(t,r,n[r].arrayEntry)})}i=i||[],o=o||{};var a=t.utils.domData.get(r,n)===undefined,f=t.utils.domData.get(r,n)||[],l=t.utils.arrayMap(f,function(e){return e.arrayEntry}),c=t.utils.compareArrays(l,i,o.dontLimitMoves),h=[],p=0,d=0,v=[],m=[],g=[],y=[],b=[],w;for(var x=0,T,N;T=c[x];x++){N=T.moved;switch(T.status){case"deleted":N===undefined&&(w=f[p],w.dependentObservable&&w.dependentObservable.dispose(),v.push.apply(v,t.utils.fixUpContinuousNodeArray(w.mappedNodes,r)),o.beforeRemove&&(g[x]=w,m.push(w))),p++;break;case"retained":E(x,p++);break;case"added":N!==undefined?E(x,N):(w={arrayEntry:T.value,indexObservable:t.observable(d++)},h.push(w),m.push(w),a||(b[x]=w))}}S(o.beforeMove,y),t.utils.arrayForEach(v,o.beforeRemove?t.cleanNode:t.removeNode);for(var x=0,C=t.virtualElements.firstChild(r),k,L;w=m[x];x++){w.mappedNodes||t.utils.extend(w,e(r,s,w.arrayEntry,u,w.indexObservable));for(var A=0;L=w.mappedNodes[A];C=L.nextSibling,k=L,A++)L!==C&&t.virtualElements.insertAfter(r,L,k);!w.initialized&&u&&(u(w.arrayEntry,w.mappedNodes,w.indexObservable),w.initialized=!0)}S(o.beforeRemove,g),S(o.afterMove,y),S(o.afterAdd,b),t.utils.domData.set(r,n,h)}}(),t.exportSymbol("utils.setDomNodeChildrenFromArrayMapping",t.utils.setDomNodeChildrenFromArrayMapping),t.nativeTemplateEngine=function(){this.allowTemplateRewriting=!1},t.nativeTemplateEngine.prototype=new t.templateEngine,t.nativeTemplateEngine.prototype.constructor=t.nativeTemplateEngine,t.nativeTemplateEngine.prototype.renderTemplateSource=function(e,n,r){var i=!(t.utils.ieVersion<9),s=i?e.nodes:null,o=s?e.nodes():null;if(o)return t.utils.makeArray(o.cloneNode(!0).childNodes);var u=e.text();return t.utils.parseHtmlFragment(u)},t.nativeTemplateEngine.instance=new t.nativeTemplateEngine,t.setTemplateEngine(t.nativeTemplateEngine.instance),t.exportSymbol("nativeTemplateEngine",t.nativeTemplateEngine),function(){t.jqueryTmplTemplateEngine=function(){function t(){if(e<2)throw new Error("Your version of jQuery.tmpl is too old. Please upgrade to jQuery.tmpl 1.0.0pre or later.")}function n(e,t,n){return jQuery.tmpl(e,t,n)}var e=this.jQueryTmplVersion=function(){if(!jQuery||!jQuery.tmpl)return 0;try{if(jQuery.tmpl.tag.tmpl.open.toString().indexOf("__")>=0)return 2}catch(e){}return 1}();this.renderTemplateSource=function(e,r,i){i=i||{},t();var s=e.data("precompiled");if(!s){var o=e.text()||"";o="{{ko_with $item.koBindingContext}}"+o+"{{/ko_with}}",s=jQuery.template(null,o),e.data("precompiled",s)}var u=[r.$data],a=jQuery.extend({koBindingContext:r},i.templateOptions),f=n(s,u,a);return f.appendTo(document.createElement("div")),jQuery.fragments={},f},this.createJavaScriptEvaluatorBlock=function(e){return"{{ko_code ((function() { return "+e+" })()) }}"},this.addTemplate=function(e,t){document.write("<script type='text/html' id='"+e+"'>"+t+"<"+"/script>")},e>0&&(jQuery.tmpl.tag.ko_code={open:"__.push($1 || '');"},jQuery.tmpl.tag.ko_with={open:"with($1) {",close:"} "})},t.jqueryTmplTemplateEngine.prototype=new t.templateEngine,t.jqueryTmplTemplateEngine.prototype.constructor=t.jqueryTmplTemplateEngine;var e=new t.jqueryTmplTemplateEngine;e.jQueryTmplVersion>0&&t.setTemplateEngine(e),t.exportSymbol("jqueryTmplTemplateEngine",t.jqueryTmplTemplateEngine)}()})})()}(),function(e,t){function n(t,n){var i,s,o,u=t.nodeName.toLowerCase();return"area"===u?(i=t.parentNode,s=i.name,t.href&&s&&"map"===i.nodeName.toLowerCase()?(o=e("img[usemap=#"+s+"]")[0],!!o&&r(o)):!1):(/input|select|textarea|button|object/.test(u)?!t.disabled:"a"===u?t.href||n:n)&&r(t)}function r(t){return e.expr.filters.visible(t)&&!e(t).parents().addBack().filter(function(){return"hidden"===e.css(this,"visibility")}).length}var i=0,s=/^ui-id-\d+$/;e.ui=e.ui||{},e.extend(e.ui,{version:"1.10.2",keyCode:{BACKSPACE:8,COMMA:188,DELETE:46,DOWN:40,END:35,ENTER:13,ESCAPE:27,HOME:36,LEFT:37,NUMPAD_ADD:107,NUMPAD_DECIMAL:110,NUMPAD_DIVIDE:111,NUMPAD_ENTER:108,NUMPAD_MULTIPLY:106,NUMPAD_SUBTRACT:109,PAGE_DOWN:34,PAGE_UP:33,PERIOD:190,RIGHT:39,SPACE:32,TAB:9,UP:38}}),e.fn.extend({focus:function(t){return function(n,r){return"number"==typeof n?this.each(function(){var t=this;setTimeout(function(){e(t).focus(),r&&r.call(t)},n)}):t.apply(this,arguments)}}(e.fn.focus),scrollParent:function(){var t;return t=e.ui.ie&&/(static|relative)/.test(this.css("position"))||/absolute/.test(this.css("position"))?this.parents().filter(function(){return/(relative|absolute|fixed)/.test(e.css(this,"position"))&&/(auto|scroll)/.test(e.css(this,"overflow")+e.css(this,"overflow-y")+e.css(this,"overflow-x"))}).eq(0):this.parents().filter(function(){return/(auto|scroll)/.test(e.css(this,"overflow")+e.css(this,"overflow-y")+e.css(this,"overflow-x"))}).eq(0),/fixed/.test(this.css("position"))||!t.length?e(document):t},zIndex:function(n){if(n!==t)return this.css("zIndex",n);if(this.length)for(var r,i,s=e(this[0]);s.length&&s[0]!==document;){if(r=s.css("position"),("absolute"===r||"relative"===r||"fixed"===r)&&(i=parseInt(s.css("zIndex"),10),!isNaN(i)&&0!==i))return i;s=s.parent()}return 0},uniqueId:function(){return this.each(function(){this.id||(this.id="ui-id-"+ ++i)})},removeUniqueId:function(){return this.each(function(){s.test(this.id)&&e(this).removeAttr("id")})}}),e.extend(e.expr[":"],{data:e.expr.createPseudo?e.expr.createPseudo(function(t){return function(n){return!!e.data(n,t)}}):function(t,n,r){return!!e.data(t,r[3])},focusable:function(t){return n(t,!isNaN(e.attr(t,"tabindex")))},tabbable:function(t){var r=e.attr(t,"tabindex"),i=isNaN(r);return(i||r>=0)&&n(t,!i)}}),e("<a>").outerWidth(1).jquery||e.each(["Width","Height"],function(n,r){function i(t,n,r,i){return e.each(s,function(){n-=parseFloat(e.css(t,"padding"+this))||0,r&&(n-=parseFloat(e.css(t,"border"+this+"Width"))||0),i&&(n-=parseFloat(e.css(t,"margin"+this))||0)}),n}var s="Width"===r?["Left","Right"]:["Top","Bottom"],o=r.toLowerCase(),u={innerWidth:e.fn.innerWidth,innerHeight:e.fn.innerHeight,outerWidth:e.fn.outerWidth,outerHeight:e.fn.outerHeight};e.fn["inner"+r]=function(n){return n===t?u["inner"+r].call(this):this.each(function(){e(this).css(o,i(this,n)+"px")})},e.fn["outer"+r]=function(t,n){return"number"!=typeof t?u["outer"+r].call(this,t):this.each(function(){e(this).css(o,i(this,t,!0,n)+"px")})}}),e.fn.addBack||(e.fn.addBack=function(e){return this.add(null==e?this.prevObject:this.prevObject.filter(e))}),e("<a>").data("a-b","a").removeData("a-b").data("a-b")&&(e.fn.removeData=function(t){return function(n){return arguments.length?t.call(this,e.camelCase(n)):t.call(this)}}(e.fn.removeData)),e.ui.ie=!!/msie [\w.]+/.exec(navigator.userAgent.toLowerCase()),e.support.selectstart="onselectstart"in document.createElement("div"),e.fn.extend({disableSelection:function(){return this.bind((e.support.selectstart?"selectstart":"mousedown")+".ui-disableSelection",function(e){e.preventDefault()})},enableSelection:function(){return this.unbind(".ui-disableSelection")}}),e.extend(e.ui,{plugin:{add:function(t,n,r){var i,s=e.ui[t].prototype;for(i in r)s.plugins[i]=s.plugins[i]||[],s.plugins[i].push([n,r[i]])},call:function(e,t,n){var r,i=e.plugins[t];if(i&&e.element[0].parentNode&&11!==e.element[0].parentNode.nodeType)for(r=0;i.length>r;r++)e.options[i[r][0]]&&i[r][1].apply(e.element,n)}},hasScroll:function(t,n){if("hidden"===e(t).css("overflow"))return!1;var r=n&&"left"===n?"scrollLeft":"scrollTop",i=!1;return t[r]>0?!0:(t[r]=1,i=t[r]>0,t[r]=0,i)}})}(jQuery),function(e,t){var n=0,r=Array.prototype.slice,i=e.cleanData;e.cleanData=function(t){for(var n,r=0;null!=(n=t[r]);r++)try{e(n).triggerHandler("remove")}catch(s){}i(t)},e.widget=function(n,r,i){var s,o,u,a,f={},l=n.split(".")[0];n=n.split(".")[1],s=l+"-"+n,i||(i=r,r=e.Widget),e.expr[":"][s.toLowerCase()]=function(t){return!!e.data(t,s)},e[l]=e[l]||{},o=e[l][n],u=e[l][n]=function(e,n){return this._createWidget?(arguments.length&&this._createWidget(e,n),t):new u(e,n)},e.extend(u,o,{version:i.version,_proto:e.extend({},i),_childConstructors:[]}),a=new r,a.options=e.widget.extend({},a.options),e.each(i,function(n,i){return e.isFunction(i)?(f[n]=function(){var e=function(){return r.prototype[n].apply(this,arguments)},t=function(e){return r.prototype[n].apply(this,e)};return function(){var n,r=this._super,s=this._superApply;return this._super=e,this._superApply=t,n=i.apply(this,arguments),this._super=r,this._superApply=s,n}}(),t):(f[n]=i,t)}),u.prototype=e.widget.extend(a,{widgetEventPrefix:o?a.widgetEventPrefix:n},f,{constructor:u,namespace:l,widgetName:n,widgetFullName:s}),o?(e.each(o._childConstructors,function(t,n){var r=n.prototype;e.widget(r.namespace+"."+r.widgetName,u,n._proto)}),delete o._childConstructors):r._childConstructors.push(u),e.widget.bridge(n,u)},e.widget.extend=function(n){for(var i,o,u=r.call(arguments,1),a=0,f=u.length;f>a;a++)for(i in u[a])o=u[a][i],u[a].hasOwnProperty(i)&&o!==t&&(n[i]=e.isPlainObject(o)?e.isPlainObject(n[i])?e.widget.extend({},n[i],o):e.widget.extend({},o):o);return n},e.widget.bridge=function(n,i){var o=i.prototype.widgetFullName||n;e.fn[n]=function(u){var f="string"==typeof u,l=r.call(arguments,1),c=this;return u=!f&&l.length?e.widget.extend.apply(null,[u].concat(l)):u,f?this.each(function(){var r,i=e.data(this,o);return i?e.isFunction(i[u])&&"_"!==u.charAt(0)?(r=i[u].apply(i,l),r!==i&&r!==t?(c=r&&r.jquery?c.pushStack(r.get()):r,!1):t):e.error("no such method '"+u+"' for "+n+" widget instance"):e.error("cannot call methods on "+n+" prior to initialization; "+"attempted to call method '"+u+"'")}):this.each(function(){var t=e.data(this,o);t?t.option(u||{})._init():e.data(this,o,new i(u,this))}),c}},e.Widget=function(){},e.Widget._childConstructors=[],e.Widget.prototype={widgetName:"widget",widgetEventPrefix:"",defaultElement:"<div>",options:{disabled:!1,create:null},_createWidget:function(t,r){r=e(r||this.defaultElement||this)[0],this.element=e(r),this.uuid=n++,this.eventNamespace="."+this.widgetName+this.uuid,this.options=e.widget.extend({},this.options,this._getCreateOptions(),t),this.bindings=e(),this.hoverable=e(),this.focusable=e(),r!==this&&(e.data(r,this.widgetFullName,this),this._on(!0,this.element,{remove:function(e){e.target===r&&this.destroy()}}),this.document=e(r.style?r.ownerDocument:r.document||r),this.window=e(this.document[0].defaultView||this.document[0].parentWindow)),this._create(),this._trigger("create",null,this._getCreateEventData()),this._init()},_getCreateOptions:e.noop,_getCreateEventData:e.noop,_create:e.noop,_init:e.noop,destroy:function(){this._destroy(),this.element.unbind(this.eventNamespace).removeData(this.widgetName).removeData(this.widgetFullName).removeData(e.camelCase(this.widgetFullName)),this.widget().unbind(this.eventNamespace).removeAttr("aria-disabled").removeClass(this.widgetFullName+"-disabled "+"ui-state-disabled"),this.bindings.unbind(this.eventNamespace),this.hoverable.removeClass("ui-state-hover"),this.focusable.removeClass("ui-state-focus")},_destroy:e.noop,widget:function(){return this.element},option:function(n,r){var i,s,o,u=n;if(0===arguments.length)return e.widget.extend({},this.options);if("string"==typeof n)if(u={},i=n.split("."),n=i.shift(),i.length){for(s=u[n]=e.widget.extend({},this.options[n]),o=0;i.length-1>o;o++)s[i[o]]=s[i[o]]||{},s=s[i[o]];if(n=i.pop(),r===t)return s[n]===t?null:s[n];s[n]=r}else{if(r===t)return this.options[n]===t?null:this.options[n];u[n]=r}return this._setOptions(u),this},_setOptions:function(e){var t;for(t in e)this._setOption(t,e[t]);return this},_setOption:function(e,t){return this.options[e]=t,"disabled"===e&&(this.widget().toggleClass(this.widgetFullName+"-disabled ui-state-disabled",!!t).attr("aria-disabled",t),this.hoverable.removeClass("ui-state-hover"),this.focusable.removeClass("ui-state-focus")),this},enable:function(){return this._setOption("disabled",!1)},disable:function(){return this._setOption("disabled",!0)},_on:function(n,r,i){var s,o=this;"boolean"!=typeof n&&(i=r,r=n,n=!1),i?(r=s=e(r),this.bindings=this.bindings.add(r)):(i=r,r=this.element,s=this.widget()),e.each(i,function(i,u){function f(){return n||o.options.disabled!==!0&&!e(this).hasClass("ui-state-disabled")?("string"==typeof u?o[u]:u).apply(o,arguments):t}"string"!=typeof u&&(f.guid=u.guid=u.guid||f.guid||e.guid++);var l=i.match(/^(\w+)\s*(.*)$/),c=l[1]+o.eventNamespace,h=l[2];h?s.delegate(h,c,f):r.bind(c,f)})},_off:function(e,t){t=(t||"").split(" ").join(this.eventNamespace+" ")+this.eventNamespace,e.unbind(t).undelegate(t)},_delay:function(e,t){function n(){return("string"==typeof e?r[e]:e).apply(r,arguments)}var r=this;return setTimeout(n,t||0)},_hoverable:function(t){this.hoverable=this.hoverable.add(t),this._on(t,{mouseenter:function(t){e(t.currentTarget).addClass("ui-state-hover")},mouseleave:function(t){e(t.currentTarget).removeClass("ui-state-hover")}})},_focusable:function(t){this.focusable=this.focusable.add(t),this._on(t,{focusin:function(t){e(t.currentTarget).addClass("ui-state-focus")},focusout:function(t){e(t.currentTarget).removeClass("ui-state-focus")}})},_trigger:function(t,n,r){var i,s,o=this.options[t];if(r=r||{},n=e.Event(n),n.type=(t===this.widgetEventPrefix?t:this.widgetEventPrefix+t).toLowerCase(),n.target=this.element[0],s=n.originalEvent)for(i in s)i in n||(n[i]=s[i]);return this.element.trigger(n,r),!(e.isFunction(o)&&o.apply(this.element[0],[n].concat(r))===!1||n.isDefaultPrevented())}},e.each({show:"fadeIn",hide:"fadeOut"},function(t,n){e.Widget.prototype["_"+t]=function(r,i,s){"string"==typeof i&&(i={effect:i});var o,u=i?i===!0||"number"==typeof i?n:i.effect||n:t;i=i||{},"number"==typeof i&&(i={duration:i}),o=!e.isEmptyObject(i),i.complete=s,i.delay&&r.delay(i.delay),o&&e.effects&&e.effects.effect[u]?r[t](i):u!==t&&r[u]?r[u](i.duration,i.easing,s):r.queue(function(n){e(this)[t](),s&&s.call(r[0]),n()})}})}(jQuery),function(e,t){var n=!1;e(document).mouseup(function(){n=!1}),e.widget("ui.mouse",{version:"1.10.0",options:{cancel:"input,textarea,button,select,option",distance:1,delay:0},_mouseInit:function(){var t=this;this.element.bind("mousedown."+this.widgetName,function(e){return t._mouseDown(e)}).bind("click."+this.widgetName,function(n){if(!0===e.data(n.target,t.widgetName+".preventClickEvent"))return e.removeData(n.target,t.widgetName+".preventClickEvent"),n.stopImmediatePropagation(),!1}),this.document.mouseup(function(e){n=!1}),this.started=!1},_mouseDestroy:function(){this.element.unbind("."+this.widgetName),this._mouseMoveDelegate&&e(this.document).unbind("mousemove."+this.widgetName,this._mouseMoveDelegate).unbind("mouseup."+this.widgetName,this._mouseUpDelegate)},_mouseDown:function(t){this._mouseStarted&&this._mouseUp(t),this._mouseDownEvent=t;var r=this,i=t.which===1,s=typeof this.options.cancel=="string"&&t.target.nodeName?e(t.target).closest(this.options.cancel).length:!1;if(!i||s||!this._mouseCapture(t))return!0;this.mouseDelayMet=!this.options.delay,this.mouseDelayMet||(this._mouseDelayTimer=setTimeout(function(){r.mouseDelayMet=!0},this.options.delay));if(this._mouseDistanceMet(t)&&this._mouseDelayMet(t)){this._mouseStarted=this._mouseStart(t)!==!1;if(!this._mouseStarted)return t.preventDefault(),!0}return!0===e.data(t.target,this.widgetName+".preventClickEvent")&&e.removeData(t.target,this.widgetName+".preventClickEvent"),this._mouseMoveDelegate=function(e){return r._mouseMove(e)},this._mouseUpDelegate=function(e){return r._mouseUp(e)},e(this.document).bind("mousemove."+this.widgetName,this._mouseMoveDelegate).bind("mouseup."+this.widgetName,this._mouseUpDelegate),t.preventDefault(),n=!0,!0},_mouseMove:function(t){return e.ui.ie&&(!document.documentMode||document.documentMode<9)&&!t.button?this._mouseUp(t):this._mouseStarted?(this._mouseDrag(t),t.preventDefault()):(this._mouseDistanceMet(t)&&this._mouseDelayMet(t)&&(this._mouseStarted=this._mouseStart(this._mouseDownEvent,t)!==!1,this._mouseStarted?this._mouseDrag(t):this._mouseUp(t)),!this._mouseStarted)},_mouseUp:function(t){return e(this.document).unbind("mousemove."+this.widgetName,this._mouseMoveDelegate).unbind("mouseup."+this.widgetName,this._mouseUpDelegate),this._mouseStarted&&(this._mouseStarted=!1,t.target===this._mouseDownEvent.target&&e.data(t.target,this.widgetName+".preventClickEvent",!0),this._mouseStop(t)),!1},_mouseDistanceMet:function(e){return Math.max(Math.abs(this._mouseDownEvent.pageX-e.pageX),Math.abs(this._mouseDownEvent.pageY-e.pageY))>=this.options.distance},_mouseDelayMet:function(){return this.mouseDelayMet},_mouseStart:function(){},_mouseDrag:function(){},_mouseStop:function(){},_mouseCapture:function(){return!0}})}(jQuery),function(e,t){function n(e,t,n){return[parseInt(e[0],10)*(p.test(e[0])?t/100:1),parseInt(e[1],10)*(p.test(e[1])?n/100:1)]}function r(t,n){return parseInt(e.css(t,n),10)||0}function i(t){var n=t[0];return n.nodeType===9?{width:t.width(),height:t.height(),offset:{top:0,left:0}}:e.isWindow(n)?{width:t.width(),height:t.height(),offset:{top:t.scrollTop(),left:t.scrollLeft()}}:n.preventDefault?{width:0,height:0,offset:{top:n.pageY,left:n.pageX}}:{width:t.outerWidth(),height:t.outerHeight(),offset:t.offset()}}e.ui=e.ui||{};var s,o=Math.max,u=Math.abs,a=Math.round,f=/left|center|right/,l=/top|center|bottom/,c=/[\+\-]\d+%?/,h=/^\w+/,p=/%$/,d=e.fn.position;e.position={scrollbarWidth:function(){if(s!==t)return s;var n,r,i=e("<div style='display:block;width:50px;height:50px;overflow:hidden;'><div style='height:100px;width:auto;'></div></div>"),o=i.children()[0];return e("body").append(i),n=o.offsetWidth,i.css("overflow","scroll"),r=o.offsetWidth,n===r&&(r=i[0].clientWidth),i.remove(),s=n-r},getScrollInfo:function(t){var n=t.isWindow?"":t.element.css("overflow-x"),r=t.isWindow?"":t.element.css("overflow-y"),i=n==="scroll"||n==="auto"&&t.width<t.element[0].scrollWidth,s=r==="scroll"||r==="auto"&&t.height<t.element[0].scrollHeight;return{width:i?e.position.scrollbarWidth():0,height:s?e.position.scrollbarWidth():0}},getWithinInfo:function(t){var n=e(t||window),r=e.isWindow(n[0]);return{element:n,isWindow:r,offset:n.offset()||{left:0,top:0},scrollLeft:n.scrollLeft(),scrollTop:n.scrollTop(),width:r?n.width():n.outerWidth(),height:r?n.height():n.outerHeight()}}},e.fn.position=function(t){if(!t||!t.of)return d.apply(this,arguments);t=e.extend({},t);var s,p,v,m,g,y,b=e(t.of),w=e.position.getWithinInfo(t.within),E=e.position.getScrollInfo(w),S=(t.collision||"flip").split(" "),x={};return y=i(b),b[0].preventDefault&&(t.at="left top"),p=y.width,v=y.height,m=y.offset,g=e.extend({},m),e.each(["my","at"],function(){var e=(t[this]||"").split(" "),n,r;e.length===1&&(e=f.test(e[0])?e.concat(["center"]):l.test(e[0])?["center"].concat(e):["center","center"]),e[0]=f.test(e[0])?e[0]:"center",e[1]=l.test(e[1])?e[1]:"center",n=c.exec(e[0]),r=c.exec(e[1]),x[this]=[n?n[0]:0,r?r[0]:0],t[this]=[h.exec(e[0])[0],h.exec(e[1])[0]]}),S.length===1&&(S[1]=S[0]),t.at[0]==="right"?g.left+=p:t.at[0]==="center"&&(g.left+=p/2),t.at[1]==="bottom"?g.top+=v:t.at[1]==="center"&&(g.top+=v/2),s=n(x.at,p,v),g.left+=s[0],g.top+=s[1],this.each(function(){var i,f,l=e(this),c=l.outerWidth(),h=l.outerHeight(),d=r(this,"marginLeft"),y=r(this,"marginTop"),T=c+d+r(this,"marginRight")+E.width,N=h+y+r(this,"marginBottom")+E.height,C=e.extend({},g),k=n(x.my,l.outerWidth(),l.outerHeight());t.my[0]==="right"?C.left-=c:t.my[0]==="center"&&(C.left-=c/2),t.my[1]==="bottom"?C.top-=h:t.my[1]==="center"&&(C.top-=h/2),C.left+=k[0],C.top+=k[1],e.support.offsetFractions||(C.left=a(C.left),C.top=a(C.top)),i={marginLeft:d,marginTop:y},e.each(["left","top"],function(n,r){e.ui.position[S[n]]&&e.ui.position[S[n]][r](C,{targetWidth:p,targetHeight:v,elemWidth:c,elemHeight:h,collisionPosition:i,collisionWidth:T,collisionHeight:N,offset:[s[0]+k[0],s[1]+k[1]],my:t.my,at:t.at,within:w,elem:l})}),t.using&&(f=function(e){var n=m.left-C.left,r=n+p-c,i=m.top-C.top,s=i+v-h,a={target:{element:b,left:m.left,top:m.top,width:p,height:v},element:{element:l,left:C.left,top:C.top,width:c,height:h},horizontal:r<0?"left":n>0?"right":"center",vertical:s<0?"top":i>0?"bottom":"middle"};p<c&&u(n+r)<p&&(a.horizontal="center"),v<h&&u(i+s)<v&&(a.vertical="middle"),o(u(n),u(r))>o(u(i),u(s))?a.important="horizontal":a.important="vertical",t.using.call(this,e,a)}),l.offset(e.extend(C,{using:f}))})},e.ui.position={fit:{left:function(e,t){var n=t.within,r=n.isWindow?n.scrollLeft:n.offset.left,i=n.width,s=e.left-t.collisionPosition.marginLeft,u=r-s,a=s+t.collisionWidth-i-r,f;t.collisionWidth>i?u>0&&a<=0?(f=e.left+u+t.collisionWidth-i-r,e.left+=u-f):a>0&&u<=0?e.left=r:u>a?e.left=r+i-t.collisionWidth:e.left=r:u>0?e.left+=u:a>0?e.left-=a:e.left=o(e.left-s,e.left)},top:function(e,t){var n=t.within,r=n.isWindow?n.scrollTop:n.offset.top,i=t.within.height,s=e.top-t.collisionPosition.marginTop,u=r-s,a=s+t.collisionHeight-i-r,f;t.collisionHeight>i?u>0&&a<=0?(f=e.top+u+t.collisionHeight-i-r,e.top+=u-f):a>0&&u<=0?e.top=r:u>a?e.top=r+i-t.collisionHeight:e.top=r:u>0?e.top+=u:a>0?e.top-=a:e.top=o(e.top-s,e.top)}},flip:{left:function(e,t){var n=t.within,r=n.offset.left+n.scrollLeft,i=n.width,s=n.isWindow?n.scrollLeft:n.offset.left,o=e.left-t.collisionPosition.marginLeft,a=o-s,f=o+t.collisionWidth-i-s,l=t.my[0]==="left"?-t.elemWidth:t.my[0]==="right"?t.elemWidth:0,c=t.at[0]==="left"?t.targetWidth:t.at[0]==="right"?-t.targetWidth:0,h=-2*t.offset[0],p,d;if(a<0){p=e.left+l+c+h+t.collisionWidth-i-r;if(p<0||p<u(a))e.left+=l+c+h}else if(f>0){d=e.left-t.collisionPosition.marginLeft+l+c+h-s;if(d>0||u(d)<f)e.left+=l+c+h}},top:function(e,t){var n=t.within,r=n.offset.top+n.scrollTop,i=n.height,s=n.isWindow?n.scrollTop:n.offset.top,o=e.top-t.collisionPosition.marginTop,a=o-s,f=o+t.collisionHeight-i-s,l=t.my[1]==="top",c=l?-t.elemHeight:t.my[1]==="bottom"?t.elemHeight:0,h=t.at[1]==="top"?t.targetHeight:t.at[1]==="bottom"?-t.targetHeight:0,p=-2*t.offset[1],d,v;a<0?(v=e.top+c+h+p+t.collisionHeight-i-r,e.top+c+h+p>a&&(v<0||v<u(a))&&(e.top+=c+h+p)):f>0&&(d=e.top-t.collisionPosition.marginTop+c+h+p-s,e.top+c+h+p>f&&(d>0||u(d)<f)&&(e.top+=c+h+p))}},flipfit:{left:function(){e.ui.position.flip.left.apply(this,arguments),e.ui.position.fit.left.apply(this,arguments)},top:function(){e.ui.position.flip.top.apply(this,arguments),e.ui.position.fit.top.apply(this,arguments)}}},function(){var t,n,r,i,s,o=document.getElementsByTagName("body")[0],u=document.createElement("div");t=document.createElement(o?"div":"body"),r={visibility:"hidden",width:0,height:0,border:0,margin:0,background:"none"},o&&e.extend(r,{position:"absolute",left:"-1000px",top:"-1000px"});for(s in r)t.style[s]=r[s];t.appendChild(u),n=o||document.documentElement,n.insertBefore(t,n.firstChild),u.style.cssText="position: absolute; left: 10.7432222px;",i=e(u).offset().left,e.support.offsetFractions=i>10&&i<11,t.innerHTML="",n.removeChild(t)}()}(jQuery),function(e,t){e.widget("ui.draggable",e.ui.mouse,{version:"1.10.1",widgetEventPrefix:"drag",options:{addClasses:!0,appendTo:"parent",axis:!1,connectToSortable:!1,containment:!1,cursor:"auto",cursorAt:!1,grid:!1,handle:!1,helper:"original",iframeFix:!1,opacity:!1,refreshPositions:!1,revert:!1,revertDuration:500,scope:"default",scroll:!0,scrollSensitivity:20,scrollSpeed:20,snap:!1,snapMode:"both",snapTolerance:20,stack:!1,zIndex:!1,drag:null,start:null,stop:null},_create:function(){this.options.helper==="original"&&!/^(?:r|a|f)/.test(this.element.css("position"))&&(this.element[0].style.position="relative"),this.options.addClasses&&this.element.addClass("ui-draggable"),this.options.disabled&&this.element.addClass("ui-draggable-disabled"),this._mouseInit()},_destroy:function(){this.element.removeClass("ui-draggable ui-draggable-dragging ui-draggable-disabled"),this._mouseDestroy()},_mouseCapture:function(t){var n=this.options;return this.helper||n.disabled||e(t.target).closest(".ui-resizable-handle").length>0?!1:(this.handle=this._getHandle(t),this.handle?(e(n.iframeFix===!0?"iframe":n.iframeFix).each(function(){e("<div class='ui-draggable-iframeFix' style='background: #fff;'></div>").css({width:this.offsetWidth+"px",height:this.offsetHeight+"px",position:"absolute",opacity:"0.001",zIndex:1e3}).css(e(this).offset()).appendTo("body")}),!0):!1)},_mouseStart:function(t){var n=this.options;return this.helper=this._createHelper(t),this.helper.addClass("ui-draggable-dragging"),this._cacheHelperProportions(),e.ui.ddmanager&&(e.ui.ddmanager.current=this),this._cacheMargins(),this.cssPosition=this.helper.css("position"),this.scrollParent=this.helper.scrollParent(),this.offset=this.positionAbs=this.element.offset(),this.offset={top:this.offset.top-this.margins.top,left:this.offset.left-this.margins.left},e.extend(this.offset,{click:{left:t.pageX-this.offset.left,top:t.pageY-this.offset.top},parent:this._getParentOffset(),relative:this._getRelativeOffset()}),this.originalPosition=this.position=this._generatePosition(t),this.originalPageX=t.pageX,this.originalPageY=t.pageY,n.cursorAt&&this._adjustOffsetFromHelper(n.cursorAt),n.containment&&this._setContainment(),this._trigger("start",t)===!1?(this._clear(),!1):(this._cacheHelperProportions(),e.ui.ddmanager&&!n.dropBehaviour&&e.ui.ddmanager.prepareOffsets(this,t),this._mouseDrag(t,!0),e.ui.ddmanager&&e.ui.ddmanager.dragStart(this,t),!0)},_mouseDrag:function(t,n){this.position=this._generatePosition(t),this.positionAbs=this._convertPositionTo("absolute");if(!this.options.axis||this.options.axis!=="y")this.helper[0].style.left=this.position.left+"px";if(!this.options.axis||this.options.axis!=="x")this.helper[0].style.top=this.position.top+"px";if(!n){var r=this._uiHash();if(this._trigger("drag",t,r)===!1)return this._mouseUp({}),!1}return e.ui.ddmanager&&e.ui.ddmanager.drag(this,t),!1},_mouseStop:function(t){var n,r=this,i=!1,s=!1;e.ui.ddmanager&&!this.options.dropBehaviour&&(s=e.ui.ddmanager.drop(this,t)),this.dropped&&(s=this.dropped,this.dropped=!1),n=this.element[0];while(n&&(n=n.parentNode))n===this.document.get(0)&&(i=!0);return!i&&this.options.helper==="original"?!1:(this.options.revert==="invalid"&&!s||this.options.revert==="valid"&&s||this.options.revert===!0||e.isFunction(this.options.revert)&&this.options.revert.call(this.element,s)?e(this.helper).animate(this.originalPosition,parseInt(this.options.revertDuration,10),function(){r._trigger("stop",t)!==!1&&r._clear()}):this._trigger("stop",t)!==!1&&this._clear(),!1)},_mouseUp:function(t){return e("div.ui-draggable-iframeFix").each(function(){this.parentNode.removeChild(this)}),e.ui.ddmanager&&e.ui.ddmanager.dragStop(this,t),e.ui.mouse.prototype._mouseUp.call(this,t)},cancel:function(){return this.helper.is(".ui-draggable-dragging")?this._mouseUp({}):this._clear(),this},_getHandle:function(t){var n=!this.options.handle||!e(this.options.handle,this.element).length?!0:!1;return e(this.options.handle,this.element).find("*").addBack().each(function(){this===t.target&&(n=!0)}),n},_createHelper:function(t){var n=this.options,r=e.isFunction(n.helper)?e(n.helper.apply(this.element[0],[t])):n.helper==="clone"?this.element.clone().removeAttr("id"):this.element;return r.parents("body").length||r.appendTo(n.appendTo==="parent"?this.element[0].parentNode:n.appendTo),r[0]!==this.element[0]&&!/(fixed|absolute)/.test(r.css("position"))&&r.css("position","absolute"),r},_adjustOffsetFromHelper:function(t){typeof t=="string"&&(t=t.split(" ")),e.isArray(t)&&(t={left:+t[0],top:+t[1]||0}),"left"in t&&(this.offset.click.left=t.left+this.margins.left),"right"in t&&(this.offset.click.left=this.helperProportions.width-t.right+this.margins.left),"top"in t&&(this.offset.click.top=t.top+this.margins.top),"bottom"in t&&(this.offset.click.top=this.helperProportions.height-t.bottom+this.margins.top)},_getParentOffset:function(){this.offsetParent=this.helper.offsetParent();var t=this.offsetParent.offset();this.cssPosition==="absolute"&&this.scrollParent[0]!==document&&e.contains(this.scrollParent[0],this.offsetParent[0])&&(t.left+=this.scrollParent.scrollLeft(),t.top+=this.scrollParent.scrollTop());if(this.offsetParent[0]===document.body||this.offsetParent[0].tagName&&this.offsetParent[0].tagName.toLowerCase()==="html"&&e.ui.ie)t={top:0,left:0};return{top:t.top+(parseInt(this.offsetParent.css("borderTopWidth"),10)||0),left:t.left+(parseInt(this.offsetParent.css("borderLeftWidth"),10)||0)}},_getRelativeOffset:function(){if(this.cssPosition==="relative"){var e=this.element.position();return{top:e.top-(parseInt(this.helper.css("top"),10)||0)+this.scrollParent.scrollTop(),left:e.left-(parseInt(this.helper.css("left"),10)||0)+this.scrollParent.scrollLeft()}}return{top:0,left:0}},_cacheMargins:function(){this.margins={left:parseInt(this.element.css("marginLeft"),10)||0,top:parseInt(this.element.css("marginTop"),10)||0,right:parseInt(this.element.css("marginRight"),10)||0,bottom:parseInt(this.element.css("marginBottom"),10)||0}},_cacheHelperProportions:function(){this.helperProportions={width:this.helper.outerWidth(),height:this.helper.outerHeight()}},_setContainment:function(){var t,n,r,i=this.options;i.containment==="parent"&&(i.containment=this.helper[0].parentNode);if(i.containment==="document"||i.containment==="window")this.containment=[i.containment==="document"?0:e(window).scrollLeft()-this.offset.relative.left-this.offset.parent.left,i.containment==="document"?0:e(window).scrollTop()-this.offset.relative.top-this.offset.parent.top,(i.containment==="document"?0:e(window).scrollLeft())+e(i.containment==="document"?document:window).width()-this.helperProportions.width-this.margins.left,(i.containment==="document"?0:e(window).scrollTop())+(e(i.containment==="document"?document:window).height()||document.body.parentNode.scrollHeight)-this.helperProportions.height-this.margins.top];if(!/^(document|window|parent)$/.test(i.containment)&&i.containment.constructor!==Array){n=e(i.containment),r=n[0];if(!r)return;t=e(r).css("overflow")!=="hidden",this.containment=[(parseInt(e(r).css("borderLeftWidth"),10)||0)+(parseInt(e(r).css("paddingLeft"),10)||0),(parseInt(e(r).css("borderTopWidth"),10)||0)+(parseInt(e(r).css("paddingTop"),10)||0),(t?Math.max(r.scrollWidth,r.offsetWidth):r.offsetWidth)-(parseInt(e(r).css("borderLeftWidth"),10)||0)-(parseInt(e(r).css("paddingRight"),10)||0)-this.helperProportions.width-this.margins.left-this.margins.right,(t?Math.max(r.scrollHeight,r.offsetHeight):r.offsetHeight)-(parseInt(e(r).css("borderTopWidth"),10)||0)-(parseInt(e(r).css("paddingBottom"),10)||0)-this.helperProportions.height-this.margins.top-this.margins.bottom],this.relative_container=n}else i.containment.constructor===Array&&(this.containment=i.containment)},_convertPositionTo:function(t,n){n||(n=this.position);var r=t==="absolute"?1:-1,i=this.cssPosition!=="absolute"||this.scrollParent[0]!==document&&!!e.contains(this.scrollParent[0],this.offsetParent[0])?this.scrollParent:this.offsetParent,s=/(html|body)/i.test(i[0].tagName);return{top:n.top+this.offset.relative.top*r+this.offset.parent.top*r-(this.cssPosition==="fixed"?-this.scrollParent.scrollTop():s?0:i.scrollTop())*r,left:n.left+this.offset.relative.left*r+this.offset.parent.left*r-(this.cssPosition==="fixed"?-this.scrollParent.scrollLeft():s?0:i.scrollLeft())*r}},_generatePosition:function(t){var n,r,i,s,o=this.options,u=this.cssPosition!=="absolute"||this.scrollParent[0]!==document&&!!e.contains(this.scrollParent[0],this.offsetParent[0])?this.scrollParent:this.offsetParent,a=/(html|body)/i.test(u[0].tagName),f=t.pageX,l=t.pageY;return this.originalPosition&&(this.containment&&(this.relative_container?(r=this.relative_container.offset(),n=[this.containment[0]+r.left,this.containment[1]+r.top,this.containment[2]+r.left,this.containment[3]+r.top]):n=this.containment,t.pageX-this.offset.click.left<n[0]&&(f=n[0]+this.offset.click.left),t.pageY-this.offset.click.top<n[1]&&(l=n[1]+this.offset.click.top),t.pageX-this.offset.click.left>n[2]&&(f=n[2]+this.offset.click.left),t.pageY-this.offset.click.top>n[3]&&(l=n[3]+this.offset.click.top)),o.grid&&(i=o.grid[1]?this.originalPageY+Math.round((l-this.originalPageY)/o.grid[1])*o.grid[1]:this.originalPageY,l=n?i-this.offset.click.top>=n[1]||i-this.offset.click.top>n[3]?i:i-this.offset.click.top>=n[1]?i-o.grid[1]:i+o.grid[1]:i,s=o.grid[0]?this.originalPageX+Math.round((f-this.originalPageX)/o.grid[0])*o.grid[0]:this.originalPageX,f=n?s-this.offset.click.left>=n[0]||s-this.offset.click.left>n[2]?s:s-this.offset.click.left>=n[0]?s-o.grid[0]:s+o.grid[0]:s)),{top:l-this.offset.click.top-this.offset.relative.top-this.offset.parent.top+(this.cssPosition==="fixed"?-this.scrollParent.scrollTop():a?0:u.scrollTop()),left:f-this.offset.click.left-this.offset.relative.left-this.offset.parent.left+(this.cssPosition==="fixed"?-this.scrollParent.scrollLeft():a?0:u.scrollLeft())}},_clear:function(){this.helper.removeClass("ui-draggable-dragging"),this.helper[0]!==this.element[0]&&!this.cancelHelperRemoval&&this.helper.remove(),this.helper=null,this.cancelHelperRemoval=!1},_trigger:function(t,n,r){return r=r||this._uiHash(),e.ui.plugin.call(this,t,[n,r]),t==="drag"&&(this.positionAbs=this._convertPositionTo("absolute")),e.Widget.prototype._trigger.call(this,t,n,r)},plugins:{},_uiHash:function(){return{helper:this.helper,position:this.position,originalPosition:this.originalPosition,offset:this.positionAbs}}}),e.ui.plugin.add("draggable","connectToSortable",{start:function(t,n){var r=e(this).data("ui-draggable"),i=r.options,s=e.extend({},n,{item:r.element});r.sortables=[],e(i.connectToSortable).each(function(){var n=e.data(this,"ui-sortable");n&&!n.options.disabled&&(r.sortables.push({instance:n,shouldRevert:n.options.revert}),n.refreshPositions(),n._trigger("activate",t,s))})},stop:function(t,n){var r=e(this).data("ui-draggable"),i=e.extend({},n,{item:r.element});e.each(r.sortables,function(){this.instance.isOver?(this.instance.isOver=0,r.cancelHelperRemoval=!0,this.instance.cancelHelperRemoval=!1,this.shouldRevert&&(this.instance.options.revert=!0),this.instance._mouseStop(t),this.instance.options.helper=this.instance.options._helper,r.options.helper==="original"&&this.instance.currentItem.css({top:"auto",left:"auto"})):(this.instance.cancelHelperRemoval=!1,this.instance._trigger("deactivate",t,i))})},drag:function(t,n){var r=e(this).data("ui-draggable"),i=this;e.each(r.sortables,function(){var s=!1,o=this;this.instance.positionAbs=r.positionAbs,this.instance.helperProportions=r.helperProportions,this.instance.offset.click=r.offset.click,this.instance._intersectsWith(this.instance.containerCache)&&(s=!0,e.each(r.sortables,function(){return this.instance.positionAbs=r.positionAbs,this.instance.helperProportions=r.helperProportions,this.instance.offset.click=r.offset.click,this!==o&&this.instance._intersectsWith(this.instance.containerCache)&&e.contains(o.instance.element[0],this.instance.element[0])&&(s=!1),s})),s?(this.instance.isOver||(this.instance.isOver=1,this.instance.currentItem=e(i).clone().removeAttr("id").appendTo(this.instance.element).data("ui-sortable-item",!0),this.instance.options._helper=this.instance.options.helper,this.instance.options.helper=function(){return n.helper[0]},t.target=this.instance.currentItem[0],this.instance._mouseCapture(t,!0),this.instance._mouseStart(t,!0,!0),this.instance.offset.click.top=r.offset.click.top,this.instance.offset.click.left=r.offset.click.left,this.instance.offset.parent.left-=r.offset.parent.left-this.instance.offset.parent.left,this.instance.offset.parent.top-=r.offset.parent.top-this.instance.offset.parent.top,r._trigger("toSortable",t),r.dropped=this.instance.element,r.currentItem=r.element,this.instance.fromOutside=r),this.instance.currentItem&&this.instance._mouseDrag(t)):this.instance.isOver&&(this.instance.isOver=0,this.instance.cancelHelperRemoval=!0,this.instance.options.revert=!1,this.instance._trigger("out",t,this.instance._uiHash(this.instance)),this.instance._mouseStop(t,!0),this.instance.options.helper=this.instance.options._helper,this.instance.currentItem.remove(),this.instance.placeholder&&this.instance.placeholder.remove(),r._trigger("fromSortable",t),r.dropped=!1)})}}),e.ui.plugin.add("draggable","cursor",{start:function(){var t=e("body"),n=e(this).data("ui-draggable").options;t.css("cursor")&&(n._cursor=t.css("cursor")),t.css("cursor",n.cursor)},stop:function(){var t=e(this).data("ui-draggable").options;t._cursor&&e("body").css("cursor",t._cursor)}}),e.ui.plugin.add("draggable","opacity",{start:function(t,n){var r=e(n.helper),i=e(this).data("ui-draggable").options;r.css("opacity")&&(i._opacity=r.css("opacity")),r.css("opacity",i.opacity)},stop:function(t,n){var r=e(this).data("ui-draggable").options;r._opacity&&e(n.helper).css("opacity",r._opacity)}}),e.ui.plugin.add("draggable","scroll",{start:function(){var t=e(this).data("ui-draggable");t.scrollParent[0]!==document&&t.scrollParent[0].tagName!=="HTML"&&(t.overflowOffset=t.scrollParent.offset())},drag:function(t){var n=e(this).data("ui-draggable"),r=n.options,i=!1;if(n.scrollParent[0]!==document&&n.scrollParent[0].tagName!=="HTML"){if(!r.axis||r.axis!=="x")n.overflowOffset.top+n.scrollParent[0].offsetHeight-t.pageY<r.scrollSensitivity?n.scrollParent[0].scrollTop=i=n.scrollParent[0].scrollTop+r.scrollSpeed:t.pageY-n.overflowOffset.top<r.scrollSensitivity&&(n.scrollParent[0].scrollTop=i=n.scrollParent[0].scrollTop-r.scrollSpeed);if(!r.axis||r.axis!=="y")n.overflowOffset.left+n.scrollParent[0].offsetWidth-t.pageX<r.scrollSensitivity?n.scrollParent[0].scrollLeft=i=n.scrollParent[0].scrollLeft+r.scrollSpeed:t.pageX-n.overflowOffset.left<r.scrollSensitivity&&(n.scrollParent[0].scrollLeft=i=n.scrollParent[0].scrollLeft-r.scrollSpeed)}else{if(!r.axis||r.axis!=="x")t.pageY-e(document).scrollTop()<r.scrollSensitivity?i=e(document).scrollTop(e(document).scrollTop()-r.scrollSpeed):e(window).height()-(t.pageY-e(document).scrollTop())<r.scrollSensitivity&&(i=e(document).scrollTop(e(document).scrollTop()+r.scrollSpeed));if(!r.axis||r.axis!=="y")t.pageX-e(document).scrollLeft()<r.scrollSensitivity?i=e(document).scrollLeft(e(document).scrollLeft()-r.scrollSpeed):e(window).width()-(t.pageX-e(document).scrollLeft())<r.scrollSensitivity&&(i=e(document).scrollLeft(e(document).scrollLeft()+r.scrollSpeed))}i!==!1&&e.ui.ddmanager&&!r.dropBehaviour&&e.ui.ddmanager.prepareOffsets(n,t)}}),e.ui.plugin.add("draggable","snap",{start:function(){var t=e(this).data("ui-draggable"),n=t.options;t.snapElements=[],e(n.snap.constructor!==String?n.snap.items||":data(ui-draggable)":n.snap).each(function(){var n=e(this),r=n.offset();this!==t.element[0]&&t.snapElements.push({item:this,width:n.outerWidth(),height:n.outerHeight(),top:r.top,left:r.left})})},drag:function(t,n){var r,i,s,o,u,a,f,l,c,h,p=e(this).data("ui-draggable"),d=p.options,v=d.snapTolerance,m=n.offset.left,g=m+p.helperProportions.width,y=n.offset.top,b=y+p.helperProportions.height;for(c=p.snapElements.length-1;c>=0;c--){u=p.snapElements[c].left,a=u+p.snapElements[c].width,f=p.snapElements[c].top,l=f+p.snapElements[c].height;if(!(u-v<m&&m<a+v&&f-v<y&&y<l+v||u-v<m&&m<a+v&&f-v<b&&b<l+v||u-v<g&&g<a+v&&f-v<y&&y<l+v||u-v<g&&g<a+v&&f-v<b&&b<l+v)){p.snapElements[c].snapping&&p.options.snap.release&&p.options.snap.release.call(p.element,t,e.extend(p._uiHash(),{snapItem:p.snapElements[c].item})),p.snapElements[c].snapping=!1;continue}d.snapMode!=="inner"&&(r=Math.abs(f-b)<=v,i=Math.abs(l-y)<=v,s=Math.abs(u-g)<=v,o=Math.abs(a-m)<=v,r&&(n.position.top=p._convertPositionTo("relative",{top:f-p.helperProportions.height,left:0}).top-p.margins.top),i&&(n.position.top=p._convertPositionTo("relative",{top:l,left:0}).top-p.margins.top),s&&(n.position.left=p._convertPositionTo("relative",{top:0,left:u-p.helperProportions.width}).left-p.margins.left),o&&(n.position.left=p._convertPositionTo("relative",{top:0,left:a}).left-p.margins.left)),h=r||i||s||o,d.snapMode!=="outer"&&(r=Math.abs(f-y)<=v,i=Math.abs(l-b)<=v,s=Math.abs(u-m)<=v,o=Math.abs(a-g)<=v,r&&(n.position.top=p._convertPositionTo("relative",{top:f,left:0}).top-p.margins.top),i&&(n.position.top=p._convertPositionTo("relative",{top:l-p.helperProportions.height,left:0}).top-p.margins.top),s&&(n.position.left=p._convertPositionTo("relative",{top:0,left:u}).left-p.margins.left),o&&(n.position.left=p._convertPositionTo("relative",{top:0,left:a-p.helperProportions.width}).left-p.margins.left)),!p.snapElements[c].snapping&&(r||i||s||o||h)&&p.options.snap.snap&&p.options.snap.snap.call(p.element,t,e.extend(p._uiHash(),{snapItem:p.snapElements[c].item})),p.snapElements[c].snapping=r||i||s||o||h}}}),e.ui.plugin.add("draggable","stack",{start:function(){var t,n=this.data("ui-draggable").options,r=e.makeArray(e(n.stack)).sort(function(t,n){return(parseInt(e(t).css("zIndex"),10)||0)-(parseInt(e(n).css("zIndex"),10)||0)});if(!r.length)return;t=parseInt(e(r[0]).css("zIndex"),10)||0,e(r).each(function(n){e(this).css("zIndex",t+n)}),this.css("zIndex",t+r.length)}}),e.ui.plugin.add("draggable","zIndex",{start:function(t,n){var r=e(n.helper),i=e(this).data("ui-draggable").options;r.css("zIndex")&&(i._zIndex=r.css("zIndex")),r.css("zIndex",i.zIndex)},stop:function(t,n){var r=e(this).data("ui-draggable").options;r._zIndex&&e(n.helper).css("zIndex",r._zIndex)}})}(jQuery),function(e,t){function n(e,t,n){return e>t&&e<t+n}e.widget("ui.droppable",{version:"1.10.1",widgetEventPrefix:"drop",options:{accept:"*",activeClass:!1,addClasses:!0,greedy:!1,hoverClass:!1,scope:"default",tolerance:"intersect",activate:null,deactivate:null,drop:null,out:null,over:null},_create:function(){var t=this.options,n=t.accept;this.isover=!1,this.isout=!0,this.accept=e.isFunction(n)?n:function(e){return e.is(n)},this.proportions={width:this.element[0].offsetWidth,height:this.element[0].offsetHeight},e.ui.ddmanager.droppables[t.scope]=e.ui.ddmanager.droppables[t.scope]||[],e.ui.ddmanager.droppables[t.scope].push(this),t.addClasses&&this.element.addClass("ui-droppable")},_destroy:function(){var t=0,n=e.ui.ddmanager.droppables[this.options.scope];for(;t<n.length;t++)n[t]===this&&n.splice(t,1);this.element.removeClass("ui-droppable ui-droppable-disabled")},_setOption:function(t,n){t==="accept"&&(this.accept=e.isFunction(n)?n:function(e){return e.is(n)}),e.Widget.prototype._setOption.apply(this,arguments)},_activate:function(t){var n=e.ui.ddmanager.current;this.options.activeClass&&this.element.addClass(this.options.activeClass),n&&this._trigger("activate",t,this.ui(n))},_deactivate:function(t){var n=e.ui.ddmanager.current;this.options.activeClass&&this.element.removeClass(this.options.activeClass),n&&this._trigger("deactivate",t,this.ui(n))},_over:function(t){var n=e.ui.ddmanager.current;if(!n||(n.currentItem||n.element)[0]===this.element[0])return;this.accept.call(this.element[0],n.currentItem||n.element)&&(this.options.hoverClass&&this.element.addClass(this.options.hoverClass),this._trigger("over",t,this.ui(n)))},_out:function(t){var n=e.ui.ddmanager.current;if(!n||(n.currentItem||n.element)[0]===this.element[0])return;this.accept.call(this.element[0],n.currentItem||n.element)&&(this.options.hoverClass&&this.element.removeClass(this.options.hoverClass),this._trigger("out",t,this.ui(n)))},_drop:function(t,n){var r=n||e.ui.ddmanager.current,i=!1;return!r||(r.currentItem||r.element)[0]===this.element[0]?!1:(this.element.find(":data(ui-droppable)").not(".ui-draggable-dragging").each(function(){var n=e.data(this,"ui-droppable");if(n.options.greedy&&!n.options.disabled&&n.options.scope===r.options.scope&&n.accept.call(n.element[0],r.currentItem||r.element)&&e.ui.intersect(r,e.extend(n,{offset:n.element.offset()}),n.options.tolerance,t))return i=!0,!1}),i?!1:this.accept.call(this.element[0],r.currentItem||r.element)?(this.options.activeClass&&this.element.removeClass(this.options.activeClass),this.options.hoverClass&&this.element.removeClass(this.options.hoverClass),this._trigger("drop",t,this.ui(r)),this.element):!1)},ui:function(e){return{draggable:e.currentItem||e.element,helper:e.helper,position:e.position,offset:e.positionAbs}}}),e.ui.intersect=function(e,t,r,i){if(!t.offset)return!1;var s,o,u=(e.positionAbs||e.position.absolute).left,a=u+e.helperProportions.width,f=(e.positionAbs||e.position.absolute).top,l=f+e.helperProportions.height,c=t.offset.left,h=c+t.proportions.width,p=t.offset.top,d=p+t.proportions.height;switch(r){case"fit":return c<=u&&a<=h&&p<=f&&l<=d;case"intersect":return c<u+e.helperProportions.width/2&&a-e.helperProportions.width/2<h&&p<f+e.helperProportions.height/2&&l-e.helperProportions.height/2<d;case"pointer":return s=i.pageX,o=i.pageY,n(o,p,t.proportions.height)&&n(s,c,t.proportions.width);case"touch":return(f>=p&&f<=d||l>=p&&l<=d||f<p&&l>d)&&(u>=c&&u<=h||a>=c&&a<=h||u<c&&a>h);default:return!1}},e.ui.ddmanager={current:null,droppables:{"default":[]},prepareOffsets:function(t,n){var r,i,s=e.ui.ddmanager.droppables[t.options.scope]||[],o=n?n.type:null,u=(t.currentItem||t.element).find(":data(ui-droppable)").addBack();e:for(r=0;r<s.length;r++){if(s[r].options.disabled||t&&!s[r].accept.call(s[r].element[0],t.currentItem||t.element))continue;for(i=0;i<u.length;i++)if(u[i]===s[r].element[0]){s[r].proportions.height=0;continue e}s[r].visible=s[r].element.css("display")!=="none";if(!s[r].visible)continue;o==="mousedown"&&s[r]._activate.call(s[r],n),s[r].offset=s[r].element.offset(),s[r].proportions={width:s[r].element[0].offsetWidth,height:s[r].element[0].offsetHeight}}},drop:function(t,n){var r=!1;return e.each(e.ui.ddmanager.droppables[t.options.scope]||[],function(){if(!this.options)return;!this.options.disabled&&this.visible&&e.ui.intersect(t,this,this.options.tolerance,n)&&(r=this._drop.call(this,n)||r),!this.options.disabled&&this.visible&&this.accept.call(this.element[0],t.currentItem||t.element)&&(this.isout=!0,this.isover=!1,this._deactivate.call(this,n))}),r},dragStart:function(t,n){t.element.parentsUntil("body").bind("scroll.droppable",function(){t.options.refreshPositions||e.ui.ddmanager.prepareOffsets(t,n)})},drag:function(t,n){t.options.refreshPositions&&e.ui.ddmanager.prepareOffsets(t,n),e.each(e.ui.ddmanager.droppables[t.options.scope]||[],function(){if(this.options.disabled||this.greedyChild||!this.visible)return;var r,i,s,o=e.ui.intersect(t,this,this.options.tolerance,n),u=!o&&this.isover?"isout":o&&!this.isover?"isover":null;if(!u)return;this.options.greedy&&(i=this.options.scope,s=this.element.parents(":data(ui-droppable)").filter(function(){return e.data(this,"ui-droppable").options.scope===i}),s.length&&(r=e.data(s[0],"ui-droppable"),r.greedyChild=u==="isover")),r&&u==="isover"&&(r.isover=!1,r.isout=!0,r._out.call(r,n)),this[u]=!0,this[u==="isout"?"isover":"isout"]=!1,this[u==="isover"?"_over":"_out"].call(this,n),r&&u==="isout"&&(r.isout=!1,r.isover=!0,r._over.call(r,n))})},dragStop:function(t,n){t.element.parentsUntil("body").unbind("scroll.droppable"),t.options.refreshPositions||e.ui.ddmanager.prepareOffsets(t,n)}}}(jQuery),function(e,t){function n(e){return parseInt(e,10)||0}function r(e){return!isNaN(parseInt(e,10))}e.widget("ui.resizable",e.ui.mouse,{version:"1.10.0",widgetEventPrefix:"resize",options:{alsoResize:!1,animate:!1,animateDuration:"slow",animateEasing:"swing",aspectRatio:!1,autoHide:!1,containment:!1,ghost:!1,grid:!1,handles:"e,s,se",helper:!1,maxHeight:null,maxWidth:null,minHeight:10,minWidth:10,zIndex:90,resize:null,start:null,stop:null},_create:function(){var t,n,r,i,s,o=this,u=this.options;this.element.addClass("ui-resizable"),e.extend(this,{_aspectRatio:!!u.aspectRatio,aspectRatio:u.aspectRatio,originalElement:this.element,_proportionallyResizeElements:[],_helper:u.helper||u.ghost||u.animate?u.helper||"ui-resizable-helper":null}),this.element[0].nodeName.match(/canvas|textarea|input|select|button|img/i)&&(this.element.wrap(e("<div class='ui-wrapper' style='overflow: hidden;'></div>").css({position:this.element.css("position"),width:this.element.outerWidth(),height:this.element.outerHeight(),top:this.element.css("top"),left:this.element.css("left")})),this.element=this.element.parent().data("ui-resizable",this.element.data("ui-resizable")),this.elementIsWrapper=!0,this.element.css({marginLeft:this.originalElement.css("marginLeft"),marginTop:this.originalElement.css("marginTop"),marginRight:this.originalElement.css("marginRight"),marginBottom:this.originalElement.css("marginBottom")}),this.originalElement.css({marginLeft:0,marginTop:0,marginRight:0,marginBottom:0}),this.originalResizeStyle=this.originalElement.css("resize"),this.originalElement.css("resize","none"),this._proportionallyResizeElements.push(this.originalElement.css({position:"static",zoom:1,display:"block"})),this.originalElement.css({margin:this.originalElement.css("margin")}),this._proportionallyResize()),this.handles=u.handles||(e(".ui-resizable-handle",this.element).length?{n:".ui-resizable-n",e:".ui-resizable-e",s:".ui-resizable-s",w:".ui-resizable-w",se:".ui-resizable-se",sw:".ui-resizable-sw",ne:".ui-resizable-ne",nw:".ui-resizable-nw"}:"e,s,se");if(this.handles.constructor===String){this.handles==="all"&&(this.handles="n,e,s,w,se,sw,ne,nw"),t=this.handles.split(","),this.handles={};for(n=0;n<t.length;n++)r=e.trim(t[n]),s="ui-resizable-"+r,i=e("<div class='ui-resizable-handle "+s+"'></div>"),i.css({zIndex:u.zIndex}),"se"===r&&i.addClass("ui-icon ui-icon-gripsmall-diagonal-se"),this.handles[r]=".ui-resizable-"+r,this.element.append(i)}this._renderAxis=function(t){var n,r,i,s;t=t||this.element;for(n in this.handles){this.handles[n].constructor===String&&(this.handles[n]=e(this.handles[n],this.element).show()),this.elementIsWrapper&&this.originalElement[0].nodeName.match(/textarea|input|select|button/i)&&(r=e(this.handles[n],this.element),s=/sw|ne|nw|se|n|s/.test(n)?r.outerHeight():r.outerWidth(),i=["padding",/ne|nw|n/.test(n)?"Top":/se|sw|s/.test(n)?"Bottom":/^e$/.test(n)?"Right":"Left"].join(""),t.css(i,s),this._proportionallyResize());if(!e(this.handles[n]).length)continue}},this._renderAxis(this.element),this._handles=e(".ui-resizable-handle",this.element).disableSelection(),this._handles.mouseover(function(){o.resizing||(this.className&&(i=this.className.match(/ui-resizable-(se|sw|ne|nw|n|e|s|w)/i)),o.axis=i&&i[1]?i[1]:"se")}),u.autoHide&&(this._handles.hide(),e(this.element).addClass("ui-resizable-autohide").mouseenter(function(){if(u.disabled)return;e(this).removeClass("ui-resizable-autohide"),o._handles.show()}).mouseleave(function(){if(u.disabled)return;o.resizing||(e(this).addClass("ui-resizable-autohide"),o._handles.hide())})),this._mouseInit()},_destroy:function(){this._mouseDestroy();var t,n=function(t){e(t).removeClass("ui-resizable ui-resizable-disabled ui-resizable-resizing").removeData("resizable").removeData("ui-resizable").unbind(".resizable").find(".ui-resizable-handle").remove()};return this.elementIsWrapper&&(n(this.element),t=this.element,this.originalElement.css({position:t.css("position"),width:t.outerWidth(),height:t.outerHeight(),top:t.css("top"),left:t.css("left")}).insertAfter(t),t.remove()),this.originalElement.css("resize",this.originalResizeStyle),n(this.originalElement),this},_mouseCapture:function(t){var n,r,i=!1;for(n in this.handles){r=e(this.handles[n])[0];if(r===t.target||e.contains(r,t.target))i=!0}return!this.options.disabled&&i},_mouseStart:function(t){var r,i,s,o=this.options,u=this.element.position(),a=this.element;return this.resizing=!0,/absolute/.test(a.css("position"))?a.css({position:"absolute",top:a.css("top"),left:a.css("left")}):a.is(".ui-draggable")&&a.css({position:"absolute",top:u.top,left:u.left}),this._renderProxy(),r=n(this.helper.css("left")),i=n(this.helper.css("top")),o.containment&&(r+=e(o.containment).scrollLeft()||0,i+=e(o.containment).scrollTop()||0),this.offset=this.helper.offset(),this.position={left:r,top:i},this.size=this._helper?{width:a.outerWidth(),height:a.outerHeight()}:{width:a.width(),height:a.height()},this.originalSize=this._helper?{width:a.outerWidth(),height:a.outerHeight()}:{width:a.width(),height:a.height()},this.originalPosition={left:r,top:i},this.sizeDiff={width:a.outerWidth()-a.width(),height:a.outerHeight()-a.height()},this.originalMousePosition={left:t.pageX,top:t.pageY},this.aspectRatio=typeof o.aspectRatio=="number"?o.aspectRatio:this.originalSize.width/this.originalSize.height||1,s=e(".ui-resizable-"+this.axis).css("cursor"),e("body").css("cursor",s==="auto"?this.axis+"-resize":s),a.addClass("ui-resizable-resizing"),this._propagate("start",t),!0},_mouseDrag:function(t){var n,r=this.helper,i={},s=this.originalMousePosition,o=this.axis,u=this.position.top,a=this.position.left,f=this.size.width,l=this.size.height,c=t.pageX-s.left||0,h=t.pageY-s.top||0,p=this._change[o];if(!p)return!1;n=p.apply(this,[t,c,h]),this._updateVirtualBoundaries(t.shiftKey);if(this._aspectRatio||t.shiftKey)n=this._updateRatio(n,t);return n=this._respectSize(n,t),this._updateCache(n),this._propagate("resize",t),this.position.top!==u&&(i.top=this.position.top+"px"),this.position.left!==a&&(i.left=this.position.left+"px"),this.size.width!==f&&(i.width=this.size.width+"px"),this.size.height!==l&&(i.height=this.size.height+"px"),r.css(i),!this._helper&&this._proportionallyResizeElements.length&&this._proportionallyResize(),e.isEmptyObject(i)||this._trigger("resize",t,this.ui()),!1},_mouseStop:function(t){this.resizing=!1;var n,r,i,s,o,u,a,f=this.options,l=this;return this._helper&&(n=this._proportionallyResizeElements,r=n.length&&/textarea/i.test(n[0].nodeName),i=r&&e.ui.hasScroll(n[0],"left")?0:l.sizeDiff.height,s=r?0:l.sizeDiff.width,o={width:l.helper.width()-s,height:l.helper.height()-i},u=parseInt(l.element.css("left"),10)+(l.position.left-l.originalPosition.left)||null,a=parseInt(l.element.css("top"),10)+(l.position.top-l.originalPosition.top)||null,f.animate||this.element.css(e.extend(o,{top:a,left:u})),l.helper.height(l.size.height),l.helper.width(l.size.width),this._helper&&!f.animate&&this._proportionallyResize()),e("body").css("cursor","auto"),this.element.removeClass("ui-resizable-resizing"),this._propagate("stop",t),this._helper&&this.helper.remove(),!1},_updateVirtualBoundaries:function(e){var t,n,i,s,o,u=this.options;o={minWidth:r(u.minWidth)?u.minWidth:0,maxWidth:r(u.maxWidth)?u.maxWidth:Infinity,minHeight:r(u.minHeight)?u.minHeight:0,maxHeight:r(u.maxHeight)?u.maxHeight:Infinity};if(this._aspectRatio||e)t=o.minHeight*this.aspectRatio,i=o.minWidth/this.aspectRatio,n=o.maxHeight*this.aspectRatio,s=o.maxWidth/this.aspectRatio,t>o.minWidth&&(o.minWidth=t),i>o.minHeight&&(o.minHeight=i),n<o.maxWidth&&(o.maxWidth=n),s<o.maxHeight&&(o.maxHeight=s);this._vBoundaries=o},_updateCache:function(e){this.offset=this.helper.offset(),r(e.left)&&(this.position.left=e.left),r(e.top)&&(this.position.top=e.top),r(e.height)&&(this.size.height=e.height),r(e.width)&&(this.size.width=e.width)},_updateRatio:function(e){var t=this.position,n=this.size,i=this.axis;return r(e.height)?e.width=e.height*this.aspectRatio:r(e.width)&&(e.height=e.width/this.aspectRatio),i==="sw"&&(e.left=t.left+(n.width-e.width),e.top=null),i==="nw"&&(e.top=t.top+(n.height-e.height),e.left=t.left+(n.width-e.width)),e},_respectSize:function(e){var t=this._vBoundaries,n=this.axis,i=r(e.width)&&t.maxWidth&&t.maxWidth<e.width,s=r(e.height)&&t.maxHeight&&t.maxHeight<e.height,o=r(e.width)&&t.minWidth&&t.minWidth>e.width,u=r(e.height)&&t.minHeight&&t.minHeight>e.height,a=this.originalPosition.left+this.originalSize.width,f=this.position.top+this.size.height,l=/sw|nw|w/.test(n),c=/nw|ne|n/.test(n);return o&&(e.width=t.minWidth),u&&(e.height=t.minHeight),i&&(e.width=t.maxWidth),s&&(e.height=t.maxHeight),o&&l&&(e.left=a-t.minWidth),i&&l&&(e.left=a-t.maxWidth),u&&c&&(e.top=f-t.minHeight),s&&c&&(e.top=f-t.maxHeight),!e.width&&!e.height&&!e.left&&e.top?e.top=null:!e.width&&!e.height&&!e.top&&e.left&&(e.left=null),e},_proportionallyResize:function(){if(!this._proportionallyResizeElements.length)return;var e,t,n,r,i,s=this.helper||this.element;for(e=0;e<this._proportionallyResizeElements.length;e++){i=this._proportionallyResizeElements[e];if(!this.borderDif){this.borderDif=[],n=[i.css("borderTopWidth"),i.css("borderRightWidth"),i.css("borderBottomWidth"),i.css("borderLeftWidth")],r=[i.css("paddingTop"),i.css("paddingRight"),i.css("paddingBottom"),i.css("paddingLeft")];for(t=0;t<n.length;t++)this.borderDif[t]=(parseInt(n[t],10)||0)+(parseInt(r[t],10)||0)}i.css({height:s.height()-this.borderDif[0]-this.borderDif[2]||0,width:s.width()-this.borderDif[1]-this.borderDif[3]||0})}},_renderProxy:function(){var t=this.element,n=this.options;this.elementOffset=t.offset(),this._helper?(this.helper=this.helper||e("<div style='overflow:hidden;'></div>"),this.helper.addClass(this._helper).css({width:this.element.outerWidth()-1,height:this.element.outerHeight()-1,position:"absolute",left:this.elementOffset.left+"px",top:this.elementOffset.top+"px",zIndex:++n.zIndex}),this.helper.appendTo("body").disableSelection()):this.helper=this.element},_change:{e:function(e,t){return{width:this.originalSize.width+t}},w:function(e,t){var n=this.originalSize,r=this.originalPosition;return{left:r.left+t,width:n.width-t}},n:function(e,t,n){var r=this.originalSize,i=this.originalPosition;return{top:i.top+n,height:r.height-n}},s:function(e,t,n){return{height:this.originalSize.height+n}},se:function(t,n,r){return e.extend(this._change.s.apply(this,arguments),this._change.e.apply(this,[t,n,r]))},sw:function(t,n,r){return e.extend(this._change.s.apply(this,arguments),this._change.w.apply(this,[t,n,r]))},ne:function(t,n,r){return e.extend(this._change.n.apply(this,arguments),this._change.e.apply(this,[t,n,r]))},nw:function(t,n,r){return e.extend(this._change.n.apply(this,arguments),this._change.w.apply(this,[t,n,r]))}},_propagate:function(t,n){e.ui.plugin.call(this,t,[n,this.ui()]),t!=="resize"&&this._trigger(t,n,this.ui())},plugins:{},ui:function(){return{originalElement:this.originalElement,element:this.element,helper:this.helper,position:this.position,size:this.size,originalSize:this.originalSize,originalPosition:this.originalPosition}}}),e.ui.plugin.add("resizable","animate",{stop:function(t){var n=e(this).data("ui-resizable"),r=n.options,i=n._proportionallyResizeElements,s=i.length&&/textarea/i.test(i[0].nodeName),o=s&&e.ui.hasScroll(i[0],"left")?0:n.sizeDiff.height,u=s?0:n.sizeDiff.width,a={width:n.size.width-u,height:n.size.height-o},f=parseInt(n.element.css("left"),10)+(n.position.left-n.originalPosition.left)||null,l=parseInt(n.element.css("top"),10)+(n.position.top-n.originalPosition.top)||null;n.element.animate(e.extend(a,l&&f?{top:l,left:f}:{}),{duration:r.animateDuration,easing:r.animateEasing,step:function(){var r={width:parseInt(n.element.css("width"),10),height:parseInt(n.element.css("height"),10),top:parseInt(n.element.css("top"),10),left:parseInt(n.element.css("left"),10)};i&&i.length&&e(i[0]).css({width:r.width,height:r.height}),n._updateCache(r),n._propagate("resize",t)}})}}),e.ui.plugin.add("resizable","containment",{start:function(){var t,r,i,s,o,u,a,f=e(this).data("ui-resizable"),l=f.options,c=f.element,h=l.containment,p=h instanceof e?h.get(0):/parent/.test(h)?c.parent().get(0):h;if(!p)return;f.containerElement=e(p),/document/.test(h)||h===document?(f.containerOffset={left:0,top:0},f.containerPosition={left:0,top:0},f.parentData={element:e(document),left:0,top:0,width:e(document).width(),height:e(document).height()||document.body.parentNode.scrollHeight}):(t=e(p),r=[],e(["Top","Right","Left","Bottom"]).each(function(e,i){r[e]=n(t.css("padding"+i))}),f.containerOffset=t.offset(),f.containerPosition=t.position(),f.containerSize={height:t.innerHeight()-r[3],width:t.innerWidth()-r[1]},i=f.containerOffset,s=f.containerSize.height,o=f.containerSize.width,u=e.ui.hasScroll(p,"left")?p.scrollWidth:o,a=e.ui.hasScroll(p)?p.scrollHeight:s,f.parentData={element:p,left:i.left,top:i.top,width:u,height:a})},resize:function(t){var n,r,i,s,o=e(this).data("ui-resizable"),u=o.options,a=o.containerOffset,f=o.position,l=o._aspectRatio||t.shiftKey,c={top:0,left:0},h=o.containerElement;h[0]!==document&&/static/.test(h.css("position"))&&(c=a),f.left<(o._helper?a.left:0)&&(o.size.width=o.size.width+(o._helper?o.position.left-a.left:o.position.left-c.left),l&&(o.size.height=o.size.width/o.aspectRatio),o.position.left=u.helper?a.left:0),f.top<(o._helper?a.top:0)&&(o.size.height=o.size.height+(o._helper?o.position.top-a.top:o.position.top),l&&(o.size.width=o.size.height*o.aspectRatio),o.position.top=o._helper?a.top:0),o.offset.left=o.parentData.left+o.position.left,o.offset.top=o.parentData.top+o.position.top,n=Math.abs((o._helper?o.offset.left-c.left:o.offset.left-c.left)+o.sizeDiff.width),r=Math.abs((o._helper?o.offset.top-c.top:o.offset.top-a.top)+o.sizeDiff.height),i=o.containerElement.get(0)===o.element.parent().get(0),s=/relative|absolute/.test(o.containerElement.css("position")),i&&s&&(n-=o.parentData.left),n+o.size.width>=o.parentData.width&&(o.size.width=o.parentData.width-n,l&&(o.size.height=o.size.width/o.aspectRatio)),r+o.size.height>=o.parentData.height&&(o.size.height=o.parentData.height-r,l&&(o.size.width=o.size.height*o.aspectRatio))},stop:function(){var t=e(this).data("ui-resizable"),n=t.options,r=t.containerOffset,i=t.containerPosition,s=t.containerElement,o=e(t.helper),u=o.offset(),a=o.outerWidth()-t.sizeDiff.width,f=o.outerHeight()-t.sizeDiff.height;t._helper&&!n.animate&&/relative/.test(s.css("position"))&&e(this).css({left:u.left-i.left-r.left,width:a,height:f}),t._helper&&!n.animate&&/static/.test(s.css("position"))&&e(this).css({left:u.left-i.left-r.left,width:a,height:f})}}),e.ui.plugin.add("resizable","alsoResize",{start:function(){var t=e(this).data("ui-resizable"),n=t.options,r=function(t){e(t).each(function(){var t=e(this);t.data("ui-resizable-alsoresize",{width:parseInt(t.width(),10),height:parseInt(t.height(),10),left:parseInt(t.css("left"),10),top:parseInt(t.css("top"),10)})})};typeof n.alsoResize=="object"&&!n.alsoResize.parentNode?n.alsoResize.length?(n.alsoResize=n.alsoResize[0],r(n.alsoResize)):e.each(n.alsoResize,function(e){r(e)}):r(n.alsoResize)},resize:function(t,n){var r=e(this).data("ui-resizable"),i=r.options,s=r.originalSize,o=r.originalPosition,u={height:r.size.height-s.height||0,width:r.size.width-s.width||0,top:r.position.top-o.top||0,left:r.position.left-o.left||0},a=function(t,r){e(t).each(function(){var t=e(this),i=e(this).data("ui-resizable-alsoresize"),s={},o=r&&r.length?r:t.parents(n.originalElement[0]).length?["width","height"]:["width","height","top","left"];e.each(o,function(e,t){var n=(i[t]||0)+(u[t]||0);n&&n>=0&&(s[t]=n||null)}),t.css(s)})};typeof i.alsoResize=="object"&&!i.alsoResize.nodeType?e.each(i.alsoResize,function(e,t){a(e,t)}):a(i.alsoResize)},stop:function(){e(this).removeData("resizable-alsoresize")}}),e.ui.plugin.add("resizable","ghost",{start:function(){var t=e(this).data("ui-resizable"),n=t.options,r=t.size;t.ghost=t.originalElement.clone(),t.ghost.css({opacity:.25,display:"block",position:"relative",height:r.height,width:r.width,margin:0,left:0,top:0}).addClass("ui-resizable-ghost").addClass(typeof n.ghost=="string"?n.ghost:""),t.ghost.appendTo(t.helper)},resize:function(){var t=e(this).data("ui-resizable");t.ghost&&t.ghost.css({position:"relative",height:t.size.height,width:t.size.width})},stop:function(){var t=e(this).data("ui-resizable");t.ghost&&t.helper&&t.helper.get(0).removeChild(t.ghost.get(0))}}),e.ui.plugin.add("resizable","grid",{resize:function(){var t=e(this).data("ui-resizable"),n=t.options,r=t.size,i=t.originalSize,s=t.originalPosition,o=t.axis,u=typeof n.grid=="number"?[n.grid,n.grid]:n.grid,a=u[0]||1,f=u[1]||1,l=Math.round((r.width-i.width)/a)*a,c=Math.round((r.height-i.height)/f)*f,h=i.width+l,p=i.height+c,d=n.maxWidth&&n.maxWidth<h,v=n.maxHeight&&n.maxHeight<p,m=n.minWidth&&n.minWidth>h,g=n.minHeight&&n.minHeight>p;n.grid=u,m&&(h+=a),g&&(p+=f),d&&(h-=a),v&&(p-=f),/^(se|s|e)$/.test(o)?(t.size.width=h,t.size.height=p):/^(ne)$/.test(o)?(t.size.width=h,t.size.height=p,t.position.top=s.top-c):/^(sw)$/.test(o)?(t.size.width=h,t.size.height=p,t.position.left=s.left-l):(t.size.width=h,t.size.height=p,t.position.top=s.top-c,t.position.left=s.left-l)}})}(jQuery),function(e){function t(e,t,n){return e>t&&t+n>e}function n(e){return/left|right/.test(e.css("float"))||/inline|table-cell/.test(e.css("display"))}e.widget("ui.sortable",e.ui.mouse,{version:"1.10.2",widgetEventPrefix:"sort",ready:!1,options:{appendTo:"parent",axis:!1,connectWith:!1,containment:!1,cursor:"auto",cursorAt:!1,dropOnEmpty:!0,forcePlaceholderSize:!1,forceHelperSize:!1,grid:!1,handle:!1,helper:"original",items:"> *",opacity:!1,placeholder:!1,revert:!1,scroll:!0,scrollSensitivity:20,scrollSpeed:20,scope:"default",tolerance:"intersect",zIndex:1e3,activate:null,beforeStop:null,change:null,deactivate:null,out:null,over:null,receive:null,remove:null,sort:null,start:null,stop:null,update:null},_create:function(){var e=this.options;this.containerCache={},this.element.addClass("ui-sortable"),this.refresh(),this.floating=this.items.length?"x"===e.axis||n(this.items[0].item):!1,this.offset=this.element.offset(),this._mouseInit(),this.ready=!0},_destroy:function(){this.element.removeClass("ui-sortable ui-sortable-disabled"),this._mouseDestroy();for(var e=this.items.length-1;e>=0;e--)this.items[e].item.removeData(this.widgetName+"-item");return this},_setOption:function(t,n){"disabled"===t?(this.options[t]=n,this.widget().toggleClass("ui-sortable-disabled",!!n)):e.Widget.prototype._setOption.apply(this,arguments)},_mouseCapture:function(t,n){var r=null,i=!1,s=this;return this.reverting?!1:this.options.disabled||"static"===this.options.type?!1:(this._refreshItems(t),e(t.target).parents().each(function(){return e.data(this,s.widgetName+"-item")===s?(r=e(this),!1):undefined}),e.data(t.target,s.widgetName+"-item")===s&&(r=e(t.target)),r?!this.options.handle||n||(e(this.options.handle,r).find("*").addBack().each(function(){this===t.target&&(i=!0)}),i)?(this.currentItem=r,this._removeCurrentsFromItems(),!0):!1:!1)},_mouseStart:function(t,n,r){var i,s,o=this.options;if(this.currentContainer=this,this.refreshPositions(),this.helper=this._createHelper(t),this._cacheHelperProportions(),this._cacheMargins(),this.scrollParent=this.helper.scrollParent(),this.offset=this.currentItem.offset(),this.offset={top:this.offset.top-this.margins.top,left:this.offset.left-this.margins.left},e.extend(this.offset,{click:{left:t.pageX-this.offset.left,top:t.pageY-this.offset.top},parent:this._getParentOffset(),relative:this._getRelativeOffset()}),this.helper.css("position","absolute"),this.cssPosition=this.helper.css("position"),this.originalPosition=this._generatePosition(t),this.originalPageX=t.pageX,this.originalPageY=t.pageY,o.cursorAt&&this._adjustOffsetFromHelper(o.cursorAt),this.domPosition={prev:this.currentItem.prev()[0],parent:this.currentItem.parent()[0]},this.helper[0]!==this.currentItem[0]&&this.currentItem.hide(),this._createPlaceholder(),o.containment&&this._setContainment(),o.cursor&&"auto"!==o.cursor&&(s=this.document.find("body"),this.storedCursor=s.css("cursor"),s.css("cursor",o.cursor),this.storedStylesheet=e("<style>*{ cursor: "+o.cursor+" !important; }</style>").appendTo(s)),o.opacity&&(this.helper.css("opacity")&&(this._storedOpacity=this.helper.css("opacity")),this.helper.css("opacity",o.opacity)),o.zIndex&&(this.helper.css("zIndex")&&(this._storedZIndex=this.helper.css("zIndex")),this.helper.css("zIndex",o.zIndex)),this.scrollParent[0]!==document&&"HTML"!==this.scrollParent[0].tagName&&(this.overflowOffset=this.scrollParent.offset()),this._trigger("start",t,this._uiHash()),this._preserveHelperProportions||this._cacheHelperProportions(),!r)for(i=this.containers.length-1;i>=0;i--)this.containers[i]._trigger("activate",t,this._uiHash(this));return e.ui.ddmanager&&(e.ui.ddmanager.current=this),e.ui.ddmanager&&!o.dropBehaviour&&e.ui.ddmanager.prepareOffsets(this,t),this.dragging=!0,this.helper.addClass("ui-sortable-helper"),this._mouseDrag(t),!0},_mouseDrag:function(t){var n,r,i,s,o=this.options,u=!1;for(this.position=this._generatePosition(t),this.positionAbs=this._convertPositionTo("absolute"),this.lastPositionAbs||(this.lastPositionAbs=this.positionAbs),this.options.scroll&&(this.scrollParent[0]!==document&&"HTML"!==this.scrollParent[0].tagName?(this.overflowOffset.top+this.scrollParent[0].offsetHeight-t.pageY<o.scrollSensitivity?this.scrollParent[0].scrollTop=u=this.scrollParent[0].scrollTop+o.scrollSpeed:t.pageY-this.overflowOffset.top<o.scrollSensitivity&&(this.scrollParent[0].scrollTop=u=this.scrollParent[0].scrollTop-o.scrollSpeed),this.overflowOffset.left+this.scrollParent[0].offsetWidth-t.pageX<o.scrollSensitivity?this.scrollParent[0].scrollLeft=u=this.scrollParent[0].scrollLeft+o.scrollSpeed:t.pageX-this.overflowOffset.left<o.scrollSensitivity&&(this.scrollParent[0].scrollLeft=u=this.scrollParent[0].scrollLeft-o.scrollSpeed)):(t.pageY-e(document).scrollTop()<o.scrollSensitivity?u=e(document).scrollTop(e(document).scrollTop()-o.scrollSpeed):e(window).height()-(t.pageY-e(document).scrollTop())<o.scrollSensitivity&&(u=e(document).scrollTop(e(document).scrollTop()+o.scrollSpeed)),t.pageX-e(document).scrollLeft()<o.scrollSensitivity?u=e(document).scrollLeft(e(document).scrollLeft()-o.scrollSpeed):e(window).width()-(t.pageX-e(document).scrollLeft())<o.scrollSensitivity&&(u=e(document).scrollLeft(e(document).scrollLeft()+o.scrollSpeed))),u!==!1&&e.ui.ddmanager&&!o.dropBehaviour&&e.ui.ddmanager.prepareOffsets(this,t)),this.positionAbs=this._convertPositionTo("absolute"),this.options.axis&&"y"===this.options.axis||(this.helper[0].style.left=this.position.left+"px"),this.options.axis&&"x"===this.options.axis||(this.helper[0].style.top=this.position.top+"px"),n=this.items.length-1;n>=0;n--)if(r=this.items[n],i=r.item[0],s=this._intersectsWithPointer(r),s&&r.instance===this.currentContainer&&i!==this.currentItem[0]&&this.placeholder[1===s?"next":"prev"]()[0]!==i&&!e.contains(this.placeholder[0],i)&&("semi-dynamic"===this.options.type?!e.contains(this.element[0],i):!0)){if(this.direction=1===s?"down":"up","pointer"!==this.options.tolerance&&!this._intersectsWithSides(r))break;this._rearrange(t,r),this._trigger("change",t,this._uiHash());break}return this._contactContainers(t),e.ui.ddmanager&&e.ui.ddmanager.drag(this,t),this._trigger("sort",t,this._uiHash()),this.lastPositionAbs=this.positionAbs,!1},_mouseStop:function(t,n){if(t){if(e.ui.ddmanager&&!this.options.dropBehaviour&&e.ui.ddmanager.drop(this,t),this.options.revert){var r=this,i=this.placeholder.offset(),s=this.options.axis,o={};s&&"x"!==s||(o.left=i.left-this.offset.parent.left-this.margins.left+(this.offsetParent[0]===document.body?0:this.offsetParent[0].scrollLeft)),s&&"y"!==s||(o.top=i.top-this.offset.parent.top-this.margins.top+(this.offsetParent[0]===document.body?0:this.offsetParent[0].scrollTop)),this.reverting=!0,e(this.helper).animate(o,parseInt(this.options.revert,10)||500,function(){r._clear(t)})}else this._clear(t,n);return!1}},cancel:function(){if(this.dragging){this._mouseUp({target:null}),"original"===this.options.helper?this.currentItem.css(this._storedCSS).removeClass("ui-sortable-helper"):this.currentItem.show();for(var t=this.containers.length-1;t>=0;t--)this.containers[t]._trigger("deactivate",null,this._uiHash(this)),this.containers[t].containerCache.over&&(this.containers[t]._trigger("out",null,this._uiHash(this)),this.containers[t].containerCache.over=0)}return this.placeholder&&(this.placeholder[0].parentNode&&this.placeholder[0].parentNode.removeChild(this.placeholder[0]),"original"!==this.options.helper&&this.helper&&this.helper[0].parentNode&&this.helper.remove(),e.extend(this,{helper:null,dragging:!1,reverting:!1,_noFinalSort:null}),this.domPosition.prev?e(this.domPosition.prev).after(this.currentItem):e(this.domPosition.parent).prepend(this.currentItem)),this},serialize:function(t){var n=this._getItemsAsjQuery(t&&t.connected),r=[];return t=t||{},e(n).each(function(){var n=(e(t.item||this).attr(t.attribute||"id")||"").match(t.expression||/(.+)[\-=_](.+)/);n&&r.push((t.key||n[1]+"[]")+"="+(t.key&&t.expression?n[1]:n[2]))}),!r.length&&t.key&&r.push(t.key+"="),r.join("&")},toArray:function(t){var n=this._getItemsAsjQuery(t&&t.connected),r=[];return t=t||{},n.each(function(){r.push(e(t.item||this).attr(t.attribute||"id")||"")}),r},_intersectsWith:function(e){var t=this.positionAbs.left,n=t+this.helperProportions.width,r=this.positionAbs.top,i=r+this.helperProportions.height,s=e.left,o=s+e.width,u=e.top,a=u+e.height,f=this.offset.click.top,l=this.offset.click.left,c=r+f>u&&a>r+f&&t+l>s&&o>t+l;return"pointer"===this.options.tolerance||this.options.forcePointerForContainers||"pointer"!==this.options.tolerance&&this.helperProportions[this.floating?"width":"height"]>e[this.floating?"width":"height"]?c:t+this.helperProportions.width/2>s&&o>n-this.helperProportions.width/2&&r+this.helperProportions.height/2>u&&a>i-this.helperProportions.height/2},_intersectsWithPointer:function(e){var n="x"===this.options.axis||t(this.positionAbs.top+this.offset.click.top,e.top,e.height),r="y"===this.options.axis||t(this.positionAbs.left+this.offset.click.left,e.left,e.width),i=n&&r,s=this._getDragVerticalDirection(),o=this._getDragHorizontalDirection();return i?this.floating?o&&"right"===o||"down"===s?2:1:s&&("down"===s?2:1):!1},_intersectsWithSides:function(e){var n=t(this.positionAbs.top+this.offset.click.top,e.top+e.height/2,e.height),r=t(this.positionAbs.left+this.offset.click.left,e.left+e.width/2,e.width),i=this._getDragVerticalDirection(),s=this._getDragHorizontalDirection();return this.floating&&s?"right"===s&&r||"left"===s&&!r:i&&("down"===i&&n||"up"===i&&!n)},_getDragVerticalDirection:function(){var e=this.positionAbs.top-this.lastPositionAbs.top;return 0!==e&&(e>0?"down":"up")},_getDragHorizontalDirection:function(){var e=this.positionAbs.left-this.lastPositionAbs.left;return 0!==e&&(e>0?"right":"left")},refresh:function(e){return this._refreshItems(e),this.refreshPositions(),this},_connectWith:function(){var e=this.options;return e.connectWith.constructor===String?[e.connectWith]:e.connectWith},_getItemsAsjQuery:function(t){var n,r,i,s,o=[],u=[],a=this._connectWith();if(a&&t)for(n=a.length-1;n>=0;n--)for(i=e(a[n]),r=i.length-1;r>=0;r--)s=e.data(i[r],this.widgetFullName),s&&s!==this&&!s.options.disabled&&u.push([e.isFunction(s.options.items)?s.options.items.call(s.element):e(s.options.items,s.element).not(".ui-sortable-helper").not(".ui-sortable-placeholder"),s]);for(u.push([e.isFunction(this.options.items)?this.options.items.call(this.element,null,{options:this.options,item:this.currentItem}):e(this.options.items,this.element).not(".ui-sortable-helper").not(".ui-sortable-placeholder"),this]),n=u.length-1;n>=0;n--)u[n][0].each(function(){o.push(this)});return e(o)},_removeCurrentsFromItems:function(){var t=this.currentItem.find(":data("+this.widgetName+"-item)");this.items=e.grep(this.items,function(e){for(var n=0;t.length>n;n++)if(t[n]===e.item[0])return!1;return!0})},_refreshItems:function(t){this.items=[],this.containers=[this];var n,r,i,s,o,u,a,f,l=this.items,c=[[e.isFunction(this.options.items)?this.options.items.call(this.element[0],t,{item:this.currentItem}):e(this.options.items,this.element),this]],h=this._connectWith();if(h&&this.ready)for(n=h.length-1;n>=0;n--)for(i=e(h[n]),r=i.length-1;r>=0;r--)s=e.data(i[r],this.widgetFullName),s&&s!==this&&!s.options.disabled&&(c.push([e.isFunction(s.options.items)?s.options.items.call(s.element[0],t,{item:this.currentItem}):e(s.options.items,s.element),s]),this.containers.push(s));for(n=c.length-1;n>=0;n--)for(o=c[n][1],u=c[n][0],r=0,f=u.length;f>r;r++)a=e(u[r]),a.data(this.widgetName+"-item",o),l.push({item:a,instance:o,width:0,height:0,left:0,top:0})},refreshPositions:function(t){this.offsetParent&&this.helper&&(this.offset.parent=this._getParentOffset());var n,r,i,s;for(n=this.items.length-1;n>=0;n--)r=this.items[n],r.instance!==this.currentContainer&&this.currentContainer&&r.item[0]!==this.currentItem[0]||(i=this.options.toleranceElement?e(this.options.toleranceElement,r.item):r.item,t||(r.width=i.outerWidth(),r.height=i.outerHeight()),s=i.offset(),r.left=s.left,r.top=s.top);if(this.options.custom&&this.options.custom.refreshContainers)this.options.custom.refreshContainers.call(this);else for(n=this.containers.length-1;n>=0;n--)s=this.containers[n].element.offset(),this.containers[n].containerCache.left=s.left,this.containers[n].containerCache.top=s.top,this.containers[n].containerCache.width=this.containers[n].element.outerWidth(),this.containers[n].containerCache.height=this.containers[n].element.outerHeight();return this},_createPlaceholder:function(t){t=t||this;var n,r=t.options;r.placeholder&&r.placeholder.constructor!==String||(n=r.placeholder,r.placeholder={element:function(){var r=t.currentItem[0].nodeName.toLowerCase(),s=e(t.document[0].createElement(r)).addClass(n||t.currentItem[0].className+" ui-sortable-placeholder").removeClass("ui-sortable-helper");return"tr"===r?s.append("<td colspan='99'> </td>"):"img"===r&&s.attr("src",t.currentItem.attr("src")),n||s.css("visibility","hidden"),s},update:function(e,o){(!n||r.forcePlaceholderSize)&&(o.height()||o.height(t.currentItem.innerHeight()-parseInt(t.currentItem.css("paddingTop")||0,10)-parseInt(t.currentItem.css("paddingBottom")||0,10)),o.width()||o.width(t.currentItem.innerWidth()-parseInt(t.currentItem.css("paddingLeft")||0,10)-parseInt(t.currentItem.css("paddingRight")||0,10)))}}),t.placeholder=e(r.placeholder.element.call(t.element,t.currentItem)),t.currentItem.after(t.placeholder),r.placeholder.update(t,t.placeholder)},_contactContainers:function(r){var s,o,u,a,f,l,c,h,p,d,v=null,m=null;for(s=this.containers.length-1;s>=0;s--)if(!e.contains(this.currentItem[0],this.containers[s].element[0]))if(this._intersectsWith(this.containers[s].containerCache)){if(v&&e.contains(this.containers[s].element[0],v.element[0]))continue;v=this.containers[s],m=s}else this.containers[s].containerCache.over&&(this.containers[s]._trigger("out",r,this._uiHash(this)),this.containers[s].containerCache.over=0);if(v)if(1===this.containers.length)this.containers[m].containerCache.over||(this.containers[m]._trigger("over",r,this._uiHash(this)),this.containers[m].containerCache.over=1);else{for(u=1e4,a=null,d=v.floating||n(this.currentItem),f=d?"left":"top",l=d?"width":"height",c=this.positionAbs[f]+this.offset.click[f],o=this.items.length-1;o>=0;o--)e.contains(this.containers[m].element[0],this.items[o].item[0])&&this.items[o].item[0]!==this.currentItem[0]&&(!d||t(this.positionAbs.top+this.offset.click.top,this.items[o].top,this.items[o].height))&&(h=this.items[o].item.offset()[f],p=!1,Math.abs(h-c)>Math.abs(h+this.items[o][l]-c)&&(p=!0,h+=this.items[o][l]),u>Math.abs(h-c)&&(u=Math.abs(h-c),a=this.items[o],this.direction=p?"up":"down"));if(!a&&!this.options.dropOnEmpty)return;if(this.currentContainer===this.containers[m])return;a?this._rearrange(r,a,null,!0):this._rearrange(r,null,this.containers[m].element,!0),this._trigger("change",r,this._uiHash()),this.containers[m]._trigger("change",r,this._uiHash(this)),this.currentContainer=this.containers[m],this.options.placeholder.update(this.currentContainer,this.placeholder),this.containers[m]._trigger("over",r,this._uiHash(this)),this.containers[m].containerCache.over=1}},_createHelper:function(t){var n=this.options,r=e.isFunction(n.helper)?e(n.helper.apply(this.element[0],[t,this.currentItem])):"clone"===n.helper?this.currentItem.clone():this.currentItem;return r.parents("body").length||e("parent"!==n.appendTo?n.appendTo:this.currentItem[0].parentNode)[0].appendChild(r[0]),r[0]===this.currentItem[0]&&(this._storedCSS={width:this.currentItem[0].style.width,height:this.currentItem[0].style.height,position:this.currentItem.css("position"),top:this.currentItem.css("top"),left:this.currentItem.css("left")}),(!r[0].style.width||n.forceHelperSize)&&r.width(this.currentItem.width()),(!r[0].style.height||n.forceHelperSize)&&r.height(this.currentItem.height()),r},_adjustOffsetFromHelper:function(t){"string"==typeof t&&(t=t.split(" ")),e.isArray(t)&&(t={left:+t[0],top:+t[1]||0}),"left"in t&&(this.offset.click.left=t.left+this.margins.left),"right"in t&&(this.offset.click.left=this.helperProportions.width-t.right+this.margins.left),"top"in t&&(this.offset.click.top=t.top+this.margins.top),"bottom"in t&&(this.offset.click.top=this.helperProportions.height-t.bottom+this.margins.top)},_getParentOffset:function(){this.offsetParent=this.helper.offsetParent();var t=this.offsetParent.offset();return"absolute"===this.cssPosition&&this.scrollParent[0]!==document&&e.contains(this.scrollParent[0],this.offsetParent[0])&&(t.left+=this.scrollParent.scrollLeft(),t.top+=this.scrollParent.scrollTop()),(this.offsetParent[0]===document.body||this.offsetParent[0].tagName&&"html"===this.offsetParent[0].tagName.toLowerCase()&&e.ui.ie)&&(t={top:0,left:0}),{top:t.top+(parseInt(this.offsetParent.css("borderTopWidth"),10)||0),left:t.left+(parseInt(this.offsetParent.css("borderLeftWidth"),10)||0)}},_getRelativeOffset:function(){if("relative"===this.cssPosition){var e=this.currentItem.position();return{top:e.top-(parseInt(this.helper.css("top"),10)||0)+this.scrollParent.scrollTop(),left:e.left-(parseInt(this.helper.css("left"),10)||0)+this.scrollParent.scrollLeft()}}return{top:0,left:0}},_cacheMargins:function(){this.margins={left:parseInt(this.currentItem.css("marginLeft"),10)||0,top:parseInt(this.currentItem.css("marginTop"),10)||0}},_cacheHelperProportions:function(){this.helperProportions={width:this.helper.outerWidth(),height:this.helper.outerHeight()}},_setContainment:function(){var t,n,r,i=this.options;"parent"===i.containment&&(i.containment=this.helper[0].parentNode),("document"===i.containment||"window"===i.containment)&&(this.containment=[0-this.offset.relative.left-this.offset.parent.left,0-this.offset.relative.top-this.offset.parent.top,e("document"===i.containment?document:window).width()-this.helperProportions.width-this.margins.left,(e("document"===i.containment?document:window).height()||document.body.parentNode.scrollHeight)-this.helperProportions.height-this.margins.top]),/^(document|window|parent)$/.test(i.containment)||(t=e(i.containment)[0],n=e(i.containment).offset(),r="hidden"!==e(t).css("overflow"),this.containment=[n.left+(parseInt(e(t).css("borderLeftWidth"),10)||0)+(parseInt(e(t).css("paddingLeft"),10)||0)-this.margins.left,n.top+(parseInt(e(t).css("borderTopWidth"),10)||0)+(parseInt(e(t).css("paddingTop"),10)||0)-this.margins.top,n.left+(r?Math.max(t.scrollWidth,t.offsetWidth):t.offsetWidth)-(parseInt(e(t).css("borderLeftWidth"),10)||0)-(parseInt(e(t).css("paddingRight"),10)||0)-this.helperProportions.width-this.margins.left,n.top+(r?Math.max(t.scrollHeight,t.offsetHeight):t.offsetHeight)-(parseInt(e(t).css("borderTopWidth"),10)||0)-(parseInt(e(t).css("paddingBottom"),10)||0)-this.helperProportions.height-this.margins.top])},_convertPositionTo:function(t,n){n||(n=this.position);var r="absolute"===t?1:-1,i="absolute"!==this.cssPosition||this.scrollParent[0]!==document&&e.contains(this.scrollParent[0],this.offsetParent[0])?this.scrollParent:this.offsetParent,s=/(html|body)/i.test(i[0].tagName);return{top:n.top+this.offset.relative.top*r+this.offset.parent.top*r-("fixed"===this.cssPosition?-this.scrollParent.scrollTop():s?0:i.scrollTop())*r,left:n.left+this.offset.relative.left*r+this.offset.parent.left*r-("fixed"===this.cssPosition?-this.scrollParent.scrollLeft():s?0:i.scrollLeft())*r}},_generatePosition:function(t){var n,r,i=this.options,s=t.pageX,o=t.pageY,u="absolute"!==this.cssPosition||this.scrollParent[0]!==document&&e.contains(this.scrollParent[0],this.offsetParent[0])?this.scrollParent:this.offsetParent,a=/(html|body)/i.test(u[0].tagName);return"relative"!==this.cssPosition||this.scrollParent[0]!==document&&this.scrollParent[0]!==this.offsetParent[0]||(this.offset.relative=this._getRelativeOffset()),this.originalPosition&&(this.containment&&(t.pageX-this.offset.click.left<this.containment[0]&&(s=this.containment[0]+this.offset.click.left),t.pageY-this.offset.click.top<this.containment[1]&&(o=this.containment[1]+this.offset.click.top),t.pageX-this.offset.click.left>this.containment[2]&&(s=this.containment[2]+this.offset.click.left),t.pageY-this.offset.click.top>this.containment[3]&&(o=this.containment[3]+this.offset.click.top)),i.grid&&(n=this.originalPageY+Math.round((o-this.originalPageY)/i.grid[1])*i.grid[1],o=this.containment?n-this.offset.click.top>=this.containment[1]&&n-this.offset.click.top<=this.containment[3]?n:n-this.offset.click.top>=this.containment[1]?n-i.grid[1]:n+i.grid[1]:n,r=this.originalPageX+Math.round((s-this.originalPageX)/i.grid[0])*i.grid[0],s=this.containment?r-this.offset.click.left>=this.containment[0]&&r-this.offset.click.left<=this.containment[2]?r:r-this.offset.click.left>=this.containment[0]?r-i.grid[0]:r+i.grid[0]:r)),{top:o-this.offset.click.top-this.offset.relative.top-this.offset.parent.top+("fixed"===this.cssPosition?-this.scrollParent.scrollTop():a?0:u.scrollTop()),left:s-this.offset.click.left-this.offset.relative.left-this.offset.parent.left+("fixed"===this.cssPosition?-this.scrollParent.scrollLeft():a?0:u.scrollLeft())}},_rearrange:function(e,t,n,r){n?n[0].appendChild(this.placeholder[0]):t.item[0].parentNode.insertBefore(this.placeholder[0],"down"===this.direction?t.item[0]:t.item[0].nextSibling),this.counter=this.counter?++this.counter:1;var i=this.counter;this._delay(function(){i===this.counter&&this.refreshPositions(!r)})},_clear:function(e,t){this.reverting=!1;var n,r=[];if(!this._noFinalSort&&this.currentItem.parent().length&&this.placeholder.before(this.currentItem),this._noFinalSort=null,this.helper[0]===this.currentItem[0]){for(n in this._storedCSS)("auto"===this._storedCSS[n]||"static"===this._storedCSS[n])&&(this._storedCSS[n]="");this.currentItem.css(this._storedCSS).removeClass("ui-sortable-helper")}else this.currentItem.show();for(this.fromOutside&&!t&&r.push(function(e){this._trigger("receive",e,this._uiHash(this.fromOutside))}),!this.fromOutside&&this.domPosition.prev===this.currentItem.prev().not(".ui-sortable-helper")[0]&&this.domPosition.parent===this.currentItem.parent()[0]||t||r.push(function(e){this._trigger("update",e,this._uiHash())}),this!==this.currentContainer&&(t||(r.push(function(e){this._trigger("remove",e,this._uiHash())}),r.push(function(e){return function(t){e._trigger("receive",t,this._uiHash(this))}}.call(this,this.currentContainer)),r.push(function(e){return function(t){e._trigger("update",t,this._uiHash(this))}}.call(this,this.currentContainer)))),n=this.containers.length-1;n>=0;n--)t||r.push(function(e){return function(t){e._trigger("deactivate",t,this._uiHash(this))}}.call(this,this.containers[n])),this.containers[n].containerCache.over&&(r.push(function(e){return function(t){e._trigger("out",t,this._uiHash(this))}}.call(this,this.containers[n])),this.containers[n].containerCache.over=0);if(this.storedCursor&&(this.document.find("body").css("cursor",this.storedCursor),this.storedStylesheet.remove()),this._storedOpacity&&this.helper.css("opacity",this._storedOpacity),this._storedZIndex&&this.helper.css("zIndex","auto"===this._storedZIndex?"":this._storedZIndex),this.dragging=!1,this.cancelHelperRemoval){if(!t){for(this._trigger("beforeStop",e,this._uiHash()),n=0;r.length>n;n++)r[n].call(this,e);this._trigger("stop",e,this._uiHash())}return this.fromOutside=!1,!1}if(t||this._trigger("beforeStop",e,this._uiHash()),this.placeholder[0].parentNode.removeChild(this.placeholder[0]),this.helper[0]!==this.currentItem[0]&&this.helper.remove(),this.helper=null,!t){for(n=0;r.length>n;n++)r[n].call(this,e);this._trigger("stop",e,this._uiHash())}return this.fromOutside=!1,!0},_trigger:function(){e.Widget.prototype._trigger.apply(this,arguments)===!1&&this.cancel()},_uiHash:function(t){var n=t||this;return{helper:n.helper,placeholder:n.placeholder||e([]),position:n.position,originalPosition:n.originalPosition,offset:n.positionAbs,item:n.currentItem,sender:t?t.element:null}}})}(jQuery),function(e,t){function n(){return++i}function r(e){return e.hash.length>1&&decodeURIComponent(e.href.replace(s,""))===decodeURIComponent(location.href.replace(s,""))}var i=0,s=/#.*$/;e.widget("ui.tabs",{version:"1.10.2",delay:300,options:{active:null,collapsible:!1,event:"click",heightStyle:"content",hide:null,show:null,activate:null,beforeActivate:null,beforeLoad:null,load:null},_create:function(){var t=this,n=this.options;this.running=!1,this.element.addClass("ui-tabs ui-widget ui-widget-content ui-corner-all").toggleClass("ui-tabs-collapsible",n.collapsible).delegate(".ui-tabs-nav > li","mousedown"+this.eventNamespace,function(t){e(this).is(".ui-state-disabled")&&t.preventDefault()}).delegate(".ui-tabs-anchor","focus"+this.eventNamespace,function(){e(this).closest("li").is(".ui-state-disabled")&&this.blur()}),this._processTabs(),n.active=this._initialActive(),e.isArray(n.disabled)&&(n.disabled=e.unique(n.disabled.concat(e.map(this.tabs.filter(".ui-state-disabled"),function(e){return t.tabs.index(e)}))).sort()),this.active=this.options.active!==!1&&this.anchors.length?this._findActive(n.active):e(),this._refresh(),this.active.length&&this.load(n.active)},_initialActive:function(){var n=this.options.active,r=this.options.collapsible,i=location.hash.substring(1);return null===n&&(i&&this.tabs.each(function(r,s){return e(s).attr("aria-controls")===i?(n=r,!1):t}),null===n&&(n=this.tabs.index(this.tabs.filter(".ui-tabs-active"))),(null===n||-1===n)&&(n=this.tabs.length?0:!1)),n!==!1&&(n=this.tabs.index(this.tabs.eq(n)),-1===n&&(n=r?!1:0)),!r&&n===!1&&this.anchors.length&&(n=0),n},_getCreateEventData:function(){return{tab:this.active,panel:this.active.length?this._getPanelForTab(this.active):e()}},_tabKeydown:function(n){var r=e(this.document[0].activeElement).closest("li"),i=this.tabs.index(r),s=!0;if(!this._handlePageNav(n)){switch(n.keyCode){case e.ui.keyCode.RIGHT:case e.ui.keyCode.DOWN:i++;break;case e.ui.keyCode.UP:case e.ui.keyCode.LEFT:s=!1,i--;break;case e.ui.keyCode.END:i=this.anchors.length-1;break;case e.ui.keyCode.HOME:i=0;break;case e.ui.keyCode.SPACE:return n.preventDefault(),clearTimeout(this.activating),this._activate(i),t;case e.ui.keyCode.ENTER:return n.preventDefault(),clearTimeout(this.activating),this._activate(i===this.options.active?!1:i),t;default:return}n.preventDefault(),clearTimeout(this.activating),i=this._focusNextTab(i,s),n.ctrlKey||(r.attr("aria-selected","false"),this.tabs.eq(i).attr("aria-selected","true"),this.activating=this._delay(function(){this.option("active",i)},this.delay))}},_panelKeydown:function(t){this._handlePageNav(t)||t.ctrlKey&&t.keyCode===e.ui.keyCode.UP&&(t.preventDefault(),this.active.focus())},_handlePageNav:function(n){return n.altKey&&n.keyCode===e.ui.keyCode.PAGE_UP?(this._activate(this._focusNextTab(this.options.active-1,!1)),!0):n.altKey&&n.keyCode===e.ui.keyCode.PAGE_DOWN?(this._activate(this._focusNextTab(this.options.active+1,!0)),!0):t},_findNextTab:function(t,n){function r(){return t>i&&(t=0),0>t&&(t=i),t}for(var i=this.tabs.length-1;-1!==e.inArray(r(),this.options.disabled);)t=n?t+1:t-1;return t},_focusNextTab:function(e,t){return e=this._findNextTab(e,t),this.tabs.eq(e).focus(),e},_setOption:function(e,n){return"active"===e?(this._activate(n),t):"disabled"===e?(this._setupDisabled(n),t):(this._super(e,n),"collapsible"===e&&(this.element.toggleClass("ui-tabs-collapsible",n),n||this.options.active!==!1||this._activate(0)),"event"===e&&this._setupEvents(n),"heightStyle"===e&&this._setupHeightStyle(n),t)},_tabId:function(e){return e.attr("aria-controls")||"ui-tabs-"+n()},_sanitizeSelector:function(e){return e?e.replace(/[!"$%&'()*+,.\/:;<=>?@\[\]\^`{|}~]/g,"\\$&"):""},refresh:function(){var t=this.options,n=this.tablist.children(":has(a[href])");t.disabled=e.map(n.filter(".ui-state-disabled"),function(e){return n.index(e)}),this._processTabs(),t.active!==!1&&this.anchors.length?this.active.length&&!e.contains(this.tablist[0],this.active[0])?this.tabs.length===t.disabled.length?(t.active=!1,this.active=e()):this._activate(this._findNextTab(Math.max(0,t.active-1),!1)):t.active=this.tabs.index(this.active):(t.active=!1,this.active=e()),this._refresh()},_refresh:function(){this._setupDisabled(this.options.disabled),this._setupEvents(this.options.event),this._setupHeightStyle(this.options.heightStyle),this.tabs.not(this.active).attr({"aria-selected":"false",tabIndex:-1}),this.panels.not(this._getPanelForTab(this.active)).hide().attr({"aria-expanded":"false","aria-hidden":"true"}),this.active.length?(this.active.addClass("ui-tabs-active ui-state-active").attr({"aria-selected":"true",tabIndex:0}),this._getPanelForTab(this.active).show().attr({"aria-expanded":"true","aria-hidden":"false"})):this.tabs.eq(0).attr("tabIndex",0)},_processTabs:function(){var t=this;this.tablist=this._getList().addClass("ui-tabs-nav ui-helper-reset ui-helper-clearfix ui-widget-header ui-corner-all").attr("role","tablist"),this.tabs=this.tablist.find("> li:has(a[href])").addClass("ui-state-default ui-corner-top").attr({role:"tab",tabIndex:-1}),this.anchors=this.tabs.map(function(){return e("a",this)[0]}).addClass("ui-tabs-anchor").attr({role:"presentation",tabIndex:-1}),this.panels=e(),this.anchors.each(function(n,i){var s,o,u,a=e(i).uniqueId().attr("id"),f=e(i).closest("li"),l=f.attr("aria-controls");r(i)?(s=i.hash,o=t.element.find(t._sanitizeSelector(s))):(u=t._tabId(f),s="#"+u,o=t.element.find(s),o.length||(o=t._createPanel(u),o.insertAfter(t.panels[n-1]||t.tablist)),o.attr("aria-live","polite")),o.length&&(t.panels=t.panels.add(o)),l&&f.data("ui-tabs-aria-controls",l),f.attr({"aria-controls":s.substring(1),"aria-labelledby":a}),o.attr("aria-labelledby",a)}),this.panels.addClass("ui-tabs-panel ui-widget-content ui-corner-bottom").attr("role","tabpanel")},_getList:function(){return this.element.find("ol,ul").eq(0)},_createPanel:function(t){return e("<div>").attr("id",t).addClass("ui-tabs-panel ui-widget-content ui-corner-bottom").data("ui-tabs-destroy",!0)},_setupDisabled:function(t){e.isArray(t)&&(t.length?t.length===this.anchors.length&&(t=!0):t=!1);for(var n,r=0;n=this.tabs[r];r++)t===!0||-1!==e.inArray(r,t)?e(n).addClass("ui-state-disabled").attr("aria-disabled","true"):e(n).removeClass("ui-state-disabled").removeAttr("aria-disabled");this.options.disabled=t},_setupEvents:function(t){var n={click:function(e){e.preventDefault()}};t&&e.each(t.split(" "),function(e,t){n[t]="_eventHandler"}),this._off(this.anchors.add(this.tabs).add(this.panels)),this._on(this.anchors,n),this._on(this.tabs,{keydown:"_tabKeydown"}),this._on(this.panels,{keydown:"_panelKeydown"}),this._focusable(this.tabs),this._hoverable(this.tabs)},_setupHeightStyle:function(t){var n,r=this.element.parent();"fill"===t?(n=r.height(),n-=this.element.outerHeight()-this.element.height(),this.element.siblings(":visible").each(function(){var t=e(this),r=t.css("position");"absolute"!==r&&"fixed"!==r&&(n-=t.outerHeight(!0))}),this.element.children().not(this.panels).each(function(){n-=e(this).outerHeight(!0)}),this.panels.each(function(){e(this).height(Math.max(0,n-e(this).innerHeight()+e(this).height()))}).css("overflow","auto")):"auto"===t&&(n=0,this.panels.each(function(){n=Math.max(n,e(this).height("").height())}).height(n))},_eventHandler:function(t){var n=this.options,r=this.active,i=e(t.currentTarget),s=i.closest("li"),o=s[0]===r[0],u=o&&n.collapsible,a=u?e():this._getPanelForTab(s),f=r.length?this._getPanelForTab(r):e(),l={oldTab:r,oldPanel:f,newTab:u?e():s,newPanel:a};t.preventDefault(),s.hasClass("ui-state-disabled")||s.hasClass("ui-tabs-loading")||this.running||o&&!n.collapsible||this._trigger("beforeActivate",t,l)===!1||(n.active=u?!1:this.tabs.index(s),this.active=o?e():s,this.xhr&&this.xhr.abort(),f.length||a.length||e.error("jQuery UI Tabs: Mismatching fragment identifier."),a.length&&this.load(this.tabs.index(s),t),this._toggle(t,l))},_toggle:function(t,n){function r(){s.running=!1,s._trigger("activate",t,n)}function i(){n.newTab.closest("li").addClass("ui-tabs-active ui-state-active"),o.length&&s.options.show?s._show(o,s.options.show,r):(o.show(),r())}var s=this,o=n.newPanel,u=n.oldPanel;this.running=!0,u.length&&this.options.hide?this._hide(u,this.options.hide,function(){n.oldTab.closest("li").removeClass("ui-tabs-active ui-state-active"),i()}):(n.oldTab.closest("li").removeClass("ui-tabs-active ui-state-active"),u.hide(),i()),u.attr({"aria-expanded":"false","aria-hidden":"true"}),n.oldTab.attr("aria-selected","false"),o.length&&u.length?n.oldTab.attr("tabIndex",-1):o.length&&this.tabs.filter(function(){return 0===e(this).attr("tabIndex")}).attr("tabIndex",-1),o.attr({"aria-expanded":"true","aria-hidden":"false"}),n.newTab.attr({"aria-selected":"true",tabIndex:0})},_activate:function(t){var n,r=this._findActive(t);r[0]!==this.active[0]&&(r.length||(r=this.active),n=r.find(".ui-tabs-anchor")[0],this._eventHandler({target:n,currentTarget:n,preventDefault:e.noop}))},_findActive:function(t){return t===!1?e():this.tabs.eq(t)},_getIndex:function(e){return"string"==typeof e&&(e=this.anchors.index(this.anchors.filter("[href$='"+e+"']"))),e},_destroy:function(){this.xhr&&this.xhr.abort(),this.element.removeClass("ui-tabs ui-widget ui-widget-content ui-corner-all ui-tabs-collapsible"),this.tablist.removeClass("ui-tabs-nav ui-helper-reset ui-helper-clearfix ui-widget-header ui-corner-all").removeAttr("role"),this.anchors.removeClass("ui-tabs-anchor").removeAttr("role").removeAttr("tabIndex").removeUniqueId(),this.tabs.add(this.panels).each(function(){e.data(this,"ui-tabs-destroy")?e(this).remove():e(this).removeClass("ui-state-default ui-state-active ui-state-disabled ui-corner-top ui-corner-bottom ui-widget-content ui-tabs-active ui-tabs-panel").removeAttr("tabIndex").removeAttr("aria-live").removeAttr("aria-busy").removeAttr("aria-selected").removeAttr("aria-labelledby").removeAttr("aria-hidden").removeAttr("aria-expanded").removeAttr("role")}),this.tabs.each(function(){var t=e(this),n=t.data("ui-tabs-aria-controls");n?t.attr("aria-controls",n).removeData("ui-tabs-aria-controls"):t.removeAttr("aria-controls")}),this.panels.show(),"content"!==this.options.heightStyle&&this.panels.css("height","")},enable:function(n){var r=this.options.disabled;r!==!1&&(n===t?r=!1:(n=this._getIndex(n),r=e.isArray(r)?e.map(r,function(e){return e!==n?e:null}):e.map(this.tabs,function(e,t){return t!==n?t:null})),this._setupDisabled(r))},disable:function(n){var r=this.options.disabled;if(r!==!0){if(n===t)r=!0;else{if(n=this._getIndex(n),-1!==e.inArray(n,r))return;r=e.isArray(r)?e.merge([n],r).sort():[n]}this._setupDisabled(r)}},load:function(t,n){t=this._getIndex(t);var i=this,s=this.tabs.eq(t),o=s.find(".ui-tabs-anchor"),u=this._getPanelForTab(s),a={tab:s,panel:u};r(o[0])||(this.xhr=e.ajax(this._ajaxSettings(o,n,a)),this.xhr&&"canceled"!==this.xhr.statusText&&(s.addClass("ui-tabs-loading"),u.attr("aria-busy","true"),this.xhr.success(function(e){setTimeout(function(){u.html(e),i._trigger("load",n,a)},1)}).complete(function(e,t){setTimeout(function(){"abort"===t&&i.panels.stop(!1,!0),s.removeClass("ui-tabs-loading"),u.removeAttr("aria-busy"),e===i.xhr&&delete i.xhr},1)})))},_ajaxSettings:function(t,n,r){var i=this;return{url:t.attr("href"),beforeSend:function(t,s){return i._trigger("beforeLoad",n,e.extend({jqXHR:t,ajaxSettings:s},r))}}},_getPanelForTab:function(t){var n=e(t).attr("aria-controls");return this.element.find(this._sanitizeSelector("#"+n))}})}(jQuery),function(e,t){var n=5;e.widget("ui.slider",e.ui.mouse,{version:"1.10.0",widgetEventPrefix:"slide",options:{animate:!1,distance:0,max:100,min:0,orientation:"horizontal",range:!1,step:1,value:0,values:null,change:null,slide:null,start:null,stop:null},_create:function(){var t,n,r=this.options,i=this.element.find(".ui-slider-handle").addClass("ui-state-default ui-corner-all"),s="<a class='ui-slider-handle ui-state-default ui-corner-all' href='#'></a>",o=[];this._keySliding=!1,this._mouseSliding=!1,this._animateOff=!0,this._handleIndex=null,this._detectOrientation(),this._mouseInit(),this.element.addClass("ui-slider ui-slider-"+this.orientation+" ui-widget"+" ui-widget-content"+" ui-corner-all"),this.range=e([]),r.range&&(r.range===!0&&(r.values?r.values.length&&r.values.length!==2?r.values=[r.values[0],r.values[0]]:e.isArray(r.values)&&(r.values=r.values.slice(0)):r.values=[this._valueMin(),this._valueMin()]),this.range=e("<div></div>").appendTo(this.element).addClass("ui-slider-range ui-widget-header"+(r.range==="min"||r.range==="max"?" ui-slider-range-"+r.range:""))),n=r.values&&r.values.length||1;for(t=i.length;t<n;t++)o.push(s);this.handles=i.add(e(o.join("")).appendTo(this.element)),this.handle=this.handles.eq(0),this.handles.add(this.range).filter("a").click(function(e){e.preventDefault()}).mouseenter(function(){r.disabled||e(this).addClass("ui-state-hover")}).mouseleave(function(){e(this).removeClass("ui-state-hover")}).focus(function(){r.disabled?e(this).blur():(e(".ui-slider .ui-state-focus").removeClass("ui-state-focus"),e(this).addClass("ui-state-focus"))}).blur(function(){e(this).removeClass("ui-state-focus")}),this.handles.each(function(t){e(this).data("ui-slider-handle-index",t)}),this._setOption("disabled",r.disabled),this._on(this.handles,this._handleEvents),this._refreshValue(),this._animateOff=!1},_destroy:function(){this.handles.remove(),this.range.remove(),this.element.removeClass("ui-slider ui-slider-horizontal ui-slider-vertical ui-widget ui-widget-content ui-corner-all"),this._mouseDestroy()},_mouseCapture:function(t){var n,r,i,s,o,u,a,f,l=this,c=this.options;return c.disabled?!1:(this.elementSize={width:this.element.outerWidth(),height:this.element.outerHeight()},this.elementOffset=this.element.offset(),n={x:t.pageX,y:t.pageY},r=this._normValueFromMouse(n),i=this._valueMax()-this._valueMin()+1,this.handles.each(function(t){var n=Math.abs(r-l.values(t));if(i>n||i===n&&(t===l._lastChangedValue||l.values(t)===c.min))i=n,s=e(this),o=t}),u=this._start(t,o),u===!1?!1:(this._mouseSliding=!0,this._handleIndex=o,s.addClass("ui-state-active").focus(),a=s.offset(),f=!e(t.target).parents().addBack().is(".ui-slider-handle"),this._clickOffset=f?{left:0,top:0}:{left:t.pageX-a.left-s.width()/2,top:t.pageY-a.top-s.height()/2-(parseInt(s.css("borderTopWidth"),10)||0)-(parseInt(s.css("borderBottomWidth"),10)||0)+(parseInt(s.css("marginTop"),10)||0)},this.handles.hasClass("ui-state-hover")||this._slide(t,o,r),this._animateOff=!0,!0))},_mouseStart:function(){return!0},_mouseDrag:function(e){var t={x:e.pageX,y:e.pageY},n=this._normValueFromMouse(t);return this._slide(e,this._handleIndex,n),!1},_mouseStop:function(e){return this.handles.removeClass("ui-state-active"),this._mouseSliding=!1,this._stop(e,this._handleIndex),this._change(e,this._handleIndex),this._handleIndex=null,this._clickOffset=null,this._animateOff=!1,!1},_detectOrientation:function(){this.orientation=this.options.orientation==="vertical"?"vertical":"horizontal"},_normValueFromMouse:function(e){var t,n,r,i,s;return this.orientation==="horizontal"?(t=this.elementSize.width,n=e.x-this.elementOffset.left-(this._clickOffset?this._clickOffset.left:0)):(t=this.elementSize.height,n=e.y-this.elementOffset.top-(this._clickOffset?this._clickOffset.top:0)),r=n/t,r>1&&(r=1),r<0&&(r=0),this.orientation==="vertical"&&(r=1-r),i=this._valueMax()-this._valueMin(),s=this._valueMin()+r*i,this._trimAlignValue(s)},_start:function(e,t){var n={handle:this.handles[t],value:this.value()};return this.options.values&&this.options.values.length&&(n.value=this.values(t),n.values=this.values()),this._trigger("start",e,n)},_slide:function(e,t,n){var r,i,s;this.options.values&&this.options.values.length?(r=this.values(t?0:1),this.options.values.length===2&&this.options.range===!0&&(t===0&&n>r||t===1&&n<r)&&(n=r),n!==this.values(t)&&(i=this.values(),i[t]=n,s=this._trigger("slide",e,{handle:this.handles[t],value:n,values:i}),r=this.values(t?0:1),s!==!1&&this.values(t,n,!0))):n!==this.value()&&(s=this._trigger("slide",e,{handle:this.handles[t],value:n}),s!==!1&&this.value(n))},_stop:function(e,t){var n={handle:this.handles[t],value:this.value()};this.options.values&&this.options.values.length&&(n.value=this.values(t),n.values=this.values()),this._trigger("stop",e,n)},_change:function(e,t){if(!this._keySliding&&!this._mouseSliding){var n={handle:this.handles[t],value:this.value()};this.options.values&&this.options.values.length&&(n.value=this.values(t),n.values=this.values()),this._lastChangedValue=t,this._trigger("change",e,n)}},value:function(e){if(arguments.length){this.options.value=this._trimAlignValue(e),this._refreshValue(),this._change(null,0);return}return this._value()},values:function(t,n){var r,i,s;if(arguments.length>1){this.options.values[t]=this._trimAlignValue(n),this._refreshValue(),this._change(null,t);return}if(!arguments.length)return this._values();if(!e.isArray(arguments[0]))return this.options.values&&this.options.values.length?this._values(t):this.value();r=this.options.values,i=arguments[0];for(s=0;s<r.length;s+=1)r[s]=this._trimAlignValue(i[s]),this._change(null,s);this._refreshValue()},_setOption:function(t,n){var r,i=0;e.isArray(this.options.values)&&(i=this.options.values.length),e.Widget.prototype._setOption.apply(this,arguments);switch(t){case"disabled":n?(this.handles.filter(".ui-state-focus").blur(),this.handles.removeClass("ui-state-hover"),this.handles.prop("disabled",!0)):this.handles.prop("disabled",!1);break;case"orientation":this._detectOrientation(),this.element.removeClass("ui-slider-horizontal ui-slider-vertical").addClass("ui-slider-"+this.orientation),this._refreshValue();break;case"value":this._animateOff=!0,this._refreshValue(),this._change(null,0),this._animateOff=!1;break;case"values":this._animateOff=!0,this._refreshValue();for(r=0;r<i;r+=1)this._change(null,r);this._animateOff=!1;break;case"min":case"max":this._animateOff=!0,this._refreshValue(),this._animateOff=!1}},_value:function(){var e=this.options.value;return e=this._trimAlignValue(e),e},_values:function(e){var t,n,r;if(arguments.length)return t=this.options.values[e],t=this._trimAlignValue(t),t;n=this.options.values.slice();for(r=0;r<n.length;r+=1)n[r]=this._trimAlignValue(n[r]);return n},_trimAlignValue:function(e){if(e<=this._valueMin())return this._valueMin();if(e>=this._valueMax())return this._valueMax();var t=this.options.step>0?this.options.step:1,n=(e-this._valueMin())%t,r=e-n;return Math.abs(n)*2>=t&&(r+=n>0?t:-t),parseFloat(r.toFixed(5))},_valueMin:function(){return this.options.min},_valueMax:function(){return this.options.max},_refreshValue:function(){var t,n,r,i,s,o=this.options.range,u=this.options,a=this,f=this._animateOff?!1:u.animate,l={};this.options.values&&this.options.values.length?this.handles.each(function(r){n=(a.values(r)-a._valueMin())/(a._valueMax()-a._valueMin())*100,l[a.orientation==="horizontal"?"left":"bottom"]=n+"%",e(this).stop(1,1)[f?"animate":"css"](l,u.animate),a.options.range===!0&&(a.orientation==="horizontal"?(r===0&&a.range.stop(1,1)[f?"animate":"css"]({left:n+"%"},u.animate),r===1&&a.range[f?"animate":"css"]({width:n-t+"%"},{queue:!1,duration:u.animate})):(r===0&&a.range.stop(1,1)[f?"animate":"css"]({bottom:n+"%"},u.animate),r===1&&a.range[f?"animate":"css"]({height:n-t+"%"},{queue:!1,duration:u.animate}))),t=n}):(r=this.value(),i=this._valueMin(),s=this._valueMax(),n=s!==i?(r-i)/(s-i)*100:0,l[this.orientation==="horizontal"?"left":"bottom"]=n+"%",this.handle.stop(1,1)[f?"animate":"css"](l,u.animate),o==="min"&&this.orientation==="horizontal"&&this.range.stop(1,1)[f?"animate":"css"]({width:n+"%"},u.animate),o==="max"&&this.orientation==="horizontal"&&this.range[f?"animate":"css"]({width:100-n+"%"},{queue:!1,duration:u.animate}),o==="min"&&this.orientation==="vertical"&&this.range.stop(1,1)[f?"animate":"css"]({height:n+"%"},u.animate),o==="max"&&this.orientation==="vertical"&&this.range[f?"animate":"css"]({height:100-n+"%"},{queue:!1,duration:u.animate}))},_handleEvents:{keydown:function(t){var r,i,s,o,u=e(t.target).data("ui-slider-handle-index");switch(t.keyCode){case e.ui.keyCode.HOME:case e.ui.keyCode.END:case e.ui.keyCode.PAGE_UP:case e.ui.keyCode.PAGE_DOWN:case e.ui.keyCode.UP:case e.ui.keyCode.RIGHT:case e.ui.keyCode.DOWN:case e.ui.keyCode.LEFT:t.preventDefault();if(!this._keySliding){this._keySliding=!0,e(t.target).addClass("ui-state-active"),r=this._start(t,u);if(r===!1)return}}o=this.options.step,this.options.values&&this.options.values.length?i=s=this.values(u):i=s=this.value();switch(t.keyCode){case e.ui.keyCode.HOME:s=this._valueMin();break;case e.ui.keyCode.END:s=this._valueMax();break;case e.ui.keyCode.PAGE_UP:s=this._trimAlignValue(i+(this._valueMax()-this._valueMin())/n);break;case e.ui.keyCode.PAGE_DOWN:s=this._trimAlignValue(i-(this._valueMax()-this._valueMin())/n);break;case e.ui.keyCode.UP:case e.ui.keyCode.RIGHT:if(i===this._valueMax())return;s=this._trimAlignValue(i+o);break;case e.ui.keyCode.DOWN:case e.ui.keyCode.LEFT:if(i===this._valueMin())return;s=this._trimAlignValue(i-o)}this._slide(t,u,s)},keyup:function(t){var n=e(t.target).data("ui-slider-handle-index");this._keySliding&&(this._keySliding=!1,this._stop(t,n),this._change(t,n),e(t.target).removeClass("ui-state-active"))}}})}(jQuery),define("jqueryUI",function(){}),define("modules/layout-selector",["jquery","ko","jqueryUI"],function(e,t){loadLayoutSelector=function(t){createCog(e("#layout-selector-pages")),createCog(e("#layout-selector-templates")),e.ajax(Headway.ajaxURL,{type:"POST",async:!0,data:{action:"headway_visual_editor",method:"get_layout_selector_pages",security:Headway.security,currentLayout:Headway.currentLayout,mode:Headway.mode},success:function(n,r){e("#layout-selector-pages").html(n),typeof t=="function"&&t.call()}}),e.ajax(Headway.ajaxURL,{type:"POST",async:!0,data:{action:"headway_visual_editor",method:"get_layout_selector_templates",security:Headway.security,currentLayout:Headway.currentLayout,mode:Headway.mode},success:function(t,n){e("#layout-selector-templates").html(t)}})},showLayoutSelector=function(){return e("div#layout-selector-select").addClass("layout-selector-visible"),e("div#layout-selector").css({left:e("div#layout-selector-select-content").offset().left}),e(document).bind("mousedown",hideLayoutSelector),Headway.iframe.contents().bind("mousedown",hideLayoutSelector),e("div#layout-selector-select")},hideLayoutSelector=function(t){if(t&&(e(t.target).is("#layout-selector-select")||e(t.target).parents("#layout-selector-select").length===1))return;return e("div#layout-selector-select").removeClass("layout-selector-visible"),e(document).unbind("mousedown",hideLayoutSelector),Headway.iframe.contents().unbind("mousedown",hideLayoutSelector),e("div#layout-selector-select")},toggleLayoutSelector=function(){e("div#layout-selector-select").hasClass("layout-selector-visible")?hideLayoutSelector(!1):showLayoutSelector()},switchToLayout=function(t,n,r){typeof t=="object"&&!t.hasClass("layout")&&(t=t.find("> span.layout"));if(t.length!==1)return!1;changeTitle("Visual Editor: Loading"),startTitleActivityIndicator();var i=t,s=i.attr("data-layout-id"),o=Headway.mode=="grid"?Headway.homeURL:i.attr("data-layout-url"),u=i.find("strong").text();e(".layout-selected","div#layout-selector").removeClass("layout-selected"),i.parent("li").addClass("layout-selected"),Headway.currentLayout=s,Headway.currentLayoutName=u,Headway.currentLayoutTemplate=!1,Headway.currentLayoutCustomized=!1,Headway.switchedToLayout=!0,Headway.currentLayoutCustomized=i.parents("li.layout-item").first().hasClass("layout-item-customized")||i.parents("#layout-selector-templates-container").length;var a=i.find(".status-template").data("template-id");typeof a!="undefined"&&a!="none"&&(Headway.currentLayoutTemplate=a,Headway.currentLayoutTemplateName=e('span.layout[data-layout-id="template-'+a+'"]').find(".template-name").text()),window.history.pushState("","",Headway.homeURL+"/?visual-editor=true&visual-editor-mode="+Headway.mode+"&ve-layout="+Headway.currentLayout);if(typeof n=="undefined"||n==1){if(typeof r=="undefined"||r==1)headwayIframeLoadNotification="Switched to <em>"+Headway.currentLayoutName+"</em>";loadIframe(Headway.instance.iframeCallback,o)}return!0};var n={init:function(){loadLayoutSelector(),n.bind()},bind:function(){var t=e("div#layout-selector");e("div#layout-selector-select-content").click(function(){return toggleLayoutSelector(),!1}),t.tabs(),t.delegate("span.edit","click",function(t){return typeof allowVECloseSwitch!="undefined"&&allowVECloseSwitch===!1&&!confirm("You have unsaved changes, are you sure you want to switch layouts?")?!1:(showIframeLoadingOverlay(),switchToLayout(e(this).parents("span.layout")),hideLayoutSelector(),t.preventDefault(),e(this).parents("span.layout"))}),t.delegate("span.revert","click",function(t){if(!confirm("Are you sure you wish to reset this layout? All blocks and content will be removed from this layout.\n\nPlease note: Any block that is mirroring a block on this layout will also lose its settings."))return!1;var n=e(this).parents("span.layout"),r=n.attr("data-layout-id"),i=n.find("strong").text();showIframeLoadingOverlay(),changeTitle("Visual Editor: Reverting "+i),startTitleActivityIndicator(),n.parent().removeClass("layout-item-customized");var s=e(n.parents(".layout-item-customized:not(.layout-selected)")[0]),o=s.find("> span.layout").attr("data-layout-id"),u=e(e("div#layout-selector-pages > ul > li.layout-item-customized")[0]),a=u.find("> span.layout").attr("data-layout-id"),f=o?s:u,l=o?o:a;if(typeof l=="undefined"||!l)l=Headway.frontPage=="posts"?"index":"front_page",f=e('div#layout-selector-pages > ul > li > span[data-layout-id="'+l+'"]').parent();return switchToLayout(f,!0,!1),e.post(Headway.ajaxURL,{security:Headway.security,action:"headway_visual_editor",method:"revert_layout",layout_to_revert:r},function(e){e==="success"?showNotification({id:"layout-reverted",message:"<em>"+i+"</em> successfully reverted!",success:!0}):showErrorNotification({id:"error-could-not-revert-layout",message:"Error: Could not revert layout."})}),!1}),t.delegate("span#add-template","click",function(t){var n=e("#template-name-input").val();return e.post(Headway.ajaxURL,{security:Headway.security,action:"headway_visual_editor",method:"add_template",layout:Headway.currentLayout,template_name:n},function(t){if(typeof t=="undefined"||!t)return showErrorNotification({id:"error-could-not-add-template",message:"Error: Could not add shared template."}),!1;var n=e('<li class="layout-item"> <span data-layout-id="template-'+t.id+'" class="layout layout-template"> <strong class="template-name">'+t.name+'</strong> <span class="delete-template" title="Delete Shared Layout">Delete</span> <span class="status status-currently-editing">Currently Editing</span> <span class="rename-template button layout-selector-button" title="Rename Shared Layout">Rename</span> <span class="assign-template button layout-selector-button">Use Layout</span> <span class="edit button layout-selector-button">Edit</span> </span> </li>');n.appendTo("div#layout-selector-templates ul"),e("li#no-templates:visible","div#layout-selector").hide(),showNotification({id:"template-added",message:"Shared layout added!",success:!0}),e("#template-name-input").val("")},"json"),!1}),t.delegate("span.delete-template","click",function(t){var n=e(e(this).parents("li")[0]),r=e(this).parent(),i=r.attr("data-layout-id"),s=i.replace("template-",""),o=r.find("strong").text();return confirm("Are you sure you wish to delete this template?")?(e.post(Headway.ajaxURL,{security:Headway.security,action:"headway_visual_editor",method:"delete_template",template_to_delete:s},function(t){if(typeof t=="undefined"||t=="failure"||t!="success")return showErrorNotification({id:"error-could-not-deleted-template",message:"Error: Could not delete shared layout."}),!1;n.remove(),e("span.layout-template","div#layout-selector").length===0&&e("li#no-templates","div#layout-selector").show(),showNotification({id:"template-deleted",message:"Shared Layout: <em>"+o+"</em> successfully deleted!",success:!0});if(i===Headway.currentLayout){var r=Headway.frontPage=="posts"?"index":"front_page";switchToLayout(e('div#layout-selector span.layout[data-layout-id="'+r+'"]'),!0,!1)}}),!1):!1}),t.delegate("span.assign-template","click",function(t){var n=e(e(this).parents("li")[0]),r=e(this).parent().attr("data-layout-id").replace("template-","");return Headway.currentLayout.indexOf("template-")===0?(alert("You cannot assign a shared layout to another shared layout."),!1):(e.post(Headway.ajaxURL,{security:Headway.security,action:"headway_visual_editor",method:"assign_template",template:r,layout:Headway.currentLayout},function(t){if(typeof t=="undefined"||t=="failure")return showErrorNotification({id:"error-could-not-assign-template",message:"Error: Could not assign shared layout."}),!1;e("li.layout-selected","div#layout-selector").removeClass("layout-item-customized"),e("li.layout-selected","div#layout-selector").addClass("layout-item-template-used"),e("li.layout-selected > span.status-template","div#layout-selector").text(t),showIframeLoadingOverlay(),changeTitle("Visual Editor: Assigning Shared Layout"),startTitleActivityIndicator(),Headway.currentLayoutTemplate="template-"+r,Headway.currentLayoutTemplateName=e('span.layout[data-layout-id="template-'+r+'"]').find(".template-name").text(),headwayIframeLoadNotification="Shared layout assigned successfully!",loadIframe(Headway.instance.iframeCallback)}),!1)}),t.delegate("span.rename-template","click",function(t){var n=e(e(this).parents("li")[0]),r=e(this).parent().attr("data-layout-id"),i=e(this).siblings(".template-name"),s=i.text(),o=prompt("Please enter new Shared Layout name",s);return e.post(Headway.ajaxURL,{security:Headway.security,action:"headway_visual_editor",method:"rename_layout_template",layout:r,newName:o},function(e){return typeof e=="undefined"||e=="failure"?(showErrorNotification({id:"error-could-not-rename-layout-template",message:"Error: Could not rename shared layout."}),!1):(i.text(o),!0)}),!1}),t.delegate("span.remove-template","click",function(t){var n=e(e(this).parents("li")[0]),r=e(this).parent().attr("data-layout-id");return confirm("Are you sure you want to remove the shared layout from "+n.find("> span.layout strong").text()+"?")?(e.post(Headway.ajaxURL,{security:Headway.security,action:"headway_visual_editor",method:"remove_template_from_layout",layout:r},function(e){return typeof e=="undefined"||e=="failure"?(showErrorNotification({id:"error-could-not-remove-template-from-layout",message:"Error: Could not remove shared layout from layout."}),!1):(n.removeClass("layout-item-template-used"),e==="customized"&&n.addClass("layout-item-customized"),r==Headway.currentLayout?(showIframeLoadingOverlay(),changeTitle("Visual Editor: Removing Shared Layout From Layout"),startTitleActivityIndicator(),Headway.currentLayoutTemplate=!1,headwayIframeLoadNotification="Shared Layout removed from layout successfully!",loadIframe(Headway.instance.iframeCallback),!0):!0)}),!1):!1}),t.delegate("span","click",function(t){e(this).hasClass("layout-open")?(e(this).removeClass("layout-open"),e(this).siblings("ul").hide()):(e(this).addClass("layout-open"),e(this).siblings("ul").show())})}};return n}),jQuery.cookie=function(e,t,n){if(arguments.length>1&&String(t)!=="[object Object]"){n=jQuery.extend({},n);if(t===null||t===undefined)n.expires=-1;if(typeof n.expires=="number"){var r=n.expires,i=n.expires=new Date;i.setDate(i.getDate()+r)}return t=String(t),document.cookie=[encodeURIComponent(e),"=",n.raw?t:encodeURIComponent(t),n.expires?"; expires="+n.expires.toUTCString():"",n.path?"; path="+n.path:"",n.domain?"; domain="+n.domain:"",n.secure?"; secure":""].join("")}n=t||{};var s,o=n.raw?function(e){return e}:decodeURIComponent;return(s=(new RegExp("(?:^|; )"+encodeURIComponent(e)+"=([^;]*)")).exec(document.cookie))?o(s[1]):null},define("deps/jquery.cookie",function(){}),!function(e,t,n){!function(e){"function"==typeof define&&define.amd?define("qtip",["jquery"],e):jQuery&&!jQuery.fn.qtip&&e(jQuery)}(function(r){function i(e,t,n,i){this.id=n,this.target=e,this.tooltip=D,this.elements={target:e},this._id=V+"-"+n,this.timers={img:{}},this.options=t,this.plugins={},this.cache={event:{},target:r(),disabled:_,attr:i,onTooltip:_,lastClass:""},this.rendered=this.destroyed=this.disabled=this.waiting=this.hiddenDuringWait=this.positioning=this.triggering=_}function s(e){return e===D||"object"!==r.type(e)}function o(e){return!(r.isFunction(e)||e&&e.attr||e.length||"object"===r.type(e)&&(e.jquery||e.then))}function u(e){var t,n,i,u;return s(e)?_:(s(e.metadata)&&(e.metadata={type:e.metadata}),"content"in e&&(t=e.content,s(t)||t.jquery||t.done?t=e.content={text:n=o(t)?_:t}:n=t.text,"ajax"in t&&(i=t.ajax,u=i&&i.once!==_,delete t.ajax,t.text=function(e,t){var s=n||r(this).attr(t.options.content.attr)||"Loading...",o=r.ajax(r.extend({},i,{context:t})).then(i.success,D,i.error).then(function(e){return e&&u&&t.set("content.text",e),e},function(e,n,r){t.destroyed||0===e.status||t.set("content.text",n+": "+r)});return u?s:(t.set("content.text",s),o)}),"title"in t&&(s(t.title)||(t.button=t.title.button,t.title=t.title.text),o(t.title||_)&&(t.title=_))),"position"in e&&s(e.position)&&(e.position={my:e.position,at:e.position}),"show"in e&&s(e.show)&&(e.show=e.show.jquery?{target:e.show}:e.show===M?{ready:M}:{event:e.show}),"hide"in e&&s(e.hide)&&(e.hide=e.hide.jquery?{target:e.hide}:{event:e.hide}),"style"in e&&s(e.style)&&(e.style={classes:e.style}),r.each(X,function(){this.sanitize&&this.sanitize(e)}),e)}function f(e,t){for(var n,r=0,i=e,s=t.split(".");i=i[s[r++]];)r<s.length&&(n=i);return[n||e,s.pop()]}function l(e,t){var n,r,i;for(n in this.checks)for(r in this.checks[n])(i=(new RegExp(r,"i")).exec(e))&&(t.push(i),("builtin"===n||this.plugins[n])&&this.checks[n][r].apply(this.plugins[n]||this,t))}function h(e){return K.concat("").join(e?"-"+e+" ":" ")}function p(n){return n&&{type:n.type,pageX:n.pageX,pageY:n.pageY,target:n.target,relatedTarget:n.relatedTarget,scrollX:n.scrollX||e.pageXOffset||t.body.scrollLeft||t.documentElement.scrollLeft,scrollY:n.scrollY||e.pageYOffset||t.body.scrollTop||t.documentElement.scrollTop}||{}}function d(e,t){return t>0?setTimeout(r.proxy(e,this),t):(e.call(this),void 0)}function v(e){return this.tooltip.hasClass(nt)?_:(clearTimeout(this.timers.show),clearTimeout(this.timers.hide),this.timers.show=d.call(this,function(){this.toggle(M,e)},this.options.show.delay),void 0)}function m(e){if(this.tooltip.hasClass(nt))return _;var t=r(e.relatedTarget),n=t.closest(Q)[0]===this.tooltip[0],i=t[0]===this.options.show.target[0];if(clearTimeout(this.timers.show),clearTimeout(this.timers.hide),this!==t[0]&&"mouse"===this.options.position.target&&n||this.options.hide.fixed&&/mouse(out|leave|move)/.test(e.type)&&(n||i))try{e.preventDefault(),e.stopImmediatePropagation()}catch(s){}else this.timers.hide=d.call(this,function(){this.toggle(_,e)},this.options.hide.delay,this)}function g(e){return this.tooltip.hasClass(nt)||!this.options.hide.inactive?_:(clearTimeout(this.timers.inactive),this.timers.inactive=d.call(this,function(){this.hide(e)},this.options.hide.inactive),void 0)}function y(e){this.rendered&&this.tooltip[0].offsetWidth>0&&this.reposition(e)}function w(e,n,i){r(t.body).delegate(e,(n.split?n:n.join(ft+" "))+ft,function(){var e=C.api[r.attr(this,J)];e&&!e.disabled&&i.apply(e,arguments)})}function E(e,n,s){var o,a,f,l,c,h=r(t.body),p=e[0]===t?h:e,d=e.metadata?e.metadata(s.metadata):D,v="html5"===s.metadata.type&&d?d[s.metadata.name]:D,m=e.data(s.metadata.name||"qtipopts");try{m="string"==typeof m?r.parseJSON(m):m}catch(g){}if(l=r.extend(M,{},C.defaults,s,"object"==typeof m?u(m):D,u(v||d)),a=l.position,l.id=n,"boolean"==typeof l.content.text){if(f=e.attr(l.content.attr),l.content.attr===_||!f)return _;l.content.text=f}if(a.container.length||(a.container=h),a.target===_&&(a.target=p),l.show.target===_&&(l.show.target=p),l.show.solo===M&&(l.show.solo=a.container.closest("body")),l.hide.target===_&&(l.hide.target=p),l.position.viewport===M&&(l.position.viewport=a.container),a.container=a.container.eq(0),a.at=new L(a.at,M),a.my=new L(a.my),e.data(V))if(l.overwrite)e.qtip("destroy",!0);else if(l.overwrite===_)return _;return e.attr($,n),l.suppress&&(c=e.attr("title"))&&e.removeAttr("title").attr(it,c).attr("title",""),o=new i(e,l,n,!!f),e.data(V,o),e.one("remove.qtip-"+n+" removeqtip.qtip-"+n,function(){var e;(e=r(this).data(V))&&e.destroy(!0)}),o}function S(e){return e.charAt(0).toUpperCase()+e.slice(1)}function x(e,t){var r,i,s=t.charAt(0).toUpperCase()+t.slice(1),o=(t+" "+wt.join(s+" ")+s).split(" "),u=0;if(bt[t])return e.css(bt[t]);for(;r=o[u++];)if((i=e.css(r))!==n)return bt[t]=r,i}function T(e,t){return Math.ceil(parseFloat(x(e,t)))}function N(e,t){this._ns="tip",this.options=t,this.offset=t.offset,this.size=[t.width,t.height],this.init(this.qtip=e)}var C,k,L,A,O,M=!0,_=!1,D=null,P="x",H="y",B="width",j="height",F="top",I="left",q="bottom",R="right",U="center",z="flipinvert",W="shift",X={},V="qtip",$="data-hasqtip",J="data-qtip-id",K=["ui-widget","ui-tooltip"],Q="."+V,G="click dblclick mousedown mouseup mousemove mouseleave mouseenter".split(" "),Y=V+"-fixed",Z=V+"-default",et=V+"-focus",tt=V+"-hover",nt=V+"-disabled",rt="_replacedByqTip",it="oldtitle",st={ie:function(){for(var e=3,n=t.createElement("div");(n.innerHTML="<!--[if gt IE "+ ++e+"]><i></i><![endif]-->")&&n.getElementsByTagName("i")[0];);return e>4?e:0/0}(),iOS:parseFloat((""+(/CPU.*OS ([0-9_]{1,5})|(CPU like).*AppleWebKit.*Mobile/i.exec(navigator.userAgent)||[0,""])[1]).replace("undefined","3_2").replace("_",".").replace("_",""))||_};k=i.prototype,k._when=function(e){return r.when.apply(r,e)},k.render=function(e){if(this.rendered||this.destroyed)return this;var t,n=this,i=this.options,s=this.cache,o=this.elements,u=i.content.text,a=i.content.title,f=i.content.button,l=i.position,c=("."+this._id+" ",[]);return r.attr(this.target[0],"aria-describedby",this._id),this.tooltip=o.tooltip=t=r("<div/>",{id:this._id,"class":[V,Z,i.style.classes,V+"-pos-"+i.position.my.abbrev()].join(" "),width:i.style.width||"",height:i.style.height||"",tracking:"mouse"===l.target&&l.adjust.mouse,role:"alert","aria-live":"polite","aria-atomic":_,"aria-describedby":this._id+"-content","aria-hidden":M}).toggleClass(nt,this.disabled).attr(J,this.id).data(V,this).appendTo(l.container).append(o.content=r("<div />",{"class":V+"-content",id:this._id+"-content","aria-atomic":M})),this.rendered=-1,this.positioning=M,a&&(this._createTitle(),r.isFunction(a)||c.push(this._updateTitle(a,_))),f&&this._createButton(),r.isFunction(u)||c.push(this._updateContent(u,_)),this.rendered=M,this._setWidget(),r.each(X,function(e){var t;"render"===this.initialize&&(t=this(n))&&(n.plugins[e]=t)}),this._unassignEvents(),this._assignEvents(),this._when(c).then(function(){n._trigger("render"),n.positioning=_,n.hiddenDuringWait||!i.show.ready&&!e||n.toggle(M,s.event,_),n.hiddenDuringWait=_}),C.api[this.id]=this,this},k.destroy=function(e){function t(){if(!this.destroyed){this.destroyed=M;var e=this.target,t=e.attr(it);this.rendered&&this.tooltip.stop(1,0).find("*").remove().end().remove(),r.each(this.plugins,function(){this.destroy&&this.destroy()}),clearTimeout(this.timers.show),clearTimeout(this.timers.hide),this._unassignEvents(),e.removeData(V).removeAttr(J).removeAttr($).removeAttr("aria-describedby"),this.options.suppress&&t&&e.attr("title",t).removeAttr(it),this._unbind(e),this.options=this.elements=this.cache=this.timers=this.plugins=this.mouse=D,delete C.api[this.id]}}return this.destroyed?this.target:(e===M&&"hide"!==this.triggering||!this.rendered?t.call(this):(this.tooltip.one("tooltiphidden",r.proxy(t,this)),!this.triggering&&this.hide()),this.target)},A=k.checks={builtin:{"^id$":function(e,t,n,i){var s=n===M?C.nextid:n,o=V+"-"+s;s!==_&&s.length>0&&!r("#"+o).length?(this._id=o,this.rendered&&(this.tooltip[0].id=this._id,this.elements.content[0].id=this._id+"-content",this.elements.title[0].id=this._id+"-title")):e[t]=i},"^prerender":function(e,t,n){n&&!this.rendered&&this.render(this.options.show.ready)},"^content.text$":function(e,t,n){this._updateContent(n)},"^content.attr$":function(e,t,n,r){this.options.content.text===this.target.attr(r)&&this._updateContent(this.target.attr(n))},"^content.title$":function(e,t,n){return n?(n&&!this.elements.title&&this._createTitle(),this._updateTitle(n),void 0):this._removeTitle()},"^content.button$":function(e,t,n){this._updateButton(n)},"^content.title.(text|button)$":function(e,t,n){this.set("content."+t,n)},"^position.(my|at)$":function(e,t,n){"string"==typeof n&&(e[t]=new L(n,"at"===t))},"^position.container$":function(e,t,n){this.rendered&&this.tooltip.appendTo(n)},"^show.ready$":function(e,t,n){n&&(!this.rendered&&this.render(M)||this.toggle(M))},"^style.classes$":function(e,t,n,r){this.rendered&&this.tooltip.removeClass(r).addClass(n)},"^style.(width|height)":function(e,t,n){this.rendered&&this.tooltip.css(t,n)},"^style.widget|content.title":function(){this.rendered&&this._setWidget()},"^style.def":function(e,t,n){this.rendered&&this.tooltip.toggleClass(Z,!!n)},"^events.(render|show|move|hide|focus|blur)$":function(e,t,n){this.rendered&&this.tooltip[(r.isFunction(n)?"":"un")+"bind"]("tooltip"+t,n)},"^(show|hide|position).(event|target|fixed|inactive|leave|distance|viewport|adjust)":function(){if(this.rendered){var e=this.options.position;this.tooltip.attr("tracking","mouse"===e.target&&e.adjust.mouse),this._unassignEvents(),this._assignEvents()}}}},k.get=function(e){if(this.destroyed)return this;var t=f(this.options,e.toLowerCase()),n=t[0][t[1]];return n.precedance?n.string():n};var ot=/^position\.(my|at|adjust|target|container|viewport)|style|content|show\.ready/i,ut=/^prerender|show\.ready/i;k.set=function(e,t){if(this.destroyed)return this;var n,i=this.rendered,s=_,o=this.options;return this.checks,"string"==typeof e?(n=e,e={},e[n]=t):e=r.extend({},e),r.each(e,function(t,n){if(i&&ut.test(t))return delete e[t],void 0;var u,l=f(o,t.toLowerCase());u=l[0][l[1]],l[0][l[1]]=n&&n.nodeType?r(n):n,s=ot.test(t)||s,e[t]=[l[0],l[1],n,u]}),u(o),this.positioning=M,r.each(e,r.proxy(l,this)),this.positioning=_,this.rendered&&this.tooltip[0].offsetWidth>0&&s&&this.reposition("mouse"===o.position.target?D:this.cache.event),this},k._update=function(e,t){var n=this,i=this.cache;return this.rendered&&e?(r.isFunction(e)&&(e=e.call(this.elements.target,i.event,this)||""),r.isFunction(e.then)?(i.waiting=M,e.then(function(e){return i.waiting=_,n._update(e,t)},D,function(e){return n._update(e,t)})):e===_||!e&&""!==e?_:(e.jquery&&e.length>0?t.empty().append(e.css({display:"block",visibility:"visible"})):t.html(e),this._waitForContent(t).then(function(e){e.images&&e.images.length&&n.rendered&&n.tooltip[0].offsetWidth>0&&n.reposition(i.event,!e.length)}))):_},k._waitForContent=function(e){var t=this.cache;return t.waiting=M,(r.fn.imagesLoaded?e.imagesLoaded():r.Deferred().resolve([])).done(function(){t.waiting=_}).promise()},k._updateContent=function(e,t){this._update(e,this.elements.content,t)},k._updateTitle=function(e,t){this._update(e,this.elements.title,t)===_&&this._removeTitle(_)},k._createTitle=function(){var e=this.elements,t=this._id+"-title";e.titlebar&&this._removeTitle(),e.titlebar=r("<div />",{"class":V+"-titlebar "+(this.options.style.widget?h("header"):"")}).append(e.title=r("<div />",{id:t,"class":V+"-title","aria-atomic":M})).insertBefore(e.content).delegate(".qtip-close","mousedown keydown mouseup keyup mouseout",function(e){r(this).toggleClass("ui-state-active ui-state-focus","down"===e.type.substr(-4))}).delegate(".qtip-close","mouseover mouseout",function(e){r(this).toggleClass("ui-state-hover","mouseover"===e.type)}),this.options.content.button&&this._createButton()},k._removeTitle=function(e){var t=this.elements;t.title&&(t.titlebar.remove(),t.titlebar=t.title=t.button=D,e!==_&&this.reposition())},k.reposition=function(n,i){if(!this.rendered||this.positioning||this.destroyed)return this;this.positioning=M;var s,o,u=this.cache,f=this.tooltip,l=this.options.position,c=l.target,h=l.my,p=l.at,d=l.viewport,v=l.container,m=l.adjust,g=m.method.split(" "),y=f.outerWidth(_),w=f.outerHeight(_),E=0,S=0,x=f.css("position"),T={left:0,top:0},N=f[0].offsetWidth>0,C=n&&"scroll"===n.type,k=r(e),L=v[0].ownerDocument,A=this.mouse;if(r.isArray(c)&&2===c.length)p={x:I,y:F},T={left:c[0],top:c[1]};else if("mouse"===c)p={x:I,y:F},!A||!A.pageX||!m.mouse&&n&&n.pageX?n&&n.pageX||((!m.mouse||this.options.show.distance)&&u.origin&&u.origin.pageX?n=u.origin:(!n||n&&("resize"===n.type||"scroll"===n.type))&&(n=u.event)):n=A,"static"!==x&&(T=v.offset()),L.body.offsetWidth!==(e.innerWidth||L.documentElement.clientWidth)&&(o=r(t.body).offset()),T={left:n.pageX-T.left+(o&&o.left||0),top:n.pageY-T.top+(o&&o.top||0)},m.mouse&&C&&A&&(T.left-=(A.scrollX||0)-k.scrollLeft(),T.top-=(A.scrollY||0)-k.scrollTop());else{if("event"===c?n&&n.target&&"scroll"!==n.type&&"resize"!==n.type?u.target=r(n.target):n.target||(u.target=this.elements.target):"event"!==c&&(u.target=r(c.jquery?c:this.elements.target)),c=u.target,c=r(c).eq(0),0===c.length)return this;c[0]===t||c[0]===e?(E=st.iOS?e.innerWidth:c.width(),S=st.iOS?e.innerHeight:c.height(),c[0]===e&&(T={top:(d||c).scrollTop(),left:(d||c).scrollLeft()})):X.imagemap&&c.is("area")?s=X.imagemap(this,c,p,X.viewport?g:_):X.svg&&c&&c[0].ownerSVGElement?s=X.svg(this,c,p,X.viewport?g:_):(E=c.outerWidth(_),S=c.outerHeight(_),T=c.offset()),s&&(E=s.width,S=s.height,o=s.offset,T=s.position),T=this.reposition.offset(c,T,v),(st.iOS>3.1&&st.iOS<4.1||st.iOS>=4.3&&st.iOS<4.33||!st.iOS&&"fixed"===x)&&(T.left-=k.scrollLeft(),T.top-=k.scrollTop()),(!s||s&&s.adjustable!==_)&&(T.left+=p.x===R?E:p.x===U?E/2:0,T.top+=p.y===q?S:p.y===U?S/2:0)}return T.left+=m.x+(h.x===R?-y:h.x===U?-y/2:0),T.top+=m.y+(h.y===q?-w:h.y===U?-w/2:0),X.viewport?(T.adjusted=X.viewport(this,T,l,E,S,y,w),o&&T.adjusted.left&&(T.left+=o.left),o&&T.adjusted.top&&(T.top+=o.top)):T.adjusted={left:0,top:0},this._trigger("move",[T,d.elem||d],n)?(delete T.adjusted,i===_||!N||isNaN(T.left)||isNaN(T.top)||"mouse"===c||!r.isFunction(l.effect)?f.css(T):r.isFunction(l.effect)&&(l.effect.call(f,this,r.extend({},T)),f.queue(function(e){r(this).css({opacity:"",height:""}),st.ie&&this.style.removeAttribute("filter"),e()})),this.positioning=_,this):this},k.reposition.offset=function(e,n,i){function s(e,t){n.left+=t*e.scrollLeft(),n.top+=t*e.scrollTop()}if(!i[0])return n;var o,u,a,f,l=r(e[0].ownerDocument),c=!!st.ie&&"CSS1Compat"!==t.compatMode,h=i[0];do"static"!==(u=r.css(h,"position"))&&("fixed"===u?(a=h.getBoundingClientRect(),s(l,-1)):(a=r(h).position(),a.left+=parseFloat(r.css(h,"borderLeftWidth"))||0,a.top+=parseFloat(r.css(h,"borderTopWidth"))||0),n.left-=a.left+(parseFloat(r.css(h,"marginLeft"))||0),n.top-=a.top+(parseFloat(r.css(h,"marginTop"))||0),o||"hidden"===(f=r.css(h,"overflow"))||"visible"===f||(o=r(h)));while(h=h.offsetParent);return o&&(o[0]!==l[0]||c)&&s(o,1),n};var at=(L=k.reposition.Corner=function(e,t){e=(""+e).replace(/([A-Z])/," $1").replace(/middle/gi,U).toLowerCase(),this.x=(e.match(/left|right/i)||e.match(/center/)||["inherit"])[0].toLowerCase(),this.y=(e.match(/top|bottom|center/i)||["inherit"])[0].toLowerCase(),this.forceY=!!t;var n=e.charAt(0);this.precedance="t"===n||"b"===n?H:P}).prototype;at.invert=function(e,t){this[e]=this[e]===I?R:this[e]===R?I:t||this[e]},at.string=function(){var e=this.x,t=this.y;return e===t?e:this.precedance===H||this.forceY&&"center"!==t?t+" "+e:e+" "+t},at.abbrev=function(){var e=this.string().split(" ");return e[0].charAt(0)+(e[1]&&e[1].charAt(0)||"")},at.clone=function(){return new L(this.string(),this.forceY)},k.toggle=function(e,n){var i=this.cache,s=this.options,o=this.tooltip;if(n){if(/over|enter/.test(n.type)&&/out|leave/.test(i.event.type)&&s.show.target.add(n.target).length===s.show.target.length&&o.has(n.relatedTarget).length)return this;i.event=p(n)}if(this.waiting&&!e&&(this.hiddenDuringWait=M),!this.rendered)return e?this.render(1):this;if(this.destroyed||this.disabled)return this;var u,a,f,l=e?"show":"hide",c=this.options[l],h=(this.options[e?"hide":"show"],this.options.position),d=this.options.content,v=this.tooltip.css("width"),m=this.tooltip.is(":visible"),g=e||1===c.target.length,y=!n||c.target.length<2||i.target[0]===n.target;return(typeof e).search("boolean|number")&&(e=!m),u=!o.is(":animated")&&m===e&&y,a=u?D:!!this._trigger(l,[90]),this.destroyed?this:(a!==_&&e&&this.focus(n),!a||u?this:(r.attr(o[0],"aria-hidden",!e),e?(i.origin=p(this.mouse),r.isFunction(d.text)&&this._updateContent(d.text,_),r.isFunction(d.title)&&this._updateTitle(d.title,_),!O&&"mouse"===h.target&&h.adjust.mouse&&(r(t).bind("mousemove."+V,this._storeMouse),O=M),v||o.css("width",o.outerWidth(_)),this.reposition(n,arguments[2]),v||o.css("width",""),c.solo&&("string"==typeof c.solo?r(c.solo):r(Q,c.solo)).not(o).not(c.target).qtip("hide",r.Event("tooltipsolo"))):(clearTimeout(this.timers.show),delete i.origin,O&&!r(Q+'[tracking="true"]:visible',c.solo).not(o).length&&(r(t).unbind("mousemove."+V),O=_),this.blur(n)),f=r.proxy(function(){e?(st.ie&&o[0].style.removeAttribute("filter"),o.css("overflow",""),"string"==typeof c.autofocus&&r(this.options.show.autofocus,o).focus(),this.options.show.target.trigger("qtip-"+this.id+"-inactive")):o.css({display:"",visibility:"",opacity:"",left:"",top:""}),this._trigger(e?"visible":"hidden")},this),c.effect===_||g===_?(o[l](),f()):r.isFunction(c.effect)?(o.stop(1,1),c.effect.call(o,this),o.queue("fx",function(e){f(),e()})):o.fadeTo(90,e?1:0,f),e&&c.target.trigger("qtip-"+this.id+"-inactive"),this))},k.show=function(e){return this.toggle(M,e)},k.hide=function(e){return this.toggle(_,e)},k.focus=function(e){if(!this.rendered||this.destroyed)return this;var t=r(Q),n=this.tooltip,i=parseInt(n[0].style.zIndex,10),s=C.zindex+t.length;return n.hasClass(et)||this._trigger("focus",[s],e)&&(i!==s&&(t.each(function(){this.style.zIndex>i&&(this.style.zIndex=this.style.zIndex-1)}),t.filter("."+et).qtip("blur",e)),n.addClass(et)[0].style.zIndex=s),this},k.blur=function(e){return!this.rendered||this.destroyed?this:(this.tooltip.removeClass(et),this._trigger("blur",[this.tooltip.css("zIndex")],e),this)},k.disable=function(e){return this.destroyed?this:("toggle"===e?e=this.rendered?!this.tooltip.hasClass(nt):!this.disabled:"boolean"!=typeof e&&(e=M),this.rendered&&this.tooltip.toggleClass(nt,e).attr("aria-disabled",e),this.disabled=!!e,this)},k.enable=function(){return this.disable(_)},k._createButton=function(){var e=this,t=this.elements,n=t.tooltip,i=this.options.content.button,s="string"==typeof i,o=s?i:"Close tooltip";t.button&&t.button.remove(),t.button=i.jquery?i:r("<a />",{"class":"qtip-close "+(this.options.style.widget?"":V+"-icon"),title:o,"aria-label":o}).prepend(r("<span />",{"class":"ui-icon ui-icon-close",html:"×"})),t.button.appendTo(t.titlebar||n).attr("role","button").click(function(t){return n.hasClass(nt)||e.hide(t),_})},k._updateButton=function(e){if(!this.rendered)return _;var t=this.elements.button;e?this._createButton():t.remove()},k._setWidget=function(){var e=this.options.style.widget,t=this.elements,n=t.tooltip,r=n.hasClass(nt);n.removeClass(nt),nt=e?"ui-state-disabled":"qtip-disabled",n.toggleClass(nt,r),n.toggleClass("ui-helper-reset "+h(),e).toggleClass(Z,this.options.style.def&&!e),t.content&&t.content.toggleClass(h("content"),e),t.titlebar&&t.titlebar.toggleClass(h("header"),e),t.button&&t.button.toggleClass(V+"-icon",!e)},k._storeMouse=function(e){(this.mouse=p(e)).type="mousemove"},k._bind=function(e,t,n,i,s){var o="."+this._id+(i?"-"+i:"");t.length&&r(e).bind((t.split?t:t.join(o+" "))+o,r.proxy(n,s||this))},k._unbind=function(e,t){r(e).unbind("."+this._id+(t?"-"+t:""))};var ft="."+V;r(function(){w(Q,["mouseenter","mouseleave"],function(e){var t="mouseenter"===e.type,n=r(e.currentTarget),i=r(e.relatedTarget||e.target),s=this.options;t?(this.focus(e),n.hasClass(Y)&&!n.hasClass(nt)&&clearTimeout(this.timers.hide)):"mouse"===s.position.target&&s.hide.event&&s.show.target&&!i.closest(s.show.target[0]).length&&this.hide(e),n.toggleClass(tt,t)}),w("["+J+"]",G,g)}),k._trigger=function(e,t,n){var i=r.Event("tooltip"+e);return i.originalEvent=n&&r.extend({},n)||this.cache.event||D,this.triggering=e,this.tooltip.trigger(i,[this].concat(t||[])),this.triggering=_,!i.isDefaultPrevented()},k._bindEvents=function(e,t,n,i,s,o){if(i.add(n).length===i.length){var u=[];t=r.map(t,function(t){var n=r.inArray(t,e);return n>-1?(u.push(e.splice(n,1)[0]),void 0):t}),u.length&&this._bind(n,u,function(e){var t=this.rendered?this.tooltip[0].offsetWidth>0:!1;(t?o:s).call(this,e)})}this._bind(n,e,s),this._bind(i,t,o)},k._assignInitialEvents=function(e){function t(e){return this.disabled||this.destroyed?_:(this.cache.event=p(e),this.cache.target=e?r(e.target):[n],clearTimeout(this.timers.show),this.timers.show=d.call(this,function(){this.render("object"==typeof e||i.show.ready)},i.show.delay),void 0)}var i=this.options,s=i.show.target,o=i.hide.target,u=i.show.event?r.trim(""+i.show.event).split(" "):[],a=i.hide.event?r.trim(""+i.hide.event).split(" "):[];/mouse(over|enter)/i.test(i.show.event)&&!/mouse(out|leave)/i.test(i.hide.event)&&a.push("mouseleave"),this._bind(s,"mousemove",function(e){this._storeMouse(e),this.cache.onTarget=M}),this._bindEvents(u,a,s,o,t,function(){clearTimeout(this.timers.show)}),(i.show.ready||i.prerender)&&t.call(this,e)},k._assignEvents=function(){var n=this,i=this.options,s=i.position,o=this.tooltip,u=i.show.target,f=i.hide.target,l=s.container,c=s.viewport,h=r(t),p=(r(t.body),r(e)),d=i.show.event?r.trim(""+i.show.event).split(" "):[],w=i.hide.event?r.trim(""+i.hide.event).split(" "):[];r.each(i.events,function(e,t){n._bind(o,"toggle"===e?["tooltipshow","tooltiphide"]:["tooltip"+e],t,null,o)}),/mouse(out|leave)/i.test(i.hide.event)&&"window"===i.hide.leave&&this._bind(h,["mouseout","blur"],function(e){/select|option/.test(e.target.nodeName)||e.relatedTarget||this.hide(e)}),i.hide.fixed?f=f.add(o.addClass(Y)):/mouse(over|enter)/i.test(i.show.event)&&this._bind(f,"mouseleave",function(){clearTimeout(this.timers.show)}),(""+i.hide.event).indexOf("unfocus")>-1&&this._bind(l.closest("html"),["mousedown","touchstart"],function(e){var t=r(e.target),n=this.rendered&&!this.tooltip.hasClass(nt)&&this.tooltip[0].offsetWidth>0,i=t.parents(Q).filter(this.tooltip[0]).length>0;t[0]===this.target[0]||t[0]===this.tooltip[0]||i||this.target.has(t[0]).length||!n||this.hide(e)}),"number"==typeof i.hide.inactive&&(this._bind(u,"qtip-"+this.id+"-inactive",g),this._bind(f.add(o),C.inactiveEvents,g,"-inactive")),this._bindEvents(d,w,u,f,v,m),this._bind(u.add(o),"mousemove",function(e){if("number"==typeof i.hide.distance){var t=this.cache.origin||{},n=this.options.hide.distance,r=Math.abs;(r(e.pageX-t.pageX)>=n||r(e.pageY-t.pageY)>=n)&&this.hide(e)}this._storeMouse(e)}),"mouse"===s.target&&s.adjust.mouse&&(i.hide.event&&this._bind(u,["mouseenter","mouseleave"],function(e){this.cache.onTarget="mouseenter"===e.type}),this._bind(h,"mousemove",function(e){this.rendered&&this.cache.onTarget&&!this.tooltip.hasClass(nt)&&this.tooltip[0].offsetWidth>0&&this.reposition(e)})),(s.adjust.resize||c.length)&&this._bind(r.event.special.resize?c:p,"resize",y),s.adjust.scroll&&this._bind(p.add(s.container),"scroll",y)},k._unassignEvents=function(){var n=[this.options.show.target[0],this.options.hide.target[0],this.rendered&&this.tooltip[0],this.options.position.container[0],this.options.position.viewport[0],this.options.position.container.closest("html")[0],e,t];this._unbind(r([]).pushStack(r.grep(n,function(e){return"object"==typeof e})))},C=r.fn.qtip=function(e,t,i){var s=(""+e).toLowerCase(),o=D,a=r.makeArray(arguments).slice(1),f=a[a.length-1],l=this[0]?r.data(this[0],V):D;return!arguments.length&&l||"api"===s?l:"string"==typeof e?(this.each(function(){var e=r.data(this,V);if(!e)return M;if(f&&f.timeStamp&&(e.cache.event=f),!t||"option"!==s&&"options"!==s)e[s]&&e[s].apply(e,a);else{if(i===n&&!r.isPlainObject(t))return o=e.get(t),_;e.set(t,i)}}),o!==D?o:this):"object"!=typeof e&&arguments.length?void 0:(l=u(r.extend(M,{},e)),this.each(function(e){var t,n;return n=r.isArray(l.id)?l.id[e]:l.id,n=!n||n===_||n.length<1||C.api[n]?C.nextid++:n,t=E(r(this),n,l),t===_?M:(C.api[n]=t,r.each(X,function(){"initialize"===this.initialize&&this(t)}),t._assignInitialEvents(f),void 0)}))},r.qtip=i,C.api={},r.each({attr:function(e,t){if(this.length){var n=this[0],i="title",s=r.data(n,"qtip");if(e===i&&s&&"object"==typeof s&&s.options.suppress)return arguments.length<2?r.attr(n,it):(s&&s.options.content.attr===i&&s.cache.attr&&s.set("content.text",t),this.attr(it,t))}return r.fn["attr"+rt].apply(this,arguments)},clone:function(e){var t=(r([]),r.fn["clone"+rt].apply(this,arguments));return e||t.filter("["+it+"]").attr("title",function(){return r.attr(this,it)}).removeAttr(it),t}},function(e,t){if(!t||r.fn[e+rt])return M;var n=r.fn[e+rt]=r.fn[e];r.fn[e]=function(){return t.apply(this,arguments)||n.apply(this,arguments)}}),r.ui||(r["cleanData"+rt]=r.cleanData,r.cleanData=function(e){for(var t,n=0;(t=r(e[n])).length;n++)if(t.attr($))try{t.triggerHandler("removeqtip")}catch(i){}r["cleanData"+rt].apply(this,arguments)}),C.version="2.2.0",C.nextid=0,C.inactiveEvents=G,C.zindex=15e3,C.defaults={prerender:_,id:_,overwrite:M,suppress:M,content:{text:M,attr:"title",title:_,button:_},position:{my:"top left",at:"bottom right",target:_,container:_,viewport:_,adjust:{x:0,y:0,mouse:M,scroll:M,resize:M,method:"flipinvert flipinvert"},effect:function(e,t){r(this).animate(t,{duration:200,queue:_})}},show:{target:_,event:"mouseenter",effect:M,delay:90,solo:_,ready:_,autofocus:_},hide:{target:_,event:"mouseleave",effect:M,delay:0,fixed:_,inactive:_,leave:"window",distance:_},style:{classes:"",widget:_,width:_,height:_,def:M},events:{render:D,move:D,show:D,hide:D,toggle:D,visible:D,hidden:D,focus:D,blur:D}};var lt,ct="margin",ht="border",pt="color",dt="background-color",vt="transparent",mt=" !important",gt=!!t.createElement("canvas").getContext,yt=/rgba?\(0, 0, 0(, 0)?\)|transparent|#123456/i,bt={},wt=["Webkit","O","Moz","ms"];if(gt)var Et=e.devicePixelRatio||1,St=function(){var e=t.createElement("canvas").getContext("2d");return e.backingStorePixelRatio||e.webkitBackingStorePixelRatio||e.mozBackingStorePixelRatio||e.msBackingStorePixelRatio||e.oBackingStorePixelRatio||1}(),xt=Et/St;else var Tt=function(e,t,n){return"<qtipvml:"+e+' xmlns="urn:schemas-microsoft.com:vml" class="qtip-vml" '+(t||"")+' style="behavior: url(#default#VML); '+(n||"")+'" />'};r.extend(N.prototype,{init:function(e){var t,n;n=this.element=e.elements.tip=r("<div />",{"class":V+"-tip"}).prependTo(e.tooltip),gt?(t=r("<canvas />").appendTo(this.element)[0].getContext("2d"),t.lineJoin="miter",t.miterLimit=1e5,t.save()):(t=Tt("shape",'coordorigin="0,0"',"position:absolute;"),this.element.html(t+t),e._bind(r("*",n).add(n),["click","mousedown"],function(e){e.stopPropagation()},this._ns)),e._bind(e.tooltip,"tooltipmove",this.reposition,this._ns,this),this.create()},_swapDimensions:function(){this.size[0]=this.options.height,this.size[1]=this.options.width},_resetDimensions:function(){this.size[0]=this.options.width,this.size[1]=this.options.height},_useTitle:function(e){var t=this.qtip.elements.titlebar;return t&&(e.y===F||e.y===U&&this.element.position().top+this.size[1]/2+this.options.offset<t.outerHeight(M))},_parseCorner:function(e){var t=this.qtip.options.position.my;return e===_||t===_?e=_:e===M?e=new L(t.string()):e.string||(e=new L(e),e.fixed=M),e},_parseWidth:function(e,t,n){var r=this.qtip.elements,i=ht+S(t)+"Width";return(n?T(n,i):T(r.content,i)||T(this._useTitle(e)&&r.titlebar||r.content,i)||T(r.tooltip,i))||0},_parseRadius:function(e){var t=this.qtip.elements,n=ht+S(e.y)+S(e.x)+"Radius";return st.ie<9?0:T(this._useTitle(e)&&t.titlebar||t.content,n)||T(t.tooltip,n)||0},_invalidColour:function(e,t,n){var r=e.css(t);return!r||n&&r===e.css(n)||yt.test(r)?_:r},_parseColours:function(e){var t=this.qtip.elements,n=this.element.css("cssText",""),i=ht+S(e[e.precedance])+S(pt),s=this._useTitle(e)&&t.titlebar||t.content,o=this._invalidColour,u=[];return u[0]=o(n,dt)||o(s,dt)||o(t.content,dt)||o(t.tooltip,dt)||n.css(dt),u[1]=o(n,i,pt)||o(s,i,pt)||o(t.content,i,pt)||o(t.tooltip,i,pt)||t.tooltip.css(i),r("*",n).add(n).css("cssText",dt+":"+vt+mt+";"+ht+":0"+mt+";"),u},_calculateSize:function(e){var t,n,r,i=e.precedance===H,s=this.options.width,o=this.options.height,u="c"===e.abbrev(),a=(i?s:o)*(u?.5:1),f=Math.pow,l=Math.round,c=Math.sqrt(f(a,2)+f(o,2)),h=[this.border/a*c,this.border/o*c];return h[2]=Math.sqrt(f(h[0],2)-f(this.border,2)),h[3]=Math.sqrt(f(h[1],2)-f(this.border,2)),t=c+h[2]+h[3]+(u?0:h[0]),n=t/c,r=[l(n*s),l(n*o)],i?r:r.reverse()},_calculateTip:function(e,t,n){n=n||1,t=t||this.size;var r=t[0]*n,i=t[1]*n,s=Math.ceil(r/2),o=Math.ceil(i/2),u={br:[0,0,r,i,r,0],bl:[0,0,r,0,0,i],tr:[0,i,r,0,r,i],tl:[0,0,0,i,r,i],tc:[0,i,s,0,r,i],bc:[0,0,r,0,s,i],rc:[0,0,r,o,0,i],lc:[r,0,r,i,0,o]};return u.lt=u.br,u.rt=u.bl,u.lb=u.tr,u.rb=u.tl,u[e.abbrev()]},_drawCoords:function(e,t){e.beginPath(),e.moveTo(t[0],t[1]),e.lineTo(t[2],t[3]),e.lineTo(t[4],t[5]),e.closePath()},create:function(){var e=this.corner=(gt||st.ie)&&this._parseCorner(this.options.corner);return(this.enabled=!!this.corner&&"c"!==this.corner.abbrev())&&(this.qtip.cache.corner=e.clone(),this.update()),this.element.toggle(this.enabled),this.corner},update:function(t,n){if(!this.enabled)return this;var i,s,o,u,f,l,c,h,p=this.qtip.elements,d=this.element,v=d.children(),m=this.options,g=this.size,y=m.mimic,b=Math.round;t||(t=this.qtip.cache.corner||this.corner),y===_?y=t:(y=new L(y),y.precedance=t.precedance,"inherit"===y.x?y.x=t.x:"inherit"===y.y?y.y=t.y:y.x===y.y&&(y[t.precedance]=t[t.precedance])),s=y.precedance,t.precedance===P?this._swapDimensions():this._resetDimensions(),i=this.color=this._parseColours(t),i[1]!==vt?(h=this.border=this._parseWidth(t,t[t.precedance]),m.border&&1>h&&!yt.test(i[1])&&(i[0]=i[1]),this.border=h=m.border!==M?m.border:h):this.border=h=0,c=this.size=this._calculateSize(t),d.css({width:c[0],height:c[1],lineHeight:c[1]+"px"}),l=t.precedance===H?[b(y.x===I?h:y.x===R?c[0]-g[0]-h:(c[0]-g[0])/2),b(y.y===F?c[1]-g[1]:0)]:[b(y.x===I?c[0]-g[0]:0),b(y.y===F?h:y.y===q?c[1]-g[1]-h:(c[1]-g[1])/2)],gt?(o=v[0].getContext("2d"),o.restore(),o.save(),o.clearRect(0,0,6e3,6e3),u=this._calculateTip(y,g,xt),f=this._calculateTip(y,this.size,xt),v.attr(B,c[0]*xt).attr(j,c[1]*xt),v.css(B,c[0]).css(j,c[1]),this._drawCoords(o,f),o.fillStyle=i[1],o.fill(),o.translate(l[0]*xt,l[1]*xt),this._drawCoords(o,u),o.fillStyle=i[0],o.fill()):(u=this._calculateTip(y),u="m"+u[0]+","+u[1]+" l"+u[2]+","+u[3]+" "+u[4]+","+u[5]+" xe",l[2]=h&&/^(r|b)/i.test(t.string())?8===st.ie?2:1:0,v.css({coordsize:c[0]+h+" "+(c[1]+h),antialias:""+(y.string().indexOf(U)>-1),left:l[0]-l[2]*Number(s===P),top:l[1]-l[2]*Number(s===H),width:c[0]+h,height:c[1]+h}).each(function(e){var t=r(this);t[t.prop?"prop":"attr"]({coordsize:c[0]+h+" "+(c[1]+h),path:u,fillcolor:i[0],filled:!!e,stroked:!e}).toggle(!!h||!!e),!e&&t.html(Tt("stroke",'weight="'+2*h+'px" color="'+i[1]+'" miterlimit="1000" joinstyle="miter"'))})),e.opera&&setTimeout(function(){p.tip.css({display:"inline-block",visibility:"visible"})},1),n!==_&&this.calculate(t,c)},calculate:function(e,t){if(!this.enabled)return _;var n,i,s=this,o=this.qtip.elements,u=this.element,a=this.options.offset,f=(o.tooltip.hasClass("ui-widget"),{});return e=e||this.corner,n=e.precedance,t=t||this._calculateSize(e),i=[e.x,e.y],n===P&&i.reverse(),r.each(i,function(r,i){var u,l,h;i===U?(u=n===H?I:F,f[u]="50%",f[ct+"-"+u]=-Math.round(t[n===H?0:1]/2)+a):(u=s._parseWidth(e,i,o.tooltip),l=s._parseWidth(e,i,o.content),h=s._parseRadius(e),f[i]=Math.max(-s.border,r?l:a+(h>u?h:-u)))}),f[e[n]]-=t[n===P?0:1],u.css({margin:"",top:"",bottom:"",left:"",right:""}).css(f),f},reposition:function(e,t,r){function i(e,t,n,r,i){e===W&&f.precedance===t&&l[r]&&f[n]!==U?f.precedance=f.precedance===P?H:P:e!==W&&l[r]&&(f[t]=f[t]===U?l[r]>0?r:i:f[t]===r?i:r)}function s(e,t,i){f[e]===U?m[ct+"-"+t]=v[e]=o[ct+"-"+t]-l[t]:(u=o[i]!==n?[l[t],-o[t]]:[-l[t],o[t]],(v[e]=Math.max(u[0],u[1]))>u[0]&&(r[t]-=l[t],v[t]=_),m[o[i]!==n?i:t]=v[e])}if(this.enabled){var o,u,a=t.cache,f=this.corner.clone(),l=r.adjusted,h=t.options.position.adjust.method.split(" "),p=h[0],d=h[1]||h[0],v={left:_,top:_,x:0,y:0},m={};this.corner.fixed!==M&&(i(p,P,H,I,R),i(d,H,P,F,q),f.string()===a.corner.string()||a.cornerTop===l.top&&a.cornerLeft===l.left||this.update(f,_)),o=this.calculate(f),o.right!==n&&(o.left=-o.right),o.bottom!==n&&(o.top=-o.bottom),o.user=this.offset,(v.left=p===W&&!!l.left)&&s(P,I,R),(v.top=d===W&&!!l.top)&&s(H,F,q),this.element.css(m).toggle(!(v.x&&v.y||f.x===U&&v.y||f.y===U&&v.x)),r.left-=o.left.charAt?o.user:p!==W||v.top||!v.left&&!v.top?o.left+this.border:0,r.top-=o.top.charAt?o.user:d!==W||v.left||!v.left&&!v.top?o.top+this.border:0,a.cornerLeft=l.left,a.cornerTop=l.top,a.corner=f.clone()}},destroy:function(){this.qtip._unbind(this.qtip.tooltip,this._ns),this.qtip.elements.tip&&this.qtip.elements.tip.find("*").remove().end().remove()}}),lt=X.tip=function(e){return new N(e,e.options.style.tip)},lt.initialize="render",lt.sanitize=function(e){if(e.style&&"tip"in e.style){var t=e.style.tip;"object"!=typeof t&&(t=e.style.tip={corner:t}),/string|boolean/i.test(typeof t.corner)||(t.corner=M)}},A.tip={"^position.my|style.tip.(corner|mimic|border)$":function(){this.create(),this.qtip.reposition()},"^style.tip.(height|width)$":function(e){this.size=[e.width,e.height],this.update(),this.qtip.reposition()},"^content.title|style.(classes|widget)$":function(){this.update()}},r.extend(M,C.defaults,{style:{tip:{corner:M,mimic:_,width:6,height:6,border:M,offset:0}}}),X.viewport=function(n,r,i,s,o,u,f){function l(e,t,n,i,s,o,u,a,f){var l=r[s],c=x[e],p=T[e],b=n===W,E=c===s?f:c===o?-f:-f/2,S=p===s?a:p===o?-a:-a/2,N=y[s]+w[s]-(v?0:d[s]),C=N-l,k=l+f-(u===B?m:g)-N,L=E-(x.precedance===e||c===x[t]?S:0)-(p===U?a/2:0);return b?(L=(c===s?1:-1)*E,r[s]+=C>0?C:k>0?-k:0,r[s]=Math.max(-d[s]+w[s],l-L,Math.min(Math.max(-d[s]+w[s]+(u===B?m:g),l+L),r[s],"center"===c?l-E:1e9))):(i*=n===z?2:0,C>0&&(c!==s||k>0)?(r[s]-=L+i,h.invert(e,s)):k>0&&(c!==o||C>0)&&(r[s]-=(c===U?-L:L)+i,h.invert(e,o)),r[s]<y&&-r[s]>k&&(r[s]=l,h=x.clone())),r[s]-l}var c,h,p,d,v,m,g,y,w,E=i.target,S=n.elements.tooltip,x=i.my,T=i.at,N=i.adjust,C=N.method.split(" "),k=C[0],L=C[1]||C[0],A=i.viewport,O=i.container,M=n.cache,D={left:0,top:0};return A.jquery&&E[0]!==e&&E[0]!==t.body&&"none"!==N.method?(d=O.offset()||D,v="static"===O.css("position"),c="fixed"===S.css("position"),m=A[0]===e?A.width():A.outerWidth(_),g=A[0]===e?A.height():A.outerHeight(_),y={left:c?0:A.scrollLeft(),top:c?0:A.scrollTop()},w=A.offset()||D,("shift"!==k||"shift"!==L)&&(h=x.clone()),D={left:"none"!==k?l(P,H,k,N.x,I,R,B,s,u):0,top:"none"!==L?l(H,P,L,N.y,F,q,j,o,f):0},h&&M.lastClass!==(p=V+"-pos-"+h.abbrev())&&S.removeClass(n.cache.lastClass).addClass(n.cache.lastClass=p),D):D}})}(window,document),define("util.tooltips",["jquery","qtip"],function(e){setupTooltips=function(t){typeof t=="undefined"&&(t=!1);if(Headway.disableTooltips==1||Headway.touch)return e("div.tooltip-button").hide(),!1;var n={style:{classes:"qtip-headway"},show:{delay:10,solo:!0,event:"mouseenter"},position:{my:"bottom left",at:"top center",viewport:e(window),effect:!1},hide:{effect:!1}};if(t=="iframe"){n.position.container=Headway.iframe.contents().find("body"),n.position.viewport=e("#iframe-container");var r=$i}else var r=e;r("div.tooltip-button:not([data-hasqtip]), .tooltip:not([data-hasqtip])").qtip(n),r(".tooltip-bottom-right:not([data-hasqtip])").qtip(e.extend(!0,{},n,{position:{my:"bottom right",at:"top center"}})),r(".tooltip-top-right:not([data-hasqtip])").qtip(e.extend(!0,{},n,{position:{my:"top right",at:"bottom center"}})),r(".tooltip-top-left:not([data-hasqtip])").qtip(e.extend(!0,{},n,{position:{my:"top left",at:"bottom center"},show:{delay:750}})),r(".tooltip-left:not([data-hasqtip])").qtip(e.extend(!0,{},n,{position:{my:"left center",at:"right center"}})),r(".tooltip-right:not([data-hasqtip])").qtip(e.extend(!0,{},n,{position:{my:"right center",at:"left center"}})),r(".tooltip-top:not([data-hasqtip])").qtip(e.extend(!0,{},n,{position:{my:"top center",at:"bottom center"}}));var i=function(){if($i(".qtip:visible").length===0||typeof iframeScrollTooltipRepositionFloodTimeout!="undefined")return;iframeScrollTooltipRepositionFloodTimeout=setTimeout(function(){$i(".qtip:visible").qtip("reposition"),delete iframeScrollTooltipRepositionFloodTimeout},400)};Headway.iframe.contents().unbind("scroll",i),Headway.iframe.contents().bind("scroll",i)},repositionTooltips=function(){$i(".qtip:visible").qtip("reposition")}}),function($){function Colorpicker(){this._mainDivId=mainDivId,this._colorDivClass=colorDivClass,this._defaults={showAnim:!0,duration:200,color:"FFFFFF",allowNull:!1,realtime:!0,invertControls:!0,controlStyle:"simple",swatches:!0,alpha:!1,alphaHex:!1,beforeShow:null,onClose:null,onSelect:null,onAddSwatch:null,onDeleteSwatch:null}}function extendRemove(e,t){$.extend(e,t);for(var n in t)if(t[n]==null||t[n]==undefined)e[n]=t[n];return e}function isset(e){return e!==undefined}var PROP_NAME="css3colorpicker",mainDivId="css3colorpicker-div",colorDivClass="color",cpDiv=$('<div id="'+mainDivId+'"></div>');cpDiv.swatchContainer=$('<div id="'+mainDivId+'-swatchContainer"></div>'),cpDiv.swatches=$('<div id="'+mainDivId+'-swatches"></div>'),cpDiv.addSwatchButton=$('<div id="'+mainDivId+'-add-swatch-button" title="Add Current Color to Swatches" class="tooltip"></div>'),cpDiv.colorDiv=$('<div id="'+mainDivId+'-color" title="Choose Color and Close Color Picker" class="tooltip"></div>'),cpDiv.oldColorDiv=$('<div id="'+mainDivId+'-colorOld" title="Revert to Previous Color" class="tooltip"></div>'),cpDiv.d1Div=$('<div id="'+mainDivId+'-1d"></div>'),cpDiv.d1Div.control=$('<div id="'+mainDivId+'-1dControl"></div>'),cpDiv.d1Div.colorDiv=$('<div id="'+mainDivId+'-1dColor"></div>'),cpDiv.d1Div.gradientDiv=$('<div id="'+mainDivId+'-1dGradient"></div>'),cpDiv.d2Div=$('<div id="'+mainDivId+'-2d"></div>'),cpDiv.d2Div.control=$('<div id="'+mainDivId+'-2dControl"></div>'),cpDiv.d2Div.colorDiv=$('<div id="'+mainDivId+'-2dColor"></div>'),cpDiv.d2Div.gradientDiv=$('<div id="'+mainDivId+'-2dGradient"></div>'),cpDiv.alphaDiv=$('<div id="'+mainDivId+'-alpha"></div>'),cpDiv.alphaDiv.control=$('<div id="'+mainDivId+'-alphaControl"></div>'),cpDiv.inputContainerHSB=$('<ul id="'+mainDivId+'-inputContainer-hsv" class="css3colorpicker-inputContainer"></ul>'),cpDiv.inputContainerRGBA=$('<ul id="'+mainDivId+'-inputContainer-rgba" class="css3colorpicker-inputContainer"></ul>'),cpDiv.inputContainerHex=$('<ul id="'+mainDivId+'-inputContainer-hex" class="css3colorpicker-inputContainer"></ul>'),cpDiv.inputs={h:$('<input type="text" data-mode="h" id="'+mainDivId+'-h"/>'),s:$('<input type="text" data-mode="s" id="'+mainDivId+'-s"/>'),v:$('<input type="text" data-mode="v" id="'+mainDivId+'-v"/>'),r:$('<input type="text" id="'+mainDivId+'-r"/>'),g:$('<input type="text" id="'+mainDivId+'-g"/>'),b:$('<input type="text" id="'+mainDivId+'-b"/>'),a:$('<input type="text" id="'+mainDivId+'-a"/>'),hex:$('<input type="text" id="'+mainDivId+'-hex" maxlength="8" />')},cpDiv.append($('<div id="'+mainDivId+'-container"></div>').append($('<div id="'+mainDivId+'-colorContainer"></div>').append(cpDiv.colorDiv,cpDiv.oldColorDiv),cpDiv.d1Div.append(cpDiv.d1Div.colorDiv,cpDiv.d1Div.gradientDiv,cpDiv.d1Div.control),cpDiv.d2Div.append(cpDiv.d2Div.colorDiv,cpDiv.d2Div.gradientDiv,cpDiv.d2Div.control),cpDiv.alphaDiv.append(cpDiv.alphaDiv.control),cpDiv.inputContainerHSB.append($("<li>H <span>°</span></li>").append(cpDiv.inputs.h),$("<li>S <span>%</span></li>").append(cpDiv.inputs.s),$("<li>B <span>%</span></li>").append(cpDiv.inputs.v)),cpDiv.inputContainerRGBA.append($("<li>R </li>").append(cpDiv.inputs.r),$("<li>G </li>").append(cpDiv.inputs.g),$("<li>B </li>").append(cpDiv.inputs.b),$('<li class="alpha">A <span>%</span></li>').append(cpDiv.inputs.a)),cpDiv.inputContainerHex.append($("<li># </li>").append(cpDiv.inputs.hex))),cpDiv.swatchContainer.append(cpDiv.swatches,cpDiv.addSwatchButton)),$.extend(Colorpicker.prototype,{cpDiv:cpDiv,mode:"h",markerClassName:"hasColorpicker",controlsClassPrefix:"controls-",minLum:50,swatches:[],swatchLimit:15,setDefaults:function(e){return extendRemove(this._defaults,e||{}),this},_setMode:function(e){["h","s","v"].indexOf(e)>=0&&(this.cpDiv.removeClass("mode-"+this.mode),this.cpDiv.addClass("mode-"+e),this.mode=e,$.colorpicker._updateMaps(),$.colorpicker._updateControls())},refresh:function(){return this._updateColorpicker(!0),this},color:function(e){this.r=0,this.g=0,this.b=0,this.a=1,this.h=0,this.s=0,this.v=0,this.l=0,this.hex="",this.hexa="",this.rgb="rgb(0,0,0)",this.rgba="rgba(0,0,0,1)",this._a=1,this._h=0,this._s=0,this._v=0,this.setRgb=function(e,t,n,r){this.isNull=!1,this.r=Math.max(0,Math.min(255,Math.round(e))),this.g=Math.max(0,Math.min(255,Math.round(t))),this.b=Math.max(0,Math.min(255,Math.round(n))),this._a=isset(r)?Math.max(0,Math.min(100,parseFloat(r))):this._a||100,this.a=Math.round(this._a);var i=$.colorpicker.rgbToHsv(this);this._h=i.h,this._s=i.s,this._v=i.v,this.h=Math.round(i.h),this.s=Math.round(i.s),this.v=Math.round(i.v),this.l=$.colorpicker.rgbToLum(this),this.hex=$.colorpicker.rgbToHex(this),this.hexa=$.colorpicker.rgbToHex(this),this.rgb="rgb("+this.r+","+this.g+","+this.b+")",this.rgba="rgba("+this.r+","+this.g+","+this.b+","+this.a/100+")"},this.setHsv=function(e,t,n,r){this.isNull=!1,this._h=Math.max(0,Math.min(360,parseFloat(e))),this._s=Math.max(0,Math.min(100,parseFloat(t))),this._v=Math.max(0,Math.min(100,parseFloat(n))),this.h=Math.round(this._h),this.s=Math.round(this._s),this.v=Math.round(this._v),this._a=isset(r)?Math.max(0,Math.min(100,parseFloat(r))):this._a||100,this.a=Math.round(this._a);var i=$.colorpicker.hsvToRgb(this);this.r=Math.round(i.r),this.g=Math.round(i.g),this.b=Math.round(i.b),this.l=$.colorpicker.rgbToLum(this),this.hex=$.colorpicker.rgbToHex(i),this.hexa=$.colorpicker.rgbToHex(i),this.rgb="rgb("+this.r+","+this.g+","+this.b+")",this.rgba="rgba("+this.r+","+this.g+","+this.b+","+this.a/100+")"},this.setHex=function(e){this.isNull=!1,this.hexa=$.colorpicker.validateHex(e),this.hex=$.colorpicker.validateHex(e);var t=$.colorpicker.hexToRgb(this.hexa);this.r=t.r,this.g=t.g,this.b=t.b,this._a=t.a,this.a=Math.round(t.a);var n=$.colorpicker.rgbToHsv(t);this._h=n.h,this._s=n.s,this._v=n.v,this.h=Math.round(n.h),this.s=Math.round(n.s),this.v=Math.round(n.v),this.l=$.colorpicker.rgbToLum(this),this.rgb="rgb("+this.r+","+this.g+","+this.b+")",this.rgba="rgba("+this.r+","+this.g+","+this.b+","+this.a/100+")"};if(e)if("hexa"in e)this.setHex(e.hexa);else if("hex"in e)this.setHex(e.hex);else if("rgb"in e){var t=e.rgb.match(/^rgba?\((\d+),\s*(\d+),\s*(\d+)(?:,\s*(0?\.?\d+))?\)/i);if(t){var n=100;typeof t[4]!="undefined"&&(n*=t[4]),this.setRgb(t[1],t[2],t[3],n)}}else"r"in e?this.setRgb(e.r,e.g,e.b,e.a):"h"in e&&this.setHsv(e.h,e.s,e.v,e.a);return this},_attachColorpicker:function(target,settings){var input=$(target);if(input.hasClass(this.markerClassName))return;input.addClass(this._colorDivClass).addClass(this.markerClassName),target.id||(this.uuid+=1,target.id="cp"+this.uuid);var inlineSettings=null;for(var attrName in this._defaults){var attrValue=target.getAttribute("color:"+attrName);if(attrValue){inlineSettings=inlineSettings||{};try{inlineSettings[attrName]=eval(attrValue)}catch(err){inlineSettings[attrName]=attrValue}}}var inst=this._newInst(input);inst.settings=$.extend({},settings||{},inlineSettings||{}),this._get(inst,"alpha")?input.addClass("alpha")[inst.settings.alphaHex?"addClass":"removeClass"]("alphaHex"):input.removeClass("alpha").removeClass("alphaHex"),this._setColor(inst,input.val()||input.data("color")||this._get(inst,"color"),!0);var swatches=this._get(inst,"swatches");swatches&&this.addSwatch(swatches),input.is("input")&&input.focus(function(){$.colorpicker._showColorpicker(target)}).keyup(function(){$.colorpicker._setColor(inst,this.value),$.colorpicker._updateColorpicker()}).bind("setData.colorpicker",function(e,t,n){inst.settings[t]=n}).bind("getData.colorpicker",function(e,t){return $.colorpicker._get(inst,t)}),input.click(function(){$.colorpicker._showColorpicker(target)}).bind("refresh",function(){var e=$(this),t=$.colorpicker._getInst(this);$.colorpicker._setColor(t,input.val()||input.data("color")||$.colorpicker._get(t,"color").hexa,!0),$.colorpicker._updateColorpicker()})},_setColor:function(e,t,n){if(!t||t.isNull)t=new $.colorpicker.color({hex:this._defaults.color}),t.isNull=this._get(e,"allowNull");if(typeof t=="string"||typeof t=="number")t.match(/^rgb/)?t=new $.colorpicker.color({rgb:t}):t=new $.colorpicker.color({hex:t});e.settings.color=new $.colorpicker.color({hex:t.hexa}),this._isDragging||(e.color=new $.colorpicker.color({hex:t.hexa})),e.color.isNull=e.settings.color.isNull=t.isNull,this._updateTarget(e,n);if(!this._isLastColor(t)){e.lastColor=t.isNull?null:t.hexa;var r=this._get(e,"onSelect");typeof r=="function"&&r(t.isNull?null:t,e)}},_newInst:function(e){var t=e[0].id.replace(/([^F-Za-z0-9_-])/g,"\\\\$1"),n={id:t,input:e,cpDiv:cpDiv,color:new $.colorpicker.color,lastColor:null};return e.data(PROP_NAME,n),n},_checkExternalClick:function(e){if(!$.colorpicker._curInst)return;var t=$(e.target);t[0].id!=$.colorpicker._mainDivId&&!t.is('label[for="'+$.colorpicker._curInst.input[0].id+'"]')&&t.parents("#"+$.colorpicker._mainDivId).length==0&&!t.hasClass($.colorpicker.markerClassName)&&$.colorpicker._hideColorpicker()},_optionColorpicker:function(e,t,n){var r=this._getInst(e),i=!1;if(arguments.length==2&&typeof t=="string")return t=="defaults"?$.extend({},$.colorpicker._defaults):r?t=="all"?$.extend({},r.settings):this._get(r,t):null;r&&this._curInst==r&&(this._hideColorpicker(e,!0),i=!0);var s=t||{};if(typeof t=="string"){s={};if(r&&t=="color"&&isset(n)){var o=n?new this.color({hex:n}):new this.color({hex:this._defaults.color});o.isNull=!n&&this._get(r,"allowNull"),n=o,this._setColor(r,n,!0),this.addSwatch(n,!0)}t=="swatches"&&n&&this.addSwatch(n),s[t]=n}r&&extendRemove(r.settings,s),i&&this._showColorpicker(e,!0)},_showColorpicker:function(e,t){e=e.target||e;var n=$(e);if(e.disabled)return;var r=$.colorpicker._getInst(e);this._curInst&&this._curInst!=r&&(this._triggerOnClose(),this.cpDiv.stop(!0,!0)),this._curInst=r,r.lastColor=r.color.isNull?null:r.color.hexa;var i=this._get(r,"alpha");$.colorpicker._updateColorpicker(),r.input.addClass("selected");var s=!t&&this._get(r,"showAnim"),o=this._get(r,"duration"),u=function(){$.colorpicker.cpDiv.addClass("visible")},a=$.colorpicker._get(r,"controlStyle").split(/\s+/);for(var f=0;f<a.length;f++)cpDiv.addClass(this.controlsClassPrefix+a[f]);cpDiv[i?"addClass":"removeClass"]("alphaOn"),cpDiv[this._get(r,"swatches")?"addClass":"removeClass"]("swatchesOn"),this.cpDiv.oldColorDiv.data("color",r.color.isNull?null:r.color.hexa).css("background-color",r.color[i?"rgba":"rgb"]);var l=this._get(r,"beforeShow");typeof l=="function"&&l(r.input,r),this._colorpickerShowing=!0,this.cpDiv[s?"fadeIn":"show"](s?o:null,u),s||u(),this._positionColorpicker()},_positionColorpicker:function(){var e=$.colorpicker._curInst.input,t=this.cpDiv,n=e.offset(),r=t.outerWidth(),i=t.defaultHeight+(this._get(this._getInst(e),"alpha")?t.alphaHeight:0)+(this._get(this._getInst(e),"swatches")?t.swatchHeight:0),s=$(window).width(),o=$(window).height(),u=10;i+=u,n.left+=e.outerWidth()+u,n.top+i>o&&(n.top=o-i),n.left+r>s&&(n.left=s-r),t.css({top:0,left:0}).offset(n)},_hideColorpicker:function(e,t){var n=this._curInst;if(!n||e&&n!=this._getInst(e))return;var r=function(){$.colorpicker._triggerOnClose(),$.colorpicker._curInst=null};if(this._colorpickerShowing){var i=!t&&this._get(n,"showAnim"),s=this._get(n,"duration");this.cpDiv[i?"fadeOut":"hide"](i?s:null,r),i||r(),this.cpDiv.removeClass("visible"),this._colorpickerShowing=!1;var o=this._get(n,"onClose");typeof o=="function"&&o(n.color,n)}else r()},_triggerOnClose:function(){var e=this._curInst;if(!e)return;e.input.removeClass("selected"),$.colorpicker.addSwatch(e.color,!0),this._setColor(e,e.color),cpDiv.removeClass(this.controlsClassPrefix+"invert");var t=$.colorpicker._get(e,"controlStyle").split(/\s+/);for(var n=0;n<t.length;n++)cpDiv.removeClass(this.controlsClassPrefix+t[n])},_updateColorpicker:function(e){var t=this._curInst;if(!t)return;var n=this._get(t,"alpha");this.cpDiv.colorDiv.data("color",t.color.isNull?null:t.color.hexa).css("background-color",t.color[n?"rgba":"rgb"]),cpDiv.d2Div.control.css("background-color",t.color.rgb),$.colorpicker._updateInputs(e),$.colorpicker._updateMaps(),$.colorpicker._updateControls(),this._get(t,"realtime")&&this._setColor(t,t.color,e)},_updateTarget:function(e,t){var n=this._get(e,"alpha"),r=this._get(e,"alphaHex");e.color.isNull?e.input.parent().addClass("color-null"):e.input.css({backgroundColor:e.color[n?"rgba":"rgb"],color:e.color.l<$.colorpicker.minLum?"#fff":"#000"}).parent().removeClass("color-null"),e.input.data("color",e.color.isNull?null:e.color.hexa);if(t||!e.input.is(":focus")){var i=e.input.val()||"";e.color.isNull?e.input.val(""):e.input.val(i.indexOf("#")>=0?"#"+e.color[r?"hexa":"hex"]:e.color[r?"hexa":"hex"]),i!=e.input.val()&&e.input.trigger("change")}},_updateInputs:function(e){var t=this._curInst;if(!t)return;var n=this._get(t,"alphaHex");for(var r in this.cpDiv.inputs)r&&isset(t.color[r])&&(e||!this.cpDiv.inputs[r].is(":focus"))&&(r=="hex"?this.cpDiv.inputs[r].val(t.color.isNull?"":t.color[n?"hexa":r]):this.cpDiv.inputs[r].val(t.color[r]))},_updateMaps:function(){var e=this._curInst;if(!e)return;this.cpDiv.alphaDiv.css("background-color",e.color.rgb);switch(this.mode){case"h":this.cpDiv.d1Div.gradientDiv.css("background",""),this.cpDiv.d2Div.colorDiv.css("background-color",(new this.color({h:e.color.h,s:100,v:100})).rgb),this.cpDiv.d1Div.gradientDiv.css("opacity",1-e.color.v/100),this.cpDiv.d1Div.colorDiv.css("opacity",e.color.s/100),this.cpDiv.d2Div.colorDiv.css("opacity",1),this.cpDiv.d2Div.gradientDiv.css("opacity",1);break;case"s":this.cpDiv.d1Div.colorDiv.css("background-color",(new this.color({h:e.color.h,s:100,v:100})).rgb),this.cpDiv.d1Div.gradientDiv.css("opacity",1-e.color.v/100),this.cpDiv.d1Div.colorDiv.css("opacity",1),this.cpDiv.d2Div.colorDiv.css("opacity",e.color.s/100),this.cpDiv.d2Div.gradientDiv.css("opacity",1);break;case"v":this.cpDiv.d1Div.gradientDiv.css("background",""),this.cpDiv.d1Div.colorDiv.css("background-color",(new this.color({h:e.color.h,s:e.color.s,v:100})).rgb),this.cpDiv.d1Div.gradientDiv.css("opacity",1),this.cpDiv.d1Div.colorDiv.css("opacity",1),this.cpDiv.d2Div.colorDiv.css("opacity",1),this.cpDiv.d2Div.gradientDiv.css("opacity",1-e.color.v/100)}$.colorpicker._updateControl()},_updateControls:function(){if(!this._curInst||this._isDragging)return;var e=this._curInst,t,n,r,i;switch(this.mode){case"h":t=e.color._s*255/100,n=255-e.color._v*255/100,r=255-e.color._h*255/360,i=e.color._a*255/100;break;case"s":t=e.color._h*255/360,n=255-e.color._v*255/100,r=255-e.color._s*255/100,i=e.color._a*255/100;break;case"v":t=e.color._h*255/360,n=255-e.color._s*255/100,r=255-e.color._v*255/100,i=e.color._a*255/100}$.colorpicker._moveControl1d(r,!0),$.colorpicker._moveControl2d(t,n,!0),$.colorpicker._moveControlAlpha(i,!0)},_moveControl1d:function(e,t){if(!$.colorpicker._curInst)return;var n=$.colorpicker._curInst;cpDiv.d1Div.control.css({top:Math.max(0,Math.min(255,Math.round(e)))+"px"});if(!t){switch($.colorpicker.mode){case"h":e=360-e*360/256;break;case"s":case"v":e=100-e*100/256}n.color["_"+$.colorpicker.mode]=e,n.color.setHsv(n.color._h,n.color._s,n.color._v,n.color.a),$.colorpicker._updateColorpicker(!0)}},_moveControl2d:function(e,t,n){if(!$.colorpicker._curInst)return;var r=$.colorpicker._curInst;cpDiv.d2Div.control.css({left:Math.max(0,Math.min(255,Math.round(e)))+"px",top:Math.max(0,Math.min(255,Math.round(t)))+"px"});if(!n){switch($.colorpicker.mode){case"h":e=e*100/256,t=100-t*100/256,r.color._s=e,r.color._v=t;break;case"s":case"v":e=e*360/256,t=100-t*100/256,r.color._h=e,r.color[$.colorpicker.mode=="s"?"_v":"_s"]=t}r.color.setHsv(r.color._h,r.color._s,r.color._v,r.color.a),$.colorpicker._updateColorpicker(!0)}},_moveControlAlpha:function(e,t){if(!$.colorpicker._curInst)return;var n=$.colorpicker._curInst;cpDiv.alphaDiv.control.css({left:Math.max(0,Math.min(255,parseInt(e)))+"px"}),t||(e*=.390625,n.color.a=e,n.color.setHsv(n.color._h,n.color._s,n.color._v,n.color.a),$.colorpicker._updateColorpicker(!0))},_mousemoveControl1d:function(e){return $.colorpicker._moveControl1d(e.pageY-$.colorpicker.cpDiv.d1Div.offset().top),e.preventDefault(),!1},_mousemoveControl2d:function(e){var t=$.colorpicker.cpDiv.d2Div.offset();return $.colorpicker._moveControl2d(e.pageX-t.left,e.pageY-t.top),e.preventDefault(),!1},_mousemoveControlAlpha:function(e){return $.colorpicker._moveControlAlpha(e.pageX-$.colorpicker.cpDiv.alphaDiv.offset().left),e.preventDefault(),!1},_updateControl:function(){if(!this._curInst||!$.colorpicker._get(this._curInst,"invertControls"))return!1;this._curInst.color.l<$.colorpicker.minLum?cpDiv.addClass(this.controlsClassPrefix+"invert"):cpDiv.removeClass(this.controlsClassPrefix+"invert")},_submit:function(e,t){var n=this._curInst;if(!n)return;if(!isset(e))var e=n.color,r=e.isNull&&this._get(n,"allowNull");else if(!e){var r=this._get(n,"allowNull");e=this._defaults.color}typeof e=="string"||typeof e=="number"?(e=new this.color({hex:e}),this._get(n,"alpha")||(e.a=e._a=100)):e=new this.color({hex:e[this._get(n,"alpha")?"hexa":"hex"]}),e.isNull=r,this._isCurrentColor(e)?($.colorpicker._hideColorpicker(),t=!0):($.colorpicker._setColor(n,e,!0),$.colorpicker._updateColorpicker(!0)),$.colorpicker.addSwatch(e,t)},_isCurrentColor:function(e){var t=this._curInst;if(!t)return;if(!e||e.isNull)return t.settings.color.isNull&&t.color.isNull;if(typeof e=="string"||typeof e=="number")e=new this.color({hex:e});return this._get(t,"alpha")?e.hexa==t.settings.color.hexa&&e.hexa==t.color.hexa:e.hex==t.settings.color.hex&&e.hex==t.color.hex},_isLastColor:function(e){var t=this._curInst;if(!t)return;if(!e||e.isNull)return t.lastColor===null;var n=new this.color({hex:t.lastColor});if(typeof e=="string"||typeof e=="number")e=new this.color({hex:e});return this._get(t,"alpha")?e.hexa==n.hexa:e.hex==n.hex},addSwatch:function(e,t){var n=this._curInst;if(n&&!this._get(n,"swatches")||!e||e.isNull)return!1;if(typeof e=="string"||typeof e=="number")e=new this.color({hex:e});if(e.hexa){var r=this.swatches.indexOf(e.hexa);if(r<0){this.swatches.unshift(e.hexa);var i=$("<div/>").addClass("swatch").attr("title","Right-click to delete swatch").data("color",e.hexa).css({backgroundColor:e.rgb,width:0,opacity:0}).append($("<div/>").css("background",e.rgba));window.setTimeout(function(){i.css({width:"",opacity:1})},0),this.cpDiv.swatches.prepend(i)}else{if(t)return!1;this.swatches.splice(r,1),this.swatches.unshift(e.hexa),this.cpDiv.swatches.prepend(this.cpDiv.swatches.children().eq(r))}this.swatchLimit&&(this.swatches=this.swatches.slice(0,this.swatchLimit));var s=n?this._get(n,"onAddSwatch"):this._defaults.onAddSwatch;typeof s=="function"&&s(e,this.swatches)}else if(e.length&&e[0])for(var o=e.length-1;o>=0;o--)this.addSwatch(e[o]);return this},deleteSwatch:function(e){var e=$(e);if(typeof e!="object"||!e||!e.length)return!1;this.swatches.splice(this.swatches.indexOf(e.data("color")),1);var t=this._curInst,n=t?this._get(t,"onDeleteSwatch"):this._defaults.onDeleteSwatch;typeof n=="function"&&n(e.data("color"),this.swatches),e.remove()},clearSwatches:function(){return this.swatches=[],this.cpDiv.swatches.empty(),this},_useSwatch:function(e){return $.colorpicker._setColor($.colorpicker._curInst,$(this).data("color")),$.colorpicker._updateColorpicker(),e.preventDefault(),!1},_get:function(e,t){return isset(e.settings[t])?e.settings[t]:this._defaults[t]},_getInst:function(e){try{return $(e).data(PROP_NAME)}catch(t){throw"Missing instance data for this colorpicker"}},hexToRgb:function(e){e=this.validateHex(e);var t="00",n="00",r="00";return e.length==6&&(a="FF",t=e.substring(0,2),n=e.substring(2,4),r=e.substring(4,6)),e.length==8&&(a=e.substring(0,2),t=e.substring(2,4),n=e.substring(4,6),r=e.substring(6,8)),{r:this.hexToInt(t),g:this.hexToInt(n),b:this.hexToInt(r),a:100*this.hexToInt(a)/255}},_hexRegExp:/[a-f0-9]{0,2}([a-f0-9]{6})|[a-f0-9]?([a-f0-9]{3})/i,_hexaRegExp:/([a-f0-9]{8}|[a-f0-9]{6}|[a-f0-9]{4}|[a-f0-9]{3})/i,validateHex:function(e){return e?(e=(""+e).match(this._hexaRegExp),e=e?e[1]||e[2]:"00000000",e=e.toUpperCase(),e.length==3&&(e=e.split(""),e=[e[0],e[0],e[1],e[1],e[2],e[2]].join("")),e.length==4&&(e=e.split(""),e=[e[0],e[0],e[1],e[1],e[2],e[2],e[3],e[3]].join("")),e.length!=8&&(e="FF"+e),e.substring(0,2)=="FF"&&(e=e.substring(2,8)),e):!1},rgbToHex:function(e){var t=this.intToHex(Math.round(e.a*255/100));t=="FF"&&(t="");var n=this.intToHex(e.r)+this.intToHex(e.g)+this.intToHex(e.b);return t+n},intToHex:function(e){var t=parseInt(e).toString(16);return t.length==1&&(t="0"+t),t.toUpperCase()},hexToInt:function(e){return parseInt(e,16)},rgbToLum:function(e){return Math.abs(Math.round((.2126*e.r+.7152*e.g+.0722*e.b)/2.55))},rgbToHsv:function(e){var t=e.r/255,n=e.g/255,r=e.b/255;hsv={h:0,s:0,v:0,a:isset(e._a)?e._a:e.a};var i=0,s=0;return t>=n&&t>=r?(s=t,i=n>r?r:n):n>=r&&n>=t?(s=n,i=t>r?r:t):(s=r,i=n>t?t:n),hsv.v=s,hsv.s=s?(s-i)/s:0,hsv.s?(delta=s-i,t==s?hsv.h=(n-r)/delta:n==s?hsv.h=2+(r-t)/delta:hsv.h=4+(t-n)/delta,hsv.h=hsv.h*60,hsv.h<0&&(hsv.h+=360)):hsv.h=0,hsv.s=Math.abs(hsv.s*100),hsv.v=Math.abs(hsv.v*100),hsv},hsvToRgb:function(e){rgb={r:0,g:0,b:0,a:isset(e._a)?e._a:e.a};var t=isset(e._h)?e._h:e.h,n=isset(e._s)?e._s:e.s,r=isset(e._v)?e._v:e.v;if(n==0)r==0?rgb.r=rgb.g=rgb.b=0:rgb.r=rgb.g=rgb.b=Math.abs(r*255/100);else{t==360&&(t=0),t/=60,n/=100,r/=100;var i=parseInt(t),s=t-i,o=r*(1-n),u=r*(1-n*s),a=r*(1-n*(1-s));switch(i){case 0:rgb.r=r,rgb.g=a,rgb.b=o;break;case 1:rgb.r=u,rgb.g=r,rgb.b=o;break;case 2:rgb.r=o,rgb.g=r,rgb.b=a;break;case 3:rgb.r=o,rgb.g=u,rgb.b=r;break;case 4:rgb.r=a,rgb.g=o,rgb.b=r;break;case 5:rgb.r=r,rgb.g=o,rgb.b=u}rgb.r=Math.abs(Math.round(rgb.r*255)),rgb.g=Math.abs(Math.round(rgb.g*255)),rgb.b=Math.abs(Math.round(rgb.b*255))}return rgb}}),$.fn.colorpicker=function(e){if(!this.length)return this;if(!$.colorpicker.initialized){$(document).mousedown($.colorpicker._checkExternalClick).find("body").append($.colorpicker.cpDiv.hide()).find("#"+mainDivId+"-"+$.colorpicker.mode).closest("li").addClass("selected");for(var t in cpDiv.inputs)if(t){var n=$(cpDiv.inputs[t]);n.data("mode")&&n.focus(function(){var e=$(this);e.closest("li").addClass("selected").siblings(".selected").removeClass("selected"),$.colorpicker._setMode(e.data("mode"))}).closest("li").click(function(){$(this).find("input").focus()}),n.blur(function(){$.colorpicker._updateInputs()});switch(t){case"h":case"s":case"v":case"a":n.keydown(function(e){if(!$.colorpicker._curInst)return;var t=$(this),n=$.colorpicker._curInst;switch(e.keyCode){case 38:case 40:t.val(parseInt(t.val())+(e.shiftKey?10:1)*(e.keyCode==40?-1:1)),n.color.setHsv(cpDiv.inputs.h.val(),cpDiv.inputs.s.val(),cpDiv.inputs.v.val(),cpDiv.inputs.a.val()),$.colorpicker._updateColorpicker(!0);break;case 13:$.colorpicker._submit();break;default:return}}).keyup(function(){if(!$.colorpicker._curInst)return;$.colorpicker._curInst.color.setHsv(cpDiv.inputs.h.val(),cpDiv.inputs.s.val(),cpDiv.inputs.v.val(),cpDiv.inputs.a.val()),$.colorpicker._updateColorpicker()});break;case"r":case"g":case"b":n.keydown(function(e){if(!$.colorpicker._curInst)return;var t=$(this),n=$.colorpicker._curInst;switch(e.keyCode){case 38:case 40:t.val(parseInt(t.val())+(e.shiftKey?10:1)*(e.keyCode==40?-1:1)),n.color.setRgb(cpDiv.inputs.r.val(),cpDiv.inputs.g.val(),cpDiv.inputs.b.val(),cpDiv.inputs.a.val()),$.colorpicker._updateColorpicker(!0);break;case 13:$.colorpicker._submit();break;default:return}}).keyup(function(){if(!$.colorpicker._curInst)return;$.colorpicker._curInst.color.setRgb(cpDiv.inputs.r.val(),cpDiv.inputs.g.val(),cpDiv.inputs.b.val(),cpDiv.inputs.a.val()),$.colorpicker._updateColorpicker()});break;case"hex":n.keydown(function(e){if(!$.colorpicker._curInst)return;switch(e.keyCode){case 13:$.colorpicker._submit();break;default:return}}).keyup(function(){var e=$.colorpicker._curInst;if(!e)return;cpDiv.inputs.hex.val()?(e.color.setHex(cpDiv.inputs.hex.val()),$.colorpicker._updateColorpicker()):(e.color=new $.colorpicker.color({hex:$.colorpicker._defaults.color}),e.color.isNull=$.colorpicker._get(e,"allowNull"),$.colorpicker._updateColorpicker())})}}cpDiv.addSwatchButton.mousedown(function(e){$.colorpicker.addSwatch($.colorpicker._curInst.color)}),cpDiv.swatches.delegate(".swatch","click",function(e){var t=$.proxy($.colorpicker._useSwatch,this);t(e),e.preventDefault()}),cpDiv.swatches.delegate(".swatch","contextmenu",function(e){return confirm("Are you sure you wish to delete this swatch?")&&$.colorpicker.deleteSwatch(this),e.preventDefault(),!1}),cpDiv.oldColorDiv.mousedown($.colorpicker._useSwatch),cpDiv.colorDiv.mousedown(function(e){return $.colorpicker._submit($(this).data("color")),e.preventDefault(),!1}),cpDiv.defaultHeight=cpDiv.outerHeight(),cpDiv.addClass("swatchesOn"),cpDiv.swatchHeight=cpDiv.outerHeight()-cpDiv.defaultHeight,cpDiv.removeClass("swatchesOn").addClass("alphaOn"),cpDiv.alphaHeight=cpDiv.outerHeight()-cpDiv.defaultHeight,cpDiv.removeClass("alphaOn"),cpDiv.d1Div.mousedown(function(e){return $.colorpicker._isDragging=!0,$.colorpicker._mousemoveControl1d(e),$(document).bind("mousemove",$.colorpicker._mousemoveControl1d),!1}),cpDiv.d2Div.mousedown(function(e){return $.colorpicker._isDragging=!0,$.colorpicker._mousemoveControl2d(e),$(document).bind("mousemove",$.colorpicker._mousemoveControl2d),!1}),cpDiv.alphaDiv.mousedown(function(e){return $.colorpicker._isDragging=!0,$.colorpicker._mousemoveControlAlpha(e),$(document).bind("mousemove",$.colorpicker._mousemoveControlAlpha),!1}),$(document).mouseup(function(){return $(document).unbind("mousemove",$.colorpicker._mousemoveControl1d).unbind("mousemove",$.colorpicker._mousemoveControl2d).unbind("mousemove",$.colorpicker._mousemoveControlAlpha),$.colorpicker._isDragging=!1,!1}),$(window).resize(function(){$.colorpicker._colorpickerShowing&&$.colorpicker._positionColorpicker()}),$.colorpicker._setMode($.colorpicker.mode),$.colorpicker.initialized=!0}var r=Array.prototype.slice.call(arguments,1);return e=="option"&&arguments.length==2&&typeof arguments[1]=="string"?$.colorpicker["_"+e+"Colorpicker"].apply($.colorpicker,[this[0]].concat(r)):this.each(function(){typeof e=="string"?$.colorpicker["_"+e+"Colorpicker"].apply($.colorpicker,[this].concat(r)):$.colorpicker._attachColorpicker(this,e)})},$.colorpicker=new Colorpicker,$.colorpicker.initialized=!1,$.colorpicker.uuid=(new Date).getTime()}(jQuery),define("deps/colorpicker",function(){}),function(){var e=this,t=e._,n={},r=Array.prototype,i=Object.prototype,s=Function.prototype,o=r.push,u=r.slice,a=r.concat,f=i.toString,l=i.hasOwnProperty,c=r.forEach,h=r.map,p=r.reduce,d=r.reduceRight,v=r.filter,m=r.every,g=r.some,y=r.indexOf,b=r.lastIndexOf,w=Array.isArray,E=Object.keys,S=s.bind,x=function(e){if(e instanceof x)return e;if(!(this instanceof x))return new x(e);this._wrapped=e};typeof exports!="undefined"?(typeof module!="undefined"&&module.exports&&(exports=module.exports=x),exports._=x):e._=x,x.VERSION="1.6.0";var T=x.each=x.forEach=function(e,t,r){if(e==null)return e;if(c&&e.forEach===c)e.forEach(t,r);else if(e.length===+e.length){for(var i=0,s=e.length;i<s;i++)if(t.call(r,e[i],i,e)===n)return}else{var o=x.keys(e);for(var i=0,s=o.length;i<s;i++)if(t.call(r,e[o[i]],o[i],e)===n)return}return e};x.map=x.collect=function(e,t,n){var r=[];return e==null?r:h&&e.map===h?e.map(t,n):(T(e,function(e,i,s){r.push(t.call(n,e,i,s))}),r)};var N="Reduce of empty array with no initial value";x.reduce=x.foldl=x.inject=function(e,t,n,r){var i=arguments.length>2;e==null&&(e=[]);if(p&&e.reduce===p)return r&&(t=x.bind(t,r)),i?e.reduce(t,n):e.reduce(t);T(e,function(e,s,o){i?n=t.call(r,n,e,s,o):(n=e,i=!0)});if(!i)throw new TypeError(N);return n},x.reduceRight=x.foldr=function(e,t,n,r){var i=arguments.length>2;e==null&&(e=[]);if(d&&e.reduceRight===d)return r&&(t=x.bind(t,r)),i?e.reduceRight(t,n):e.reduceRight(t);var s=e.length;if(s!==+s){var o=x.keys(e);s=o.length}T(e,function(u,a,f){a=o?o[--s]:--s,i?n=t.call(r,n,e[a],a,f):(n=e[a],i=!0)});if(!i)throw new TypeError(N);return n},x.find=x.detect=function(e,t,n){var r;return C(e,function(e,i,s){if(t.call(n,e,i,s))return r=e,!0}),r},x.filter=x.select=function(e,t,n){var r=[];return e==null?r:v&&e.filter===v?e.filter(t,n):(T(e,function(e,i,s){t.call(n,e,i,s)&&r.push(e)}),r)},x.reject=function(e,t,n){return x.filter(e,x.negate(t),n)},x.every=x.all=function(e,t,r){t||(t=x.identity);var i=!0;return e==null?i:m&&e.every===m?e.every(t,r):(T(e,function(e,s,o){if(!(i=i&&t.call(r,e,s,o)))return n}),!!i)};var C=x.some=x.any=function(e,t,r){t||(t=x.identity);var i=!1;return e==null?i:g&&e.some===g?e.some(t,r):(T(e,function(e,s,o){if(i||(i=t.call(r,e,s,o)))return n}),!!i)};x.contains=x.include=function(e,t){return e==null?!1:y&&e.indexOf===y?e.indexOf(t)!=-1:C(e,function(e){return e===t})},x.invoke=function(e,t){var n=u.call(arguments,2),r=x.isFunction(t);return x.map(e,function(e){return(r?t:e[t]).apply(e,n)})},x.pluck=function(e,t){return x.map(e,x.property(t))},x.where=function(e,t){return x.filter(e,x.matches(t))},x.findWhere=function(e,t){return x.find(e,x.matches(t))},x.max=function(e,t,n){var r=-Infinity,i=-Infinity,s,o;if(!t&&x.isArray(e))for(var u=0,a=e.length;u<a;u++)s=e[u],s>r&&(r=s);else T(e,function(e,s,u){o=t?t.call(n,e,s,u):e,o>i&&(r=e,i=o)});return r},x.min=function(e,t,n){var r=Infinity,i=Infinity,s,o;if(!t&&x.isArray(e))for(var u=0,a=e.length;u<a;u++)s=e[u],s<r&&(r=s);else T(e,function(e,s,u){o=t?t.call(n,e,s,u):e,o<i&&(r=e,i=o)});return r},x.shuffle=function(e){var t,n=0,r=[];return T(e,function(e){t=x.random(n++),r[n-1]=r[t],r[t]=e}),r},x.sample=function(e,t,n){return t==null||n?(e.length!==+e.length&&(e=x.values(e)),e[x.random(e.length-1)]):x.shuffle(e).slice(0,Math.max(0,t))};var k=function(e){return e==null?x.identity:x.isFunction(e)?e:x.property(e)};x.sortBy=function(e,t,n){return t=k(t),x.pluck(x.map(e,function(e,r,i){return{value:e,index:r,criteria:t.call(n,e,r,i)}}).sort(function(e,t){var n=e.criteria,r=t.criteria;if(n!==r){if(n>r||n===void 0)return 1;if(n<r||r===void 0)return-1}return e.index-t.index}),"value")};var L=function(e){return function(t,n,r){var i={};return n=k(n),T(t,function(s,o){var u=n.call(r,s,o,t);e(i,u,s)}),i}};x.groupBy=L(function(e,t,n){x.has(e,t)?e[t].push(n):e[t]=[n]}),x.indexBy=L(function(e,t,n){e[t]=n}),x.countBy=L(function(e,t){x.has(e,t)?e[t]++:e[t]=1}),x.sortedIndex=function(e,t,n,r){n=k(n);var i=n.call(r,t),s=0,o=e.length;while(s<o){var u=s+o>>>1;n.call(r,e[u])<i?s=u+1:o=u}return s},x.toArray=function(e){return e?x.isArray(e)?u.call(e):e.length===+e.length?x.map(e,x.identity):x.values(e):[]},x.size=function(e){return e==null?0:e.length===+e.length?e.length:x.keys(e).length},x.first=x.head=x.take=function(e,t,n){return e==null?void 0:t==null||n?e[0]:t<0?[]:u.call(e,0,t)},x.initial=function(e,t,n){return u.call(e,0,e.length-(t==null||n?1:t))},x.last=function(e,t,n){return e==null?void 0:t==null||n?e[e.length-1]:u.call(e,Math.max(e.length-t,0))},x.rest=x.tail=x.drop=function(e,t,n){return u.call(e,t==null||n?1:t)},x.compact=function(e){return x.filter(e,x.identity)};var A=function(e,t,n,r){if(t&&x.every(e,x.isArray))return a.apply(r,e);for(var i=0,s=e.length;i<s;i++){var u=e[i];!x.isArray(u)&&!x.isArguments(u)?n||r.push(u):t?o.apply(r,u):A(u,t,n,r)}return r};x.flatten=function(e,t){return A(e,t,!1,[])},x.without=function(e){return x.difference(e,u.call(arguments,1))},x.partition=function(e,t,n){t=k(t);var r=[],i=[];return T(e,function(e){(t.call(n,e)?r:i).push(e)}),[r,i]},x.uniq=x.unique=function(e,t,n,r){if(e==null)return[];x.isFunction(t)&&(r=n,n=t,t=!1);var i=[],s=[];for(var o=0,u=e.length;o<u;o++){var a=e[o];n&&(a=n.call(r,a,o,e));if(t?!o||s!==a:!x.contains(s,a))t?s=a:s.push(a),i.push(e[o])}return i},x.union=function(){return x.uniq(A(arguments,!0,!0,[]))},x.intersection=function(e){var t=u.call(arguments,1);return x.filter(x.uniq(e),function(e){return x.every(t,function(t){return x.contains(t,e)})})},x.difference=function(e){var t=A(u.call(arguments,1),!0,!0,[]);return x.filter(e,function(e){return!x.contains(t,e)})},x.zip=function(){var e=x.max(x.pluck(arguments,"length").concat(0)),t=new Array(e);for(var n=0;n<e;n++)t[n]=x.pluck(arguments,""+n);return t},x.object=function(e,t){if(e==null)return{};var n={};for(var r=0,i=e.length;r<i;r++)t?n[e[r]]=t[r]:n[e[r][0]]=e[r][1];return n},x.indexOf=function(e,t,n){if(e==null)return-1;var r=0,i=e.length;if(n){if(typeof n!="number")return r=x.sortedIndex(e,t),e[r]===t?r:-1;r=n<0?Math.max(0,i+n):n}if(y&&e.indexOf===y)return e.indexOf(t,n);for(;r<i;r++)if(e[r]===t)return r;return-1},x.lastIndexOf=function(e,t,n){if(e==null)return-1;var r=n!=null;if(b&&e.lastIndexOf===b)return r?e.lastIndexOf(t,n):e.lastIndexOf(t);var i=r?n:e.length;while(i--)if(e[i]===t)return i;return-1},x.range=function(e,t,n){arguments.length<=1&&(t=e||0,e=0),n=arguments[2]||1;var r=Math.max(Math.ceil((t-e)/n),0),i=0,s=new Array(r);while(i<r)s[i++]=e,e+=n;return s};var O=function(){};x.bind=function(e,t){var n,r;if(S&&e.bind===S)return S.apply(e,u.call(arguments,1));if(!x.isFunction(e))throw new TypeError;return n=u.call(arguments,2),r=function(){if(this instanceof r){O.prototype=e.prototype;var i=new O;O.prototype=null;var s=e.apply(i,n.concat(u.call(arguments)));return Object(s)===s?s:i}return e.apply(t,n.concat(u.call(arguments)))}},x.partial=function(e){var t=u.call(arguments,1);return function(){var n=0,r=t.slice();for(var i=0,s=r.length;i<s;i++)r[i]===x&&(r[i]=arguments[n++]);while(n<arguments.length)r.push(arguments[n++]);return e.apply(this,r)}},x.bindAll=function(e){var t=u.call(arguments,1);if(t.length===0)throw new Error("bindAll must be passed function names");return T(t,function(t){e[t]=x.bind(e[t],e)}),e},x.memoize=function(e,t){var n={};return t||(t=x.identity),function(){var r=t.apply(this,arguments);return x.has(n,r)?n[r]:n[r]=e.apply(this,arguments)}},x.delay=function(e,t){var n=u.call(arguments,2);return setTimeout(function(){return e.apply(null,n)},t)},x.defer=function(e){return x.delay.apply(x,[e,1].concat(u.call(arguments,1)))},x.throttle=function(e,t,n){var r,i,s,o=null,u=0;n||(n={});var a=function(){u=n.leading===!1?0:x.now(),o=null,s=e.apply(r,i),r=i=null};return function(){var f=x.now();!u&&n.leading===!1&&(u=f);var l=t-(f-u);return r=this,i=arguments,l<=0||l>t?(clearTimeout(o),o=null,u=f,s=e.apply(r,i),r=i=null):!o&&n.trailing!==!1&&(o=setTimeout(a,l)),s}},x.debounce=function(e,t,n){var r,i,s,o,u,a=function(){var f=x.now()-o;f<t&&f>0?r=setTimeout(a,t-f):(r=null,n||(u=e.apply(s,i),s=i=null))};return function(){s=this,i=arguments,o=x.now();var f=n&&!r;return r||(r=setTimeout(a,t)),f&&(u=e.apply(s,i),s=i=null),u}},x.once=function(e){var t=!1,n;return function(){return t?n:(t=!0,n=e.apply(this,arguments),e=null,n)}},x.wrap=function(e,t){return x.partial(t,e)},x.negate=function(e){return function(){return!e.apply(this,arguments)}},x.compose=function(){var e=arguments;return function(){var t=arguments;for(var n=e.length-1;n>=0;n--)t=[e[n].apply(this,t)];return t[0]}},x.after=function(e,t){return function(){if(--e<1)return t.apply(this,arguments)}},x.keys=function(e){if(!x.isObject(e))return[];if(E)return E(e);var t=[];for(var n in e)x.has(e,n)&&t.push(n);return t},x.values=function(e){var t=x.keys(e),n=t.length,r=new Array(n);for(var i=0;i<n;i++)r[i]=e[t[i]];return r},x.pairs=function(e){var t=x.keys(e),n=t.length,r=new Array(n);for(var i=0;i<n;i++)r[i]=[t[i],e[t[i]]];return r},x.invert=function(e){var t={},n=x.keys(e);for(var r=0,i=n.length;r<i;r++)t[e[n[r]]]=n[r];return t},x.functions=x.methods=function(e){var t=[];for(var n in e)x.isFunction(e[n])&&t.push(n);return t.sort()},x.extend=function(e){return T(u.call(arguments,1),function(t){if(t)for(var n in t)e[n]=t[n]}),e},x.pick=function(e,t,n){var i={};if(x.isFunction(t))for(var s in e){var o=e[s];t.call(n,o,s,e)&&(i[s]=o)}else{var f=a.apply(r,u.call(arguments,1));for(var l=0,c=f.length;l<c;l++){var s=f[l];s in e&&(i[s]=e[s])}}return i},x.omit=function(e,t,n){var i;return x.isFunction(t)?t=x.negate(t):(i=a.apply(r,u.call(arguments,1)),t=function(e,t){return!x.contains(i,t)}),x.pick(e,t,n)},x.defaults=function(e){return T(u.call(arguments,1),function(t){if(t)for(var n in t)e[n]===void 0&&(e[n]=t[n])}),e},x.clone=function(e){return x.isObject(e)?x.isArray(e)?e.slice():x.extend({},e):e},x.tap=function(e,t){return t(e),e};var M=function(e,t,n,r){if(e===t)return e!==0||1/e==1/t;if(e==null||t==null)return e===t;e instanceof x&&(e=e._wrapped),t instanceof x&&(t=t._wrapped);var i=f.call(e);if(i!=f.call(t))return!1;switch(i){case"[object String]":return e==String(t);case"[object Number]":return e!=+e?t!=+t:e==0?1/e==1/t:e==+t;case"[object Date]":case"[object Boolean]":return+e==+t;case"[object RegExp]":return e.source==t.source&&e.global==t.global&&e.multiline==t.multiline&&e.ignoreCase==t.ignoreCase}if(typeof e!="object"||typeof t!="object")return!1;var s=n.length;while(s--)if(n[s]==e)return r[s]==t;var o=e.constructor,u=t.constructor;if(o!==u&&!(x.isFunction(o)&&o instanceof o&&x.isFunction(u)&&u instanceof u)&&"constructor"in e&&"constructor"in t)return!1;n.push(e),r.push(t);var a=0,l=!0;if(i=="[object Array]"){a=e.length,l=a==t.length;if(l)while(a--)if(!(l=M(e[a],t[a],n,r)))break}else{for(var c in e)if(x.has(e,c)){a++;if(!(l=x.has(t,c)&&M(e[c],t[c],n,r)))break}if(l){for(c in t)if(x.has(t,c)&&!(a--))break;l=!a}}return n.pop(),r.pop(),l};x.isEqual=function(e,t){return M(e,t,[],[])},x.isEmpty=function(e){if(e==null)return!0;if(x.isArray(e)||x.isString(e))return e.length===0;for(var t in e)if(x.has(e,t))return!1;return!0},x.isElement=function(e){return!!e&&e.nodeType===1},x.isArray=w||function(e){return f.call(e)=="[object Array]"},x.isObject=function(e){return e===Object(e)},T(["Arguments","Function","String","Number","Date","RegExp"],function(e){x["is"+e]=function(t){return f.call(t)=="[object "+e+"]"}}),x.isArguments(arguments)||(x.isArguments=function(e){return!!e&&!!x.has(e,"callee")}),typeof /./!="function"&&(x.isFunction=function(e){return typeof e=="function"}),x.isFinite=function(e){return isFinite(e)&&!isNaN(parseFloat(e))},x.isNaN=function(e){return x.isNumber(e)&&e!=+e},x.isBoolean=function(e){return e===!0||e===!1||f.call(e)=="[object Boolean]"},x.isNull=function(e){return e===null},x.isUndefined=function(e){return e===void 0},x.has=function(e,t){return l.call(e,t)},x.noConflict=function(){return e._=t,this},x.identity=function(e){return e},x.constant=function(e){return function(){return e}},x.noop=function(){},x.property=function(e){return function(t){return t[e]}},x.matches=function(e){return function(t){if(t===e)return!0;for(var n in e)if(e[n]!==t[n])return!1;return!0}},x.times=function(e,t,n){var r=Array(Math.max(0,e));for(var i=0;i<e;i++)r[i]=t.call(n,i);return r},x.random=function(e,t){return t==null&&(t=e,e=0),e+Math.floor(Math.random()*(t-e+1))},x.now=Date.now||function(){return(new Date).getTime()};var _={escape:{"&":"&","<":"<",">":">",'"':""","'":"'"}};_.unescape=x.invert(_.escape);var D={escape:new RegExp("["+x.keys(_.escape).join("")+"]","g"),unescape:new RegExp("("+x.keys(_.unescape).join("|")+")","g")};x.each(["escape","unescape"],function(e){x[e]=function(t){return t==null?"":(""+t).replace(D[e],function(t){return _[e][t]})}}),x.result=function(e,t){if(e==null)return void 0;var n=e[t];return x.isFunction(n)?n.call(e):n},x.mixin=function(e){T(x.functions(e),function(t){var n=x[t]=e[t];x.prototype[t]=function(){var e=[this._wrapped];return o.apply(e,arguments),F.call(this,n.apply(x,e))}})};var P=0;x.uniqueId=function(e){var t=++P+"";return e?e+t:t},x.templateSettings={evaluate:/<%([\s\S]+?)%>/g,interpolate:/<%=([\s\S]+?)%>/g,escape:/<%-([\s\S]+?)%>/g};var H=/(.)^/,B={"'":"'","\\":"\\","\r":"r","\n":"n"," ":"t","\u2028":"u2028","\u2029":"u2029"},j=/\\|'|\r|\n|\t|\u2028|\u2029/g;x.template=function(e,t,n){var r;n=x.defaults({},n,x.templateSettings);var i=new RegExp([(n.escape||H).source,(n.interpolate||H).source,(n.evaluate||H).source].join("|")+"|$","g"),s=0,o="__p+='";e.replace(i,function(t,n,r,i,u){return o+=e.slice(s,u).replace(j,function(e){return"\\"+B[e]}),n&&(o+="'+\n((__t=("+n+"))==null?'':_.escape(__t))+\n'"),r&&(o+="'+\n((__t=("+r+"))==null?'':__t)+\n'"),i&&(o+="';\n"+i+"\n__p+='"),s=u+t.length,t}),o+="';\n",n.variable||(o="with(obj||{}){\n"+o+"}\n"),o="var __t,__p='',__j=Array.prototype.join,print=function(){__p+=__j.call(arguments,'');};\n"+o+"return __p;\n";try{r=new Function(n.variable||"obj","_",o)}catch(u){throw u.source=o,u}if(t)return r(t,x);var a=function(e){return r.call(this,e,x)};return a.source="function("+(n.variable||"obj")+"){\n"+o+"}",a},x.chain=function(e){return x(e).chain()};var F=function(e){return this._chain?x(e).chain():e};x.mixin(x),T(["pop","push","reverse","shift","sort","splice","unshift"],function(e){var t=r[e];x.prototype[e]=function(){var n=this._wrapped;return t.apply(n,arguments),(e=="shift"||e=="splice")&&n.length===0&&delete n[0],F.call(this,n)}}),T(["concat","join","slice"],function(e){var t=r[e];x.prototype[e]=function(){return F.call(this,t.apply(this._wrapped,arguments))}}),x.extend(x.prototype,{chain:function(){return this._chain=!0,this},value:function(){return this._wrapped}}),typeof define=="function"&&define.amd&&define("underscore",[],function(){return x})}.call(this),define("util.image-uploader",["jquery","underscore"],function(e,t){openImageUploader=function(t){if(!boxExists("input-image")){isNaN(Headway.currentLayout)&&(iframePostID=0);var n={id:"input-image",title:"Select an image",description:"Upload or select an image",src:Headway.homeURL+"/?headway-trigger=media-uploader",load:function(){initiateImageUploader(t)},width:e(window).width()-200,height:e(window).height()-200,center:!0,draggable:!1,deleteWhenClosed:!0,blackOverlay:!0},r=createBox(n);e("#box-input-image").css({width:"auto",height:"auto",top:"70px",left:"70px",right:"70px",bottom:"70px",margin:0})}openBox("input-image")},initiateImageUploader=function(n){if(!e("#box-input-image iframe").length||typeof e("#box-input-image iframe")[0].contentWindow.wp=="undefined"||typeof e("#box-input-image iframe")[0].contentWindow.wp.media=="undefined"||typeof e("#box-input-image iframe")[0].contentWindow.wp.media()=="undefined")return setTimeout(function(){initiateImageUploader(n)},100);wpMedia=e("#box-input-image iframe")[0].contentWindow.wp.media;var r=parent.Headway.currentLayout.split("-");return t.first(r)=="single"&&!isNaN(t.last(r))&&(wpMedia.model.settings.post.id=t.last(r)),wpMedia.frames={file_frame:wpMedia({title:"",button:{text:"Use Image"},multiple:!1})},wpMedia.frames.file_frame.on("select",function(){attachment=wpMedia.frames.file_frame.state().get("selection").first().toJSON();if(typeof e=="undefined")var e=attachment.url;var t=e.split("/")[e.split("/").length-1];n(e,t),parent.closeBox("input-image",!0)}),wpMedia.frames.file_frame.on("escape",function(){parent.closeBox("input-image",!0)}),wpMedia.frames.file_frame.open()}}),define("modules/panel.inputs",["jquery","deps/colorpicker","util.image-uploader"],function($){handleInputTogglesInContainer=function(e){e.each(function(){$(this).find('[id*="input-"]').reverse().each(function(){handleInputToggle($(this))})})},handleInputToggle=function(e,t){if(!e||!e.length||typeof e.attr("data-toggle")=="undefined")return;var n=$.parseJSON(e.attr("data-toggle")),r=".panel";if(e.parents(".repeater-group").length)var r=".repeater-group";if(typeof t=="undefined")var t=e.val().toString();e.attr("type")=="checkbox"&&(e.is(":checked")?t="true":t="false");if(t&&n&&typeof n=="object"&&n.hasOwnProperty(t)){if(typeof n[t].show=="string"){var i=e.parents(r).find(n[t].show);i.show(),i.find("*[data-toggle]").not(e).each(function(){handleInputToggle($(this))})}else typeof n[t].show=="object"&&$.each(n[t].show,function(t,n){var i=e.parents(r).find(n).show();i.show(),i.find("*[data-toggle]").not(e).each(function(){handleInputToggle($(this))})});if(typeof n[t].hide=="string"){var s=e.parents(r).find(n[t].hide);s.find("*[data-toggle]").not(e).each(function(){handleInputToggleHideAll($(this))}),s.hide()}else typeof n[t].hide=="object"&&$.each(n[t].hide,function(t,n){var i=e.parents(r).find(n);i.find("*[data-toggle]").not(e).each(function(){handleInputToggleHideAll($(this))}),i.hide()})}},handleInputToggleHideAll=function(e){if(!e||!e.length||typeof e.attr("data-toggle")=="undefined")return;var t=$.parseJSON(e.attr("data-toggle")),n=".panel";if(e.parents(".input").parent().attr("class")==="repeater-group")var n=".repeater-group";$.each(t,function(t,r){if(typeof r.hide=="undefined"||!r.hide||!r.hide.length)return;if(typeof r.hide=="string"){var i=e.parents(n).find(r.hide);i.hide()}else typeof r.hide=="object"&&$.each(r.hide,function(t,r){var i=e.parents(n).find(r);i.hide()})})};var panelInputs={delegate:function(){var context="div#panel";$(context).delegate("div.input-select select","change",function(){dataHandleInput($(this));var e=$(this),t=$(this).val();handleInputToggle(e,t)}),$(context).delegate("div.input-text input","keyup blur",function(){dataHandleInput($(this))}),$(context).delegate("div.input-textarea textarea","keyup blur",function(){dataHandleInput($(this))}),$(context).delegate("div.input-textarea span.textarea-open","click",function(){var e=$(this).siblings(".textarea-container"),t=e.find("textarea"),n=$(this).parents(".input").offset();e.css({top:n.top-e.outerHeight(!0),left:n.left}),$("div.sub-tabs-content-container").css("overflow-y","hidden"),e.data("visible")!==!0?(e.show(),e.data("visible",!0),t.trigger("focus"),$(document).bind("mousedown",{textareaContainer:e},textareaClose),Headway.iframe.contents().bind("mousedown",{textareaContainer:e},textareaClose),$(window).bind("resize",{textareaContainer:e},textareaClose)):(e.hide(),e.data("visible",!1),$("div.sub-tabs-content-container").css("overflow-y","auto"),$(document).unbind("mousedown",textareaClose),Headway.iframe.contents().unbind("mousedown",textareaClose),$(window).unbind("resize",textareaClose))}),textareaClose=function(e){if($(e.target).parents("div.input-textarea div.input-right").length===1)return;var t=e.data.textareaContainer;t.hide(),t.data("visible",!1),$("div.sub-tabs-content-container").css("overflow-y","auto"),$(document).unbind("mousedown",textareaClose),Headway.iframe.contents().unbind("mousedown",textareaClose),$(window).unbind("resize",textareaClose)},inputWYSIWYGChange=function(e){dataHandleInput(this.$element,this.get())},inputWYSIWYGTextareaChange=function(){dataHandleInput($(this))},$(context).delegate("div.input-wysiwyg span.wysiwyg-open","click",function(){var e=$(this).siblings(".wysiwyg-container"),t=$(this).parents(".input").offset(),n=t.top-e.outerHeight(!0);n<50&&(n=50),e.css({top:n,left:t.left}),$("div.sub-tabs-content-container").css("overflow-y","hidden");if(e.data("visible")!==!0){e.show(),e.css("marginLeft",""),e.data("visible",!0);if($("div#side-panel-container").length)var r=$("div#side-panel-container").outerWidth()-$("div#side-panel-container").css("right").replace("px","");else var r=0;var i=$(document).width()-r-(e.offset().left+e.width());i<0&&e.css("marginLeft",i-30);var s=function(){e.find("textarea").redactor({path:Headway.headwayURL+"/library/resources/redactor/",plugins:["fontcolor","fontsize"],buttons:["html","|","formatting","|","bold","italic","deleted","|","unorderedlist","orderedlist","outdent","indent","|","table","link","|","image","|","alignleft","aligncenter","alignright","|","horizontalrule"],allowedTags:["inline","code","span","div","label","a","br","p","b","i","del","strike","u","img","video","audio","iframe","object","embed","param","blockquote","mark","cite","small","ul","ol","li","hr","dl","dt","dd","sup","sub","big","pre","code","figure","figcaption","strong","em","table","tr","td","th","tbody","thead","tfoot","h1","h2","h3","h4","h5","h6","frame","frameset","script","hgroup","form","label","input","textarea","select","fieldset","legend"],iframe:!0,css:Headway.headwayURL+"/library/resources/redactor/css/redactor-iframe.css",changeCallback:inputWYSIWYGChange,blurCallback:inputWYSIWYGChange,imageUpload:Headway.ajaxURL+"?action=headway_visual_editor&method=redactor_upload_image&security="+Headway.security,convertDivs:!1}),e.find("textarea").bind("keyup",inputWYSIWYGTextareaChange),e.find("textarea").redactor("focusEnd"),e.data("setupRedactor",!0)};if($("body").data("loadedRedactor")!==!0){var o=$("<link>").attr({rel:"stylesheet",href:Headway.headwayURL+"/library/resources/redactor/css/redactor.css",type:"text/css",media:"screen"}).appendTo($("head")),u=jQuery.ajax({dataType:"script",cache:!0,url:Headway.headwayURL+"/library/resources/redactor/redactor.min.js"}),a=jQuery.ajax({dataType:"script",cache:!0,url:Headway.headwayURL+"/library/resources/redactor/fontcolor.js"}),f=jQuery.ajax({dataType:"script",cache:!0,url:Headway.headwayURL+"/library/resources/redactor/fontsize.js"});$.when(u,a,f).then(function(){s(),$("body").data("loadedRedactor",!0)})}else $("body").data("loadedRedactor")===!0&&e.data("setupRedactor")!==!0?s():e.find("textarea").redactor("focusEnd");$(document).bind("mousedown",{wysiwygContainer:e},wysiwygClose),Headway.iframe.contents().bind("mousedown",{wysiwygContainer:e},wysiwygClose),$(window).bind("resize",{wysiwygContainer:e},wysiwygClose)}else e.hide(),e.data("visible",!1),$("div.sub-tabs-content-container").css("overflow-y","auto"),$(document).unbind("mousedown",wysiwygClose),Headway.iframe.contents().unbind("mousedown",wysiwygClose),$(window).unbind("resize",wysiwygClose)}),wysiwygClose=function(e){if($(e.target).parents("div.input-wysiwyg div.input-right").length===1||$(e.target).parents(".redactor_dropdown").length===1||$(e.target).parents("#redactor_modal").length===1)return;var t=e.data.wysiwygContainer;t.hide(),t.data("visible",!1),$("div.sub-tabs-content-container").css("overflow-y","auto"),$(document).unbind("mousedown",wysiwygClose),Headway.iframe.contents().unbind("mousedown",wysiwygClose),$(window).unbind("resize",wysiwygClose)},$(context).delegate("div.input-integer input","focus",function(){typeof originalValues!="undefined"&&delete originalValues,originalValues=new Object,originalValues[$(this).attr("name")]=$(this).val()}),$(context).delegate("div.input-integer input","keyup blur",function(e){t=$(this).val();if(e.type=="keyup"&&t=="-")return;if(isNaN(t)){t=t.replace(/[^0-9]*/ig,"");if(t==="")var t=originalValues[$(this).attr("name")];$(this).val(t)}t.length>1&&t[0]==0&&(t=t.replace(/^[0]+/g,""),$(this).val(t)),dataHandleInput($(this),t)}),$(context).delegate("div.input-checkbox input","change",function(e){var t=$(this).parents(".input-checkbox").first(),n=t.find("input"),r=t.find("label"),i=n.is(":checked");return Headway.history.add({up:function(){n.val(i),n.prop("checked",i),dataHandleInput(n,i),handleInputToggle(n,i),n.trigger("blur")},down:function(){var e=!e;n.val(e),n.prop("checked",e),dataHandleInput(n,e),handleInputToggle(n,e),n.trigger("blur")}}),allowSaving(),e.preventDefault(),e.stopPropagation(),!1}),$(context).delegate("div.input-multi-select select","click",function(){dataHandleInput($(this))}),$(context).delegate("div.input-multi-select span.multi-select-open","click",function(){var e=$(this).siblings(".multi-select-container"),t=e.find("select"),n=$(this).parents(".input").offset();e.css({top:n.top-e.outerHeight(!0),left:n.left}),$("div.sub-tabs-content-container").css("overflow-y","hidden"),e.data("visible")!==!0?(e.show(),e.data("visible",!0),$(document).bind("mousedown",{multiSelectContainer:e},multiSelectClose),Headway.iframe.contents().bind("mousedown",{multiSelectContainer:e},multiSelectClose),$(window).bind("resize",{multiSelectContainer:e},multiSelectClose)):(e.hide(),e.data("visible",!1),$("div.sub-tabs-content-container").css("overflow-y","auto"),$(document).unbind("mousedown",multiSelectClose),Headway.iframe.contents().unbind("mousedown",multiSelectClose),$(window).unbind("resize",multiSelectClose))}),multiSelectClose=function(e){if($(e.target).parents("div.input-multi-select div.input-right").length===1)return;var t=e.data.multiSelectContainer;t.hide(),t.data("visible",!1),$("div.sub-tabs-content-container").css("overflow-y","auto"),$(document).unbind("mousedown",multiSelectClose),Headway.iframe.contents().unbind("mousedown",multiSelectClose),$(window).unbind("resize",multiSelectClose)},$(context).delegate("div.input-image span.button","click",function(){var e=this;openImageUploader(function(t,n){$(e).siblings("input").val(t),$(e).siblings("span.src").show().text(n),$(e).siblings("span.delete-image").show(),dataHandleInput($(e).siblings("input"),t,{action:"add"})})}),$(context).delegate("div.input-image span.delete-image","click",function(){if(!confirm("Are you sure you wish to remove this image?"))return!1;$(this).siblings(".src").hide(),$(this).hide(),$(this).siblings("input").val(""),dataHandleInput($(this).siblings("input"),"",{action:"delete"})}),updateRepeaterValues=function(e){var t={};return e.find("div.repeater-group:visible").each(function(e){var n={};$(this).find("select, input, textarea").each(function(){var e=$(this).val();$(this).is('[type="checkbox"]')&&!$(this).is(":checked")&&(e=!1),n[$(this).attr("name")]=e}),t[e]=n}),dataHandleInput(e.find("input.repeater-group-input"),t)},$(context).delegate("div.repeater .add-group","click",function(){var e=$(this).parents("div.repeater"),t=$(this).parents("div.repeater-group"),n=e.find(".repeater-group-template");if(e.hasClass("limit-met"))return;var r=n.clone().hide().removeClass("repeater-group-template");r.insertAfter(t).fadeIn(300),e.find(".repeater-group-single").removeClass("repeater-group-single");var i=e.data("repeater-limit");!isNaN(i)&&i>=1&&e.find("div.repeater-group:not(.repeater-group-template):visible").length==i&&e.addClass("limit-met"),updateRepeaterValues(e)}),$(context).delegate("div.repeater .remove-group","click",function(){if(!confirm("Are you sure?"))return;var e=$(this).parents("div.repeater"),t=$(this).parents("div.repeater-group");t.fadeOut(300,function(){e.find("div.repeater-group:visible").length===1&&e.find("div.repeater-group:visible").addClass("repeater-group-single");var t=e.data("repeater-limit");!isNaN(t)&&t>=1&&e.find("div.repeater-group:not(.repeater-group-template):visible").length<t&&e.removeClass("limit-met"),updateRepeaterValues(e)})}),$(context).delegate("div.input-colorpicker div.colorpicker-box","click",function(){$("div.sub-tabs-content-container").css("overflow-y","hidden");var input=$(this).parent().siblings("input"),inputVal=input.val();inputVal=="transparent"&&(inputVal="00FFFFFF");var colorpickerHandleVal=function(color,inst){var colorValue="#"+color.hex;if(color.a!=100)var colorValue=color.rgba;input.val(colorValue),dataHandleInput(input,colorValue);var callback=eval(input.attr("data-callback"));typeof callback=="function"&&callback({input:input,value:color.rgba,colorObj:color})};$(this).colorpicker({realtime:!0,alpha:!0,alphaHex:!0,allowNull:!1,swatches:typeof Headway.colorpickerSwatches=="object"&&Headway.colorpickerSwatches.length?Headway.colorpickerSwatches:!0,color:inputVal,showAnim:!1,beforeShow:function(e,t){showIframeOverlay()},onClose:function(e,t){colorpickerHandleVal(e,t),hideIframeOverlay(),$("div.sub-tabs-content-container").css("overflow-y","auto")},onSelect:function(e,t){colorpickerHandleVal(e,t)},onAddSwatch:function(e,t){dataSetOption("general","colorpicker-swatches",t)},onDeleteSwatch:function(e,t){dataSetOption("general","colorpicker-swatches",t)}}),$.colorpicker._showColorpicker($(this)),setupTooltips()}),$(context).delegate("div.input-button span.button","click",function(){dataHandleInput($(this))}),$(context).delegate("div.input-import-file span.button","click",function(){$(this).siblings('input[type="file"]').trigger("click")}),$(context).delegate('div.input-import-file input[type="file"]',"change",function(e){if(e.target.files[0].name.split(".").slice(-1)[0]!="json")return $(this).val(null),alert("Invalid Headway import file. Please be sure that the Headway import file is a valid JSON formatted file.");$(this).siblings("span.src").show().text($(this).val().split(/(\\|\/)/g).pop()),$(this).siblings("span.delete-file").show(),dataHandleInput($(this))}),$(context).delegate("div.input-import-file .delete-file","click",function(){if(!confirm("Are you sure?"))return;$(this).fadeOut(100),$(this).siblings("span.src").fadeOut(100);var fileInput=$(this).siblings('input[type="file"]'),callback=eval(fileInput.attr("data-callback"));fileInput.val(null),dataHandleInput(fileInput)})},bind:function(e){if(typeof t=="undefined")var t="div#panel";$("div.input-slider div.input-slider-bar",t).each(function(){var e=this,t=parseInt($(this).parents(".input-slider").find("input.input-slider-bar-hidden").val()),n=parseInt($(this).attr("slider_min")),r=parseInt($(this).attr("slider_max")),i=parseInt($(this).attr("slider_interval")),s=$(this).siblings("div.input-slider-bar-text").find(".input-slider-bar-input"),o=function(e,t){Headway.history.add({up:function(){$(e).val(t),$(e).prev().text(t),$(e).parents(".input-slider").find(".input-slider-bar").slider("value",t),dataHandleInput($(e).parents(".input-slider").find("input.input-slider-bar-hidden"),t)},down:function(){var t=$(e).parents(".input-slider").find("input.input-slider-bar-hidden").data("value-original");$(e).val(t),$(e).prev().text(t),$(e).parents(".input-slider").find(".input-slider-bar").slider("value",t),dataHandleInput($(e).parents(".input-slider").find("input.input-slider-bar-hidden"),t)}})};$(this).slider({range:"min",value:t,min:n,max:r,step:i,start:function(e,t){$(this).parents(".input-slider").find("input.input-slider-bar-hidden").data("value-original",t.value)},slide:function(e,t){$(this).siblings("div.input-slider-bar-text").find(".input-slider-bar-input").val(t.value),$(this).parents(".input-slider").find("input.input-slider-bar-hidden").val(t.value),dataHandleInput($(this).parents(".input-slider").find("input.input-slider-bar-hidden"),t.value)},stop:function(e,t){o(s,t.value)}}),s.on("keydown",function(e){var t=e.charCode||e.keyCode||0;return t==8||t==9||t==46||t==110||t>=35&&t<=40||t>=48&&t<=57||t>=96&&t<=105}),s.on("focus",function(e){$(this).parents(".input-slider").find("input.input-slider-bar-hidden").data("value-original",$(this).val())}),s.on("keyup change",function(e){if(e.which===13)return;if(this.value<=r&&this.value>=n){var t=this;o(this,this.value)}}),s.on("blur",function(e){var t=this.value;this.value>r?t=r:this.value<n&&(t=n),o(this,t)})}),$(".repeater-sortable",t).sortable({items:".repeater-group",containment:"parent",forcePlaceholderSize:!0,handle:".sortable-handle",stop:function(){updateRepeaterValues($(this))}}),$(".repeater",t).each(function(){var e=$(this).data("repeater-limit");!isNaN(e)&&e>=1&&$(this).find("div.repeater-group:not(.repeater-group-template):visible").length>=e&&$(this).addClass("limit-met")})}};return panelInputs}),define("modules/panel",["jquery","jqueryUI","deps/jquery.cookie","util.tooltips","modules/panel.inputs"],function(e,t,n,r,i){selectTab=function(e,t){var n=t.find(".ui-tabs-nav"),r=n.find('li[aria-controls="'+e+'"] a').length?n.find('li[aria-controls="'+e+'"] a'):n.find('li[aria-controls="'+e+'-content"] a');return r.trigger("click")},addPanelTab=function(t,n,r,i,s,o){if(e('ul#panel-top li a[href="#'+t+'-tab"]').length!==0)return!1;if(typeof i=="undefined")var i=!1;if(typeof s=="undefined")var s=!1;if(typeof o=="undefined")var o=!1;var u=e('<li><a href="#'+t+'-tab">'+n+"</a></li>").appendTo("div#panel #panel-top"),a=e('<div id="'+t+'-tab"></div>').appendTo("div#panel"),f=u.find("a");e("div#panel").tabs("refresh"),e(f).bind("click",showPanel),showPanel(),e("body").removeClass("panel-empty"),a.addClass("panel");if(typeof r=="string")a.html(r);else{var l=r.url,c=r.data||!1,h=function(){typeof r.callback=="function"&&r.callback.call()};createCog(a,!0),e("div#panel div#"+t+"-tab").load(l,c,h)}return o&&a.addClass("panel-"+o),i&&f.parent().append('<span class="close">X</span>'),f.parent().addClass("tab-close-on-layout-switch"),u},removePanelTab=function(t){var t=t.replace("-tab","");return e("#"+t+"-tab").length===0?!1:(e("#panel").find("#"+t+"-tab").remove(),e("#panel-top").find('a[href="#'+t+'-tab"]').parent().remove(),e("#panel-top").find("li").length||e("body").addClass("panel-empty"),e("div#panel").tabs("refresh"))},removeLayoutSwitchPanels=function(){e("li.tab-close-on-layout-switch").each(function(){var t=e(this).find("a").attr("href").replace("#","");removePanelTab(t)})},togglePanel=function(){return e("div#panel").hasClass("panel-hidden")?showPanel():hidePanel()},hidePanel=function(){if(e("div#panel").hasClass("panel-hidden"))return!1;var t={bottom:-e("div#panel").height()},n={bottom:e("ul#panel-top").outerHeight()};return e("div#panel").css(t).addClass("panel-hidden"),e("div#iframe-container").css(n),setTimeout(repositionTooltips,400),e("body").addClass("panel-hidden"),e("ul#panel-top-right li#minimize span").text("^"),typeof $i=="function"&&$i(".block-selected").removeClass("block-selected block-hover"),e.cookie("hide-panel",!0),!0},showPanel=function(){if(!e("div#panel").hasClass("panel-hidden"))return!1;var t={bottom:0},n={bottom:e("div#panel").outerHeight()};return e("div#panel").css(t).removeClass("panel-hidden"),e("div#iframe-container").css(n),setTimeout(repositionTooltips,400),e("body").removeClass("panel-hidden"),e("ul#panel-top-right li#minimize span").text("g"),e("ul#panel-top > li.ui-state-active a").length&&$i("#"+e("ul#panel-top > li.ui-state-active a").attr("href").replace("#","").replace("-tab","")).addClass("block-selected block-hover"),e.cookie("hide-panel",!1),!0};var s={init:function(){i.delegate(),i.bind()},getPanelMaxHeight:function(){return e(window).height()-275},resizePanel:function(t,n){var r=e("div#panel"),i=r.find("ul#panel-top");if(typeof t=="undefined"||t==0)t=e("div#panel").height();t>s.getPanelMaxHeight()&&(t=s.getPanelMaxHeight()>o?s.getPanelMaxHeight():o),t<o&&(t=o);if(typeof n!="undefined"&&n&&t<s.getPanelMaxHeight())return;r.height(t);var u=r.hasClass("panel-hidden")?i.outerHeight():r.outerHeight(),a=r.hasClass("panel-hidden")?i.outerHeight()+e("div#layout-selector-tabs").height():r.outerHeight()+e("div#layout-selector-tabs").height();e("div#iframe-container").css({bottom:u}),r.hasClass("panel-hidden")&&e("div#panel").css({bottom:-e("div#panel").height()}),e.cookie("panel-height",r.height())}};e("ul#panel-top").find("li").length||e("body").addClass("panel-empty"),e("ul#panel-top").delegate("span.close","click",function(){var t=e(this).siblings("a").attr("href").replace("#","").replace("-tab","");return removePanelTab(t)}),e("div#panel").tabs({tabTemplate:"<li><a href='#{href}'>#{label}</a></li>",add:function(t,n,r){e(n.panel).append(r)},activate:function(t,n){var r=e(n.newTab).children("a").attr("href").replace("#","").replace("-tab","");$i(".block-selected").removeClass("block-selected block-hover"),r.indexOf("block-")===0&&$i("#"+r).addClass("block-selected block-hover")}}),e("ul#panel-top li a").on("click",showPanel),e("div.sub-tab").tabs();var o=120;return e(document).ready(function(){e.cookie("panel-height")&&s.resizePanel(e.cookie("panel-height"))}),e("div#panel").resizable({maxHeight:s.getPanelMaxHeight(),minHeight:120,handles:"n",resize:function(t,n){e(this).css({width:"100%",position:"fixed",bottom:0,top:""}),e("div#iframe-container").css({bottom:e("div#panel").outerHeight()}),showIframeOverlay()},start:function(){showIframeOverlay()},stop:function(){e.cookie("panel-height",e(this).height()),hideIframeOverlay()}}),e(window).bind("resize",function(t){if(t.target!=window)return;e("div#panel").resizable("option",{maxHeight:s.getPanelMaxHeight()}),s.resizePanel(!1,!0)}),e("div#panel-top-container").bind("dblclick",function(e){if(e.target.id!="panel-top-container")return!1;togglePanel()}),e("ul#panel-top-right li#minimize").bind("click",function(e){return togglePanel(),!1}),e.cookie("hide-panel")==="true"&&hidePanel(!0),s}),define("deps/itstylesheet",function(){}),define("util.saving",["jquery","util.loader"],function(e,t){save=function(){if(typeof isSavingAllowed=="undefined"||isSavingAllowed===!1)return!1;if(typeof currentlySaving!="undefined"&¤tlySaving===!0)return!1;currentlySaving=!0,savedTitle=e("title").text(),saveButton=e("span#save-button"),saveButton.text("Saving...").addClass("active").css("cursor","wait"),changeTitle("Visual Editor: Saving"),startTitleActivityIndicator();var t=e.param(GLOBALunsavedValues);e.post(Headway.ajaxURL,{security:Headway.security,action:"headway_visual_editor",method:"save_options",options:t,layout:Headway.currentLayout,mode:Headway.mode},function(t){delete currentlySaving;if(t==="0")return saveButton.stop(!0),saveButton.text("Save"),saveButton.removeClass("active"),saveButton.css("cursor","pointer"),showErrorNotification({id:"error-wordpress-authentication",message:'<strong>Notice!</strong><br /><br />Your WordPress authentication has expired and you must log in before you can save.<br /><br /><a href="'+Headway.adminURL+'" target="_blank">Click Here to log in</a>, then switch back to the window/tab the Visual Editor is in.',closeTimer:!1,closable:!0});if(typeof t.errors!="undefined"||typeof t!="object"&&t!="success"){saveButton.stop(!0),saveButton.text("Save"),saveButton.removeClass("active"),saveButton.css("cursor","pointer");var n="There was an error while saving. Please try again";return typeof t.errors!="undefined"&&(n+="<br /><ul>",e.each(t.errors,function(e,t){n+="<li>"+t+"</li>"}),n+="</ul>"),showErrorNotification({id:"error-invalid-save-response",message:n,closeTimer:!1,closable:!0})}hideNotification("error-wordpress-authentication"),hideNotification("error-invalid-save-response"),saveButton.animate({boxShadow:"0 0 0 #7dd1e2"},350),setTimeout(function(){saveButton.css("boxShadow",""),saveButton.stop(!0),saveButton.text("Save"),saveButton.removeClass("active"),saveButton.css("cursor","pointer"),typeof t["block-id-mapping"]!="undefined"&&e.each(t["block-id-mapping"],function(t,n){var r=$i('.block[data-temp-id="'+t+'"]');r.attr("id","block-"+n).data("id",n).attr("data-id",n).removeAttr("data-temp-id").removeAttr("data-desired-id").removeData("temp-id").removeData("desired-id"),updateBlockContentCover(r);if(e("#block-"+t+"-tab").length){var i=e("#block-"+t+"-tab").find(".sub-tabs .ui-tabs-active").attr("aria-controls");removePanelTab("block-"+t),openBlockOptions(r,i)}}),typeof t["wrapper-id-mapping"]!="undefined"&&e.each(t["wrapper-id-mapping"],function(t,n){var r=$i('.wrapper[data-temp-id="'+t+'"]');r.attr("id","wrapper-"+n).data("id",n).attr("data-id",n).removeData("temp-id").removeData("desired-id"),e("#wrapper-"+t+"-tab").length&&(removePanelTab("wrapper-"+t),openWrapperOptions(n))}),clearUnsavedValues(),typeof t.snapshot!="undefined"&&typeof t.snapshot.timestamp!="undefined"&&(showNotification({id:"snapshot-saved",message:"Snapshot automatically saved.",success:!0}),Headway.viewModels.snapshots.snapshots.unshift({id:t.snapshot.id,timestamp:t.snapshot.timestamp,comments:t.snapshot.comments})),e("li.layout-selected").addClass("layout-item-customized"),disallowSaving(),setTimeout(function(){stopTitleActivityIndicator(),changeTitle(savedTitle),showNotification({id:"saving-complete",message:"Saving Complete!",closeTimer:3500,success:!0})},150)},350),allowVEClose()})},clearUnsavedValues=function(){delete GLOBALunsavedValues},allowSaving=function(){if(Headway.mode=="grid"&&$i(".block").length===0||typeof Headway.overlappingBlocks!="undefined"&&Headway.overlappingBlocks)return disallowSaving();if(typeof isSavingAllowed!="undefined"&&isSavingAllowed===!0)return;return e("body").addClass("allow-saving"),isSavingAllowed=!0,prohibitVEClose(),!0},disallowSaving=function(){return isSavingAllowed=!1,e("body").removeClass("allow-saving"),(typeof Headway.overlappingBlocks=="undefined"||!Headway.overlappingBlocks)&&allowVEClose(),!0}}),function(e,t,n){function m(e,t,n){if(e.addEventListener){e.addEventListener(t,n,!1);return}e.attachEvent("on"+t,n)}function g(e){if(e.type=="keypress"){var t=String.fromCharCode(e.which);return e.shiftKey||(t=t.toLowerCase()),t}return r[e.which]?r[e.which]:i[e.which]?i[e.which]:String.fromCharCode(e.which).toLowerCase()}function y(e,t){return e.sort().join(",")===t.sort().join(",")}function b(e){e=e||{};var t=!1,n;for(n in l){if(e[n]){t=!0;continue}l[n]=0}t||(d=!1)}function w(e,t,n,r,i,s){var o,u,f=[],c=n.type;if(!a[e])return[];c=="keyup"&&k(e)&&(t=[e]);for(o=0;o<a[e].length;++o){u=a[e][o];if(!r&&u.seq&&l[u.seq]!=u.level)continue;if(c!=u.action)continue;if(c=="keypress"&&!n.metaKey&&!n.ctrlKey||y(t,u.modifiers)){var h=!r&&u.combo==i,p=r&&u.seq==r&&u.level==s;(h||p)&&a[e].splice(o,1),f.push(u)}}return f}function E(e){var t=[];return e.shiftKey&&t.push("shift"),e.altKey&&t.push("alt"),e.ctrlKey&&t.push("ctrl"),e.metaKey&&t.push("meta"),t}function S(e){if(e.preventDefault){e.preventDefault();return}e.returnValue=!1}function x(e){if(e.stopPropagation){e.stopPropagation();return}e.cancelBubble=!0}function T(e,t,n,r){if(B.stopCallback(t,t.target||t.srcElement,n,r))return;e(t,n)===!1&&(S(t),x(t))}function N(e,t,n){var r=w(e,t,n),i,s={},o=0,u=!1;for(i=0;i<r.length;++i)r[i].seq&&(o=Math.max(o,r[i].level));for(i=0;i<r.length;++i){if(r[i].seq){if(r[i].level!=o)continue;u=!0,s[r[i].seq]=1,T(r[i].callback,n,r[i].combo,r[i].seq);continue}u||T(r[i].callback,n,r[i].combo)}var a=n.type=="keypress"&&p;n.type==d&&!k(e)&&!a&&b(s),p=u&&n.type=="keydown"}function C(e){typeof e.which!="number"&&(e.which=e.keyCode);var t=g(e);if(!t)return;if(e.type=="keyup"&&h===t){h=!1;return}B.handleKey(t,E(e),e)}function k(e){return e=="shift"||e=="ctrl"||e=="alt"||e=="meta"}function L(){clearTimeout(c),c=setTimeout(b,1e3)}function A(){if(!u){u={};for(var e in r){if(e>95&&e<112)continue;r.hasOwnProperty(e)&&(u[r[e]]=e)}}return u}function O(e,t,n){return n||(n=A()[e]?"keydown":"keypress"),n=="keypress"&&t.length&&(n="keydown"),n}function M(e,t,n,r){function i(t){return function(){d=t,++l[e],L()}}function s(t){T(n,t,e),r!=="keyup"&&(h=g(t)),setTimeout(b,10)}l[e]=0;for(var o=0;o<t.length;++o){var u=o+1===t.length,a=u?s:i(r||D(t[o+1]).action);P(t[o],a,r,e,o)}}function _(e){return e==="+"?["+"]:e.split("+")}function D(e,t){var n,r,i,u=[];n=_(e);for(i=0;i<n.length;++i)r=n[i],o[r]&&(r=o[r]),t&&t!="keypress"&&s[r]&&(r=s[r],u.push("shift")),k(r)&&u.push(r);return t=O(r,u,t),{key:r,modifiers:u,action:t}}function P(e,t,n,r,i){f[e+":"+n]=t,e=e.replace(/\s+/g," ");var s=e.split(" "),o;if(s.length>1){M(e,s,t,n);return}o=D(e,n),a[o.key]=a[o.key]||[],w(o.key,o.modifiers,{type:o.action},r,e,i),a[o.key][r?"unshift":"push"]({callback:t,modifiers:o.modifiers,action:o.action,seq:r,level:i,combo:e})}function H(e,t,n){for(var r=0;r<e.length;++r)P(e[r],t,n)}var r={8:"backspace",9:"tab",13:"enter",16:"shift",17:"ctrl",18:"alt",20:"capslock",27:"esc",32:"space",33:"pageup",34:"pagedown",35:"end",36:"home",37:"left",38:"up",39:"right",40:"down",45:"ins",46:"del",91:"meta",93:"meta",224:"meta"},i={106:"*",107:"+",109:"-",110:".",111:"/",186:";",187:"=",188:",",189:"-",190:".",191:"/",192:"`",219:"[",220:"\\",221:"]",222:"'"},s={"~":"`","!":"1","@":"2","#":"3",$:"4","%":"5","^":"6","&":"7","*":"8","(":"9",")":"0",_:"-","+":"=",":":";",'"':"'","<":",",">":".","?":"/","|":"\\"},o={option:"alt",command:"meta","return":"enter",escape:"esc",mod:/Mac|iPod|iPhone|iPad/.test(navigator.platform)?"meta":"ctrl"},u,a={},f={},l={},c,h=!1,p=!1,d=!1;for(var v=1;v<20;++v)r[111+v]="f"+v;for(v=0;v<=9;++v)r[v+96]=v;m(t,"keypress",C),m(t,"keydown",C),m(t,"keyup",C);var B={bind:function(e,t,n){return e=e instanceof Array?e:[e],H(e,t,n),this},unbind:function(e,t){return B.bind(e,function(){},t)},trigger:function(e,t){return f[e+":"+t]&&f[e+":"+t]({},e),this},reset:function(){return a={},f={},this},stopCallback:function(e,t){return(" "+t.className+" ").indexOf(" mousetrap ")>-1?!1:t.tagName=="INPUT"||t.tagName=="SELECT"||t.tagName=="TEXTAREA"||t.isContentEditable},bindEventsTo:function(e){e==n&&(e=t),m(e,"keypress",C),m(e,"keydown",C),m(e,"keyup",C)},handleKey:N};e.Mousetrap=B,typeof define=="function"&&define.amd&&define("deps/mousetrap",B)}(window,document),function(e){typeof define=="function"&&define.amd?define("deps/jquery.ui.touchpunch",["jquery"],e):e(jQuery)}(function(e){function s(e){var t=window.pageXOffset,n=window.pageYOffset,r=e.clientX,i=e.clientY;if(e.pageY===0&&Math.floor(i)>Math.floor(e.pageY)||e.pageX===0&&Math.floor(r)>Math.floor(e.pageX))r-=t,i-=n;else if(i<e.pageY-n||r<e.pageX-t)r=e.pageX-t,i=e.pageY-n;return{clientX:r,clientY:i}}function o(e,n){if(!t&&e.originalEvent.touches&&e.originalEvent.touches.length>1||t&&!e.isPrimary)return;e.preventDefault();var r;t?r=e.originalEvent:e.originalEvent.changedTouches?r=e.originalEvent.changedTouches[0]:r=e,simulatedEvent=document.createEvent("MouseEvents"),coord=s(r),simulatedEvent.initMouseEvent(n,!0,!0,window,1,r.screenX,r.screenY,coord.clientX,coord.clientY,!1,!1,!1,!1,0,null),e.target.dispatchEvent(simulatedEvent)}var t=window.navigator.pointerEnabled||window.navigator.msPointerEnabled;e.support.touch=e.support.touch||(typeof Modernizr!="undefined"?Modernizr.touch:"ontouchend"in document||"createTouch"in document||t);if(!e.support.touch&&!navigator.msPointerEnabled)return;var n=e.ui.mouse.prototype,r=n._mouseInit,i;n._touchStart=function(e){var n=this;if(i||!t&&!n._mouseCapture(e.originalEvent.changedTouches[0]))return;i=!0,n._touchMoved=!1,o(e,"mouseover"),o(e,"mousemove"),o(e,"mousedown")},n._touchMove=function(e){if(!i)return;this._touchMoved=!0,o(e,"mousemove")},n._touchEnd=function(e){if(!i)return;o(e,"mouseup"),o(e,"mouseout"),this._touchMoved||o(e,"click"),i=!1},n._mouseInit=function(){var n=this;n.element.off("touchstart").off("touchmove").off("touchend"),t?n.element.on("pointerDown",e.proxy(n,"_touchStart")).on("pointerMove",e.proxy(n,"_touchMove")).on("pointerUp",e.proxy(n,"_touchEnd")).on("MSPointerDown",e.proxy(n,"_touchStart")).on("MSPointerMove",e.proxy(n,"_touchMove")).on("MSPointerUp",e.proxy(n,"_touchEnd")):(n.element.on(navigator.msPointerEnabled?"MSPointerDown":"touchstart",e.proxy(n,"_touchStart")).on(navigator.msPointerEnabled?"MSPointerMove":"touchmove",e.proxy(n,"_touchMove")).on(navigator.msPointerEnabled?"MSPointerUp":"touchend",e.proxy(n,"_touchEnd")),n.element.css({msTouchAction:"none"})),r.call(n)}}),function(e){function n(e){var n=jQuery(this);settings=jQuery.extend({},t,e.data);if(typeof n.data("events")!="undefined"&&typeof n.data("events").click!="undefined"){for(var r in n.data("events").click)if(n.data("events").click[r].namespace==""){var i=n.data("events").click[r].handler;n.data("taphold_click_handler",i),n.unbind("click",i);break}}else typeof settings.clickHandler=="function"&&n.data("taphold_click_handler",settings.clickHandler);n.data("taphold_triggered",!1),n.data("taphold_clicked",!1),n.data("taphold_cancelled",!1),n.data("taphold_timer",setTimeout(function(){!n.data("taphold_cancelled")&&!n.data("taphold_clicked")&&(n.trigger(jQuery.extend(e,jQuery.Event("taphold"))),n.data("taphold_triggered",!0))},settings.duration))}function r(e){var t=jQuery(this);if(t.data("taphold_cancelled"))return;clearTimeout(t.data("taphold_timer")),!t.data("taphold_triggered")&&!t.data("taphold_clicked")&&(typeof t.data("taphold_click_handler")=="function"&&t.data("taphold_click_handler")(jQuery.extend(e,jQuery.Event("click"))),t.data("taphold_clicked",!0))}function i(t){e(this).data("taphold_cancelled",!0)}var t={duration:1e3,clickHandler:null},s="ontouchstart"in window||"onmsgesturechange"in window,o=e.event.special.taphold={setup:function(t){e(this).bind(s?"touchstart":"mousedown",t,n).bind(s?"touchend":"mouseup",r).bind(s?"touchmove":"mouseleave",i)},teardown:function(t){e(this).unbind(s?"touchstart":"mousedown",n).unbind(s?"touchend":"mouseup",r).unbind(s?"touchmove":"mouseleave",i)}}}(jQuery),define("deps/jquery.taphold",function(){}),define("util.usability",["jquery","deps/mousetrap"],function(e,t){prohibitVEClose=function(){window.onbeforeunload=function(){return"You have unsaved changes. Are you sure you wish to leave the Visual Editor?"},allowVECloseSwitch=!1},allowVEClose=function(){window.onbeforeunload=function(){return null},allowVECloseSwitch=!0},disableBadKeys=function(){var t=function(t){var n=e(t.target);if(t.which===8&&!n.is("input")&&!n.is("textarea")&&!n.hasClass("allow-backspace-key")&&!n.parents(".wysiwyg-container").length)return t.preventDefault(),!1;if(t.which===9&&!n.is("input")&&!n.is("textarea")&&!n.hasClass("allow-tab-key")&&!n.parents(".wysiwyg-container").length)return t.preventDefault(),!1;if(t.which==13&&!n.is("textarea")&&!n.hasClass("allow-enter-key")&&!n.parents(".wysiwyg-container").length)return t.preventDefault(),!1};e(document).bind("keypress",t),e(document).bind("keydown",t),$i("html").bind("keypress",t),$i("html").bind("keydown",t)},bindKeyShortcuts=function(){t.bindEventsTo($i("body").get(0));var n=function(t){if(!e(".qtip-tour").is(":visible"))return;e(document.body).qtip("hide")};t.bind("esc",n),t.bind(["ctrl+s","command+s"],function(e){return save(),!1}),t.bind(["ctrl+p","command+p"],function(e){return togglePanel(),!1}),t.bind("ctrl+l",toggleLayoutSelector),typeof designEditor!="undefined"&&typeof designEditor.processElementCopy=="function"&&(t.bind(["ctrl+c","command+c"],designEditor.processElementCopy),t.bind(["ctrl+v","command+v"],designEditor.processElementPaste),t.bind("ctrl+e",function(){boxOpen("live-css")?closeBox("live-css"):e("#open-live-css").trigger("click")}),t.bind("ctrl+i",toggleInspector),t.bind("tab",toggleDesignEditor))},Headway.touch&&require(["deps/jquery.ui.touchpunch","deps/jquery.taphold"],function(){})}),define("modules/iframe",["jquery","deps/itstylesheet","util.saving","util.usability","util.tooltips"],function(e,t,n){$i=function(t){return typeof Headway.iframe=="undefined"||typeof Headway.iframe.contents()=="undefined"?e():Headway.iframe.contents().find(t)},$iDocument=function(){return e(Headway.iframe.contents())},loadIframe=function(e,t){if(typeof t=="undefined"||!t)var t=Headway.homeURL;var n=Headway.iframe;startTitleActivityIndicator(),showIframeLoadingOverlay(),closeBox("grid-wizard"),iframeURL=t,iframeURL=updateQueryStringParameter(iframeURL,"ve-iframe","true"),iframeURL=updateQueryStringParameter(iframeURL,"ve-layout",Headway.currentLayout),iframeURL=updateQueryStringParameter(iframeURL,"ve-iframe-mode",Headway.mode),iframeURL=updateQueryStringParameter(iframeURL,"rand",Math.floor(Math.random()*100000001)),n.contents().find(".ui-headway-grid").length&&typeof n.contents().find(".ui-headway-grid").headwayGrid!="undefined"&&n.contents().find(".ui-headway-grid").headwayGrid("destroy"),n.contents().find("*").unbind().remove(),n[0].src=iframeURL,waitForIframeLoad(e,n)},waitForIframeLoad=function(e,t){if(typeof t=="undefined"||!t)var t=Headway.iframe;return typeof iframeTimeout=="undefined"&&(iframeTimeout=setTimeout(r.loadTimeout,4e4)),typeof t=="undefined"||t.contents().find("body.iframe-loaded").length!=1?setTimeout(function(){waitForIframeLoad(e,t)},100):(clearTimeout(iframeTimeout),r.loadCallback(e))},showIframeOverlay=function(){var t=e("div#iframe-overlay");t.show()},hideIframeOverlay=function(t){if(typeof t!="undefined"&&t==0)return e("div#iframe-overlay").hide();setTimeout(function(){e("div#iframe-overlay").hide()},250)},showIframeLoadingOverlay=function(){return e("div#iframe-container").css("overflow","hidden"),e("div#iframe-loading-overlay").css({top:e("div#iframe-container").scrollTop()}),e("div#iframe-loading-overlay").is(":visible")||(createCog(e("div#iframe-loading-overlay"),!0),e("div#iframe-loading-overlay").show()),e("div#iframe-loading-overlay")},hideIframeLoadingOverlay=function(){e("div#iframe-container").css("overflow","auto"),e("div#iframe-loading-overlay").hide().html("")};var r={init:function(){e(document).ready(function(){Headway.iframe=e("iframe#content"),r.bindFocusBlur()})},bindFocusBlur:function(){Headway.iframe.on("mouseleave",function(){e(this).trigger("blur"),$i("[data-hasqtip]").qtip("disable",!0)}),Headway.iframe.on("mouseenter mousedown",function(){if(e("textarea:focus, input:focus").length===1)return;$i("[data-hasqtip]").qtip("enable"),e(this).trigger("focus")})},loadCallback:function(t){return clearUnsavedValues(),typeof t=="function"&&t(),r.defaultLoadCallback(),r.stopFirefoxLoadingIndicator(),e("body").triggerHandler("headwayIframeLoad"),!0},defaultLoadCallback:function(){stopTitleActivityIndicator(),changeTitle("Visual Editor: "+Headway.currentLayoutName),e("span#current-layout").text(Headway.currentLayoutName),setupTooltips(),setupTooltips("iframe"),stylesheet=new ITStylesheet({document:Headway.iframe.contents()[0],href:Headway.homeURL+"/?headway-trigger=compiler&file=general-design-editor"},"find"),css=new ITStylesheet({document:Headway.iframe.contents()[0]},"load"),hideIframeOverlay(!1),Headway.currentLayoutTemplate&&(showIframeOverlay(),$i("body").prepend('<div id="no-edit-notice"><div><h1>To edit this layout, remove the shared layout from this layout.</h1></div></div>')),disableBadKeys(),bindKeyShortcuts(),$i("html, body").bind("keydown",function(t){e(document).trigger(t),t.stopPropagation()}),$i("html, body").bind("keypress",function(t){e(document).trigger(t),t.stopPropagation()}),$i("html, body").bind("keyup",function(t){e(document).trigger(t),t.stopPropagation()}),Headway.touch&&Headway.iframe.contents().find("body").css("-webkit-touch-callout","none"),Headway.iframe.contents().find("body").delegate('a, input[type="submit"], button',"click",function(t){if(e(this).hasClass("allow-click"))return;return t.preventDefault(),!1}),typeof headwayIframeLoadNotification!="undefined"&&(showNotification({id:"iframe-load-notification",message:headwayIframeLoadNotification,overwriteExisting:!0}),delete headwayIframeLoadNotification),removeLayoutSwitchPanels();var t=e('div#layout-selector span.layout[data-layout-id="'+Headway.currentLayout+'"]'),n=t.parent();!$i(".block").length&&(!Headway.currentLayoutCustomized||Headway.currentLayout.indexOf("template-")===0)&&!Headway.currentLayoutTemplate&&Headway.mode=="grid"?(hidePanel(),e(document).ready(function(){openBox("grid-wizard")})):closeBox("grid-wizard"),hideIframeLoadingOverlay()},loadTimeout:function(){iframeTimeout=!0,stopTitleActivityIndicator(),changeTitle("Visual Editor: Error!"),e("#iframe-container, #menu, #panel, #layout-selector-offset").hide(),alert("ERROR: There was a problem while loading the visual editor.\n\nYour browser will automatically refresh to attempt loading again."),document.location.reload(!0)},stopFirefoxLoadingIndicator:function(){if(/Firefox[\/\s](\d+\.\d+)/.test(navigator.userAgent)){var e;e==null&&(e=document.createElement("iframe"),e.style.display="none"),document.body.appendChild(e),document.body.removeChild(e)}}};return r}),function(e,t,n){function s(t,n){this.name=r,this.el=t,this.$el=e(t),this.options=e.extend({},i,n),this.$document=e(this.$el[0].ownerDocument),this.$body=this.$document.find("body"),this.moveTrigger="MSPointerMove touchmove mousemove",this.startTrigger="MSPointerDown touchstart mousedown",this.stopTrigger="MSPointerUp touchend mouseup",this.startTriggerArray=this.startTrigger.split(" "),this.moveTriggerArray=this.moveTrigger.split(" "),this.stopTriggerArray=this.stopTrigger.split(" "),this.stopEvents=[this.stopTrigger,this.options.stopEvents].join(" "),this.options.constrainTo==="window"?this.$container=this.$document:this.options.constrainTo&&this.options.constrainTo!=="parent"?this.$container=e(this.options.constrainTo):this.$container=this.$el.parent(),this.isPointerEventCompatible()&&this.applyMSDefaults(),this.CSSEaseHash=this.getCSSEaseHash(),this.scale=1,this.started=!1,this.disabled=!1,this.resetVelocityQueue(),this.init()}var r="pep",i={initiate:function(){},start:function(){},drag:function(){},stop:function(){},rest:function(){},moveTo:!1,callIfNotStarted:["stop","rest"],startThreshold:[0,0],grid:[1,1],debug:!1,activeClass:"pep-active",multiplier:1,velocityMultiplier:2.5,shouldPreventDefault:!0,allowDragEventPropagation:!0,stopEvents:"",hardwareAccelerate:!0,useCSSTranslation:!0,disableSelect:!0,cssEaseString:"cubic-bezier(0.190, 1.000, 0.220, 1.000)",cssEaseDuration:1e3,shouldEase:!0,droppable:!1,droppableActiveClass:"pep-dpa",overlapFunction:!1,constrainTo:!1,removeMargins:!0,place:!0,deferPlacement:!1,axis:null,forceNonCSS3Movement:!1,elementsWithInteraction:"input",revert:!1,revertAfter:"stop",revertIf:function(){return!0}};s.prototype.init=function(){this.options.debug&&this.buildDebugDiv(),this.options.disableSelect&&this.disableSelect(),this.options.place&&!this.options.deferPlacement&&(this.positionParent(),this.placeObject()),this.ev={},this.pos={},this.subscribe()},s.prototype.subscribe=function(){var e=this;this.$el.on(this.startTrigger,function(t){e.handleStart(t)}),this.$el.on(this.startTrigger,this.options.elementsWithInteraction,function(e){e.stopPropagation()}),this.$document.on(this.stopEvents,function(t){e.handleStop(t)}),this.$document.on(this.moveTrigger,function(t){e.moveEvent=t})},s.prototype.handleStart=function(t){var n=this;if(this.isValidMoveEvent(t)&&!this.disabled){this.isPointerEventCompatible()&&t.preventManipulation&&t.preventManipulation(),t=this.normalizeEvent(t),this.options.place&&this.options.deferPlacement&&(this.positionParent(),this.placeObject()),this.log({type:"event",event:t.type}),this.options.hardwareAccelerate&&!this.hardwareAccelerated&&(this.hardwareAccelerate(),this.hardwareAccelerated=!0);var r=this.options.initiate.call(this,t,this);if(r===!1)return;clearTimeout(this.restTimeout),this.$el.addClass(this.options.activeClass),this.removeCSSEasing(),this.startX=this.ev.x=t.pep.x,this.startY=this.ev.y=t.pep.y,this.initialPosition=this.initialPosition||this.$el.position(),this.startEvent=this.moveEvent=t,this.active=!0,this.options.shouldPreventDefault&&t.preventDefault(),this.options.allowDragEventPropagation||t.stopPropagation(),function i(){if(!n.active)return;n.handleMove(),n.requestAnimationFrame(i)}(e,n)}},s.prototype.handleMove=function(){if(typeof this.moveEvent=="undefined")return;var n=this.normalizeEvent(this.moveEvent),r=t.parseInt(n.pep.x/this.options.grid[0])*this.options.grid[0],i=t.parseInt(n.pep.y/this.options.grid[1])*this.options.grid[1];this.addToLIFO({time:n.timeStamp,x:r,y:i});var s,o;e.inArray(n.type,this.startTriggerArray)>-1?(s=0,o=0):(s=r-this.ev.x,o=i-this.ev.y),this.dx=s,this.dy=o,this.ev.x=r,this.ev.y=i;if(s===0&&o===0){this.log({type:"event",event:"** stopped **"});return}var u=Math.abs(this.startX-r),a=Math.abs(this.startY-i);!this.started&&(u>this.options.startThreshold[0]||a>this.options.startThreshold[1])&&(this.started=!0,this.$el.addClass("pep-start"),this.options.start.call(this,this.startEvent,this)),this.options.droppable&&this.calculateActiveDropRegions();var f=this.options.drag.call(this,n,this);if(f===!1){this.resetVelocityQueue();return}this.log({type:"event",event:n.type}),this.log({type:"event-coords",x:this.ev.x,y:this.ev.y}),this.log({type:"velocity"});var l=this.handleConstraint(s,o),c,h;typeof this.options.moveTo=="function"?(c=s>=0?"+="+Math.abs(s/this.scale)*this.options.multiplier:"-="+Math.abs(s/this.scale)*this.options.multiplier,h=o>=0?"+="+Math.abs(o/this.scale)*this.options.multiplier:"-="+Math.abs(o/this.scale)*this.options.multiplier,this.options.constrainTo&&(c=l.x!==!1?l.x:c,h=l.y!==!1?l.y:h),this.options.axis==="x"&&(h=l.y),this.options.axis==="y"&&(c=l.x),this.options.moveTo.call(this,c,h)):this.shouldUseCSSTranslation()?(s=s/this.scale*this.options.multiplier,o=o/this.scale*this.options.multiplier,this.options.constrainTo&&(s=l.x===!1?s:0,o=l.y===!1?o:0),this.options.axis==="x"&&(o=0),this.options.axis==="y"&&(s=0),this.moveToUsingTransforms(s,o)):(c=s>=0?"+="+Math.abs(s/this.scale)*this.options.multiplier:"-="+Math.abs(s/this.scale)*this.options.multiplier,h=o>=0?"+="+Math.abs(o/this.scale)*this.options.multiplier:"-="+Math.abs(o/this.scale)*this.options.multiplier,this.options.constrainTo&&(c=l.x!==!1?l.x:c,h=l.y!==!1?l.y:h),this.options.axis==="x"&&(h=l.y),this.options.axis==="y"&&(c=l.x),this.moveTo(c,h))},s.prototype.handleStop=function(t){if(!this.active)return;this.log({type:"event",event:t.type}),this.active=!1,this.$el.removeClass("pep-start").addClass("pep-ease"),this.options.droppable&&this.calculateActiveDropRegions(),(this.started||!this.started&&e.inArray("stop",this.options.callIfNotStarted)>-1)&&this.options.stop.call(this,t,this),this.options.shouldEase?this.ease(t,this.started):this.removeActiveClass(),this.options.revert&&(this.options.revertAfter==="stop"||!this.options.shouldEase)&&this.options.revertIf&&this.options.revertIf()&&this.revert(),this.started=!1,this.resetVelocityQueue()},s.prototype.ease=function(t,n){var r=this.$el.position(),i=this.velocity(),s=this.dt,o=i.x/this.scale*this.options.multiplier,u=i.y/this.scale*this.options.multiplier,a=this.handleConstraint(o,u,!0);this.cssAnimationsSupported()&&this.$el.css(this.getCSSEaseHash());var f=i.x>0?"+="+o:"-="+Math.abs(o),l=i.y>0?"+="+u:"-="+Math.abs(u);this.options.constrainTo&&(f=a.x!==!1?a.x:f,l=a.y!==!1?a.y:l),this.options.axis==="x"&&(l="+=0"),this.options.axis==="y"&&(f="+=0");var c=!this.cssAnimationsSupported()||this.options.forceNonCSS3Movement;typeof this.options.moveTo=="function"?this.options.moveTo.call(this,f,l):this.moveTo(f,l,c);var h=this;this.restTimeout=setTimeout(function(){h.options.droppable&&h.calculateActiveDropRegions(),(n||!n&&e.inArray("rest",h.options.callIfNotStarted)>-1)&&h.options.rest.call(h,t,h),h.options.revert&&h.options.revertAfter==="ease"&&h.options.shouldEase&&h.options.revertIf&&h.options.revertIf()&&h.revert(),h.removeActiveClass()},this.options.cssEaseDuration)},s.prototype.normalizeEvent=function(e){return e.pep={},this.isPointerEventCompatible()||!this.isTouch(e)?(e.pageX?(e.pep.x=e.pageX,e.pep.y=e.pageY):(e.pep.x=e.originalEvent.pageX,e.pep.y=e.originalEvent.pageY),e.pep.type=e.type):(e.pep.x=e.originalEvent.touches[0].pageX,e.pep.y=e.originalEvent.touches[0].pageY,e.pep.type=e.type),e},s.prototype.resetVelocityQueue=function(){this.velocityQueue=new Array(5)},s.prototype.moveTo=function(e,t,n){this.log({type:"delta",x:e,y:t}),n?this.$el.animate({top:t,left:e},this.options.cssEaseDuration/2,"easeOutQuad",{queue:!1}):this.$el.stop(!0,!1).css({top:t,left:e})},s.prototype.moveToUsingTransforms=function(e,t){var n=this.matrixToArray(this.matrixString());this.cssX||(this.cssX=this.xTranslation(n)),this.cssY||(this.cssY=this.yTranslation(n)),this.cssX=this.cssX+e,this.cssY=this.cssY+t,this.log({type:"delta",x:e,y:t}),n[4]=this.cssX,n[5]=this.cssY,this.translation=this.arrayToMatrix(n),this.transform(this.translation)},s.prototype.transform=function(e){this.$el.css({"-webkit-transform":e,"-moz-transform":e,"-ms-transform":e,"-o-transform":e,transform:e})},s.prototype.xTranslation=function(e){return e=e||this.matrixToArray(this.matrixString()),parseInt(e[4],10)},s.prototype.yTranslation=function(e){return e=e||this.matrixToArray(this.matrixString()),parseInt(e[5],10)},s.prototype.matrixString=function(){var e=function(e){return!(!e||e==="none"||e.indexOf("matrix")<0)},t="matrix(1, 0, 0, 1, 0, 0)";return e(this.$el.css("-webkit-transform"))&&(t=this.$el.css("-webkit-transform")),e(this.$el.css("-moz-transform"))&&(t=this.$el.css("-moz-transform")),e(this.$el.css("-ms-transform"))&&(t=this.$el.css("-ms-transform")),e(this.$el.css("-o-transform"))&&(t=this.$el.css("-o-transform")),e(this.$el.css("transform"))&&(t=this.$el.css("transform")),t},s.prototype.matrixToArray=function(e){return e.split("(")[1].split(")")[0].split(",")},s.prototype.arrayToMatrix=function(e){return"matrix("+e.join(",")+")"},s.prototype.addToLIFO=function(e){var t=this.velocityQueue;t=t.slice(1,t.length),t.push(e),this.velocityQueue=t},s.prototype.velocity=function(){var e=0,t=0;for(var n=0;n<this.velocityQueue.length-1;n++)this.velocityQueue[n]&&(e+=this.velocityQueue[n+1].x-this.velocityQueue[n].x,t+=this.velocityQueue[n+1].y-this.velocityQueue[n].y,this.dt=this.velocityQueue[n+1].time-this.velocityQueue[n].time);return{x:e*this.options.velocityMultiplier,y:t*this.options.velocityMultiplier}},s.prototype.revert=function(){this.shouldUseCSSTranslation()&&this.moveToUsingTransforms(-this.xTranslation(),-this.yTranslation()),this.moveTo(this.initialPosition.left,this.initialPosition.top)},s.prototype.requestAnimationFrame=function(e){return t.requestAnimationFrame&&t.requestAnimationFrame(e)||t.webkitRequestAnimationFrame&&t.webkitRequestAnimationFrame(e)||t.mozRequestAnimationFrame&&t.mozRequestAnimationFrame(e)||t.oRequestAnimationFrame&&t.mozRequestAnimationFrame(e)||t.msRequestAnimationFrame&&t.msRequestAnimationFrame(e)||t.setTimeout(e,1e3/60)},s.prototype.positionParent=function(){if(!this.options.constrainTo||this.parentPositioned)return;this.parentPositioned=!0,this.options.constrainTo==="parent"?this.$container.css({position:"relative"}):this.options.constrainTo==="window"&&this.$container.get(0).nodeName!=="#document"&&this.$container.css("position")!=="static"&&this.$container.css({position:"static"})},s.prototype.placeObject=function(){if(this.objectPlaced)return;this.objectPlaced=!0,this.offset=this.options.constrainTo==="parent"||this.hasNonBodyRelative()?this.$el.position():this.$el.offset(),parseInt(this.$el.css("left"),10)&&(this.offset.left=this.$el.css("left")),parseInt(this.$el.css("top"),10)&&(this.offset.top=this.$el.css("top")),this.options.removeMargins&&this.$el.css({margin:0}),this.$el.css({position:"absolute",top:this.offset.top,left:this.offset.left})},s.prototype.hasNonBodyRelative=function(){return this.$el.parents().filter(function(){var t=e(this);return t.is("body")||t.css("position")==="relative"}).length>1},s.prototype.setScale=function(e){this.scale=e},s.prototype.setMultiplier=function(e){this.options.multiplier=e},s.prototype.removeCSSEasing=function(){this.cssAnimationsSupported()&&this.$el.css(this.getCSSEaseHash(!0))},s.prototype.disableSelect=function(){this.$el.css({"-webkit-touch-callout":"none","-webkit-user-select":"none","-khtml-user-select":"none","-moz-user-select":"none","-ms-user-select":"none","user-select":"none"})},s.prototype.removeActiveClass=function(){this.$el.removeClass([this.options.activeClass,"pep-ease"].join(" "))},s.prototype.handleConstraint=function(t,r,i){var s=this,o=this.$el.position();this.pos.x=o.left,this.pos.y=o.top;var u={x:!1,y:!1},a,f,l,c;this.log({type:"pos-coords",x:this.pos.x,y:this.pos.y});if(e.isArray(this.options.constrainTo))this.options.constrainTo[3]!==n&&this.options.constrainTo[1]!==n&&(f=this.options.constrainTo[1]===!1?Infinity:this.options.constrainTo[1],l=this.options.constrainTo[3]===!1?-Infinity:this.options.constrainTo[3]),this.options.constrainTo[0]!==!1&&this.options.constrainTo[2]!==!1&&(a=this.options.constrainTo[2]===!1?Infinity:this.options.constrainTo[2],c=this.options.constrainTo[0]===!1?-Infinity:this.options.constrainTo[0]),this.pos.x+t<l&&(u.x=l),this.pos.y+r<c&&(u.y=c);else if(typeof this.options.constrainTo=="string"){l=0,c=0,f=this.$container.width()-this.$el.outerWidth(),a=this.$container.height()-this.$el.outerHeight(),this.$el.each(function(){e(this).position().left+t<0&&(u.x=0),e(this).position().top+r<0&&(u.y=0)});var h=this.$container[0].getBoundingClientRect(),p=this.ev.x>h.left&&this.ev.x<h.right&&this.ev.y>h.top+e(this.$el[0].ownerDocument).scrollTop()&&this.ev.y<h.bottom+e(this.$el[0].ownerDocument).scrollTop();p||(u.x=l,u.y=c)}return this.$el.each(function(){f=s.$container.width()-e(this).outerWidth(),a=s.$container.height()-e(this).outerHeight(),e(this).position().left+t>f&&(u.x=f),e(this).position().top+r>a&&(u.y=a)}),this.shouldUseCSSTranslation()&&i&&(u.x===l&&this.xTranslation()&&(u.x=l-this.xTranslation()),u.x===f&&this.xTranslation()&&(u.x=f-this.xTranslation()),u.y===c&&this.yTranslation()&&(u.y=c-this.yTranslation()),u.y===a&&this.yTranslation()&&(u.y=a-this.yTranslation())),u},s.prototype.getCSSEaseHash=function(e){typeof e=="undefined"&&(e=!1);var t;if(e)t="";else{if(this.CSSEaseHash)return this.CSSEaseHash;t=["all",this.options.cssEaseDuration+"ms",this.options.cssEaseString].join(" ")}return{"-webkit-transition":t,"-moz-transition":t,"-ms-transition":t,"-o-transition":t,transition:t}},s.prototype.calculateActiveDropRegions=function(){var t=this;this.activeDropRegions=[],e.each(e(this.options.droppable),function(n,r){var i=e(r);t.isOverlapping(i,t.$el)?(i.addClass(t.options.droppableActiveClass),t.activeDropRegions.push(i)):i.removeClass(t.options.droppableActiveClass)})},s.prototype.isOverlapping=function(e,t){if(this.options.overlapFunction)return this.options.overlapFunction(e,t);var n=e[0].getBoundingClientRect(),r=t[0].getBoundingClientRect();return!(n.right<r.left||n.left>r.right||n.bottom<r.top||n.top>r.bottom)},s.prototype.isTouch=function(e){return e.type.search("touch")>-1},s.prototype.isPointerEventCompatible=function(){return"MSPointerEvent"in t},s.prototype.applyMSDefaults=function(e){this.$el.css({"-ms-touch-action":"none","touch-action":"none","-ms-scroll-chaining":"none","-ms-scroll-limit":"0 0 0 0"})},s.prototype.isValidMoveEvent=function(e){return!this.isTouch(e)||this.isTouch(e)&&e.originalEvent.touches&&e.originalEvent.touches.length===1},s.prototype.shouldUseCSSTranslation=function(){if(typeof this.useCSSTranslation!="undefined")return this.useCSSTranslation;var e=!1;return!this.options.useCSSTranslation||typeof Modernizr!="undefined"&&!Modernizr.csstransforms?e=!1:e=!0,this.useCSSTranslation=e,e},s.prototype.cssAnimationsSupported=function(){if(typeof this.cssAnimationsSupport!="undefined")return this.cssAnimationsSupport;if(typeof Modernizr!="undefined"&&Modernizr.cssanimations)return this.cssAnimationsSupport=!0,!0;var e=!1,t=document.createElement("div"),r="animation",i="",s="Webkit Moz O ms Khtml".split(" "),o="";t.style.animationName&&(e=!0);if(e===!1)for(var u=0;u<s.length;u++)if(t.style[s[u]+"AnimationName"]!==n){o=s[u],r=o+"Animation",i="-"+o.toLowerCase()+"-",e=!0;break}return this.cssAnimationsSupport=e,e},s.prototype.hardwareAccelerate=function(){this.$el.css({"-webkit-perspective":1e3,perspective:1e3,"-webkit-backface-visibility":"hidden","backface-visibility":"hidden"})},s.prototype.getMovementValues=function(){return{ev:this.ev,pos:this.pos,velocity:this.velocity()}},s.prototype.buildDebugDiv=function(){var t;e("#pep-debug").length===0&&(t=e("<div></div>"),t.attr("id","pep-debug").append("<div style='font-weight:bold; background: red; color: white;'>DEBUG MODE</div>").append("<div id='pep-debug-event'>no event</div>").append("<div id='pep-debug-ev-coords'>event coords: <span class='pep-x'>-</span>, <span class='pep-y'>-</span></div>").append("<div id='pep-debug-pos-coords'>position coords: <span class='pep-x'>-</span>, <span class='pep-y'>-</span></div>").append("<div id='pep-debug-velocity'>velocity: <span class='pep-x'>-</span>, <span class='pep-y'>-</span></div>").append("<div id='pep-debug-delta'>Δ movement: <span class='pep-x'>-</span>, <span class='pep-y'>-</span></div>").css({position:"fixed",bottom:5,right:5,zIndex:99999,textAlign:"right",fontFamily:"Arial, sans",fontSize:10,border:"1px solid #DDD",padding:"3px",background:"white",color:"#333"}));var n=this;setTimeout(function(){n.debugElements={$event:e("#pep-debug-event"),$velocityX:e("#pep-debug-velocity .pep-x"),$velocityY:e("#pep-debug-velocity .pep-y"),$dX:e("#pep-debug-delta .pep-x"),$dY:e("#pep-debug-delta .pep-y"),$evCoordsX:e("#pep-debug-ev-coords .pep-x"),$evCoordsY:e("#pep-debug-ev-coords .pep-y"),$posCoordsX:e("#pep-debug-pos-coords .pep-x"),$posCoordsY:e("#pep-debug-pos-coords .pep-y")}},0),e("body").append(t)},s.prototype.log=function(e){if(!this.options.debug)return;switch(e.type){case"event":this.debugElements.$event.text(e.event);break;case"pos-coords":this.debugElements.$posCoordsX.text(e.x),this.debugElements.$posCoordsY.text(e.y);break;case"event-coords":this.debugElements.$evCoordsX.text(e.x),this.debugElements.$evCoordsY.text(e.y);break;case"delta":this.debugElements.$dX.text(e.x),this.debugElements.$dY.text(e.y);break;case"velocity":var t=this.velocity();this.debugElements.$velocityX.text(Math.round(t.x)),this.debugElements.$velocityY.text(Math.round(t.y))}},s.prototype.toggle=function(e){typeof e=="undefined"?this.disabled=!this.disabled:this.disabled=!e},e.extend(e.easing,{easeOutQuad:function(e,t,n,r,i){return-r*(t/=i)*(t-2)+n},easeOutCirc:function(e,t,n,r,i){return r*Math.sqrt(1-(t=t/i-1)*t)+n},easeOutExpo:function(e,t,n,r,i){return t===i?n+r:r*(-Math.pow(2,-10*t/i)+1)+n}}),e.fn[r]=function(t){return this.each(function(){if(!e.data(this,"plugin_"+r)){var n=new s(this,t);e.data(this,"plugin_"+r,n),e.pep.peps.push(n)}})},e.pep={},e.pep.peps=[],e.pep.toggleAll=function(t){e.each(this.peps,function(e,n){n.toggle(t)})},e.pep.unbind=function(e){var t=e.data("plugin_"+r);if(typeof t=="undefined")return;t.toggle(!1),e.removeData("plugin_"+r)}}(jQuery,window),define("deps/jquery.pep",function(){}),define("helper.boxes",["modules/iframe","deps/jquery.pep"],function(iframe){createBox=function(e){var t={},n={id:null,title:null,description:null,content:null,src:null,load:null,width:500,height:300,center:!0,closable:!0,resizable:!1,draggable:!0,deleteWhenClosed:!1,blackOverlay:!1,blackOverlayOpacity:.6,blackOverlayIframe:!1};$.extend(t,n,e);var r=$('<div class="box" id="box-'+t.id+'"><div class="box-top"></div><div class="box-content-bg"><div class="box-content"></div></div></div>');return r.attr("black_overlay",t.blackOverlay),r.attr("black_overlay_opacity",t.blackOverlayOpacity),r.attr("black_overlay_iframe",t.blackOverlayIframe),r.attr("load_with_ajax",!1),r.appendTo("div#boxes"),typeof t.src!="string"?r.find(".box-content").html(t.content):(r.find(".box-content").addClass("box-content-with-iframe"),r.find(".box-content").html('<iframe src="'+t.src+'"></iframe>'),typeof t.load=="function"&&r.find(".box-content iframe").bind("load",t.load)),r.find(".box-top").append("<strong>"+t.title+"</strong>"),typeof t.description=="string"&&r.find(".box-top").append("<span>"+t.description+"</span>"),setupBox(t.id,t),r},setupBox=function(e,t){var n={},r={width:600,height:300,center:!0,closable:!0,deleteWhenClosed:!1,draggable:!1,resizable:!1};$.extend(n,r,t);var i=$("div#box-"+e);n.draggable&&(i.draggable({handle:i.find(".box-top"),start:showIframeOverlay,stop:hideIframeOverlay,shouldEase:!1}),i.find(".box-top").css("cursor","move")),n.closable&&(i.find(".box-top").append('<span class="box-close">X</span>'),i.find(".box-close").bind("click",function(){closeBox(e,n.deleteWhenClosed)})),n.resizable&&i.resizable({start:showIframeOverlay,stop:hideIframeOverlay,handles:"n, e, s, w, ne, se, sw, nw",minWidth:n.minWidth,minHeight:n.minHeight}),i.css({width:n.width,height:n.height});if(n.center){var s=-(i.width()/2),o=-(i.height()/2);i.css({top:"50%",left:"50%",marginLeft:s,marginTop:o})}},setupStaticBoxes=function(){$("div.box").each(function(){var e=hwBoolean($(this).attr("draggable")),t=hwBoolean($(this).attr("closable")),n=hwBoolean($(this).attr("resizable")),r=hwBoolean($(this).attr("center")),i=$(this).attr("width"),s=$(this).attr("height"),o=$(this).attr("min_width"),u=$(this).attr("min_height"),a=$(this).attr("id").replace("box-","");setupBox(a,{draggable:e,closable:t,resizable:n,center:r,width:i,height:s,minWidth:o,minHeight:u}),$(this).attr("draggable",null),$(this).attr("closable",null),$(this).attr("resizable",null),$(this).attr("center",null),$(this).attr("width",null),$(this).attr("height",null),$(this).attr("min_width",null),$(this).attr("min_height",null)})},openBox=function(id){var id=id.replace("box-",""),box=$("div#box-"+id);if(box.length===0)return!1;var blackOverlay=hwBoolean(box.attr("black_overlay")),blackOverlayOpacity=box.attr("black_overlay_opacity"),blackOverlayIframe=hwBoolean(box.attr("black_overlay_iframe")),loadWithAjax=hwBoolean(box.attr("load_with_ajax"));if(blackOverlay&&!boxOpen(id)){var overlay=$('<div class="black-overlay"></div>').hide().attr("id","black-overlay-box-"+id).appendTo("#boxes");blackOverlayIframe===!0&&overlay.css("zIndex",4),isNaN(blackOverlayOpacity)||overlay.css("background","rgba(0, 0, 0, "+blackOverlayOpacity+")"),overlay.show()}return loadWithAjax&&!box.data("currently-ajax-loading")&&(box.find("*").removeData(),box.find(".box-content *").remove(),createCog(box.find(".box-content"),!0),box.data("currently-ajax-loading",!0),box.find(".box-content").load(Headway.ajaxURL,{security:Headway.security,action:"headway_visual_editor",method:"load_box_ajax_content",box_id:id,layout:Headway.currentLayout},function(){var loadWithAjaxCallback=eval(box.attr("load_with_ajax_callback"));loadWithAjaxCallback.call(),box.removeData("currently-ajax-loading")})),box.show()},closeBox=function(e,t){var e=e.replace("box-",""),n=$("div#box-"+e);return n.hide(),typeof t!="undefined"&&t==1&&n.remove(),$("div#black-overlay-box-"+e).remove(),!0},boxOpen=function(e){return $("div#box-"+e).is(":visible")},boxExists=function(e){return $("div#box-"+e).length===1?!0:!1},toggleBox=function(e){boxOpen(e)?closeBox(e):openBox(e)},setupStaticBoxes(),$("#boxes").on("click","div.black-overlay",function(){var e=$(this).attr("id").replace("black-overlay-","");if($("#"+e).length===0)return;if($(".qtip-tour").is(":visible"))return;closeBox(e)})}),define("helper.history",["jquery","modules/iframe","deps/mousetrap"],function(e,t,n){var r=function(e){this.settings={limit:20,call:!0},this.set(e),this.clear()};r.prototype.set=function(e){for(var t in e)this.settings[t]=e[t];return this},r.prototype.add=function(e){return this.redos=[],!e instanceof r.Occurence&&(e=new r.Occurence(e)),this.undos.unshift(e),(e.call===!0||typeof e.call=="undefined"&&this.settings.call===!0)&&e.up(),this.settings.limit&&this.undos.splice(this.settings.limit),typeof this.settings.onAdd=="function"&&this.settings.onAdd(e),this},r.prototype.clear=function(){return this.redos=[],this.undos=[],typeof this.settings.onClear=="function"&&this.settings.onClear(),this},r.prototype.revert=function(){var e;while(e=this.undos.shift())e.down();return this.clear()},r.prototype.undo=function(){var e;if(e=this.undos.shift())this.redos.unshift(e),e.down(),typeof this.settings.onUndo=="function"&&this.settings.onUndo(e),this.undos.length==0&&typeof this.settings.onBegin=="function"&&this.settings.onBegin(e);return this},r.prototype.redo=function(){var e;if(e=this.redos.shift())this.undos.unshift(e),e.up(),typeof this.settings.onRedo=="function"&&this.settings.onRedo(e),this.redos.length==0&&typeof this.settings.onEnd=="function"&&this.settings.onEnd(e);return this},r.Occurence=function(e){e=e||{},this.up=e.up||function(){},this.down=e.down||function(){}};var i={init:function(){Headway.history=new r({limit:0}),i.bind()},bind:function(){n.bind(["ctrl+z","command+z"],function(e){return Headway.history.undo(),!1}),n.bind(["ctrl+y","command+y"],function(e){return Headway.history.redo(),!1})}};return i}),define("helper.blocks",["modules/panel.inputs","helper.history"],function(panelInputs,history){getBlockByID=function(e){var e=e.toString().replace("block-","");return $i('.block[data-id="'+e+'"]')},getBlock=function(e){return $(e).length===0?$():($(e).hasClass("block")?block=$(e):$(e).parents(".block").length===1?block=$(e).parents(".block"):block=!1,block)},getBlockID=function(e){var t=getBlock(e);return t?t.data("id"):!1},getBlockWrapper=function(e){var t=getBlock(e);return t.closest(".wrapper")},getBlockType=function(e){var t=getBlock(e);return t?t.data("type"):!1},getBlockTypeNice=function(e){return typeof e!="string"?!1:getBlockTypeObject(e).name},getBlockTypeIcon=function(e,t){return typeof t=="undefined"&&(t=!1),typeof Headway.allBlockTypes[e]!="object"?null:t===!0?Headway.blockTypeURLs[e]+"/icon-white.png":Headway.blockTypeURLs[e]+"/icon.png"},getBlockTypeObject=function(e){var t=Headway.allBlockTypes;return typeof t[e]=="undefined"?{"fixed-height":!1}:t[e]},getBlockGridWidth=function(e){var t=getBlock(e);return t?t.attr("data-width"):!1},setBlockGridWidth=function(e,t){var n=getBlock(e);if(!n)return!1;var r=n.attr("data-width");return r&&n.removeClass("grid-width-"+r),n.css("width",""),n.addClass("grid-width-"+t),n.attr("data-width",String(t).replace("grid-width-","")),n},getBlockGridLeft=function(e){var t=getBlock(e);return t?t.attr("data-grid-left"):!1},setBlockGridLeft=function(e,t){var n=getBlock(e);if(!n)return!1;var r=getBlockGridLeft(n);return r&&n.removeClass("grid-left-"+r),n.addClass("grid-left-"+t),n.attr("data-grid-left",String(t).replace("grid-left-","")),n},getBlockDimensions=function(e){var t=getBlock(e);return t?{width:getBlockGridWidth(t),height:t.attr("data-height")}:!1},getBlockDimensionsPixels=function(e){var t=getBlock(e);return t?{width:t.width(),height:t.height()}:!1},getBlockPosition=function(e){var t=getBlock(e);return t?{left:getBlockGridLeft(t),top:t.attr("data-grid-top")}:!1},getBlockPositionPixels=function(e){var t=getBlock(e);return t?{left:t.position().left,top:t.position().top}:!1},isBlockMirrored=function(e){var t=getBlock(e);return t.hasClass("block-mirrored")},getBlockMirrorOrigin=function(e){var t=getBlock(e);return isBlockMirrored(t)?t.data("block-mirror"):!1},getBlockMirrorLayoutName=function(e){var t=getBlock(e);return isBlockMirrored(t)?t.data("block-mirror-layout-name"):!1},updateBlockContentCover=function(e){if(Headway.mode!="grid")return!1;e.children(".block-content-cover").remove();var t=getBlockType(e),n=getBlockTypeNice(t),r="";return e.data("temp-id")&&(r=" <span>Unsaved</span>"),n||(n="Select Block Type"),e.data("alias")&&(n=e.data("alias")+" - "+n),e.append(' <div class="block-content-cover"> <svg xmlns="http://www.w3.org/2000/svg" version="1.1"> <line class="x-line" x1="0" y1="0" x2="100%" y2="100%" /> <line class="x-line" x1="0" y1="100%" x2="100%" y2="0" /> </svg> <span class="block-type-and-id">'+n+r+"</span> </div> "),e.find("div.block-content-cover")},loadBlockContent=function(e){var t={},n={blockElement:!1,blockSettings:{},blockOrigin:!1,blockDefault:!1,callback:function(e){},callbackArgs:null};$.extend(t,n,e);var r=t.blockElement.find("div.block-content"),i=getBlockType(t.blockElement);return Headway.gridSafeMode==1?r.html('<div class="alert alert-red block-safe-mode"><p>Grid Safe mode enabled. Block content not outputted.</p></div>'):Headway.mode=="grid"&&!getBlockTypeObject(i)["show-content-in-grid"]?(typeof t.callback=="function"&&t.callback(t.callbackArgs),r.html("")):(createCog(r,!0,!0,Headway.iframe.contents(),1),$.ajax({url:Headway.ajaxURL,cache:!1,type:"POST",dataType:"text",data:{security:Headway.security,action:"headway_visual_editor",method:"load_block_content",unsaved_block_settings:t.blockSettings,block_origin:t.blockOrigin,block_default:t.blockDefault,layout:Headway.currentLayout,mode:Headway.mode}}).done(function(e){typeof t.callback=="function"&&t.callback(t.callbackArgs);if(Headway.mode=="grid"){var e=e.replace(/script/g,"SCRIPTTOCHECK"),n=$($.parseHTML(e));n.find("SCRIPTTOCHECK").remove()}else var n=$(e);return typeof window.frames["content"].jQuery!="undefined"&&window.frames.content.jQuery("#block-"+getBlockID(t.blockElement)).html(n).length?(Headway.mode=="design"&&refreshInspector(),window.frames.content.jQuery("#block-"+getBlockID(t.blockElement))):(r.html(n),Headway.mode=="design"&&refreshInspector(),r)}))},refreshBlockContent=function(e,t,n,r){if(typeof e=="undefined"||!e)return!1;if(typeof r=="undefined")var r=!0;var i=function(){var r=$i('.block[data-id="'+e+'"]'),i=GLOBALunsavedValues.blocks[e].settings;loadBlockContent({blockElement:r,blockSettings:{settings:i,dimensions:getBlockDimensions(r),position:getBlockPosition(r)},blockOrigin:e,blockDefault:{type:getBlockType(r),id:0,layout:Headway.currentLayout},callback:t,callbackArgs:n})};if(!r)return i();typeof updateBlockContentFloodTimeoutAfter!="undefined"&&clearTimeout(updateBlockContentFloodTimeoutAfter),typeof updateBlockContentFloodTimeout=="undefined"?(i.call(),updateBlockContentFloodTimeout=setTimeout(function(){delete updateBlockContentFloodTimeout},500)):updateBlockContentFloodTimeoutAfter=setTimeout(function(){i.call(),delete updateBlockContentFloodTimeoutAfter},600)},setupBlockContextMenu=function(e){if(typeof e=="undefined")var e=!0;setupContextMenu({id:"block",elements:".block:visible",title:function(e){var t=getBlock(e.currentTarget),n=getBlockID(t),r=getBlockType(t),i=r?getBlockTypeNice(r)+" ":"",s=getBlockTypeIcon(r,!0),o=s?' style="background-image:url('+s+');"':null;return'<span class="type type-'+r+'" '+o+"></span>"+i+"Block"},contentsCallback:function(t){var n=$(this),r=getBlock(t.currentTarget),i=getBlockID(r),s=getBlockType(r),o=getBlockTypeNice(s),u=Headway.touch?"tap":"click";$('<li class="context-menu-block-options"><span>Open Block Options</span></li>').appendTo(n).on(u,function(){openBlockOptions(r)}),$('<li class="context-menu-block-switch-type"><span>Switch Block Type</span></li>').appendTo(n).on(u,function(){openBlockTypeSelector(r)}),$('<li class="context-menu-set-alias"><span>Set Block Alias</span></li>').appendTo(n).on(u,function(){var e=prompt("Please enter the desired block alias.",r.data("alias"));if(!e)return;dataSetBlockOption(getBlockID(r),"alias",e),r.data("alias",e),updateBlockContentCover(r)}),isBlockMirrored(r)&&$('<li class="context-menu-block-unmirror"><span>Unmirror Block</span></li>').appendTo(n).on(u,function(){if(!confirm("Are you sure you want to unmirror this block?\n\nIt will no longer copy the options and styling from the block it is currently mirroring."))return;updateBlockMirrorStatus(!1,r,""),dataSetBlockOption(getBlockID(r),"mirror-block",""),reloadBlockOptions(getBlockID(r))}),e&&$('<li class="context-menu-block-delete"><span>Delete Block</span></li>').appendTo(n).on(u,function(e){if(!confirm("Are you sure you want to delete this block?"))return!1;deleteBlock(r)})}})},bindBlockDimensionsTooltip=function(){if(Headway.touch)return!1;$i("body").delegate(".block","mouseenter",function(e){var t=this,n=typeof $(this).data("qtip")=="undefined"?!0:!1;if(typeof Headway.disableBlockDimensions!="undefined"&&Headway.disableBlockDimensions)return!1;n&&(addBlockDimensionsTooltip($(this)),$(this).data("hoverWaitTimeout",setTimeout(function(){$(t).qtip("reposition"),$(t).qtip("show"),typeof $(t).data("qtip")!="undefined"&&$i("#qtip-"+$(t).data("qtip").id).show()},300)))}),$i("body").delegate(".block","mouseleave",function(e){clearTimeout($(this).data("hoverWaitTimeout"))})},addBlockDimensionsTooltip=function(e){return Headway.touch?!1:($(e).qtip({style:{classes:"qtip-headway qtip-block-dimensions"},position:{my:"top center",at:"bottom center",container:Headway.iframe.contents().find("body"),viewport:$("#iframe-container"),effect:!1},show:{delay:300,solo:!0,effect:!1},hide:{delay:25,effect:!1},content:{text:blockDimensionsTooltipContent}}),$(e).qtip("api"))},blockDimensionsTooltipContent=function(e){var t=getBlock(this),n=getBlockID(t),r=getBlockDimensionsPixels(t).width,i=getBlockDimensionsPixels(t).height,s=getBlockType(t);if(typeof s!="undefined")var o=getBlockTypeNice(s),u=getBlockTypeIcon(s,!0),a=u?' style="background-image:url('+u+');"':null,f=t.data("alias")?": "+t.data("alias"):"",l=getBlockMirrorLayoutName(t)?" from "+getBlockMirrorLayoutName(t):"",c=isBlockMirrored(t)?'<span class="block-info-mirroring">Mirroring'+l+"</span>":"",h=isBlockMirrored(t)?"main-block-info main-block-info-mirrored":"main-block-info",p='<div class="block-info"><span class="block-info-type" '+a+"></span>"+'<span class="'+h+'">'+o+" "+f+"</span>"+c+"</div>";else var p="";if(getBlockTypeObject(s)["fixed-height"])var i=i,d="Height";else var i=Headway.mode=="grid"?i:t.css("minHeight").replace("px",""),d="Min. Height";var v='<span class="block-height"><strong>'+d+":</strong> "+i+"<small>px</small></span>",m='<span class="block-width"><strong>Width:</strong> '+r+"<small>px</small></span>";if($("#input-enable-responsive-grid label.checkbox-checked").length==1||Headway.mode!="grid"&&Headway.responsiveGrid)var m='<span class="block-width"><strong>Max Width:</strong> <small>~</small>'+r+"<small>px</small></span>";var g=getBlockTypeObject(s)["fixed-height"]?"":'<span class="block-fluid-height-message">Height will auto-expand</span>';return p+m+' <span class="block-dimensions-separator">☓</span> '+v+g+'<span class="right-click-message">Right-click to open block options</span>'},openBlockOptions=function(block,subTab){if(typeof block.target!="undefined"||!block)var block=getBlock(this);if(typeof subTab=="undefined")var subTab=null;if(!block||block.hasClass("block-type-unknown"))return!1;var blockID=getBlockID(block),blockType=getBlockType(block),blockTypeName=getBlockTypeNice(blockType),readyTabs=function(){var tab=$("div#block-"+blockID+"-tab");tab.tabs(),panelInputs.bind("div#block-"+blockID+"-tab"),setupTooltips();var callback=eval(tab.find("ul.sub-tabs").attr("data-open-js-callback"));typeof callback=="function"&&callback({block:block,blockID:blockID,blockType:blockType}),handleInputTogglesInContainer(tab.find("div.sub-tabs-content")),subTab&&selectTab(subTab,$("div#block-"+blockID+"-tab")),$("div#block-"+blockID+"-tab").find("select#input-"+blockID+"-mirror-block").val()!=""&&($("div#block-"+blockID+"-tab ul.sub-tabs li:not(#sub-tab-config)").hide(),selectTab("sub-tab-config",$("div#block-"+blockID+"-tab")))},blockTypeIconURL=getBlockTypeIcon(blockType,!0),blockTypeIconStyle=blockTypeIconURL?"background-image:url("+blockTypeIconURL+");":null,blockTabName=blockTypeName+" Block";block.data("alias")&&block.data("alias").length&&(blockTabName=block.data("alias")),addPanelTab("block-"+blockID,'<span class="block-type-icon" style="'+blockTypeIconStyle+'"></span>'+blockTabName,{url:Headway.ajaxURL,data:{security:Headway.security,action:"headway_visual_editor",method:"load_block_options",block_type:blockType,block_id:blockID,unsaved_block_options:getUnsavedBlockOptionValues(blockID),layout:Headway.currentLayout},callback:readyTabs},!0,!0,"block-type-"+blockType),$("div#panel").tabs("option","active",$("#panel-top").children('li[role="tab"]').index($('[aria-controls="block-'+blockID+'-tab"]')))},reloadBlockOptions=function(e,t){if(!$("ul#panel-top").find('[aria-controls="block-'+e+'-tab"]').length)return;if(typeof e=="undefined"||!e)var e=$("ul#panel-top > li.ui-state-active").attr("aria-controls").replace("block-","").replace("-tab","");if($("ul#panel-top > li.ui-state-active").attr("aria-controls").indexOf("block-")!==0)return!1;if(typeof t=="undefined"||!t)var t=$("div#block-"+e+"-tab ul.sub-tabs .ui-state-active a").attr("href").replace("#","");return removePanelTab("block-"+e),openBlockOptions(getBlockByID(e),t)},getUnsavedBlockOptionValues=function(e){if(typeof GLOBALunsavedValues=="object"&&typeof GLOBALunsavedValues["blocks"]=="object"&&typeof GLOBALunsavedValues["blocks"][e]=="object"&&typeof GLOBALunsavedValues["blocks"][e]["settings"]=="object")var t=GLOBALunsavedValues.blocks[e].settings;return typeof t=="object"&&Object.keys(t).length>0?t:null},openBlockTypeSelector=function(e){var t=getBlockID(e);removePanelTab("block-"+t),addPanelTab("block-"+t,"Select Block Type","",!0,!0);var n=$("#block-"+t+"-tab"),r=$(".block-type-selector-original").clone().removeClass("block-type-selector-original").appendTo(n).show();r.find("div.block-type").addClass("tooltip"),setupTooltips(),r.find("div.block-type").bind("click",function(n){var r=$(this).attr("id").replace("block-type-","");if(e.hasClass("blank-block"))e.parents(".wrapper").headwayGrid("setupBlankBlock",r);else if(confirm("Are you sure you wish to switch block types? All settings for this block will be lost.")){var i=switchBlockType(e,r);t=i}$(".qtip").qtip("hide"),removePanelTab("block-"+t),openBlockOptions(getBlockByID(t))}),e.hasClass("blank-block")&&($(".wrapper").bind("mousedown",{block:e},hideBlankBlockTypeSelector),$(document).bind("keyup.esc",{block:e},hideBlankBlockTypeSelector),$i("html").bind("keyup.esc",{block:e},hideBlankBlockTypeSelector),$('ul#panel-top li a[href="#block-'+t+'-tab"]').siblings("span.close").bind("mouseup",{block:e},hideBlankBlockTypeSelector)),$("div#panel").tabs("option","active",$("#panel-top").children('li[role="tab"]').index($('[aria-controls="block-'+t+'-tab"]')));return},hideBlankBlockTypeSelector=function(e){var t=e.data.block;return t.hasClass("blank-block")&&$(e.target).parents(".block").first().get(0)!=$(t).get(0)&&(removePanelTab("block-"+getBlockID(t)),t.remove(),$(".wrapper").unbind("mousedown",hideBlankBlockTypeSelector),$(document).unbind("keyup.esc",hideBlankBlockTypeSelector),$i("html").unbind("keyup.esc",hideBlankBlockTypeSelector)),!0},switchBlockType=function(e,t,n){var r=getBlockTypeIcon(t,!0),i=getBlockType(e),s=getBlockID(e);e.removeClass("block-type-"+i),e.addClass("block-type-"+t),e.data("type",t),(typeof n=="undefined"||n)&&loadBlockContent({blockElement:e,blockOrigin:{type:t,id:0,layout:Headway.currentLayout},blockSettings:{dimensions:getBlockDimensions(e),position:getBlockPosition(e)}}),getBlockTypeObject(t)["fixed-height"]===!0?(e.removeClass("block-fluid-height"),e.addClass("block-fixed-height"),e.css("min-height").replace("px","")!="0"&&e.css({height:e.css("min-height")})):(e.removeClass("block-fixed-height"),e.addClass("block-fluid-height"),e.css("height").replace("px","")!="auto"&&e.css({height:e.css("height")})),getBlockTypeObject(t)["show-content-in-grid"]?e.removeClass("hide-content-in-grid"):e.addClass("hide-content-in-grid"),e.removeClass("block-type-unknown"),oldBlockID=s;var o=Math.ceil(Math.random()*1e9);return e.attr("id","block-"+o).removeData("id").removeData("temp-id").attr("data-id",o).attr("data-temp-id",o),removePanelTab("block-"+oldBlockID),dataDeleteBlock(oldBlockID),dataAddBlock(e),dataSetBlockPosition(o,getBlockPosition(e)),dataSetBlockDimensions(o,getBlockDimensions(e)),dataSetBlockWrapper(o,getBlockWrapper(e).attr("id")),updateBlockContentCover(e),updateBlockMirrorStatus(!1,e,"",!1),allowSaving(),$(".qtip").qtip("hide"),o},blockIntersectCheck=function(e,t){if(typeof t=="undefined"||!t)var t=block.parents(".grid-container").first();var n=blockIntersectCheckCallback(e,t.find(".block"));if(n.length>1){n.addClass("block-error");var r=!1}else{var i=0;t.find(".block-error").each(function(){var e=blockIntersectCheckCallback(this,t.find(".block"));e.length===1||!e?$(this).removeClass("block-error"):i++});var r=i===0?!0:!1}return r?(Headway.overlappingBlocks=!1,hideNotification("overlapping-blocks")):(Headway.overlappingBlocks=!0,showErrorNotification({id:"overlapping-blocks",message:"There are <strong>overlapping blocks</strong>.<br />Please separate them before saving.",closeTimer:!1})),r},blockIntersectCheckCallback=function(e,t){if(e==0||t==0||!$(e).is(":visible"))return!1;var n=[],r=5,i=$(e),s=i.offset(),o=[s.left,s.left+i.outerWidth()],u=[s.top,s.top+i.outerHeight()];return $(t).each(function(){var e=$(this);if(!e.is(":visible"))return;var t=e.offset(),i=[t.left,t.left+e.outerWidth()],s=[t.top,t.top+e.outerHeight()];o[0]+r<i[1]&&o[1]-r>i[0]&&u[0]<s[1]&&u[1]>s[0]&&n.push(this)}),$(n)},deleteBlock=function(e){if(typeof e!="object")var e=$i('.block[data-id="'+e+'"]');var t=getBlockID(e),n=getBlock(e),r=n.parents(".grid-container");Headway.history.add({description:"Deleted block",up:function(){n.hide(),removePanelTab("block-"+t),dataDeleteBlock(t),blockIntersectCheck(!1,r)},down:function(){n.show(),typeof GLOBALunsavedValues["blocks"][getBlockID(n)]["delete"]!="undefined"&&delete GLOBALunsavedValues.blocks[getBlockID(n)]["delete"],blockIntersectCheck(n,r)}}),allowSaving()},exportBlockSettingsButtonCallback=function(e){var t={security:Headway.security,action:"headway_visual_editor",method:"export_block_settings","block-id":e.blockID},n=Headway.ajaxURL+"?"+$.param(t);return window.open(n)},initiateBlockSettingsImport=function(e){var t=e.input,n=e.blockID,r=$(t).parents(".ui-tabs-panel").first().find('input[name="block-import-settings-file"]'),i=hwBoolean($(t).parents(".ui-tabs-panel").first().find('input[name="block-import-settings-include-options"]').val()),s=hwBoolean($(t).parents(".ui-tabs-panel").first().find('input[name="block-import-settings-include-design"]').val());if(!r.val())return alert("You must select a block settings export file before importing.");if(!i&&!s)return alert("You must import at least the options or design when importing block settings.");var o=r.get(0).files[0];if(o&&typeof o.name!="undefined"&&typeof o.type!="undefined"){var u=new FileReader;u.onload=function(e){var t=e.target.result,r=JSON.parse(t);if(r["data-type"]!="block-settings")return alert("Cannot load block settings. Please insure that the block settings are a proper Headway block settings export.");if(getBlockType(getBlockByID(n))!=r["type"])return alert("Block type mismatch. Be sure that the block settings export is the same type of block type that you're importing to.");typeof r["image-definitions"]!="undefined"&&Object.keys(r["image-definitions"]).length?(showNotification({id:"importing-images",message:"Currently importing images.",closeTimer:1e4}),$.post(Headway.ajaxURL,{security:Headway.security,action:"headway_visual_editor",method:"import_images",importFile:r},function(e){var t=e;if(typeof t["error"]!="undefined")return alert("Error while importing images for block: "+t.error);importBlockSettingsAJAXCallback(n,t,i,s)})):importBlockSettingsAJAXCallback(n,r,i,s)},u.readAsText(o)}else alert("Cannot load block settings. Please insure that the block settings are a proper Headway block settings export.")},importBlockSettingsAJAXCallback=function(e,t,n,r){if(n){var e=switchBlockType(getBlockByID(e),getBlockType(getBlockByID(e)));importBlockSettings(t.settings,e),removePanelTab("block-"+e),openBlockOptions(getBlockByID(e))}r&&typeof t["styling"]!="undefined"&&typeof t["id"]!="undefined"&&(dataPrepareDesignEditor(),$.each(t.styling,function(n,r){var i=t.id,s=e,n=n.replace("block-"+i,"block-"+s);$.each(r.properties,function(e,t){dataSetDesignEditorProperty({element:r.element,property:e,value:t!==null?t.toString():null,specialElementType:"instance",specialElementMeta:n})})}),showNotification({id:"block-design-imported-"+e,message:"Block design successfully imported",closeTimer:6e3,success:!0})),allowSaving()},importBlockSettings=function(e,t){dataPrepareBlock(t),GLOBALunsavedValues.blocks[t].settings=e,refreshBlockContent(t),showNotification({id:"block-settings-imported-"+t,message:"Block settings successfully imported",closeTimer:6e3,success:!0})},updateBlockMirrorStatus=function(e,t,n,r){if(typeof e=="undefined"||e==0)e=$();typeof r=="undefined"&&(r=!0);if(typeof t!="object")var t=getBlock($i('.block[data-id="'+t+'"]'));typeof n=="undefined"||n==""?(e.parents(".panel").find("ul.sub-tabs li:not(#sub-tab-config)").show(),t.attr("id","block-"+t.data("id")),t.data("block-mirror",!1),t.removeClass("block-mirrored")):(e.parents(".panel").find("ul.sub-tabs li:not(#sub-tab-config)").hide(),t.attr("id","block-"+n),t.data("block-mirror",n),t.addClass("block-mirrored"))}}),define("modules/design/mode-design",["jquery","underscore","deps/colorpicker","helper.blocks"],function(e,t){designEditorRequestElements=function(t){return Headway.elementsRequest&&(!t||typeof t=="undefined")?Headway.elementsRequest:(Headway.elementsRequest=e.post(Headway.ajaxURL,{security:Headway.security,action:"headway_visual_editor",method:"get_design_editor_elements",layout:Headway.currentLayout},function(t){Headway.elementGroups=e.extend({},t.groups),delete t.groups,Headway.elements=t},"json"),Headway.elementsRequest)},designEditorRequestElementData=function(t){return Headway.elementDataRequest&&(!t||typeof t=="undefined")?Headway.elementDataRequest:(Headway.elementDataRequest=e.post(Headway.ajaxURL,{security:Headway.security,action:"headway_visual_editor",method:"get_design_editor_element_data",layout:Headway.currentLayout},function(e){Headway.elementData=e},"json"),Headway.elementDataRequest)},designEditorTabEditor=function(){var n=this;this._init=function(){createCog(e("#design-editor-element-selector")),e.when(designEditorRequestElements(),designEditorRequestElementData()).then(this.setupElementSelector),this.bindElementSelector(),this.setupTabs(),this.setupBoxes(),this.bindDesignEditorInfo()},this.setupTabs=function(){e("#side-panel-top").tabs()},this.setupBoxes=function(){designEditorBindPropertyBoxToggle()},this.setupElementSelector=function(){e("#design-editor-element-selector").empty(),e.each(Headway.elementGroups,function(t,n){var r=e('<li id="element-group-'+t+'" class="element-group has-children"> <span class="element-group-name">'+n.name+'</span> <span class="element-expander"></span> <ul class="group-elements"></ul> </li>');typeof n.description!="undefined"&&n.description&&r.find(".element-group-name").after('<small class="description">'+n.description+"</small>"),r.appendTo("#design-editor-element-selector")}),e.each(Headway.elements,designEditor.addElementToSelector),e("#design-editor-element-selector li.element").each(function(){var t=e(this).data("parent");if(!t)return;var n=e("#design-editor-element-selector li#element-"+t);n.hasClass("has-children")||(n.addClass("has-children"),n.prepend('<span class="element-expander"></span>'),n.append('<ul class="children-elements"></ul>')),e(this).appendTo(n.find("> ul.children-elements")),e(this).hasClass("customized-element")&&n.addClass("had-customized-children")}),e("#design-editor-element-selector li.element").each(function(){designEditor.addElementStates(e(this)),designEditor.addElementInstances(e(this))}),e("body").bind("headwayIframeLoad",function(){designEditor.showOnlyLayoutElements()})},this.showAllElements=function(t){e("#design-editor-element-selector-container").removeClass("show-only-layout-elements"),e("#design-editor-element-selector li.not-on-layout").each(function(){e(this).show().removeClass("not-on-layout")})},this.showOnlyLayoutElements=function(){e("#design-editor-element-selector-container").addClass("show-only-layout-elements"),e("#design-editor-element-selector li.element").each(function(){if(!e(this).data("selector"))return;!$i(e(this).data("selector")).length&&!e(this).data("state-id")?e(this).hide().addClass("not-on-layout"):e(this).show().removeClass("not-on-layout")})},this.bindElementSelector=function(){var t=e("ul#design-editor-element-selector"),n=e("ul#design-editor-styles");t.on("click",designEditor.processNoElementClick),t.on("mouseenter","li span.element-name",designEditor.processElementMouseEnter),t.on("mouseleave","li span.element-name",designEditor.processElementMouseLeave),t.on("click","li span.element-name",designEditor.processElementClick),t.on("click","li span.element-expander",designEditor.processElementExpanderClick),t.on("click","li span.element-name span.element-name-button-layout-specific",designEditor.processElementNameLayoutSpecific),t.on("click","li span.element-name span.element-name-button-live-css",designEditor.processElementNameLiveCSS),n.on("click","li.property .property-value",designEditor.processPropertyValueClick),n.on("click","li.property .property-delete",designEditor.processPropertyDeleteClick),e("#side-panel-collapse-arrow").on("click",toggleDesignEditor),e("#element-selector-show-current-layout-elements").on("click",designEditor.showOnlyLayoutElements),e("#element-selector-show-all-elements").on("click",designEditor.showAllElements)},this.addElementToSelector=function(t,n){var r=n.description?'<small class="description">'+n.description+"</small>":"",i=e('<li id="element-'+t+'" data-element-id="'+t+'" class="element" data-selector="'+n.selector+'"> <span class="element-name">'+n.name+"</span> "+r+" </li>");i.data({group:n.group,parent:n.parent,selector:n.selector,id:t}),n.customized&&i.addClass("customized-element"),i.appendTo(e("li#element-group-"+n.group+" ul.group-elements"))},this.addElementInstances=function(n){var r=n.data("element-id"),i=designEditorGetElementObject(r,!1).instances;if(t.isEmpty(i))return!1;var s=e.map(i,function(e,t){return[e]});s.sort(function(e,t){return e.name<t.name?-1:e.name>t.name?1:0}),n.hasClass("has-children")||(n.addClass("has-children"),n.prepend('<span class="element-expander"></span>'),n.append('<ul class="children-elements"></ul>')),n.children(".children-elements").prepend(' <li id="element-'+r+'-instances" class="element element-instances-container has-children"> <span class="element-expander"></span> <span class="element-name">Instances</span> <ul class="children-elements"></ul> </li> '),n.addClass("instances-visible"),e.each(s,function(t,i){var s=i.id,o=i.name;typeof i["state-of"]!="undefined"&&i["state-of"]&&(o=" -- "+i["state-name"]);var u=e('<li id="element-instance-'+s+'" data-element-id="'+r+'" data-instance-id="'+s+'" data-selector="'+i.selector+'" class="element element-instance"> <span class="element-name">'+o+'</span> <small class="description">'+i["layout-name"]+"</small> </li>").appendTo(n.find("> ul.children-elements > li.element-instances-container > ul.children-elements"));u.data({selector:i.selector}),typeof i["customized"]!="undefined"&&i.customized&&u.addClass("customized-element")})},this.addElementStates=function(n){var r=n.data("element-id"),i=designEditorGetElementObject(r).states;if(t.isEmpty(i))return!1;n.hasClass("has-children")||(n.addClass("has-children"),n.prepend('<span class="element-expander"></span>'),n.append('<ul class="children-elements"></ul>')),n.children(".children-elements").prepend(' <li id="element-'+r+'-states" class="element element-states-container has-children"> <span class="element-expander"></span> <span class="element-name">States</span> <ul class="children-elements"></ul> </li> '),n.addClass("states-visible"),e.each(i,function(t,i){var s=e('<li id="element-state-'+t+"-for-"+r+'" data-element-id="'+r+'" data-state-id="'+t+'" data-selector="'+i.selector+'" class="element element-state"> <span class="element-name">'+i.name+"</span> </li>").appendTo(n.find("> ul.children-elements > li.element-states-container > ul.children-elements"));s.data({selector:i.selector})})},this.showElementProperties=function(r){if(typeof r!="object")var r=e(this);var i=r.data("element-id");e("ul#design-editor-styles").empty().show(),e(".design-editor-styles-message").hide();if(t.isEmpty(Headway.elementData[i])){e("ul#design-editor-styles").empty(),e("#design-editor-styles-no-styles").show(),e("#design-editor-styles-nothing-selected").hide();return}e("ul#design-editor-styles").prepend("<h2>"+r.children(".element-name").first().text()+"</h2>");var s=Headway.elementData[i],o=e('<li class="properties"><ul></ul></li>'),u=e("ul#design-editor-styles");t.isEmpty(Headway.elementData[i].properties)||e.each(Headway.elementData[i].properties,function(e,t){n.addElementProperty(u,e,t)});var a=["instance","state","layout"];return e.each(a,function(r,s){t.isEmpty(Headway.elementData[i]["special-element-"+s])||e.each(Headway.elementData[i]["special-element-"+s],function(r,o){if(s=="layout")var a=e('#layout-selector span[data-layout-id="'+r+'"] strong').text(),f="";else{if(!!t.isUndefined(designEditorGetElementObject(i,!1)[s+"s"][r]))return;var a=designEditorGetElementObject(i,!1)[s+"s"][r].name;if(typeof designEditorGetElementObject(i,false)[s+"s"][r]["layout-name"]!="undefined")var f=" – Layout: "+designEditorGetElementObject(i,!1)[s+"s"][r]["layout-name"];else var f=""}e.each(o,function(e,t){n.addElementProperty(u,e,t,{type:s,id:r,name:a,layoutName:f})})})}),setupTooltips(),o},this.showElementPropertiesThrottled=t.throttle(this.showElementProperties,300),this.addElementProperty=function(n,r,i,s){if(i=="DELETE")return!1;if(typeof Headway.designEditorProperties[r]=="undefined")return!1;var o,u=Headway.designEditorProperties[r],a=u.group.toLowerCase().replace(" ","-");n.find('.property-value-group-name[data-property-group-id="'+a+'"]').length||(n.append('<li class="property-value-group-name" data-property-group-id="'+a+'">'+u.group+"</strong></li>"),n.append('<ul data-property-group-id="'+a+'"></ul>'));if(t.isEmpty(i))o="Inheriting";else if(u["type"]=="color"){var f=i.replace("#","");f.length==6&&(f="#"+f),o=' <div class="colorpicker-box-container"> <div style="background-color: '+f+'" class="colorpicker-box"></div> </div>',i.replace("#","").toUpperCase().length==6&&(o+='<span style="font-family:monospace;">#'+i.replace("#","").toUpperCase()+"</span>")}else if(u["type"]=="image")o=' <span class="tooltip tooltip-left" title="<img src=\''+i+"' style='max-width:300px;height:auto;' />\" >Preview</span> ";else if(u.unit&&i){if(typeof u["unit"]!="object")var l=u.unit;else{var l=i.replace(/^[+-]?\d+(\.\d+)?/g,"");l||(u.unit["default"]||(u.unit["default"]="px"),l=u.unit["default"]),i=i.replace(l,"")}o=i+'<span class="unit">'+l+"</span>"}else if(u["type"]=="font-family-select"){var c=i.split("|"),h=t.first(c)=="google"?!0:!1;if(h){var p=c[1];webFontQuickLoad(i)}else var p=i;o='<span style="font-family:'+p+';">'+p.capitalize()+"</span>"}else t.isString(i)&&(o=i.capitalize());if(typeof s=="undefined"){var d=e(' <li class="property" data-property-id="'+r+'" data-property-group-id="'+a+'"> <strong title="'+u.name+'">'+u.name+'</strong> <span class="property-delete"></span> <span class="property-value" title="Click to Edit">'+o+"</span> </li> ");d.appendTo(n.find('ul[data-property-group-id="'+a+'"]'))}else{n.find('[data-property-id="'+r+'"]:not([data-special-element-type])').length||n.find('ul[data-property-group-id="'+a+'"]').append(' <li class="property" data-property-id="'+r+'" data-property-group-id="'+a+'"> <strong>'+u.name+"</strong> </li> ");var d=e(' <li class="property" data-property-id="'+r+'" data-property-group-id="'+a+'" data-special-element-type="'+s.type+'" data-special-element-id="'+s.id+'"> <strong title="'+s.name.split(" – ")[0]+s.layoutName+'">'+s.name.split(" – ")[0]+'</strong> <span class="property-delete"></span> <span class="property-value" title="Click to Edit">'+o+"</span> </li> ");n.find('[data-property-id="'+r+'"]').not("[data-special-element-type]").last().addClass("has-special-element-properties"),d.insertAfter(n.find('[data-property-id="'+r+'"]').last())}},this.processPropertyValueClick=function(){var n=e("ul#design-editor-element-selector li.ui-state-active").first(),r=n.data("element-id"),i=e(this).parents("li.property").first(),s=i.data("special-element-type"),o=i.data("special-element-id");return t.isEmpty(s)?n.children("span.element-name").trigger("click",[i.data("property-group-id")]):designEditor.selectSpecialElement(r,s,o,i.data("property-group-id"))},this.processPropertyDeleteClick=function(){var n=e("ul#design-editor-element-selector li.ui-state-active").first(),r=designEditorGetElementObject(n.data("element-id"),!1),i=e(this).parents("li.property").first(),s=i.data("property-id"),o=i.data("special-element-type"),u=i.data("special-element-id");if(t.isEmpty(o))var a=r.selector;else if(o=="layout")var a=("body.layout-using-"+u+" "+r.selector).replace(" body","");else var a=r[o+"s"][u].selector;stylesheet.delete_rule_property(a,s),i.remove(),n.find("> .children-elements > .properties ul li").length||(n.find("> .children-elements > .properties").remove(),n.removeClass("properties-visible"),n.find("> .children-elements li").length||(n.find("> .children-elements, > .element-expander").remove(),n.removeClass("has-children").removeClass("children-visible"))),dataSetDesignEditorProperty({element:r.id,property:s,value:"DELETE",specialElementType:o,specialElementMeta:u})},this.processNoElementClick=function(t){if(e(t.target).is("span"))return;e("body").removeClass("design-editor-element-selected"),e("ul#design-editor-element-selector").find(".ui-state-active").addClass("element-just-selected").removeClass("ui-state-active"),removeInspectorVisibleBoxModal(),setSelectedElement({}),$i(".inspector-element-selected").removeClass("inspector-element-selected"),e("#design-editor-styles-no-styles").hide(),e("#design-editor-styles-nothing-selected").show(),e("ul#design-editor-styles").empty().hide()},this.processElementExpanderClick=function(t){e(this).parent().toggleClass("children-visible")},this.processElementMouseEnter=function(t){var n=e(this).parent();if(n.hasClass("element-group")||n.hasClass("element-instances-container")||n.hasClass("element-states-container"))return;var r=n.data("element-id"),i=designEditorGetElementObject(r,!1);e(".element-just-selected").removeClass("element-just-selected"),$i(".inspector-element-hover").removeClass("inspector-element-hover"),$i(n.data("selector")).addClass("inspector-element-hover");if(!n.hasClass("element-name-has-buttons")){var s=n.children(".element-name");!n.hasClass("element-instance")&&!n.hasClass("element-state")&&s.append('<span class="element-name-button element-name-button-layout-specific tooltip" title="Edit Element Only On This Layout"></span>'),s.append('<span class="element-name-button element-name-button-live-css tooltip" title="Edit in Live CSS"></span>'),s.find(".tooltip").qtip({style:{classes:"qtip-headway qtip-headway-element-selector",tip:!1},position:{my:"bottom left",at:"top center",viewport:e(window),adjust:{y:-5,method:"flipinvert"}}}),n.addClass("element-name-has-buttons")}},this.processElementMouseLeave=function(t){var n=e(this).parent();if(n.hasClass("element-group")||n.hasClass("ui-state-active")||n.hasClass("element-instances-container"))return;var r=n.data("element-id"),i=designEditorGetElementObject(r);$i(n.data("selector")).removeClass("inspector-element-hover"),n.children(".element-name").find(".element-name-button").each(function(){e(this).qtip("api").destroy(!0),e(this).remove()}),n.removeClass("element-name-has-buttons")},this.processElementClick=function(t,n){var r=e(this).parent();if(e(t.target).hasClass("element-name-button")||r.hasClass("element-instances-container"))return;if(r.hasClass("element-group"))return;if(r.hasClass("element-instance"))return designEditor.selectSpecialElement(r.data("element-id"),"instance",r.data("instance-id"),n);if(r.hasClass("element-state"))return designEditor.selectSpecialElement(r.data("element-id"),"state",r.data("state-id"),n);var i=getElementNodeName(r),s=r.data("element-id"),o=designEditorGetElementObject(s,!1);e("body").addClass("design-editor-element-selected"),r.hasClass("has-children")&&r.addClass("children-visible"),e(this).parents("li.has-children").addClass("children-visible"),e("div#design-editor-element-selector-container").animate({scrollTop:r.offset().top-(150-e("div#design-editor-element-selector-container").scrollTop())},300),e("div.design-editor-info span.customize-for-regular-element").hide(),e("div.design-editor-info span.customize-element-for-layout").show(),inspectorSelectElement(o.selector),setSelectedElement({id:s,name:i,object:o}),designEditorShowCog(),e.when(designEditor.loadElementInputs(s)).then(function(){designEditorShowContent(n)}),e("ul#design-editor-element-selector").find(".ui-state-active").removeClass("ui-state-active"),r.addClass("ui-state-active"),designEditor.showElementProperties(r)},this.processElementNameLayoutSpecific=function(){var t=e(this).parents("li.element").first(),n=t.data("element-id");designEditor.selectSpecialElement(n,"layout",Headway.currentLayout)},this.processElementNameLiveCSS=function(){var t=e(this).parents("li.element").first(),n=t.data("selector"),r=typeof liveCSSEditor=="undefined"||!liveCSSEditor?e("textarea#live-css").val():liveCSSEditor.getValue(),i=r?"\n\n":"";e("textarea#live-css").val(r+i+n+" {\n\n}"),e("#open-live-css").trigger("click");if(typeof liveCSSEditor!="undefined"){liveCSSEditor.setValue(e("textarea#live-css").val());var s=liveCSSEditor.session.getLength();liveCSSEditor.gotoLine(s-1),liveCSSEditor.focus()}},this.processElementCopy=function(n){var r=getSelectedElement();if(!r)return;var i=typeof r.specialElementName!="undefined"?r.specialElementName:r.name;if(!t.isEmpty(Headway.elementData[r.id]))if(r.specialElementType&&!t.isEmpty(Headway.elementData[r.id]["special-element-"+r.specialElementType])){if(!t.isEmpty(Headway.elementData[r.id]["special-element-"+r.specialElementType][r.specialElementID]))var s=Headway.elementData[r.id]["special-element-"+r.specialElementType][r.specialElementID]}else if(!t.isEmpty(Headway.elementData[r.id].properties))var s=Headway.elementData[r.id].properties;if(typeof s=="undefined"||t.isEmpty(s))return!1;showNotification({id:"copied-design-properties",message:"Copied properties from <strong>"+i+"</strong>",closeTimer:2e3,overwriteExisting:!0}),Headway.designEditorClipboard=e.extend({},s)},this.processElementPaste=function(n){var r=getSelectedElement();if(!r||typeof Headway.designEditorClipboard=="undefined")return;var i=typeof r.specialElementName!="undefined"?r.specialElementName:r.name;if(!t.isEmpty(Headway.elementData[r.id]))if(r.specialElementType&&!t.isEmpty(Headway.elementData[r.id]["special-element-"+r.specialElementType])){if(!t.isEmpty(Headway.elementData[r.id]["special-element-"+r.specialElementType][r.specialElementID]))var s=Headway.elementData[r.id]["special-element-"+r.specialElementType][r.specialElementID]}else if(!t.isEmpty(Headway.elementData[r.id].properties))var s=Headway.elementData[r.id].properties;if(typeof s=="undefined")var s={};e.each(s,function(e,t){dataSetDesignEditorProperty({element:r.id,property:e,value:"DELETE",specialElementType:r.specialElementType,specialElementMeta:r.specialElementID})}),e.each(Headway.designEditorClipboard,function(e,t){typeof Headway.designEditorProperties[e]["unit"]!="undefined"&&!isNaN(t)&&(typeof Headway.designEditorProperties[e]["unit"]=="string"?t+=Headway.designEditorProperties[e].unit:typeof Headway.designEditorProperties[e]["unit"]["default"]!="undefined"&&(t+=Headway.designEditorProperties[e].unit["default"])),dataSetDesignEditorProperty({element:r.id,property:e,value:t,specialElementType:r.specialElementType,specialElementMeta:r.specialElementID})});if(r.specialElementType)var s=Headway.elementData[r.id]["special-element-"+r.specialElementType][r.specialElementID];else var s=Headway.elementData[r.id].properties;e.each(s,function(e,t){dataDesignEditorPropertyFeedback({element:r.id,property:e,value:t,specialElementType:r.specialElementType,specialElementMeta:r.specialElementID})}),showNotification({id:"copied-design-properties",message:"Pasted properties onto <strong>"+i+"</strong>",closeTimer:2e3,overwriteExisting:!0,success:!0})},this.loadElementInputs=function(t,n){var r={security:Headway.security,action:"headway_visual_editor",method:"get_element_inputs",unsavedValues:designEditorGetUnsavedValues(t),element:designEditorGetElementObject(t)};if(typeof n=="object"){var i=Object.keys(n)[0],s=n[i];r.specialElementType=i,r.specialElementMeta=s,r.unsavedValues=designEditorGetUnsavedValues(t,i,s),i=="instance"&&(r.element=designEditorGetElementObject(t,!0,s))}return e.post(Headway.ajaxURL,r).success(function(n){var r=e("div.design-editor-options");r.html(n),e("div.design-editor-options").data({element:t,specialElementType:!1,specialElementMeta:!1}),e("div.design-editor-options").find(".property-font-family-select").each(function(){webFontQuickLoad(e(this).find("span.font-name").data("webfont-value"))}),Headway.iframe.focus()})},this.bindDesignEditorInfo=function(){e("span.customize-element-for-layout").bind("click",function(){var e=designEditor.getCurrentElement(),t=e.data("element-id");designEditor.selectSpecialElement(t,"layout",Headway.currentLayout)}),e("span.customize-for-regular-element").bind("click",function(){designEditor.getCurrentElement().find("> span.element-name").trigger("click")})},this.selectSpecialElement=function(t,n,r,i){var s=e("ul#design-editor-element-selector li.element-"+n).filter("[data-"+n+'-id="'+r+'"]').filter('[data-element-id="'+t+'"]');s.length||(s=e('ul#design-editor-element-selector li.element[data-element-id="'+t+'"]').first());var o=designEditorGetElementObject(t,!1),u=n!="layout"?o[n+"s"][r].name:Headway.currentLayoutName,a=n!="layout"?o[n+"s"][r].selector:o.selector;e("body").addClass("design-editor-element-selected"),s.parents("li").addClass("children-visible"),e("div#design-editor-element-selector-container").animate({scrollTop:s.offset().top-(e("div#design-editor-element-selector-container").height()/1.5-e("div#design-editor-element-selector-container").scrollTop())},300),designEditor.showElementProperties(s),n=="layout"?(e("div.design-editor-info span.customize-for-regular-element").show(),e("div.design-editor-info span.customize-element-for-layout").hide()):(e("div.design-editor-info span.customize-for-regular-element").hide(),e("div.design-editor-info span.customize-element-for-layout").hide()),inspectorSelectElement(a);var f={},l={};f[n]=u,l[n]=r,setSelectedElement({id:t,selector:a,name:o.name,specialElementType:n,specialElementID:r,specialElementName:u,object:o});if(typeof loadInputs=="undefined"||loadInputs)designEditorShowCog(),e.when(designEditor.loadElementInputs(t,l)).then(function(){designEditorShowContent(i)});e("ul#design-editor-element-selector").find(".ui-state-active").removeClass("ui-state-active"),s.addClass("ui-state-active")},this.getCurrentElement=function(){return e("ul#design-editor-element-selector li.ui-state-active")},this.switchLayout=function(){if(typeof Headway.switchedToLayout=="undefined"||!Headway.switchedToLayout)return;e.when(designEditorRequestElements(!0)).then(function(){designEditor.setupElementSelector.apply(designEditor),e("div.design-editor-options").hide()})}},toggleDesignEditor=function(){return e("body").hasClass("side-panel-hidden")?showDesignEditor():hideDesignEditor()},hideDesignEditor=function(){return e("body").hasClass("side-panel-hidden")?!1:(e("body").addClass("side-panel-hidden"),setTimeout(repositionTooltips,400),e("#design-editor-toggle span").text("eee"),e.cookie("hide-design-editor",!0),!0)},showDesignEditor=function(){return e("body").hasClass("side-panel-hidden")?(e("body").removeClass("side-panel-hidden"),setTimeout(repositionTooltips,400),e("#design-editor-toggle span").text("iii"),e.cookie("hide-design-editor",!1),!0):!1},designEditorShowCog=function(){e("div#side-panel").addClass("properties-loading"),e("div.design-editor-info").hide(),e("div.design-editor-options").hide(),createCog(e("div#side-panel-bottom"),!0,!0)},designEditorShowContent=function(n){e("div#side-panel-bottom").find(".cog-container").remove(),e("div.design-editor-info").show(),e("div.design-editor-options").show(),e("div#side-panel").removeClass("properties-loading"),t.isEmpty(n)||e(".design-editor-box-"+n).find(".design-editor-box-title").trigger("click"),setupTooltips()},designEditorGetElementObject=function(t,n,r){var i=e("ul#design-editor-element-selector").find("#element-"+t),s=i.data("group"),o=i.data("parent");if(typeof n=="undefined")var n=!0;var t=jQuery.extend(!0,{},Headway.elements[t]);return n&&(typeof r!="undefined"&&r?e.each(t.instances,function(e,n){e!=r&&delete t.instances[e]}):delete t.instances),t},designEditorGetUnsavedValues=function(e,n,r){if(typeof n=="undefined")var n=!1;if(typeof r=="undefined")var r=!1;if(typeof GLOBALunsavedValues=="undefined"||typeof GLOBALunsavedValues["design-editor"]=="undefined"||typeof GLOBALunsavedValues["design-editor"][e]=="undefined")return null;if(!n||!r){if(typeof GLOBALunsavedValues["design-editor"][e]["properties"]=="undefined")return null;var i=GLOBALunsavedValues["design-editor"][e].properties}else{if(typeof GLOBALunsavedValues["design-editor"][e]["special-element-"+n]=="undefined")return null;if(typeof GLOBALunsavedValues["design-editor"][e]["special-element-"+n][r]=="undefined")return null;var i=GLOBALunsavedValues["design-editor"][e]["special-element-"+n][r]}return t.isEmpty(i)?null:i},designEditorBindPropertyBoxToggle=function(){e("div.design-editor-options").delegate("span.design-editor-box-title","click",function(){var t=e(this).parents("div.design-editor-box"),n=t.hasClass("design-editor-box-open");e("div.design-editor-options div.design-editor-box-open").removeClass("design-editor-box-open"),!t.hasClass("design-editor-box-open")&&!n&&t.addClass("design-editor-box-open")})},designEditorBindPropertyInputs=function(){e(".design-editor-options-container").delegate("div.customize-property","click",function(){var t=e(this).parents("li").first();if(t.hasClass("lockable-property")&&t.parents(".box-model-inputs").hasClass("box-model-inputs-locked"))var t=e(this).parents(".box-model-inputs").find("> li.lockable-property");t.each(function(){e(this).find(".customize-property").fadeOut(150),e(this).removeClass("uncustomized-property"),e(this).addClass("customized-property-by-user"),e(this).attr("title","You have customized this property.");var t=e(this).find("input.property-hidden-input"),n=t.parent().find("select, input:not(.property-hidden-input)").first();!t.val()&&n.length&&t.val(n.val()),dataHandleDesignEditorInput({hiddenInput:t,value:t.val()})})}),e(".design-editor-options-container").delegate("span.uncustomize-property","click",function(){if(!confirm("Are you sure you wish to delete this customization?"))return!1;var t=e(this).parents("li").first();if(t.hasClass("lockable-property")&&t.parents(".box-model-inputs").hasClass("box-model-inputs-locked"))var t=e(this).parents(".box-model-inputs").find("> li.lockable-property");t.each(function(){var t=e(this).find("input.property-hidden-input");e(this).find("div.customize-property").fadeIn(150),dataHandleDesignEditorInput({hiddenInput:t,value:"DELETE",unit:""}),e(this).addClass("uncustomized-property",150),e(this).removeClass("customized-property-by-user"),e(this).attr("title","You have set this property to inherit.")})}),e(".design-editor-options-container").delegate(".design-editor-property-font-family span.open-font-browser","click",function(){typeof fontBrowserOpen=="function"&&fontBrowserOpen.apply(this)}),e(".design-editor-options-container").delegate("span.design-editor-lock-sides","click",function(){e(this).parent().hasClass("box-model-inputs-locked")?e(this).attr("data-locked",!1).attr("title","Unlock sides").parent().removeClass("box-model-inputs-locked"):e(this).attr("data-locked",!0).attr("title","Lock sides").parent().addClass("box-model-inputs-locked")}),e(".design-editor-options-container").delegate('.box-model-inputs-locked li.lockable-property input[type="number"]',"keyup blur change",function(t,n){if(typeof n!="undefined"&&n)return;e(this).parents(".box-model-inputs-locked").find(".lockable-property").removeClass("uncustomized-property"),e(this).parents(".box-model-inputs-locked").find('li.lockable-property input[type="number"]').not(e(this)).val(e(this).val()).trigger("change",[!0])}),e(".design-editor-options-container").delegate(".box-model-inputs-locked li.lockable-property select","change",function(t,n){if(typeof n!="undefined"&&n)return;e(this).parents(".box-model-inputs-locked").find(".lockable-property").removeClass("uncustomized-property"),e(this).parents(".box-model-inputs-locked").find("li.lockable-property select").not(e(this)).val(e(this).val()).trigger("change",[!0])}),e(".design-editor-options-container").delegate("div.property-select select","change",designEditorInputSelect),e(".design-editor-options-container").delegate("div.property-integer input","focus",designEditorInputIntegerFocus),e(".design-editor-options-container").delegate("div.property-integer input","keyup blur change",designEditorInputIntegerChange),e(".design-editor-options-container").delegate("div.property-integer .property-unit-select select","change",designEditorInputIntegerUnitChange),e(".design-editor-options-container").delegate("div.property-image span.button","click",designEditorInputImageUpload),e(".design-editor-options-container").delegate("div.property-image span.delete-image","click",designEditorInputImageUploadDelete),e(".design-editor-options-container").delegate("div.property-color div.colorpicker-box","click",designEditorInputColor)},designEditorInputSelect=function(t){var n=e(this).parent().siblings("input.property-hidden-input");dataHandleDesignEditorInput({hiddenInput:n,value:e(this).val()})},designEditorInputIntegerFocus=function(t){typeof originalValues!="undefined"&&delete originalValues,originalValues=new Object;var n=e(this).siblings("input.property-hidden-input"),r=n.attr("selector")+"-"+n.attr("property");originalValues[r]=e(this).val()},designEditorInputIntegerUnitChange=function(t){e(this).parents(".property-integer").find('input[type="number"]').trigger("change")},designEditorInputIntegerChange=function(t){var n=e(this).siblings("input.property-hidden-input"),r=e(this).val();if(t.type=="keyup"&&r=="-")return;if(isNaN(r)){r=r.replace(/[^0-9]*/ig,"");if(r==="")var i=n.attr("selector")+"-"+n.attr("property"),r=originalValues[i];e(this).val(r)}r.length>1&&r[0]==0&&(r=r.replace(/^[0]+/g,""),e(this).val(r)),dataHandleDesignEditorInput({hiddenInput:n,value:e(this).val()})},designEditorInputImageUpload=function(t){var n=this;openImageUploader(function(t,r){var i=e(n).siblings("input");e(n).siblings(".image-input-controls-container").find("span.src").text(r),e(n).siblings(".image-input-controls-container").show(),dataHandleDesignEditorInput({hiddenInput:i,value:t})})},designEditorInputImageUploadDelete=function(t){if(!confirm("Are you sure you wish to remove this image?"))return!1;e(this).parent(".image-input-controls-container").hide(),e(this).hide();var n=e(this).parent().siblings("input");dataHandleDesignEditorInput({hiddenInput:n,value:"none"})},designEditorInputColor=function(t){e("div.design-editor-options-container").css("overflow-y","hidden");var n=e(this).parent().siblings("input"),r=n.val();r=="transparent"&&(r="00FFFFFF");var i=function(e,t){var r="#"+e.hex;if(e.a!=100)var r=e.rgba;dataHandleDesignEditorInput({hiddenInput:n,value:r})};e(this).colorpicker({realtime:!0,alpha:!0,alphaHex:!0,allowNull:!1,showAnim:!1,swatches:typeof Headway.colorpickerSwatches=="object"&&Headway.colorpickerSwatches.length?Headway.colorpickerSwatches:!0,color:r,beforeShow:function(e,t){showIframeOverlay()},onClose:function(t,n){i(t,n),hideIframeOverlay(),e("div.design-editor-options-container").css("overflow-y","auto")},onSelect:function(e,t){i(e,t)},onAddSwatch:function(e,t){dataSetOption("general","colorpicker-swatches",t)},onDeleteSwatch:function(e,t){dataSetOption("general","colorpicker-swatches",t)}}),e.colorpicker._showColorpicker(e(this)),setupTooltips()},propertyInputCallbackFontFamily=function(t){var n=t.selector,r=t.value,i=t.element,s=t.stack?t.stack:t.value;if(!r){stylesheet.delete_rule_property(n,"font-family");return}if(!r.match(/\|/g)){stylesheet.update_rule(n,{"font-family":s});return}var o=r.split("|"),u={},a="";typeof o[2]!="undefined"&&o[2]&&(a=":"+o[2]),u[o[0]]={families:[o[1]+a]};var s=o[1];stylesheet.update_rule(n,{"font-family":s}),typeof e("iframe#content").get(0).contentWindow.WebFont=="object"&&e("iframe#content").get(0).contentWindow.WebFont.load(u)},propertyInputCallbackBackgroundImage=function(e){var t=e.selector,n=e.value,r=e.element;n!="none"?stylesheet.update_rule(t,{"background-image":"url("+n+")"}):n=="none"&&stylesheet.update_rule(t,{"background-image":"none"})},propertyInputCallbackFontStyling=function(e){var t=e.selector,n=e.value,r=e.element;n==="normal"?stylesheet.update_rule(t,{"font-style":"normal","font-weight":"normal"}):n==="bold"?stylesheet.update_rule(t,{"font-style":"normal","font-weight":"bold"}):n==="light"?stylesheet.update_rule(t,{"font-style":"normal","font-weight":"lighter"}):n==="italic"?stylesheet.update_rule(t,{"font-style":"italic","font-weight":"normal"}):n==="bold-italic"?stylesheet.update_rule(t,{"font-style":"italic","font-weight":"bold"}):n===null&&(stylesheet.delete_rule_property(t,"font-style"),stylesheet.delete_rule_property(t,"font-weight"))},propertyInputCallbackCapitalization=function(e){var t=e.selector,n=e.value,r=e.element;n==="none"||n==null?stylesheet.update_rule(t,{"text-transform":"none","font-variant":"normal"}):n==="small-caps"?stylesheet.update_rule(t,{"text-transform":"none","font-variant":"small-caps"}):stylesheet.update_rule(t,{"text-transform":n,"font-variant":"normal"})},propertyInputCallbackShadow=function(t){var n=t.selector,r=t.value,i=t.element,s=t.property,o=s.indexOf("box-shadow")===0?"box-shadow":"text-shadow",u=$i(n).css(o)||!1;if(u==0||u=="none")u="rgba(0, 0, 0, 0) 0 0 0";var a=u.replace(/, /g,",").replace(/px/g,"").split(" "),f=e('li[data-property-id="'+o+"-color"+'"] input').val()||a[0],l=e('li[data-property-id="'+o+"-horizontal-offset"+'"] input').val()||a[1],c=e('li[data-property-id="'+o+"-vertical-offset"+'"] input').val()||a[2],h=e('li[data-property-id="'+o+"-blur"+'"] input').val()||a[3],p=e('li[data-property-id="'+o+"-position"+'"] input').val()||a[4];switch(s){case o+"-horizontal-offset":l=r||0;break;case o+"-vertical-offset":c=r||0;break;case o+"-blur":h=r||0;break;case o+"-inset":p=r;break;case o+"-color":f=r}if(!f)return stylesheet.delete_rule_property(n,o);p=="inset"?p=" inset":p="";var d=f+" "+l+"px "+c+"px "+h+"px"+p,v={};v[o]=d,stylesheet.update_rule(n,v),updateInspectorVisibleBoxModal()},addInspector=function(t){if(typeof Headway.elements=="undefined")return e.when(designEditorRequestElements()).then(addInspector);e.each(Headway.elements,function(e,t){if(!t.inspectable)return;addInspectorProcessElement(t)}),(typeof t=="undefined"||t!==!0)&&$i("body").qtip({id:"",style:{classes:"qtip-headway qtip-inspector-tooltip"},position:{target:[-9999,-9999],my:"center",at:"center",container:$i("body"),viewport:$iDocument(),effect:!1,adjust:{x:35,y:35,method:"flipinvert"}},content:{text:"Hover over an element."},show:{event:!1,ready:!0},hide:!1,events:{render:function(t,n){delete inspectorElement,delete inspectorTooltip,delete inspectorElementOptions,inspectorTooltip=n,e("#toggle-inspector").hasClass("inspector-disabled")?disableInspector():enableInspector()}}})},refreshInspector=function(){return addInspector(!0)},addInspectorProcessElement=function(t){if(t["group"]=="default-elements")return;if(!$i(t.selector).length)return;t["selector"].indexOf(":")==-1&&($i(t.selector).data({inspectorElementOptions:t}),$i(t.selector).addClass("inspector-element")),e.each(t.instances,function(n,r){if(!$i(r.selector).length)return;var i=jQuery.extend(!0,{},t);i.parentName=t.name,i.instance=r.id,i.name=r.name,i.selector=r.selector,i.instances={},e.each(t.instances,function(e,t){t["state-of"]==n&&(i.instances[e]=t)}),e.each(i.selector.split(","),function(e,t){if(t.indexOf(":")!=-1)return;$i(t).data({inspectorElementOptions:i}),$i(t).addClass("inspector-element")})})},enableInspector=function(){if(Headway.mode!="design"||!Headway.designEditorSupport)return!1;Headway.inspectorDisabled=!1,Headway.disableBlockDimensions=!0,$i("body").addClass("disable-block-hover").removeClass("inspector-disabled"),$i(".block[data-hasqtip]").each(function(){var t=e(this).qtip("api");t.destroy()}),inspectorTooltip.show();var t=Headway.touch?"tap":"mousemove";$i("html").bind(t,inspectorMouseMove),setupInspectorContextMenu(),deactivateContextMenu("block"),Headway.iframe.contents().bind("keydown",inspectorNudging),Headway.iframe.bind("keydown",inspectorNudging),Headway.iframe.bind("mouseover",function(){Headway.iframe.focus()}),showNotification({id:"inspector",message:"<strong>Right-click</strong> highlighted elements to style them.<br /><br />Once an element is selected, you may nudge it using your arrow keys.<br /><br />The faded orange and purple are the margins and padding. These colors are only visible when the inspector is active.",closeConfirmMessage:"Please be sure you understand how the Design Editor inspector works before hiding this message.",closeTimer:!1,closable:!0,doNotShowAgain:!0}),updateInspectorVisibleBoxModal(),e("#toggle-inspector").removeClass("inspector-disabled")},disableInspector=function(){if(Headway.mode!="design"||!Headway.designEditorSupport)return!1;Headway.inspectorDisabled=!0,delete Headway.disableBlockDimensions,delete inspectorElement,$i(".inspector-element-hover").removeClass("inspector-element-hover"),$i("body").removeClass("disable-block-hover").addClass("inspector-disabled"),$i(".block").qtip("enable"),e(inspectorTooltip.elements.tooltip).hide(),hideNotification("inspector"),$i("html").unbind("mousemove",inspectorMouseMove),deactivateContextMenu("inspector"),setupBlockContextMenu(!1),Headway.iframe.contents().unbind("keydown",inspectorNudging),Headway.iframe.unbind("keydown",inspectorNudging),removeInspectorVisibleBoxModal(),e("#toggle-inspector").addClass("inspector-disabled")},toggleInspector=function(){if(Headway.mode!="design"||!Headway.designEditorSupport)return!1;if(e("#toggle-inspector").hasClass("inspector-disabled"))return enableInspector();disableInspector()},inspectorSelectElement=function(t){$i(".inspector-element-selected").each(function(){e(this).removeClass("inspector-element-selected"),removeInspectorVisibleBoxModal(e(this))}),$i(t).addClass("inspector-element-selected"),updateInspectorVisibleBoxModal()},removeInspectorVisibleBoxModal=function(t){if(typeof t=="undefined")var t=$i(".inspector-element-selected");return e(t).data("previousBoxShadow")?(e(t).data("previousBoxShadow",null),e(t).css("boxShadow","")):!1},updateInspectorVisibleBoxModal=function(){if(typeof Headway.inspectorDisabled!="undefined"&&Headway.inspectorDisabled)return;$i(".inspector-element-selected").each(function(){removeInspectorVisibleBoxModal(e(this));var t=this,n=e(this).css("box-shadow"),r=n!="none"?n.split(","):[];e(this).data("previousBoxShadow",n),e.each(["paddingTop","paddingRight","paddingBottom","paddingLeft","marginTop","marginRight","marginBottom","marginLeft"],function(n,i){var s=e(t).css(i).replace(/^[+-]?\d+(\.\d+)?/g,""),o=e(t).css(i).replace(s,"");if(o=="auto")return;var u=i.indexOf("padding")!==-1?"rgba(0, 0, 255, .15)":"rgba(255, 127, 0, .15)",a="",f="";if(i=="paddingRight"||i=="paddingBottom"||i=="marginLeft"||i=="marginTop")a="-";var l=a+o+s;if(i.toLowerCase().indexOf("left")!==-1||i.toLowerCase().indexOf("right")!==-1)var c=l+" 0";else var c="0 "+l;i.indexOf("padding")!==-1&&(f="inset "),r.push(f+c+" 0 0 "+u)}),e(this).css({boxShadow:r.join(",")})})},inspectorMouseMove=function(t){if(Headway.inspectorDisabled)return;var n=e(t.target);n.hasClass("inspector-element")||(n=n.parents(".inspector-element").first());if(typeof inspectorElement=="undefined"||!n.is(inspectorElement)){inspectorElement=e(t.target),inspectorElement.hasClass("inspector-element")||(inspectorElement=inspectorElement.parents(".inspector-element").first());var r=inspectorElement.data("inspectorElementOptions");if(typeof r=="object"){$i(".inspector-element-hover").removeClass("inspector-element-hover"),$i(r.selector).addClass("inspector-element-hover");var i=e("#design-editor-element-selector").find("li#element-"+r.id),s=i.children(".element-name").text(),o='<span class="inspector-tooltip-element-path">',u=[];i.parents("li").reverse().each(function(){u.push(e(this).children(".element-group-name, .element-name").first().text())});var a="";typeof r.instance!="undefined"&&(r.name.indexOf(" – ")!==-1?a='<span class="inspector-tooltip-instance">Inside <strong>'+r.name.split(" – ")[0]+"</strong></span>":s=r.name);if(u.join(" > ").length+s.length>40)while(u.join(" > ").length+s.length>40&&s.length<40)u.shift(),tooltipElementPathStr='<span class="ellipsis">...</span> '+u.join(" › ");else tooltipElementPathStr=u.join(" › ");o+=tooltipElementPathStr,o+=" › <strong>"+s+"</strong></span>",o+=a,o+='<small class="right-click-message">Right-click to style</small>',inspectorTooltip.set("content.text",o)}}inspectorTooltip.show();var f=$i("#ui-tooltip-inspector-tooltip").width(),l=$i("body").width()-t.pageX-f+15,c=l>0?t.pageX:t.pageX+l;inspectorTooltip.set("position.target",[c,t.pageY])},setupInspectorContextMenu=function(){return setupContextMenu({id:"inspector",elements:"body",title:function(e){return inspectorElement.data("inspectorElementOptions").name},onShow:inspectorContextMenuOnShow,onHide:function(){inspectorTooltip.show(),Headway.inspectorDisabled=!1},onItemClick:inspectorContextMenuItemClick,contentsCallback:inspectorContextMenuContents})},inspectorContextMenuOnShow=function(t){e(this).data("element-options",inspectorElement.data("inspectorElementOptions")),e(inspectorTooltip.elements.tooltip).hide(),Headway.inspectorDisabled=!0},inspectorContextMenuItemClick=function(t,n){if(e(this).hasClass("group-title")&&!e(this).hasClass("group-title-clickable"))return;if(e(this).parents("li").first().hasClass("inspector-context-menu-block-options"))openBlockOptions(getBlock(e(inspectorElement)));else{var r=t.data("element-options"),i=e(this).parents("li").first().data("instance-id"),s=e(this).parents("li").first().data("state-id");inspectorTooltip.show(),Headway.inspectorDisabled=!1,e("#design-editor-element-selector-container .ui-state-active").removeClass("ui-state-active"),typeof i!="undefined"?designEditor.selectSpecialElement(r.id,"instance",i):typeof s!="undefined"?designEditor.selectSpecialElement(r.id,"state",s):e(this).parents("li").first().hasClass("inspector-context-menu-parent")||e("ul#design-editor-element-selector li#element-"+r.id).find("> span").trigger("click"),e(this).parents("li").first().hasClass("inspector-context-menu-edit-for-layout")&&designEditor.selectSpecialElement(r.id,"layout",Headway.currentLayout)}},inspectorContextMenuContents=function(n){var r=e(this),i=r.data("element-options"),s=typeof i.instance!="undefined"&&i.instance,o=r;if(s){r.append('<li class="inspector-context-menu-edit-instance" data-instance-id="'+i.instance+'"><span>Edit This Instance</span></li>');var o=e('<li class="inspector-context-menu-edit-normal"><span class="group-title group-title-clickable">Edit Regular Element<small>'+i.parentName+"</small></span><ul></ul></li>").appendTo(r);o=o.find("ul").first()}else o.append('<li class="inspector-context-menu-edit-normal"><span>Edit</span></li>');o.append('<li class="inspector-context-menu-edit-for-layout"><span>Edit For This Layout</span></li>');if(!t.isEmpty(i.states)){var u=e('<li class="inspector-context-menu-states"><span class="group-title">States</span><ul></ul></li>').appendTo(o);e.each(i.states,function(e,t){u.find("ul").append('<li data-state-id="'+e+'"><span>Edit '+t.name+"</span></li>")})}if(!t.isEmpty(i.instances)){if(typeof i.instance=="undefined"||!i.instance)var a=e('<li class="inspector-context-menu-instances"><span class="group-title">Instances</span><ul></ul></li>').appendTo(r);else var a=!1;e.each(i.instances,function(t,n){n["state-of"]==i.instance&&(r.find("> li.inspector-context-menu-instance-states").length||e('<li class="inspector-context-menu-instance-states"><span class="group-title">Instance States</span><ul></ul></li>').insertAfter(r.find("li.inspector-context-menu-edit-instance")),r.find("> li.inspector-context-menu-instance-states ul").append('<li data-instance-id="'+t+'"><span>Edit '+n["state-name"]+"</span></li>"))}),a&&!a.find("ul li").length&&a.remove()}if(inspectorElement.parents(".inspector-element").length){var f=e('<li class="inspector-context-menu-parents"><span class="group-title">Parents</span><ul></ul></li>').appendTo(r);inspectorElement.parents(".inspector-element").each(function(){var t=e(this);e('<li class="inspector-context-menu-parent" data-parent-id="'+e(this).data("inspectorElementOptions").id+'"><span>'+e(this).data("inspectorElementOptions").name+"</span></li>").appendTo(f.find("ul")).bind("click",function(){inspectorElement=t;var e=typeof n.data!="undefined"?n.data.x:n.originalEvent.clientX,r=typeof n.data!="undefined"?n.data.y:n.originalEvent.clientY;t.trigger("contextmenu",{x:e,y:r})})})}if(getBlock(inspectorElement))var l=getBlock(inspectorElement),c=getBlockID(l),h=getBlockTypeNice(getBlockType(l)),p=e('<li class="inspector-context-menu-block-options"><span>Open Block Options</span></li>').appendTo(r)},inspectorNudging=function(t){var n=t.keyCode;if(n<37||n>40||!$i(".inspector-element-selected").length||$i(".inspector-element-selected").is("body"))return;var r=t.shiftKey?5:1,i=e(".design-editor-box-nudging .design-editor-property-position select",".design-editor-options-container"),s=i.parents(".design-editor-property-position").find('input[type="hidden"]'),o=s.attr("element_selector");e(".design-editor-box-nudging .uncustomized-property .customize-property span",".design-editor-options-container").trigger("click");if($i(".inspector-element-selected").css("position")!="static"){var u=$i(".inspector-element-selected").css("position");$i(".inspector-element-selected").css({position:u}),i.val(u).trigger("change")}else{var u="relative";$i(".inspector-element-selected").css({position:u}),i.val(u).trigger("change")}switch(n){case 37:var a=parseInt($i(".inspector-element-selected").css("left"));if(isNaN(a))var a=0;stylesheet.update_rule(o,{left:a-r+"px"});var f=$i(".inspector-element-selected").css("left").replace("px","");e('.design-editor-box-nudging .design-editor-property-left input[type="text"]',".design-editor-options-container").val(f).trigger("change");break;case 38:var l=parseInt($i(".inspector-element-selected").css("top"));isNaN(l)&&(l=0),stylesheet.update_rule(o,{top:l-r+"px"});var c=$i(".inspector-element-selected").css("top").replace("px","");e('.design-editor-box-nudging .design-editor-property-top input[type="text"]',".design-editor-options-container").val(c).trigger("change");break;case 39:var a=parseInt($i(".inspector-element-selected").css("left"));if(isNaN(a))var a=0;stylesheet.update_rule(o,{left:a+r+"px"});var f=$i(".inspector-element-selected").css("left").replace("px","");e('.design-editor-box-nudging .design-editor-property-left input[type="text"]',".design-editor-options-container").val(f).trigger("change");break;case 40:var l=parseInt($i(".inspector-element-selected").css("top"));isNaN(l)&&(l=0),stylesheet.update_rule(o,{top:l+r+"px"});var c=$i(".inspector-element-selected").css("top").replace("px","");e('.design-editor-box-nudging .design-editor-property-top input[type="text"]',".design-editor-options-container").val(c).trigger("change")}return t.preventDefault(),!1},getElementNodeName=function(e){var t=e.clone();return t.find("> span").children().remove().end().text()},getSelectedElement=function(){return typeof Headway.designEditorCurrentElement!="undefined"?Headway.designEditorCurrentElement:null},setSelectedElement=function(e){Headway.designEditorCurrentElement=e;if(t.isEmpty(e))return;var n={};typeof e.specialElementType!="undefined"&&(n[e.specialElementType]=e.specialElementName),setSelectedElementDetails(n,e.object)},setSelectedElementDetails=function(n,r){var n=e.extend({},{instance:r.name,layout:"all layouts",state:"all states"},n),i=e("span.design-editor-selection-details");i.find(".design-editor-selected-element").html(n.instance),i.find("strong.design-editor-selection-details-layout").html(n.layout),typeof r.states=="undefined"||t.isEmpty(r.states)?i.find("span.design-editor-selection-details-state-container").hide():(i.find("span.design-editor-selection-details-state-container").show(),n.state=="all states"?i.find(".design-editor-selection-details-state-before").text("and"):i.find(".design-editor-selection-details-state-before").text("when"),n.state=="Hover"&&(n.state="hovered"),i.find("strong.design-editor-selection-details-state").html(n.state.toLowerCase()));var s=e(".design-editor-info").outerHeight();return e(".design-editor-info").css("marginTop","-"+s+"px"),e("#side-panel-bottom").css("paddingTop",s+"px"),e("span.design-editor-selection-details")},sanitizeElementName=function(t){return e.trim(t.escapeHTML())};var n={init:function(){designEditor=new designEditorTabEditor,designEditor._init(),n.bind(),designEditorBindPropertyInputs();try{e.getScript(Headway.headwayURL+"/library/visual-editor/"+Headway.scriptFolder+"/util.fonts-browser.js"),e.getScript("//ajax.googleapis.com/ajax/libs/webfont/1.4.7/webfont.js")}catch(t){}e.cookie("hide-design-editor")==="true"&&hideDesignEditor()},bind:function(){e("#toggle-inspector").bind("click",toggleInspector)},iframeCallback:function(){bindBlockDimensionsTooltip(),addInspector(),designEditor.switchLayout()}};return n}),define("util.tour",["jquery","util.tooltips","helper.boxes","modules/panel"],function(e,t,n){return tourStepsGrid=[{beginning:!0,title:"Welcome to the Headway Visual Editor!",content:"<p>If this is your first time in the Headway Visual Editor, <strong>we recommend following this tour so you can get the most out of Headway</strong>.</p><p>Or, if you're experienced or want to dive in right away, just click the close button in the top right at any time.</p>"},{target:e("li#mode-grid"),title:"Mode Selector",content:"<p>The Headway Visual Editor is split up into 2 modes.</p><p><ul><li><strong>Grid</strong> – Build your layouts</li><li><strong>Design</strong> – Add colors, customize fonts, and more!</li></ul></p>",position:{my:"top left",at:"bottom center"}},{target:e("#layout-selector-select-content"),title:"Layout Selector",content:'<p style="font-size:12px;">Since you may not want every page to be the same, you may use the Layout Selector to select which page, post, or archive to edit.</p><p style="font-size:12px;">The Layout Selector is based off of inheritance. For example, you can customize the "Page" layout and all pages will follow that layout. Plus, you can customize a specific page and it\'ll be different than all other pages.</p><p style="font-size:12px;">The layout selector will allow you to be as precise or broad as you wish. It\'s completely up to you!</p>',position:{my:"top center",at:"bottom center"}},{target:e("div#box-grid-wizard"),title:"The Headway Grid",content:'<p>Now we\'re ready to get started with the Headway Grid. In other words, the good stuff.</p><p>To build your first layout, please select a preset to the right to pre-populate the grid. Or, you may select "Use Empty Grid" to start with a completely blank grid.</p><p>Once you have a preset selected, click "Finish".</p>',position:{my:"right top",at:"left center"},nextHandler:{showButton:!1,clickElement:"#grid-wizard-button-preset-use-preset, span.grid-wizard-use-empty-grid",message:'Please click <strong>"Finish"</strong> or <strong>"Use Empty Grid"</strong> to continue.'}},{iframeTarget:"div.grid-container",title:"Adding Blocks",content:"<p>To add a block, simply place your mouse into the grid then click at where you'd like the top-left point of the block to be.</p><p>Drag your mouse and the block will appear! Once the block appears, you may choose the block type.</p><p>Hint: Don't worry about being precise, you may always move or resize the block.</p>",position:{my:"right top",at:"left top",adjustY:100},maxWidth:280},{iframeTarget:"div.grid-container",title:"Modifying Blocks",content:' <p style="font-size:12px;">After you\'ve added the desired blocks to your layout, you may move, resize, delete, or change the options of the block at any time.</p> <ul style="font-size:12px;"> <li><strong>Moving Blocks</strong> – Click and drag the block. If you wish to move multiple blocks simultaneously, double-click on a block to enter <em>Mass Block Selection Mode</em>.</li> <li><strong>Resizing Blocks</strong> – Grab the border or corner of the block and drag your mouse.</li> <li><strong>Block Options (e.g. header image)</strong> – Hover over the block then click the block options icon in the top-right.</li> <li><strong>Deleting Blocks</strong> – Move your mouse over the desired block, then click the <em>X</em> icon in the top-right.</li> </ul>',position:{my:"right top",at:"left top",adjustY:100},maxWidth:280},{target:e("#save-button-container"),title:"Saving",content:"<p>Now that you hopefully have a few changes to be saved, you can save using this spiffy Save button.</p><p>For those of you who like hotkeys, use <strong>Ctrl + S</strong> to save.</p>",position:{my:"top right",at:"bottom center"},tip:"top right"},{target:e("li#mode-design a"),title:"Design Mode",content:"<p>Thanks for sticking with us!</p><p>Now that you have an understanding of the Grid Mode, we hope you stick with us and head on over to the Design Mode.</p>",position:{my:"top left",at:"bottom center",adjustY:5},tip:"top left",buttonText:"Continue to Design Mode",buttonCallback:function(){e.post(Headway.ajaxURL,{security:Headway.security,action:"headway_visual_editor",method:"ran_tour",mode:"grid",complete:function(){Headway.ranTour.grid=!0,e("li#mode-design a").trigger("click"),window.location=e("li#mode-design a").attr("href")}})}}],tourStepsDesign=[{beginning:!0,title:"Welcome to the Headway Design Editor!",content:"<p>In the <strong>Design Editor</strong>, you can style your elements however you'd like.</p><p>Whether it's fonts, colors, padding, borders, shadows, or rounded corners, you can use the design editor.</p><p>Stick around to learn more!</p>"},{target:"#side-panel-top",title:"Element Selector",content:"<p>The element selector allows you choose which element to edit.</p>",position:{my:"right top",at:"left center"},callback:function(){e("li#element-block-header > span.element-name").trigger("click")}},{target:"#toggle-inspector",title:"Inspector",content:" <p>Instead of using the <em>Element Selector</em>, let the Inspector do the work for you.</p> <p><strong>Try it out!</strong> Point and right-click on the element you wish to edit and it will become selected!</p> ",position:{my:"top right",at:"bottom center",adjustX:10,adjustY:5}},{target:"window",title:"Have fun building with Headway!",content:'<p>We hope you find Headway to the most powerful and easy-to-use WordPress framework around.</p><p>If you have any questions, please don\'t hesitate to visit the <a href="http://support.headwaythemes.com/?utm_source=visualeditor&utm_medium=headway&utm_campaign=tour" target="_blank">support forums</a>.</p>',end:!0}],{start:function(){if(Headway.mode=="grid"){var t=tourStepsGrid;hidePanel(),openBox("grid-wizard")}else{if(Headway.mode!="design")return;var t=tourStepsDesign;showPanel(),require(["modules/design/mode-design"],function(){showDesignEditor()}),typeof e("div#panel").data("ui-tabs")!="undefined"&&selectTab("editor-tab",e("div#panel"))}e('<div class="black-overlay"></div>').hide().attr("id","black-overlay-tour").css("zIndex",15).appendTo("body").fadeIn(500),e(document.body).qtip({id:"tour",content:{text:t[0].content+'<div id="tour-next-container"><span id="tour-next" class="tour-button button button-blue">Continue Tour <span class="arrow">›</span></span></div>',title:{text:t[0].title,button:"Skip Tour"}},style:{classes:"qtip-tour",tip:{width:18,height:10,mimic:"center",offset:10}},position:{my:"center",at:"center",target:e(window),viewport:e(window),adjust:{y:5,method:"shift shift"}},show:{event:!1,ready:!0,effect:function(){e(this).fadeIn(500)}},hide:!1,events:{render:function(n,r){var i=r.elements.tooltip;r.step=0,i.bind("next",function(n){e(window).trigger("resize"),r.step+=1,r.step=Math.min(t.length-1,Math.max(0,r.step)),currentTourStep=t[r.step],e("div#black-overlay-tour").fadeOut(100,function(){e(this).remove()}),typeof currentTourStep.callback=="function"&¤tTourStep.callback.apply(r),currentTourStep.target=="window"?currentTourStep.target=e(window):typeof currentTourStep.target=="string"?currentTourStep.target=e(currentTourStep.target):typeof currentTourStep.iframeTarget=="string"&&(currentTourStep.target=$i(currentTourStep.iframeTarget).first()),r.set("position.target",currentTourStep.target),typeof currentTourStep.maxWidth!="undefined"&&window.innerWidth<1440?e(".qtip-tour").css("maxWidth",currentTourStep.maxWidth):e(".qtip-tour").css("maxWidth",350);var i="Next";if(typeof currentTourStep.buttonText=="string")var i=currentTourStep.buttonText;if(typeof currentTourStep.end!="undefined"&¤tTourStep.end===!0)var s='<div id="tour-next-container"><span id="tour-finish" class="tour-button button button-blue">Close Tour <span class="arrow">›</span></div>';else if(typeof currentTourStep.nextHandler=="undefined"||currentTourStep.nextHandler.showButton)var s='<div id="tour-next-container"><span id="tour-next" class="tour-button button button-blue">'+i+' <span class="arrow">›</span></div>';else var s='<div id="tour-next-container"><p>'+currentTourStep.nextHandler.message+"</p></div>";if(typeof currentTourStep.nextHandler!="undefined"&&e(currentTourStep.nextHandler.clickElement)){var o=function(t){e(".qtip-tour").triggerHandler("next"),t.preventDefault(),e(this).unbind("click",o)};e(currentTourStep.nextHandler.clickElement).bind("click",o)}r.set("content.text",currentTourStep.content+s),r.set("content.title",currentTourStep.title),typeof currentTourStep.end=="undefined"?(typeof currentTourStep.position!="undefined"?(r.set("position.my",currentTourStep.position.my),r.set("position.at",currentTourStep.position.at),typeof currentTourStep.position.adjustX!="undefined"?r.set("position.adjust.x",currentTourStep.position.adjustX):r.set("position.adjust.x",0),typeof currentTourStep.position.adjustY!="undefined"?r.set("position.adjust.y",currentTourStep.position.adjustY):r.set("position.adjust.y",0)):(r.set("position.my","top center"),r.set("position.at","bottom center")),typeof currentTourStep.tip!="undefined"&&r.set("style.tip.corner",currentTourStep.tip)):(r.set("position.my","center"),r.set("position.at","center"))}),e("div.qtip-tour").on("click","span#tour-next",function(t){typeof currentTourStep=="object"&&typeof currentTourStep.buttonCallback=="function"&¤tTourStep.buttonCallback.call(),e(".qtip-tour").triggerHandler("next"),t.preventDefault()}),e("div.qtip-tour").on("click","span#tour-finish",function(t){e(".qtip-tour").qtip("hide")})},hide:function(t,n){e("div#tour-overlay").remove(),e("div#black-overlay-tour").fadeOut(100,function(){e(this).remove()}),e(".qtip-tour").fadeOut(100,function(){e(this).qtip("destroy")}),Headway.ranTour[Headway.mode]==0&&Headway.ranTour.legacy!=1&&(e.post(Headway.ajaxURL,{security:Headway.security,action:"headway_visual_editor",method:"ran_tour",mode:Headway.mode}),Headway.ranTour[Headway.mode]=!0)}}})}}}),define("modules/menu",["jquery","util.tour"],function(e,t){var n={init:function(){n.bind()},bind:function(){e("ul#modes li").on("click",function(){e(this).siblings("li").removeClass("active"),e(this).addClass("active")}),e("ul#modes li a").bind("click",function(){e(this).attr("href",e(this).attr("href")+"&ve-layout="+Headway.currentLayout)}),e("#menu-link-view-site a").bind("click",function(){e(this).attr("href",Headway.homeURL+"/?headway-trigger=layout-redirect&layout="+Headway.currentLayout)}),e("span#save-button").click(function(){return save(),!1}),e("#snapshots-button").bind("click",function(){openBox("snapshots")}),e("#tools-tour").bind("click",t.start),e("#tools-grid-wizard").bind("click",function(){hidePanel(),openBox("grid-wizard")}),e("#open-live-css").bind("click",function(){if(typeof liveCSSWindow!="undefined"&&!liveCSSWindow.closed)return liveCSSWindow.focus();var t={width:750,height:550};t.left=screen.width/2-t.width/2,t.top=screen.height/2-t.height/2,liveCSSWindow=window.open(Headway.homeURL+"/?headway-trigger=ace-editor&mode=css","_blank","width="+t.width+",height="+t.height+",top="+t.top+",left="+t.left,!0),liveCSSWindow.focus(),window.onunload=function(){typeof liveCSSWindow!="undefined"&&!liveCSSWindow.closed&&liveCSSWindow.close()},e(liveCSSWindow).bind("load",function(){var t=liveCSSWindow.window.ace,n=Headway.headwayURL+"/library/visual-editor/"+Headway.scriptFolder+"/deps/ace/";t.config.set("basePath",n),t.config.set("modePath",n),t.config.set("workerPath",n),t.config.set("themePath",n),liveCSSEditor=t.edit(e(liveCSSWindow.document).contents().find("#ace-editor").get(0)),liveCSSEditorSession=liveCSSEditor.getSession(),liveCSSEditor.setTheme("ace/theme/textmate"),liveCSSEditorSession.setMode("ace/mode/css"),liveCSSEditor.setShowPrintMargin(!1),liveCSSEditor.setValue(e("textarea#live-css").val());var r=liveCSSEditorSession.getLength();liveCSSEditor.gotoLine(r,liveCSSEditorSession.getLine(r-1).length),liveCSSEditorSession.on("change",function(t){var n=liveCSSEditor.getValue(),r=e("textarea#live-css");r.val(n),dataHandleInput(r),$i("style#live-css-holder").html(n),allowSaving()})})}),e("#tools-clear-cache").bind("click",function(){var t={security:Headway.security,action:"headway_visual_editor",method:"clear_cache"};e.post(Headway.ajaxURL,t,function(e){e==="success"?showNotification({id:"cache-cleared",message:"The cache was successfully cleared!",success:!0}):showErrorNotification({id:"error-could-not-clear-cache",message:"Error: Could not clear cache."})})})}};return n}),define("modules/snapshots",["jquery","ko"],function(e,t){var n={init:function(){n.bind(),n.setupViewModel()},setupViewModel:function(){Headway.viewModels.snapshots={snapshots:t.observableArray(Headway.snapshots),formatSnapshotDatetime:function(e){var t=e.split(/[- :]/);return(new Date(Date.UTC(t[0],t[1]-1,t[2],t[3],t[4],t[5]))).toLocaleString()},rollbackToSnapshot:function(t,n){if(!confirm("Are you sure you wish to rollback?\n\nYou will lose all between this snapshot and now unless you save another snapshot."))return!1;var r=e(n.target);if(r.attr("disabled"))return!1;r.attr("disabled",!0),r.addClass("button-depressed"),r.text("Rolling Back.."),e.post(Headway.ajaxURL,{security:Headway.security,action:"headway_visual_editor",method:"rollback_to_snapshot",layout:Headway.currentLayout,snapshot_id:t.id,mode:Headway.mode},function(e){if(typeof e.error!="undefined")return;showNotification({id:"rolled-back-successfully",message:"Successfully rolled back to snapshot.<br /><br /><strong>Refreshing Visual Editor in 3 seconds</strong>.",success:!0}),r.text("Rolled Back!"),setTimeout(function(){allowVEClose(),document.location.reload(!0)},1e3)})},deleteSnapshot:function(t,n){if(!confirm("Are you sure you wish to delete this snapshot?\n\nYou cannot undo this or restore another snapshot to bring this snapshot back."))return!1;var r=e(n.target);if(r.hasClass("deletion-in-progress"))return!1;r.addClass("deletion-in-progress"),e.post(Headway.ajaxURL,{security:Headway.security,action:"headway_visual_editor",method:"delete_snapshot",layout:Headway.currentLayout,snapshot_id:t.id,mode:Headway.mode},function(e){if(typeof e.error!="undefined")return;showNotification({id:"deleted-snapshot-successfully",message:"Successfully deleted snapshot.",success:!0}),Headway.viewModels.snapshots.snapshots.remove(t)})},saveSnapshot:function(t,n){var r=e(n.target);if(r.attr("disabled"))return!1;r.attr("disabled",!0),r.text("Saving Snapshot..."),r.siblings(".spinner").show();var i=prompt("(Optional)\n\nEnter name or description of the changes in this snapshot.");e.post(Headway.ajaxURL,{security:Headway.security,action:"headway_visual_editor",method:"save_snapshot",layout:Headway.currentLayout,mode:Headway.mode,snapshot_comments:i},function(e){if(typeof e.timestamp=="undefined")return;showNotification({id:"snapshot-saved",message:"Snapshot saved.",success:!0}),Headway.viewModels.snapshots.snapshots.unshift({id:e.id,timestamp:e.timestamp,comments:e.comments}),r.text("Save Snapshot"),r.removeAttr("disabled"),r.siblings(".spinner").hide()})}},e(document).ready(function(){t.applyBindings(Headway.viewModels.snapshots,e("#box-snapshots").get(0))})},bind:function(){}};return n}),define("helper.data",["underscore"],function(_){dataHandleInput=function(input,value,additionalCallbackArgs){var input=$(input);if(!input.length)return!1;if(typeof value=="undefined")var value=input.val();var optionID=input.attr("name").toLowerCase(),optionGroup=input.attr("data-group").toLowerCase(),callback=eval(input.attr("data-callback")),dataHandlerOverrideCallback=eval(input.attr("data-data-handler-callback"))||null,panelArgs=input.parents(".sub-tabs-content-container").first().data("panel-args")||{},callbackArgs=$.extend({},{input:input,value:value},panelArgs);typeof additionalCallbackArgs=="object"&&(callbackArgs=$.extend({},callbackArgs,additionalCallbackArgs)),allowSaving();if(!input.hasClass("repeater-group-input")&&input.parents(".repeater-group").length)return updateRepeaterValues(input.parents(".repeater")),typeof callback=="function"&&callback(callbackArgs),input.parents(".repeater-group");if(input.attr("data-no-save"))return typeof callback=="function"&&callback(callbackArgs),input;if(typeof dataHandlerOverrideCallback=="function")dataHandlerOverrideCallback(callbackArgs);else{if(typeof panelArgs.block!="undefined"&&panelArgs.block){var blockID=panelArgs.blockID;return dataSetBlockOption(blockID,optionID,value),refreshBlockContent(blockID,callback,callbackArgs),input}typeof panelArgs.wrapper!="undefined"&&panelArgs.wrapper?dataSetWrapperOption(panelArgs.wrapper.id,optionID,value):dataSetOption(optionGroup,optionID,value)}return typeof callback=="function"&&callback(callbackArgs),input},dataSetOption=function(e,t,n){return dataPrepareOptionGroup(e),GLOBALunsavedValues.options[e][t]=n,allowSaving(),GLOBALunsavedValues.options[e]},dataPrepareOptionGroup=function(e){return typeof GLOBALunsavedValues!="object"&&(GLOBALunsavedValues={}),typeof GLOBALunsavedValues["options"]!="object"&&(GLOBALunsavedValues.options={}),typeof GLOBALunsavedValues["options"][e]!="object"&&(GLOBALunsavedValues.options[e]={}),GLOBALunsavedValues.options[e]},dataSetBlockOption=function(e,t,n){return dataPrepareBlock(e),GLOBALunsavedValues.blocks[e].settings[t]=n,allowSaving(),GLOBALunsavedValues.blocks[e]},dataSetBlockPosition=function(e,t){if(typeof e=="string"&&e.indexOf("block-")!==-1)var e=e.replace("block-","");var t=t.left+","+t.top;return dataPrepareBlock(e),GLOBALunsavedValues.blocks[e].position=t,allowSaving(),GLOBALunsavedValues.blocks[e]},dataSetBlockDimensions=function(e,t){if(typeof e=="string"&&e.indexOf("block-")!==-1)var e=e.replace("block-","");var t=t.width+","+t.height;return dataPrepareBlock(e),GLOBALunsavedValues.blocks[e].dimensions=t,allowSaving(),GLOBALunsavedValues.blocks[e]},dataSetBlockWrapper=function(e,t){return dataPrepareBlock(e),GLOBALunsavedValues.blocks[e].wrapper=t.toString().replace("wrapper-",""),allowSaving(),GLOBALunsavedValues.blocks[e]},dataDeleteBlock=function(e){if(typeof e=="string"&&e.indexOf("block-")!==-1)var e=e.replace("block-","");return dataPrepareBlock(e),GLOBALunsavedValues.blocks[e]["delete"]=!0,allowSaving(),GLOBALunsavedValues.blocks[e]},dataAddBlock=function(e){var t,n;return typeof e=="string"&&t.indexOf("block-")!==-1?t=e.replace("block-",""):t=getBlockID(e),n=getBlockType(e),dataPrepareBlock(t),GLOBALunsavedValues.blocks[t]["new"]=n,GLOBALunsavedValues.blocks[t].insert_id=e.data("desired-id"),delete GLOBALunsavedValues.blocks[t]["delete"],allowSaving(),GLOBALunsavedValues.blocks[t]},dataPrepareBlock=function(e){return typeof GLOBALunsavedValues!="object"&&(GLOBALunsavedValues={}),typeof GLOBALunsavedValues["blocks"]!="object"&&(GLOBALunsavedValues.blocks={}),typeof GLOBALunsavedValues["blocks"][e]!="object"&&(GLOBALunsavedValues.blocks[e]={}),typeof GLOBALunsavedValues["blocks"][e]["settings"]!="object"&&(GLOBALunsavedValues.blocks[e].settings={}),GLOBALunsavedValues.blocks[e]},dataSetWrapperOption=function(e,t,n){return e=String(e).replace("wrapper-",""),dataPrepareWrapper(e),GLOBALunsavedValues.wrappers[e].settings[t]=n,allowSaving(),GLOBALunsavedValues.wrappers[e]},dataAddWrapper=function(e,t,n){return wrapperID=String(e.attr("id")).replace("wrapper-",""),dataPrepareWrapper(wrapperID),GLOBALunsavedValues.wrappers[wrapperID]={"new":!0,insert_id:e.data("desired-id"),position:n,settings:jQuery.extend({},{columns:Headway.defaultGridColumnCount,"column-width":Headway.globalGridColumnWidth,"gutter-width":Headway.globalGridGutterWidth},t)},dataSortWrappers(),allowSaving(),GLOBALunsavedValues.wrappers[wrapperID]},dataDeleteWrapper=function(e){return e=String(e).replace("wrapper-",""),dataPrepareWrapper(e),GLOBALunsavedValues.wrappers[e]["delete"]=!0,allowSaving(),GLOBALunsavedValues.wrappers[e]},dataSetWrapperWidth=function(e,t){var n=t=="fluid";return dataSetWrapperOption(e,"fluid",n)},dataSetWrapperGridWidth=function(e,t){var n=t=="fluid";return dataSetWrapperOption(e,"fluid-grid",n)},dataSortWrappers=function(){$i(".wrapper:visible").each(function(){var e=$(this).data("id");dataPrepareWrapper(e),GLOBALunsavedValues.wrappers[e].position=$i(".wrapper").index(this)})},dataPrepareWrapper=function(e){e=String(e).replace("wrapper-",""),typeof GLOBALunsavedValues!="object"&&(GLOBALunsavedValues={}),typeof GLOBALunsavedValues["wrappers"]=="undefined"&&(GLOBALunsavedValues.wrappers={}),typeof GLOBALunsavedValues["wrappers"][e]=="undefined"&&(GLOBALunsavedValues.wrappers[e]={}),typeof GLOBALunsavedValues["wrappers"][e]["settings"]=="undefined"&&(GLOBALunsavedValues.wrappers[e].settings={})},dataHandleDesignEditorInput=function(e){var t=$(e.hiddenInput),n=e.value;if(!t.length)return!1;if(t.parents("li.uncustomized-property").length==1)return!1;var r=t.attr("element").toLowerCase(),i=t.attr("property").toLowerCase(),s=t.attr("element_selector")||!1,o=t.attr("special_element_type").toLowerCase()||!1,u=t.attr("special_element_meta").toLowerCase()||!1;e.unit=t.siblings(".property-unit-select").find("select").val(),dataSetDesignEditorProperty({element:r,property:i,value:n,specialElementType:o,specialElementMeta:u,unit:e.unit});if(n==="null"||n=="DELETE")n=null;return t.val(n),$("#design-editor-element-selector-container").find("li#element-"+r).addClass("customized-element").attr("title","You have customized a property in this property group."),$("#design-editor-main-elements").find(".ui-state-active").length&&$("#design-editor-sub-elements").find(".ui-state-active").length&&$("#design-editor-main-elements").find(".ui-state-active").addClass("has-customized-children"),t.parents(".design-editor-box").first().addClass("design-editor-box-customized"),t.parents(".design-editor-box").first().find(".design-editor-box-title").attr("title","You have customized a property in this property group."),dataDesignEditorPropertyFeedback({element:r,property:i,value:n,specialElementType:o,specialElementMeta:u,unit:e.unit})},dataDesignEditorPropertyFeedback=function(args){var element=args.element.toLowerCase(),property=args.property.toLowerCase(),value=args.value,specialElementType=args.specialElementType||!1,specialElementMeta=args.specialElementMeta||!1;if(value==="null"||value=="DELETE")args.value=null,value=null;if(!specialElementType||specialElementType=="layout")var selector=Headway.elements[element].selector;else var selector=Headway.elements[element][specialElementType+"s"][specialElementMeta].selector;if(Headway.designEditorProperties.hasOwnProperty(property)){var callback=eval("(function(params){"+Headway.designEditorProperties[property]["js-callback"]+"})");args.selector=selector,args.element=$i(selector),typeof args["unit"]=="undefined"&&(args.unit=""),callback(args)}return value==null&&selector&&property&&stylesheet.delete_rule_property(selector,property),selector},dataSetDesignEditorProperty=function(e){var t=e.element.toLowerCase(),n=e.property.toLowerCase(),r=e.value,i=e.unit,s=e.specialElementType||!1,o=e.specialElementMeta||!1;i&&i.length&&r!="null"&&r!="DELETE"&&(r+=i),dataPrepareDesignEditor(),typeof GLOBALunsavedValues["design-editor"][t]!="object"&&(GLOBALunsavedValues["design-editor"][t]={});if(s==0||o==0)typeof GLOBALunsavedValues["design-editor"][t]["properties"]!="object"&&(GLOBALunsavedValues["design-editor"][t].properties=new Object),GLOBALunsavedValues["design-editor"][t].properties[n]=r,typeof Headway.elementData!="object"&&(Headway.elementData=new Object),typeof Headway.elementData[t]=="undefined"&&(Headway.elementData[t]={properties:{}}),typeof Headway.elementData[t]["properties"]=="undefined"&&(Headway.elementData[t].properties={}),Headway.elementData[t].properties[n]=r;else{typeof GLOBALunsavedValues["design-editor"][t]["special-element-"+s]!="object"&&(GLOBALunsavedValues["design-editor"][t]["special-element-"+s]=new Object),typeof GLOBALunsavedValues["design-editor"][t]["special-element-"+s][o]!="object"&&(GLOBALunsavedValues["design-editor"][t]["special-element-"+s][o]=new Object),GLOBALunsavedValues["design-editor"][t]["special-element-"+s][o][n]=r,typeof Headway.elementData!="object"&&(Headway.elementData=new Object),typeof Headway.elementData[t]!="object"&&(Headway.elementData[t]=new Object),typeof Headway.elementData[t]["special-element-"+s]!="object"&&(Headway.elementData[t]["special-element-"+s]=new Object);if(!_.isObject(Headway.elementData[t]["special-element-"+s][o])||_.isArray(Headway.elementData[t]["special-element-"+s][o]))Headway.elementData[t]["special-element-"+s][o]=new Object;Headway.elementData[t]["special-element-"+s][o][n]=r}if(typeof designEditor!="undefined"){var u=$('ul#design-editor-element-selector li.element[data-element-id="'+t+'"]');s=="instance"?u=u.filter('[data-instance-id="'+o+'"]'):s=="state"&&(u=u.filter('[data-state-id="'+o+'"]')),designEditor.showElementPropertiesThrottled(u)}return allowSaving(),!0},dataPrepareDesignEditor=function(){return typeof GLOBALunsavedValues!="object"&&(GLOBALunsavedValues={}),typeof GLOBALunsavedValues["design-editor"]!="object"&&(GLOBALunsavedValues["design-editor"]={}),GLOBALunsavedValues["design-editor"]}}),define("helper.wrappers",["modules/panel.inputs"],function(e){getWrapperID=function(e){return e.attr("id").replace("wrapper-","")},openWrapperOptions=function(t){var t="wrapper-"+t,n=function(){var n=$("div#"+t+"-tab");n.tabs(),e.bind("div#"+t+"-tab"),handleInputTogglesInContainer(n.find("div.sub-tabs-content")),setupTooltips(),updateGridWidthInput($("div#"+t+"-tab")),$("div#"+t+"-tab").find('select[name="mirror-wrapper"]').val()&&($("div#"+t+"-tab ul.sub-tabs li:not(#sub-tab-config)").hide(),selectTab("sub-tab-config",$("div#"+t+"-tab")))},r=t.replace("wrapper-",""),i="Wrapper";typeof $i("#"+t).data("alias")!="undefined"&&$i("#"+t).data("alias")&&(i+=" ("+$i("#"+t).data("alias")+")"),addPanelTab(t,i,{url:Headway.ajaxURL,data:{security:Headway.security,action:"headway_visual_editor",method:"load_wrapper_options",wrapper_id:t.replace("wrapper-",""),unsaved_wrapper_options:getUnsavedWrapperOptionValues(t),layout:Headway.currentLayout},callback:n},!0,!0,"wrapper-options"),$("div#panel").tabs("option","active",$("#panel-top").children('li[role="tab"]').index($('[aria-controls="'+t+'-tab"]')))},getUnsavedWrapperOptionValues=function(e){if(typeof GLOBALunsavedValues=="object"&&typeof GLOBALunsavedValues["wrappers"]=="object"&&typeof GLOBALunsavedValues["wrappers"][e]=="object")var t=GLOBALunsavedValues.wrappers[e];return typeof t=="object"&&Object.keys(t).length>0?t:null},getWrapperMirror=function(e){return $i("div#wrapper-"+e.replace("wrapper-","")).data("mirror-wrapper")},updateWrapperMirrorStatus=function(e,t,n){var e=e.replace("wrapper-",""),r=$i("#wrapper-"+e);populateWrapperMirrorNotice($i("#wrapper-"+e));if(t){var t=t.replace("wrapper-","");r.addClass("wrapper-mirrored"),r.headwayGrid("disable"),typeof n!="undefined"&&n.parents(".panel").find("ul.sub-tabs li:not(#sub-tab-config)").hide()}else r.removeClass("wrapper-mirrored"),r.headwayGrid("enable"),typeof n!="undefined"&&n.parents(".panel").find("ul.sub-tabs li:not(#sub-tab-config)").show();r.data("ui-headwayGrid").updateGridContainerHeight(),r.data("ui-headwayGrid").resetGridCalculations(),r.data("ui-headwayGrid").alignAllBlocksWithGuides()}}),setupContextMenu=function(e){if(typeof e!="object")return!1;var e=$.extend(!0,{},{isIframeElement:!0},e);deactivateContextMenu(e.id);var t=Headway.touch?"taphold.contextMenu"+e.id:"contextmenu.contextMenu"+e.id;e.isIframeElement?$iDocument().on(t,e.elements,function(t,n){t.data=n,contextMenuCreator(e,t,!0)}):$(document).on(t,e.elements,function(t,n){t.data=n,contextMenuCreator(e,t,!1)});var n=function(t){if(t.which!==0&&t.which!==1||$(t.originalEvent.target).parents("#context-menu-"+e.id).length)return;var n=$("#context-menu-"+e.id);typeof e.onHide=="function"&&e.onHide.apply(n),n.remove()},r=Headway.touch?"touchstart":"click";$("body").on(r+".contextMenu"+e.id,n),$i("body").on(r+".contextMenu"+e.id,n)},deactivateContextMenu=function(e){return $(document).off(".contextMenu"+e),$iDocument().off(".contextMenu"+e),$("body").off(".contextMenu"+e),$i("body").off(".contextMenu"+e),!0},contextMenuCreator=function(e,t,n){t.stopPropagation();if(typeof e!="object")return!1;$(".context-menu").remove();var r=typeof e.title=="function"?e.title.apply(undefined,[t]):e.title,i=$('<ul id="context-menu-'+e.id+'" class="context-menu"><h3>'+r+"</h3></ul>");typeof e.onShow=="function"&&e.onShow.apply(i,[t]),e.contentsCallback.apply(i,[t]);var s=t,o=function(t){typeof e.onItemClick=="function"&&e.onItemClick.apply(this,[i,s]),typeof e.onHide=="function"&&e.onHide.apply(i),i.remove()},u=Headway.touch?"tap":"click";i.delegate("span",u,o);if(typeof t.originalEvent!="undefined"&&typeof t.originalEvent.clientX!="undefined")var a=t.originalEvent.clientX,f=t.originalEvent.clientY+40;else var a=t.data.x,f=t.data.y+40;i.css({left:a,top:f}),i.delegate("li:has(ul) span","hover",function(){var e=$(this).siblings("ul"),t=e.offset();if(!t||e.offset().left+e.outerWidth()<$("iframe.content").width())return;e.css("right",e.css("left")),e.css("left","auto"),e.css("width","190px"),e.css("zIndex","999999")}),i.appendTo($("body"));if(a+i.outerWidth()>$(window).width()){var l=$(window).width()-(a+i.outerWidth());i.css("left",a+l-20)}if(f+i.outerHeight()>$(window).height()){var l=$(window).height()-(f+i.outerHeight());i.css("top",f+l-20)}return t.preventDefault(),!1},define("helper.context-menus",function(){}),showNotification=function(e){var e=$.extend({},{id:null,message:null,error:!1,success:!1,closeTimer:3e3,closable:!1,closeOnEscKey:!1,closeCallback:function(){},closeConfirmMessage:null,fadeInDuration:350,timerFadeOutDuration:1500,closeFadeOutDuration:350,doNotShowAgain:!1,overwriteExisting:!1,opacity:1},e);if(e.doNotShowAgain&&$.cookie("headway-hide-notification-"+e.id))return;if($("#notification-"+e.id).length){if(!e.overwriteExisting)return $("#notification-"+e.id).fadeIn(e.fadeInDuration);hideNotification(e.id)}var t=$('<div class="notification"><p>'+e.message+"</p></div>");t.attr("id","notification-"+e.id),e.error&&t.addClass("notification-error"),e.success&&t.addClass("notification-success"),e.closable&&t.addClass("notification-closable"),t.css("opacity",e.notification).hide(),t.data("notification-args",e);if(e.closable){var n=$('<span class="close">Close</span>'),r=function(){if(e.closeConfirmMessage&&!confirm(e.closeConfirmMessage))return!1;hideNotification(e.id),$(document).unbind(".notification_"+e.id),$i("html").unbind(".notification_"+e.id)};n.appendTo(t),n.on("click",r),e.closeOnEscKey&&($(document).bind("keyup.notification_"+e.id,r),$i("html").bind("keyup.notification_"+e.id,r))}return e.closeTimer&&setTimeout(function(){t.fadeOut(e.timerFadeOutDuration,function(){$(this).remove()})},e.closeTimer),t.appendTo("#notification-center").fadeIn(350),t},showErrorNotification=function(e){var e=$.extend({},{error:!0,closeTimer:6e3},e);return showNotification(e)},hideNotification=function(e,t){var n=$("#notification-"+e);if(!n||!n.length)return!1;var r=n.data("notification-args");return typeof r.closeCallback=="function"&&r.closeCallback.apply(n),typeof t=="undefined"||t?n.fadeOut(r.closeFadeOutDuration,function(){$(this).remove(),r.doNotShowAgain&&$.cookie("headway-hide-notification-"+r.id,!0)}):(n.remove(),r.doNotShowAgain&&$.cookie("headway-hide-notification-"+r.id,!0)),n},updateNotification=function(e,t){var n=$("#notification-"+e);return n.find("p").html(t)},define("helper.notifications",function(){}),define("modules/grid/grid",["jquery","helper.history","helper.data"],function(e,t){e.widget("ui.headwayGrid",e.ui.mouse,{options:{useIndependentGrid:!1,columns:Headway.defaultGridColumnCount,columnWidth:Headway.defaultGridColumnWidth,gutterWidth:Headway.defaultGridGutterWidth,yGridInterval:5,minBlockHeight:10,selectedBlocksContainerClass:"selected-blocks-container",defaultBlockClass:"block",defaultBlockContentClass:"block-content"},_create:function(){this.wrapper=this.element,this.container=this.wrapper.find(".grid-container"),this.iframe=e(Headway.iframe),this.contents=e(this.iframe).contents(),this.document=e(this.iframe).contents(),this.options.useIndependentGrid=this.wrapper.data("wrapper-settings")["use-independent-grid"],this.wrapper.data("wrapper-settings").columns&&(this.options.columns=this.wrapper.data("wrapper-settings").columns),this.wrapper.data("wrapper-settings")["column-width"]&&(this.options.columnWidth=this.wrapper.data("wrapper-settings")["column-width"]),this.wrapper.data("wrapper-settings")["gutter-width"]&&(this.options.gutterWidth=this.wrapper.data("wrapper-settings")["gutter-width"]),this.addColumnGuides(),this.updateGridCSS(),this.helperTemplate=e('<div class="ui-grid-helper block"></div>'),this.offset=this.container.offset(),this.wrapper.addClass("ui-headway-grid"),this.wrapper.disableSelection(),this._mouseInit(),this._on(this.wrapper,{mousedown:"wrapperMouseDown"}),this._on(this.contents,{mousedown:"iframeMouseDown",mouseup:"iframeMouseUp"}),this._on(this.iframe,{mouseleave:"iframeMouseLeave"}),this._on(this.contents,{mousemove:"iframeMouseMove"}),this._on(e(window),{resize:"resetGridCalculations"}),this._on(e(window),{resize:"alignAllBlocksWithGuides"}),this.initResizable(this.container.children("."+this.options.defaultBlockClass.replace(".",""))),this.initDraggable(this.container.children("."+this.options.defaultBlockClass.replace(".",""))),this.updateGridContainerHeight(),this.container.delegate("."+this.options.defaultBlockClass.replace(".",""),"dblclick",function(t){var n=e(this).parents(".ui-headway-grid").data("ui-headwayGrid");e(this).hasClass("grouped-block")&&n.container.find(".grouped-block").length===1?(e(this).removeClass("grouped-block"),n.container.removeClass("grouping-active"),hideNotification("mass-block-selection")):e(this).hasClass("grouped-block")?e(this).removeClass("grouped-block"):(e(this).addClass("grouped-block"),n.container.addClass("grouping-active"),showNotification({id:"mass-block-selection",message:"Mass Block Selection Mode",closable:!0,closeOnEscKey:!0,closeTimer:!1,opacity:.8,closeCallback:function(){$i(".grouped-block").removeClass("grouped-block"),n.container.removeClass("grouping-active")}}))}),this.alignAllBlocksWithGuides()},resetGridCalculations:function(){this.grid={columns:this.container.find(".grid-guide").length,columnWidth:parseInt(this.container.find(".grid-guide:eq(1)").outerWidth()),gutterWidth:parseInt(this.container.find(".grid-guide:eq(1)").css("marginLeft").replace("px",""))};var t=this;this.wrapper.find(".block:visible").each(function(){e(this).data("plugin_pep")&&(e(this).data("plugin_pep").options.grid=[t.grid.columnWidth+t.grid.gutterWidth,t.options.yGridInterval]),e(this).data("ui-resizable")&&(e(this).resizable("option","grid",[t.grid.columnWidth+t.grid.gutterWidth,t.options.yGridInterval]),e(this).resizable("option","maxWidth",t.grid.columns*(t.grid.columnWidth+t.grid.gutterWidth)))})},_destroy:function(){return this.element.resizable("destroy"),this.element.removeClass("ui-grid ui-grid-disabled").removeData("grid").unbind(".grid"),this._mouseDestroy(),this.element.find(".ui-resizable").resizable("destroy"),this},disable:function(){this.element.resizable("disable"),this.element.find(".ui-resizable").resizable("disable")},enable:function(){this.element.resizable("enable"),this.element.find(".ui-resizable").resizable("enable")},iframeMouseDown:function(t){this._iframeMouseDownEvent=t,this._iframeMouseDownEventElement=e(t.originalEvent.target)},iframeMouseUp:function(e){delete this._iframeMouseDownEvent,delete this._iframeMouseDownEventElement},iframeMouseLeave:function(e){$iDocument().trigger("mouseup")},iframeMouseMove:function(t){if(typeof this._iframeMouseDownEvent!="undefined"||typeof this._doingHoverBlockToTop!="undefined"||!Headway.touch)return;this._doingHoverBlockToTop=!0,setTimeout(e.proxy(function(){var n=[],r=t.pageX,i=t.pageY;e(this.container).find(".block").each(function(){var t=e(this),s=t.offset(),o=s.left,u=s.top,a=o+t.width(),f=u+t.height();if(r<o||r>a)return;if(i<u||i>f)return;n.push(t)}),n.sort(function(e,t){return t.width()*t.height()>e.width()*e.height()?1:0}),this.sendBlockToTop(e(n.pop())),delete this._doingHoverBlockToTop},this),50)},wrapperMouseDown:function(t){if(!t||this.container.hasClass("grouping-active")||getBlock(t.target))return;$i(".blank-block").each(function(){removePanelTab("block-"+getBlockID(e(this))),e(this).remove()})},_mouseStart:function(t){this.mouseStartPosition=[t.pageX-this.container.offset().left,t.pageY-this.container.offset().top];var n=e(t.target);return!t||t.ctrlKey||this.container.hasClass("grouping-active")||getBlock(t.target)||n.hasClass("wrapper-handle")||n.parents(".wrapper-handle").length||n.hasClass("ui-resizable-handle")&&n.parent().hasClass("wrapper")||this.wrapper.hasClass("wrapper-mirrored")?!0:(this._trigger("start",t),this.helper=e(this.helperTemplate).clone().appendTo(this.container),this.helper.css({width:this.grid.columnWidth,height:0,top:0,left:0,display:"none"}),this.wrapper.hasClass("wrapper-fluid")&&this.wrapper.find(".wrapper-buttons").hide(),this.draggingOnWrapper=!0,addBlockDimensionsTooltip(this.helper),!0)},_mouseDrag:function(t){var n=e(t.target);if(!t||!this.helper||t.ctrlKey||this.container.hasClass("grouping-active")||!this.helper&&getBlock(t.target)||n.hasClass("wrapper-handle")||n.parents(".wrapper-handle").length||n.hasClass("ui-resizable-handle")&&n.parent().hasClass("wrapper")||!this.draggingOnWrapper||typeof this.draggingOnWrapper=="undefined"||this.wrapper.hasClass("wrapper-mirrored"))return;var r=e(this.container),i=r.offset(),s=this.mouseStartPosition[0],o=this.mouseStartPosition[1],u=t.pageX-i.left,a=t.pageY-i.top;if(s>u){var f=u;u=s,s=f}if(o>a){var f=a;a=o,o=f}var l=i.left,c=i.top,h=r.height(),p=r.width();if(u>=p&&s>=p)return;if(a>=h&&o>=h)return;s<0&&(s=0),o<0&&(o=0),a>h&&(a=h);var d=s.toNearest(this.grid.columnWidth+this.grid.gutterWidth),v=o.toNearest(this.options.yGridInterval),m=u.toNearest(this.grid.columnWidth+this.grid.gutterWidth)-d-this.grid.gutterWidth,g=a.toNearest(this.options.yGridInterval)-o.toNearest(this.options.yGridInterval);Headway.blankBlockOptions={display:"block",left:d,top:v,width:m,height:g},d+m>this.grid.columns*(this.grid.columnWidth+this.grid.gutterWidth)&&(Headway.blankBlockOptions.width=p-Headway.blankBlockOptions.left),t.pageY>c+h&&(Headway.blankBlockOptions.height=h-v),this.helper.css(Headway.blankBlockOptions);var y=Math.round((Headway.blankBlockOptions.width+this.grid.gutterWidth)/(this.grid.columnWidth+this.grid.gutterWidth)),b=Math.round(Headway.blankBlockOptions.left/(this.grid.columnWidth+this.grid.gutterWidth));return y==0&&(y=1),y&&setBlockGridWidth(this.helper,y),b&&setBlockGridLeft(this.helper,b),this.alignBlockWithGuides(this.helper),Headway.blankBlockOptions.height<this.options.minBlockHeight?this.helper.addClass("block-error"):this.helper.hasClass("block-error")&&this.helper.removeClass("block-error"),e.support.touch||(this.helper.qtip("option","hide.delay",1e4),this.helper.qtip("option","show.delay",10),this.helper.qtip("show"),this.helper.qtip("option","content.text",blockDimensionsTooltipContent),this.helper.qtip("reposition")),this._trigger("drag",t),this.draggingOnWrapper=!0,!1},_mouseStop:function(e){if(!e||e.ctrlKey||this.container.hasClass("grouping-active")||!this.helper||this.wrapper.hasClass("wrapper-mirrored"))return;return this._trigger("stop",e),Headway.blankBlockOptions={width:getBlockGridWidth(this.helper),left:getBlockGridLeft(this.helper),pixelWidth:this.helper.width(),pixelLeft:this.helper.position().left,height:this.helper.height(),top:this.helper.position().top},this.helper.qtip("api")&&this.helper.qtip("api").destroy(!0),this.wrapper.find(".wrapper-buttons").show(),this.helper.remove(),delete this.helper,Headway.blankBlockOptions.pixelWidth<this.grid.columnWidth||Headway.blankBlockOptions.height<this.options.minBlockHeight?!1:(this.addBlankBlock(Headway.blankBlockOptions),this.mouseStartPosition=!1,delete this.draggingOnWrapper,!1)},initResizable:function(t){if(typeof t=="string")var t=e(t);t.resizable({handles:"n, e, s, w, ne, se, sw, nw",grid:[this.grid.columnWidth+this.grid.gutterWidth,this.options.yGridInterval],containment:this.container,minHeight:this.options.minBlockHeight,maxWidth:this.grid.columns*(this.grid.columnWidth+this.grid.gutterWidth),start:this.resizableStart,resize:this.resizableResize,stop:this.resizableStop})},resizableStart:function(t,n){var r=getBlock(n.element),i=r.parents(".ui-headway-grid").data("ui-headwayGrid"),s=parseInt(r.css("minHeight").replace("px","")),o=r.height();s<=o&&r.css("minHeight",0),r.addClass("block-hover"),r.qtip("option","hide.delay",1e4),r.qtip("show"),r.qtip("reposition"),e(r).data("old-position",getBlockPosition(r)),e(r).data("old-position-pixels",getBlockPositionPixels(r)),e(r).data("old-dimensions",getBlockDimensions(r)),e(r).data("old-dimensions-pixels",getBlockDimensionsPixels(r)),i.wrapper.hasClass("wrapper-fluid")&&i.wrapper.find(".wrapper-buttons").hide()},resizableResize:function(e,t){var n=getBlock(t.element),r=n.parents(".ui-headway-grid").data("ui-headwayGrid"),i=Math.round((n.width()+r.grid.gutterWidth)/(r.grid.columnWidth+r.grid.gutterWidth)),s=Math.round(n.position().left/(r.grid.columnWidth+r.grid.gutterWidth));setBlockGridWidth(n,i),setBlockGridLeft(n,s),r.alignBlockWithGuides(n);var o=n.data("qtip");$i("#qtip-"+o.id).remove(),o.rendered=!1,o.render(),o.show()},resizableStop:function(e,t){var n=getBlock(t.element),r=n.parents(".ui-headway-grid").data("ui-headwayGrid"),i=n.data("old-position"),s=n.data("old-dimensions"),o={left:Math.round(n.position().left/(r.grid.columnWidth+r.grid.gutterWidth)),top:getBlockPositionPixels(n).top},u={width:Math.ceil(n.width()/(r.grid.columnWidth+r.grid.gutterWidth)),height:getBlockDimensionsPixels(n).height};r.wrapper.find(".wrapper-buttons").show();var a=function(e,t){setBlockGridWidth(n,e.width),setBlockGridLeft(n,t.left),n.height(e.height),n.css("top",t.top+"px"),n.attr({"data-grid-top":t.top,"data-height":e.height}),f()},f=function(){n.css("width",""),n.css("left",""),r.alignBlockWithGuides(n),dataSetBlockDimensions(getBlockID(n),getBlockDimensions(n)),dataSetBlockPosition(getBlockID(n),getBlockPosition(n)),blockIntersectCheck(n)?allowSaving():disallowSaving(),n.qtip("option","show.delay",300),n.qtip("option","hide.delay",25),n.qtip("show"),n.qtip("reposition"),n.removeClass("block-hover")};Headway.history.add({description:"Resized block",up:function(){a(u,o)},down:function(){a(s,i)}})},initDraggable:function(t){typeof t=="string"&&(t=e(t)),t.css("cursor","move").pep({grid:[this.grid.columnWidth+this.grid.gutterWidth,this.options.yGridInterval],constrainTo:"parent",shouldEase:!1,start:this.draggableStart,stop:this.draggableStop,drag:this.draggableDrag})},draggableStart:function(t,n){if(t.ctrlKey)return!1;if(e(t.target).hasClass("ui-resizable-handle"))return e(n.el).trigger("stop"),!1;var r=n.el,i=getBlock(r).parents(".ui-headway-grid").data("ui-headwayGrid");blockGroupingOriginals={},blockGroupingOriginals[getBlockID(r)]={top:getBlockPositionPixels(r).top,left:getBlockPositionPixels(r).left},e(r).hasClass("grouped-block")?(e(r).data("plugin_pep").$el=i.container.find(".grouped-block"),i.container.find(".grouped-block").each(function(t){e(this).data("old-position",getBlockPosition(e(this))),e(this).data("old-position-pixels",getBlockPositionPixels(e(this)))}),i.sendBlockToTop(i.container.find(".grouped-block"))):(i.container.removeClass("grouping-active"),i.container.find(".grouped-block").removeClass("grouped-block"),hideNotification("mass-block-selection"),i.sendBlockToTop(e(r)),e(r).data("plugin_pep").$el=e(r),e(r).data("old-position",getBlockPosition(r)),e(r).data("old-position-pixels",getBlockPositionPixels(r))),i.wrapper.hasClass("wrapper-fluid")&&i.wrapper.find(".wrapper-buttons").hide(),e(getBlock(n.el)).qtip("hide"),e(getBlock(n.el)).qtip("disable")},draggableDrag:function(t,n){if(e(n.startEvent.target).hasClass("ui-resizable-handle"))return!1;var r=n.el,i=e(r),s,o=getBlock(e(r)).parents(".grid-container"),u=getBlock(e(r)).parents(".ui-headway-grid").data("ui-headwayGrid"),a=getBlock(e(r)).parents(".wrapper");$i(".grid-container").length>1&&!u.container.find(".grouped-block").length&&($i(".grid-container").not(o).each(function(){var n=e(this).closest(".wrapper")[0].getBoundingClientRect(),i=e(this)[0].getBoundingClientRect();s=t.pageX>n.left&&t.pageX<n.right&&t.pageY>n.top+$iDocument().scrollTop()&&t.pageY<n.bottom+$iDocument().scrollTop(),s?e(this).addClass("ui-state-hover"):e(this).removeClass("ui-state-hover");if(s){var o=e(r).data("wrapper-droppable-clone"),a={top:t.pageY-i.top-$iDocument().scrollTop(),left:t.pageX-i.left};if(!o){var o=e(r).clone().css({transform:"",left:e(r).position().left.toNearest(u.grid.columnWidth+u.grid.gutterWidth)}).appendTo(e(this));o.data("left-difference",a.left-e(r).position().left.toNearest(u.grid.columnWidth+u.grid.gutterWidth)),e(r).data("ghost-position",e(r).position()).css({transform:"",left:blockGroupingOriginals[getBlockID(e(r))].left,top:blockGroupingOriginals[getBlockID(e(r))].top}).addClass("block-ghost"),e(r).data("wrapper-droppable-clone",o),delete e(r).data("plugin_pep").translation,delete e(r).data("plugin_pep").cssX,delete e(r).data("plugin_pep").cssY}var f=parseInt(a.top).toNearest(u.options.yGridInterval),l=parseInt(a.left-o.data("left-difference")).toNearest(u.grid.columnWidth+u.grid.gutterWidth);return f<0&&(f=0),l<0&&(l=0),parseInt(l)+parseInt(e(r).width())>e(this).width()&&(l=e(this).width()-e(r).width()),e(r).height()+f>e(this).height()&&(f=e(this).height()-e(r).height()),e(r).height()>e(this).height()&&(e(this).attr("data-original-height")||e(this).attr("data-original-height",e(this).height()),e(this).height(e(r).height())),e(o).css({transform:"",top:parseInt(f).toNearest(u.options.yGridInterval),left:parseInt(l).toNearest(u.grid.columnWidth+u.grid.gutterWidth)}),!1}}),s||($i(".block-ghost").each(function(){e(this).data("wrapper-droppable-clone").remove(),e(this).removeData("wrapper-droppable-clone"),e(this).removeClass("block-ghost"),e(this).css({left:e(this).data("ghost-position").left,top:e(this).data("ghost-position").top})}),$i("[data-original-height]").each(function(){e(this).height(e(this).data("original-height")),e(this).removeAttr("data-original-height")})));if(s)return!1;e(getBlock(n.helper)).qtip("hide")},draggableStop:function(t,n){if(e(n.startEvent.target).hasClass("ui-resizable-handle"))return!1;var r=e(n.el),i=getBlock(e(r)).parents(".grid-container"),s=getBlock(e(r)).parents(".ui-headway-grid").data("ui-headwayGrid"),o,u;$i(".grid-container").length>1&&!s.container.find(".grouped-block").length&&$i(".grid-container").not(i).each(function(){var n=e(this).closest(".wrapper")[0].getBoundingClientRect();o=t.pageX>n.left&&t.pageX<n.right&&t.pageY>n.top+$iDocument().scrollTop()&&t.pageY<n.bottom+$iDocument().scrollTop();if(o||!t.originalEvent&&e(this).find(e(r).data("wrapper-droppable-clone")).length)return o=!0,u=e(this),!1;u=!1}),$i(".grid-container.ui-state-hover").removeClass("ui-state-hover");if(o&&$i(".grid-container").length>1){var a=u.parents(".wrapper").data("ui-headwayGrid"),f=r.parents(".grid-container");u.append(r),e(r).css(e(r).data("wrapper-droppable-clone").position()),e(r).data("wrapper-droppable-clone").remove(),e(r).removeClass("block-ghost").removeData("wrapper-droppable-clone"),setBlockGridLeft(r,Math.round(e(r).position().left/(s.grid.columnWidth+s.grid.gutterWidth))),$i("[data-original-height]").removeAttr("data-original-height"),r.resizable("destroy"),u.parents(".wrapper").headwayGrid("initResizable",r),e.pep.unbind(r),u.parents(".wrapper").headwayGrid("initDraggable",r),blockIntersectCheck(!1,f),blockIntersectCheck(!1,u),dataSetBlockPosition(getBlockID(r),getBlockPosition(r)),dataSetBlockWrapper(getBlockID(r),getBlockWrapper(r).attr("id")),r.parents(".ui-headway-grid").first().data("ui-headwayGrid").alignBlockWithGuides(r)}if(s.container.find(".grouped-block").length)var l=s.container.find(".grouped-block");else var l=getBlock(n.el);s.wrapper.find(".wrapper-buttons").show();var c=[];if(l.length===1)var h="Moved block";else var h="Mass Moved Blocks: ";l.each(function(){c.push({block:e(this),newPosition:{left:Math.round(e(this).position().left/(s.grid.columnWidth+s.grid.gutterWidth)),top:getBlockPositionPixels(e(this)).top},newPositionPixels:getBlockPositionPixels(e(this)),oldPosition:e(this).data("old-position"),oldPositionPixels:e(this).data("old-position-pixels")}),l.length>1&&(h+=", ")}),l.length>1&&(h=h.substring(0,h.length-2));var p=function(e,t){var n=e.block,r=e.newPosition.left,i=e.newPosition.top,s=e.newPositionPixels.left;t&&(r=e.oldPosition.left,i=e.oldPosition.top,s=e.oldPositionPixels.left),setBlockGridLeft(n,r),n.attr({"data-grid-top":i}),n.css("top",i+"px"),n.css("left",s+"px"),n.css({transform:"","-webkit-transform":"","-moz-transform":"","-ms-transform":"","-o-transform":""}),delete n.data("plugin_pep").translation,delete n.data("plugin_pep").cssX,delete n.data("plugin_pep").cssY,dataSetBlockPosition(getBlockID(n),getBlockPosition(n)),dataSetBlockWrapper(getBlockID(n),getBlockWrapper(n).attr("id")),blockIntersectCheck(n)?allowSaving():disallowSaving()};Headway.history.add({description:h,up:function(){jQuery.each(c,function(e,t){p(t,!1)})},down:function(){jQuery.each(c,function(e,t){p(t,!0)})}}),e(document).focus(),e(getBlock(n.el)).qtip("enable"),e(getBlock(n.el)).qtip("show"),e(r).data("hoverWaitTimeout",setTimeout(function(){e(getBlock(n.el)).qtip("reposition"),e(getBlock(n.el)).qtip("show")},300))},addBlankBlock:function(t,n){var r={top:0,left:0,width:140,height:this.options.minBlockHeight,id:null};t=e.extend({},r,t);if(typeof i=="undefined")var i=!0;typeof n=="undefined"&&(n=!1);var s=Math.ceil(Math.random()*1e9);Headway.blankBlock=e('<div><div class="block-content-fade block-content"></div></div>').attr("id","block-"+s).attr("data-id",s).attr("data-temp-id",s).attr("data-desired-id",t.id?t.id:null).addClass(this.options.defaultBlockClass.replace(".","")).addClass("blank-block").addClass("hide-content-in-grid"),updateBlockContentCover(Headway.blankBlock);var o=Headway.blankBlock;return o.css({height:parseInt(t.height),top:parseInt(t.top),position:"absolute",visibility:"hidden",left:"",width:""}),setBlockGridLeft(o,t.left),setBlockGridWidth(o,t.width),o.attr({"data-height":parseInt(t.height),"data-grid-top":parseInt(t.top)}),o.appendTo(this.container),this.alignBlockWithGuides(o),o.css("visibility","visible"),n==0&&openBlockTypeSelector(e(Headway.blankBlock)),this.initResizable(o),this.initDraggable(o),blockIntersectCheck(o),o},setupBlankBlock:function(e,t,n){if(typeof n=="undefined")var n=!0;if(typeof t=="undefined")var t=!1;Headway.blankBlock.removeClass("blank-block"),Headway.blankBlock.addClass("block-type-"+e),Headway.blankBlock.data("type",e),n&&loadBlockContent({blockElement:Headway.blankBlock,blockOrigin:{type:e,id:0,layout:Headway.currentLayout},blockSettings:{dimensions:getBlockDimensions(Headway.blankBlock),position:getBlockPosition(Headway.blankBlock)}}),getBlockTypeObject(e)["fixed-height"]===!0?Headway.blankBlock.addClass("block-fixed-height"):Headway.blankBlock.addClass("block-fluid-height"),getBlockTypeObject(e)["show-content-in-grid"]&&Headway.blankBlock.removeClass("hide-content-in-grid"),dataAddBlock(Headway.blankBlock),dataSetBlockPosition(getBlockID(Headway.blankBlock),getBlockPosition(Headway.blankBlock)),dataSetBlockDimensions(getBlockID(Headway.blankBlock),getBlockDimensions(Headway.blankBlock)),dataSetBlockWrapper(getBlockID(Headway.blankBlock),Headway.blankBlock.closest(".wrapper").attr("id")),blockIntersectCheck(Headway.blankBlock)?allowSaving():disallowSaving(),updateBlockContentCover(Headway.blankBlock);var r=Headway.blankBlock;return Headway.history.add({description:"Added "+getBlockTypeNice(e)+" block",up:function(){r.show(),typeof GLOBALunsavedValues["blocks"][getBlockID(r)]["delete"]!="undefined"&&delete GLOBALunsavedValues.blocks[getBlockID(r)]["delete"],blockIntersectCheck(r,r.parents(".grid-container"))},down:function(){r.hide(),removePanelTab("block-"+getBlockID(r)),dataDeleteBlock(getBlockID(r)),blockIntersectCheck(!1,r.parents(".grid-container"))}}),delete Headway.blankBlock,delete Headway.blankBlockOptions,r},addBlock:function(t){var n={top:0,left:0,width:1,height:this.options.minBlockHeight,type:null,id:null,settings:[]},t=e.extend({},n,t);if(this.addBlankBlock(t,!0)){var r=this.setupBlankBlock(t.type,!0,!1),i=getBlockID(r);return e.each(t.settings,function(e,t){dataSetBlockOption(i,e,t),e=="mirror-block"&&updateBlockMirrorStatus(!1,r,t,!1)}),refreshBlockContent(i,!1,!1,!1),this.updateGridContainerHeight(),r}return!1},sendBlockToTop:function(e){if(typeof e=="string")var e=getBlock(e);if(!e||!e.length)return;$i(".block").css("zIndex",1),e.css("zIndex",2)},updateGridContainerHeight:function(){var t=this.container,n=this.wrapper;t.css("height",this.wrapper.height());if(t.find(".block:visible").length){var r=0;t.find(".block:visible").each(function(){var t=e(this).outerHeight()+e(this).position().top;t>r&&(r=t)}),t.height(r)}},addColumnGuides:function(){var t=this.container;t.find(".grid-guides").remove();var n=e('<div class="grid-guides grid-guides-grey"></div><!-- #grid -->');for(i=1;i<=this.options.columns;i++)n.append('<div class="grid-guide grid-width-1 grid-guide-'+i+'"></div>');n.prependTo(t)},alignBlockWithGuides:function(t){var n=this.container.children(".grid-guides:visible");if(!n.length)return;var r=parseInt(getBlockGridLeft(t)),i=parseInt(getBlockGridWidth(t));if(typeof r=="undefined"||isNaN(r)||r<0)r=0;if(typeof i=="undefined"||isNaN(i)||i==0)i=1;var s=r+1<this.grid.columns?r+1:this.grid.columns,o=n.find(".grid-guide-"+s),u=r+i<this.grid.columns?r+i:this.grid.columns,a=n.find(".grid-guide-"+u);a.length||(a=o);if(r+1<=r+i){var f=parseInt(o.css("marginLeft").replace("px","")),l=parseInt(a.css("marginLeft").replace("px","")),c=o.position().left+f,h=a.position().left+a.outerWidth()-o.position().left-1;r==0&&(h+=l),t.css({top:e(t).position().top,transform:"",left:Math.ceil(c)+"px",width:Math.ceil(h)+"px"})}},alignAllBlocksWithGuides:function(){var t=this;this.container.find(".block:visible").each(function(){t.alignBlockWithGuides(e(this))})},updateGridCSS:function(){var t=this,n=this.wrapper,r=e("div#wrapper-"+getWrapperID(n)+"-tab"),i="div#"+n.attr("id");return n.attr("data-temp-id")&&(i='div.wrapper[data-temp-id="'+n.attr("data-temp-id")+'"]'),typeof this.options.useIndependentGrid!="undefined"&&this.options.useIndependentGrid===!0||typeof this.options.useIndependentGrid=="string"&&hwBoolean(this.options.useIndependentGrid)?updateGridCSS(i,this.options.columns,this.options.columnWidth,this.options.gutterWidth,r):updateGridCSS(i,this.options.columns,Headway.globalGridColumnWidth,Headway.globalGridGutterWidth,r),this.resetGridCalculations(),e($iDocument()).ready(function(){t.alignAllBlocksWithGuides()}),n}}),e.extend(e.ui.headwayGrid,{version:"2.1"})}),define("util.custommouse",["jquery","jqueryUI"],function(e){e.widget("ui.custommouse",e.ui.mouse,{options:{mouseStart:function(e){},mouseDrag:function(e){},mouseStop:function(e){},mouseCapture:function(e){return!0}},_mouseStart:function(e){return this.options.mouseStart(e)},_mouseDrag:function(e){return this.options.mouseDrag(e)},_mouseStop:function(e){return this.options.mouseStop(e)},_mouseCapture:function(e){return this.options.mouseCapture(e)},widgetEventPrefix:"custommouse",_init:function(){return this._mouseInit()},_create:function(){return this.element.addClass("ui-custommouse")},_destroy:function(){return this._mouseDestroy(),this.element.removeClass("ui-custommouse")}})}),define("modules/grid/wrappers",["util.custommouse","qtip","helper.data"],function(){setupWrapperSortables=function(){return $i("#whitewrap").sortable({items:"div.wrapper",handle:"div.wrapper-drag-handle",axis:"y",tolerance:"pointer",placeholder:"wrapper-sortable-placeholder",start:function(e,t){$i(".wrapper").each(function(){$(this).data("current-height",$(this).height())}),$i(".wrapper-fixed").css({height:"100px"}),$i(".wrapper-fluid").css({height:"130px"}),$i(".wrapper .grid-container").css({height:"100px",overflow:"hidden"}),$(t.item).hasClass("wrapper-fixed-grid")&&$(t.item).css({left:"50%",marginLeft:"-"+$(t.item).outerWidth()/2+"px"}),t.placeholder.css({width:t.item.outerWidth(),height:t.item.outerHeight(),marginTop:t.item.css("marginTop"),marginBottom:t.item.css("marginBottom")}),$("#iframe-container").scrollTop(t.placeholder.offset().top-300),$(this).sortable("refreshPositions")},stop:function(e,t){$i(".wrapper").css({marginLeft:"",left:""}),$i(".wrapper").each(function(){$(this).height($(this).data("current-height")),$(this).removeData("current-height")}),$i(".wrapper, .wrapper .grid-container").css({overflow:""}),$i(".wrapper").each(function(){$(this).headwayGrid("updateGridContainerHeight")}),dataSortWrappers()}})},setupWrapperResizable=function(e){if(typeof e=="undefined")var e=$i(".wrapper");e.each(function(){var e=parseInt($(this).css("minHeight").replace("px",""));$(this).resizable({handles:"n, s",grid:5,minHeight:e,start:function(t,n){$(t.toElement).hasClass("ui-resizable-n")?$(this).data("resizing-position","n"):$(this).data("resizing-position","s");if($(this).find(".block").length){var r=0,i=null;$(this).find(".block:visible").each(function(){var e=$(this).position().top,t=$(this).outerHeight()+e;t>r&&(r=t);if(e<i||i===null)i=e;$(this).data("resize-original-block-top",$(this).position().top)});if($(this).data("resizing-position")=="n")var s=r-i;else var s=r}else var s=e;$(this).resizable("option","minHeight",s)},resize:function(e,t){var n=t.originalSize.height-t.size.height,r=t.size.height;$(this).find(".grid-container").height(r),$(this).css({top:"",height:""});if($(this).data("resizing-position")=="n"){var i=!1;$(this).find(".block").each(function(){if($(this).data("resize-original-block-top")-n<0)return i=!0,!1}),i||$(this).find(".block").each(function(){$(this).css({top:$(this).data("resize-original-block-top")-n})})}},stop:function(){$(this).find(".block").each(function(){var e=$(this),t=getBlockID(e);e.attr("data-grid-top",e.position().top),dataSetBlockPosition(t,getBlockPosition(e))}),$(this).data("resizing-position",null)}})})},stopWrapperResizable=function(e){if(!e.length||!e.resizable)return!1;e.resizable("destroy"),setupWrapperResizable(e)},addEdgeInsertWrapperButtons=function(){var e='<div class="add-wrapper-button-fixed tooltip" title="Add Wrapper">+</div>';$('<div class="add-wrapper-buttons add-wrapper-buttons-top">'+e+"</div>").data("position","top").prependTo($i("body")),$('<div class="add-wrapper-buttons add-wrapper-buttons-bottom">'+e+"</div>").data("position","bottom").appendTo($i("body"))},setupWrapperContextMenu=function(){setupContextMenu({id:"wrapper",elements:".wrapper",title:function(e){var t=$(e.currentTarget),n=getWrapperID(t);return"Wrapper"},contentsCallback:function(e){var t=$(this),n=$(e.currentTarget),r=getWrapperID(n);$('<li class="context-menu-wrapper-options"><span>Open Wrapper Options</span></li>').appendTo(t).on("click",function(){openWrapperOptions(r)}),n.hasClass("wrapper-fluid")?($('<li class="context-menu-wrapper-to-fixed"><span>Change Wrapper to Fixed</span></li>').appendTo(t).find("span").on("click",function(){n.removeClass("wrapper-fluid"),n.removeClass("wrapper-fluid-grid"),n.addClass("wrapper-fixed"),n.addClass("wrapper-fixed-grid"),dataSetWrapperWidth(getWrapperID(n),"fixed"),dataSetWrapperGridWidth(getWrapperID(n),"fixed"),n.data("ui-headwayGrid").resetGridCalculations(),n.data("ui-headwayGrid").alignAllBlocksWithGuides(),n.data("ui-headwayGrid").updateGridContainerHeight()}),n.hasClass("wrapper-fixed-grid")?$('<li class="context-menu-wrapper-grid-to-fluid"><span>Change Grid to Fluid</span></li>').appendTo(t).find("span").on("click",function(){n.removeClass("wrapper-fixed-grid"),n.addClass("wrapper-fluid-grid"),dataSetWrapperWidth(getWrapperID(n),"fluid"),dataSetWrapperGridWidth(getWrapperID(n),"fluid"),n.data("ui-headwayGrid").resetGridCalculations(),n.data("ui-headwayGrid").alignAllBlocksWithGuides(),n.data("ui-headwayGrid").updateGridContainerHeight()}):n.hasClass("wrapper-fluid-grid")&&$('<li class="context-menu-wrapper-grid-to-fixed"><span>Change Grid to Fixed</span></li>').appendTo(t).find("span").on("click",function(){n.removeClass("wrapper-fluid-grid"),n.addClass("wrapper-fixed-grid"),dataSetWrapperWidth(getWrapperID(n),"fluid"),dataSetWrapperGridWidth(getWrapperID(n),"fixed"),n.data("ui-headwayGrid").resetGridCalculations(),n.data("ui-headwayGrid").alignAllBlocksWithGuides(),n.data("ui-headwayGrid").updateGridContainerHeight()})):n.hasClass("wrapper-fixed")&&$('<li class="context-menu-wrapper-to-fluid"><span>Change Wrapper to Fluid</span></li>').appendTo(t).on("click",function(){n.removeClass("wrapper-fixed"),n.addClass("wrapper-fluid"),n.addClass("wrapper-fixed-grid"),dataSetWrapperWidth(getWrapperID(n),"fluid"),dataSetWrapperGridWidth(getWrapperID(n),"fixed"),n.data("ui-headwayGrid").resetGridCalculations(),n.data("ui-headwayGrid").alignAllBlocksWithGuides(),n.data("ui-headwayGrid").updateGridContainerHeight()}),$('<li class="context-menu-set-alias"><span>Set Wrapper Alias</span></li>').appendTo(t).on("click",function(){var e=prompt("Please enter the desired wrapper alias.",n.data("alias"));if(!e)return;dataSetWrapperOption(getWrapperID(n),"alias",e),n.data("alias",e)}),$i(".wrapper:visible").length>=2&&$('<li class="context-menu-wrapper-delete"><span>Delete Wrapper</span></li>').appendTo(t).on("click",function(){deleteWrapper(r)})}})},bindWrapperButtons=function(){$i("body").delegate(".add-wrapper-button-fixed","click",function(){return addWrapper($(this).parents(".add-wrapper-buttons").data("position"),{fluid:!1})}),$i("body").delegate(".add-wrapper-fluid-fixed-grid","click",function(){return addWrapper($(this).parents(".add-wrapper-buttons").data("position"),{fluid:!0})}),$i("body").delegate(".add-wrapper-fluid-fluid-grid","click",function(){return addWrapper($(this).parents(".add-wrapper-buttons").data("position"),{fluid:!0,"fluid-grid":!0})}),$i("body").delegate(".wrapper-buttons .wrapper-options","click",function(){return openWrapperOptions(getWrapperID($(this).closest(".wrapper")))}),bindWrapperMarginButtons($i(".wrapper-buttons .wrapper-margin-handle"))},addWrapper=function(e,t,n){typeof t.id!="undefined"&&delete t.id;var t=$.extend({},{fluid:!1,"fluid-grid":!1,"use-independent-grid":!1},t);typeof t["fluid"]!="boolean"&&(t.fluid=hwBoolean(t.fluid)),typeof t["fluid-grid"]!="boolean"&&(t["fluid-grid"]=hwBoolean(t["fluid-grid"]));var r=Math.ceil(Math.random()*1e9),i=$('<div class="wrapper"><div class="grid-container"></div></div>');i.attr("id","wrapper-"+r).attr("data-id",r).attr("data-temp-id",r).attr("data-desired-id",t.id?t.id:null),i.prepend('<div class="wrapper-mirror-overlay"></div>'),i.find(".grid-container").append(' <div class="wrapper-mirror-notice"> <div> <h2>Wrapper Mirrored</h2> <p>This wrapper is mirroring blocks from another wrapper.</p> <small>Mirroring can be disabled via Wrapper Options in the right-click menu</small> </div> </div><!-- .wrapper-mirror-notice --> '),addWrapperButtons(i),t.fluid?i.addClass("wrapper-fluid"):i.addClass("wrapper-fixed"),t["fluid-grid"]?i.addClass("wrapper-fluid-grid"):i.addClass("wrapper-fixed-grid");switch(e){case"top":i.prependTo($i("#whitewrap"));break;case"bottom":i.insertBefore($i("#wrapper-buttons-template"))}t.fluid&&(i.css("margin"+e.capitalize(),0),dataSetDesignEditorProperty({element:"wrapper",property:"margin-"+e,value:0,specialElementType:"instance",specialElementMeta:"wrapper-"+r})),dataAddWrapper(i,t,$i(".wrapper").index(i)),allowSaving(),i.find(".grid-container").height(100),i.data("wrapper-settings",t),i.headwayGrid(),setupWrapperResizable(i),bindWrapperMarginButtons(i.find(".wrapper-margin-handle"));var s=t.fluid?"Fluid":"Fixed";return(typeof n=="undefined"||!n)&&showNotification({id:"wrapper-created-"+r,message:s+" wrapper created.",closable:!0,closeTimer:5e3}),setupTooltips("iframe"),i},deleteWrapper=function(e,t){var n=$i("#wrapper-"+e);return n.length&&(t||confirm("Are you sure you want to remove this wrapper? All blocks inside the wrapper will be deleted as well."))?(dataDeleteWrapper(e),n.find(".block").each(function(){deleteBlock($(this))}),n.remove()):!1},addWrapperButtons=function(e){e.each(function(){if($(this).find(".wrapper-buttons").length)return;var e=$i("#wrapper-buttons-template").first().clone().attr("id","").addClass("wrapper-buttons");return e.prependTo($(this))})},bindWrapperMarginButtons=function(e){var t=function(e){var t=$(e.target);t.length||(t=$i(".wrapper-handle[data-dragging]").first());var n=t.closest(".wrapper"),r=t.hasClass("wrapper-top-margin-handle")?"Top":"Bottom",i='<span style="opacity: .8;">'+r+" Margin:</span> "+n.css("margin"+r),s=t.data("dragging")?"":"Drag to change wrapper's <strong>"+r.toLowerCase()+" margin</strong><br />";return s+i};e.qtip({content:{text:t},style:{classes:"qtip-headway"},show:{delay:10,event:"mouseenter"},position:{my:"right center",at:"left center",container:Headway.iframe.contents().find("body"),viewport:$("#iframe-container"),effect:!1}}),e.custommouse({mouseStart:function(e){this.handle=$(e.currentTarget).hasClass("wrapper-margin-handle")?$(e.currentTarget):$(e.currentTarget).parents(".wrapper-margin-handle").first(),this.dragStart={left:e.pageX,top:e.pageY},this.marginToChange=this.handle.hasClass("wrapper-top-margin-handle")?"marginTop":"marginBottom",this.wrapper=$(e.currentTarget).closest(".wrapper"),this.originalWrapperMargin=parseInt(this.wrapper.css(this.marginToChange).replace("px","")),this.handle.siblings(".wrapper-handle[data-hasqtip], .wrapper-options[data-hasqtip]").each(function(){var e=$(this).qtip("api");typeof e!="undefined"&&e.rendered&&(e.disable(),e.hide())}),this.wrapper.addClass("wrapper-handle-in-use")},mouseDrag:function(e){var n=e.pageY-this.dragStart.top,r=2,i=Math.round(n/r),s=this.originalWrapperMargin+i;if(s<0)return!1;this.handle.attr("data-dragging",!0),this.handle.qtip("show"),this.handle.qtip("reposition"),this.handle.qtip("option","content.text",t),this.wrapper.css(this.marginToChange,s),dataSetDesignEditorProperty({element:"wrapper",property:"margin-"+this.marginToChange.replace("margin","").toLowerCase(),value:s.toString(),specialElementType:"instance",specialElementMeta:"wrapper-"+getWrapperID(this.wrapper)})},mouseStop:function(e){this.handle.removeAttr("data-dragging"),this.handle.data("dragging",!1);var t=this.handle.qtip("api");t.hide(),$i("#qtip-"+t.id).hide(),this.handle.siblings(".wrapper-handle, .wrapper-options").qtip("enable"),this.wrapper.removeClass("wrapper-handle-in-use")}})},populateWrapperMirrorNotice=function(e){var t=getWrapperMirror(getWrapperID(e));if(!t)return;e.find(".wrapper-mirror-notice-id").text(t.replace("wrapper-","")),e.find(".wrapper-mirror-notice-layout").hide()},assignDefaultWrapperID=function(){if($i("#wrapper-default").length){var e=Math.ceil(Math.random()*1e9),t=$i("#wrapper-default");t.attr("id","wrapper-"+e).attr("data-id",e).attr("data-temp-id",e).attr("data-desired-id",null),dataAddWrapper(t,{fluid:!1,"fluid-grid":!1},$i(".wrapper").index(t)),t.find(".block").each(function(){dataSetBlockWrapper(getBlockID($(this)),e)})}}}),wrapperOptionCallbackIndependentGrid=function(e,t){var n=$i("#wrapper-"+e.parents("[data-panel-args]").data("panel-args").wrapper.id);if(typeof n=="undefined"||!n.length)return!1;var r=n.data("ui-headwayGrid");r.options.useIndependentGrid=t,r.updateGridCSS()},wrapperOptionCallbackColumnCount=function(e,t){var n=$i("#wrapper-"+e.parents("[data-panel-args]").data("panel-args").wrapper.id);if(typeof n=="undefined"||!n.length)return!1;if(n.find(".block:visible").length)return alert("This wrapper must be empty of blocks before you can change the number of columns.\n\nEither drag the blocks to another wrapper or delete them if they are no longer needed."),!1;var r=n.data("ui-headwayGrid");r.options.columns=t,r.addColumnGuides(),r.updateGridCSS()},wrapperOptionCallbackColumnWidth=function(e,t){var n=$i("#wrapper-"+e.parents("[data-panel-args]").data("panel-args").wrapper.id);if(typeof n=="undefined"||!n.length)return!1;var r=n.data("ui-headwayGrid");r.options.columnWidth=t,r.updateGridCSS()},wrapperOptionCallbackGutterWidth=function(e,t){var n=$i("#wrapper-"+e.parents("[data-panel-args]").data("panel-args").wrapper.id);if(typeof n=="undefined"||!n.length)return!1;var r=n.data("ui-headwayGrid");r.options.gutterWidth=t,r.updateGridCSS()},wrapperOptionCallbackMarginTop=function(e,t){var n=$i("#wrapper-"+e.parents("[data-panel-args]").data("panel-args").wrapper.id);if(typeof n=="undefined"||!n.length)return!1;n.css({marginTop:t}),wrapperMarginFeedbackCreator(n,"top")},wrapperOptionCallbackMarginBottom=function(e,t){var n=$i("#wrapper-"+e.parents("[data-panel-args]").data("panel-args").wrapper.id);if(typeof n=="undefined"||!n.length)return!1;n.css({marginBottom:t}),wrapperMarginFeedbackCreator(n,"bottom")},wrapperMarginFeedbackCreator=function(e,t){e.find(".wrapper-margin-feedback").length&&(clearTimeout(e.find(".wrapper-margin-feedback").data("fadeout-timeout")),e.find(".wrapper-margin-feedback").remove());var n=$('<div class="wrapper-margin-feedback"></div>').prependTo(e),r=parseInt(e.css("margin"+t.capitalize()).replace("px","")),i={position:"absolute",width:e.outerWidth(),left:0,height:r,backgroundColor:"rgba(255, 127, 0, .35)"};return i[t]="-"+r+"px",n.css(i),n.data("fadeout-timeout",setTimeout(function(){n.fadeOut(200)},400)),n},updateGridWidthInput=function(e){var t=$(e).find('input[name="columns"]').val(),n=$(e).find('input[name="column-width"]').val(),r=$(e).find('input[name="gutter-width"]').val(),i=n*t+(t-1)*r;return $(e).find('input[name="grid-width"]').val(i)},define("modules/grid/wrapper-inputs",function(){}),bindGridWizard=function(){var e={"right-sidebar":[{top:0,left:0,width:24,height:130,type:"header"},{top:140,left:0,width:24,height:40,type:"navigation"},{top:190,left:0,width:18,height:320,type:"content"},{top:190,left:18,width:6,height:270,type:"widget-area",mirroringOrigin:"sidebar-1"},{top:520,left:0,width:24,height:70,type:"footer"}],"left-sidebar":[{top:0,left:0,width:24,height:130,type:"header"},{top:140,left:0,width:24,height:40,type:"navigation"},{top:190,left:0,width:6,height:270,type:"widget-area",mirroringOrigin:"sidebar-1"},{top:190,left:6,width:18,height:320,type:"content"},{top:520,left:0,width:24,height:70,type:"footer"}],"two-right":[{top:0,left:0,width:24,height:130,type:"header"},{top:140,left:0,width:24,height:40,type:"navigation"},{top:190,left:0,width:16,height:320,type:"content"},{top:190,left:16,width:4,height:270,type:"widget-area",mirroringOrigin:"sidebar-1"},{top:190,left:20,width:4,height:270,type:"widget-area",mirroringOrigin:"sidebar-2"},{top:520,left:0,width:24,height:70,type:"footer"}],"two-both":[{top:0,left:0,width:24,height:130,type:"header"},{top:140,left:0,width:24,height:40,type:"navigation"},{top:190,left:0,width:4,height:270,type:"widget-area",mirroringOrigin:"sidebar-1"},{top:190,left:4,width:16,height:320,type:"content"},{top:190,left:20,width:4,height:270,type:"widget-area",mirroringOrigin:"sidebar-2"},{top:520,left:0,width:24,height:70,type:"footer"}],"all-content":[{top:0,left:0,width:24,height:130,type:"header"},{top:140,left:0,width:24,height:40,type:"navigation"},{top:190,left:0,width:24,height:320,type:"content"},{top:520,left:0,width:24,height:70,type:"footer"}]};$("div#boxes").delegate("div#box-grid-wizard span.layout-preset","mousedown",function(){$("div#box-grid-wizard span.layout-preset-selected").removeClass("layout-preset-selected"),$(this).addClass("layout-preset-selected")}),$("div#boxes").delegate("span#grid-wizard-button-preset-next","click",function(){var e=$("div#box-grid-wizard span.layout-preset-selected").attr("id").replace("layout-","");switch(e){case"right-sidebar":$("div#grid-wizard-presets-mirroring-select-sidebar-1").show(),$("div#grid-wizard-presets-mirroring-select-sidebar-2").hide(),$("div#grid-wizard-presets-mirroring-select-sidebar-1 h5").text("Right Sidebar");break;case"left-sidebar":$("div#grid-wizard-presets-mirroring-select-sidebar-1").show(),$("div#grid-wizard-presets-mirroring-select-sidebar-2").hide(),$("div#grid-wizard-presets-mirroring-select-sidebar-1 h5").text("Left Sidebar");break;case"two-right":$("div#grid-wizard-presets-mirroring-select-sidebar-1").show(),$("div#grid-wizard-presets-mirroring-select-sidebar-2").show(),$("div#grid-wizard-presets-mirroring-select-sidebar-1 h5").text("Left Sidebar"),$("div#grid-wizard-presets-mirroring-select-sidebar-2 h5").text("Right Sidebar");break;case"two-both":$("div#grid-wizard-presets-mirroring-select-sidebar-1").show(),$("div#grid-wizard-presets-mirroring-select-sidebar-2").show(),$("div#grid-wizard-presets-mirroring-select-sidebar-1 h5").text("Left Sidebar"),$("div#grid-wizard-presets-mirroring-select-sidebar-2 h5").text("Right Sidebar");break;case"all-content":$("div#grid-wizard-presets-mirroring-select-sidebar-1").hide(),$("div#grid-wizard-presets-mirroring-select-sidebar-2").hide()}$(this).hide(),$("span#grid-wizard-button-preset-previous").show(),$("span#grid-wizard-button-preset-use-preset").show(),$("div#grid-wizard-presets-step-1").hide(),$("div#grid-wizard-presets-step-2").show()}),$("div#boxes").delegate("span#grid-wizard-button-preset-previous","click",function(){$(this).hide(),$("span#grid-wizard-button-preset-use-preset").hide(),$("span#grid-wizard-button-preset-next").show(),$("div#grid-wizard-presets-step-2").hide(),$("div#grid-wizard-presets-step-1").show()}),$("div#boxes").delegate("span#grid-wizard-button-preset-use-preset","click",function(){var t=$("div#box-grid-wizard span.layout-preset-selected").attr("id").replace("layout-","");return $i(".block").each(function(){deleteBlock(this)}),$.each(e[t],function(){var e=this;delete e.mirroringOrigin;var t=typeof this.mirroringOrigin!="undefined"?this.mirroringOrigin:this.type,n=$("div#grid-wizard-presets-mirroring-select-"+t+" select").val();n!==""&&(e.settings={},e.settings["mirror-block"]=n),$i(".ui-headway-grid").first().data("ui-headwayGrid").addBlock(e)}),closeBox("grid-wizard")}),$("div#boxes").delegate("span#grid-wizard-button-clone-page","click",function(){var e=$("select#grid-wizard-pages-to-clone").val();if(e===""||!e)return alert("Please select a page to clone.");if($(this).hasClass("button-depressed"))return;$(this).text("Cloning...").addClass("button-depressed").css("cursor","default");var t=$.ajax(Headway.ajaxURL,{type:"POST",async:!0,data:{action:"headway_visual_editor",method:"get_layout_blocks_in_json",security:Headway.security,layout:e},success:function(e,t){if(t==0)return!1;$i(".wrapper").each(function(){deleteWrapper(getWrapperID($(this)),!0)});var n=e.wrappers,r=e.blocks,i=Object.keys(r).length,s={};return $.each(n,function(e,t){var n=t.styling;delete t.styling;var r=addWrapper("bottom",t.settings,!0),i=getWrapperID(r);s[e.replace("wrapper-","")]=i,typeof t["mirror_id"]!="undefined"&&(updateWrapperMirrorStatus(i,t.mirror_id),dataSetWrapperOption(i,"mirror-wrapper",t.mirror_id)),$.each(n,function(e,t){dataSetDesignEditorProperty({element:"wrapper",property:e,value:t!==null?t.toString():null,specialElementType:"instance",specialElementMeta:"wrapper-"+i});if(e.indexOf("margin")===0){var n=e.replace("margin-","").capitalize();r.css("margin"+n,t+"px")}else if(e.indexOf("padding")===0){var s=e.replace("padding-","").capitalize();r.css("padding"+s,t+"px")}})}),$.each(r,function(){var e=this.mirror_id?this.mirror_id:this.id,t={type:this.type,top:this.position.top,left:this.position.left,width:this.dimensions.width,height:this.dimensions.height,settings:$.extend({},this.settings,{"mirror-block":e})},n=typeof this.wrapper_id!="undefined"&&this.wrapper_id?this.wrapper_id:"default";if(typeof s[n.replace("wrapper-","")]!="undefined")var r="#wrapper-"+s[n.replace("wrapper-","")],i=$i(".ui-headway-grid").filter(r).first();else var i=$i(".ui-headway-grid").last();var o=i.data("ui-headwayGrid").addBlock(t),u=getBlockID(o),a=this.id;typeof this.styling!="undefined"&&this.styling&&$.each(this.styling,function(e,t){var e=e.replace("block-"+a,"block-"+u);$.each(t.properties,function(n,r){dataSetDesignEditorProperty({group:"blocks",element:t.element,property:n,value:r!==null?r.toString():null,specialElementType:"instance",specialElementMeta:e})})})}),closeBox("grid-wizard")}})}),$("div#boxes").delegate("span#grid-wizard-button-assign-template","click",function(){var e=$("select#grid-wizard-assign-template").val().replace("template-","");return e===""?alert("Please select a shared layout to assign."):($.post(Headway.ajaxURL,{action:"headway_visual_editor",method:"assign_template",security:Headway.security,template:e,layout:Headway.currentLayout},function(t){if(typeof t=="undefined"||t=="failure")return showErrorNotification({id:"error-could-not-assign-template",message:"Error: Could not assign shared layout."}),!1;$("div#layout-selector li.layout-selected").removeClass("layout-item-customized"),$("div#layout-selector li.layout-selected").addClass("layout-item-template-used"),$("div#layout-selector li.layout-selected span.status-template").text(t),showIframeLoadingOverlay(),changeTitle("Visual Editor: Assigning Template"),startTitleActivityIndicator(),Headway.currentLayoutTemplate="template-"+e,Headway.currentLayoutTemplateName=$('span.layout[data-layout-id="template-'+e+'"]').find(".template-name").text(),headwayIframeLoadNotification="Template assigned successfully!",loadIframe(Headway.instance.iframeCallback)}),closeBox("grid-wizard"))}),$("div#boxes").delegate("span.grid-wizard-use-empty-grid","click",function(){$i(".block").each(function(){deleteBlock(this)}),closeBox("grid-wizard")}),initiateLayoutImport=function(e){var t=e;if(!t.val())return alert("You must select a Headway layout file before importing.");var n=t.get(0).files[0];if(n&&typeof n.name!="undefined"&&typeof n.type!="undefined"){var r=new FileReader;r.onload=function(e){var t=e.target.result,n=JSON.parse(t);if(n["data-type"]!="layout")return alert("Cannot load layout file. Please insure that the selected file is a valid Headway layout export.");typeof n["image-definitions"]!="undefined"&&Object.keys(n["image-definitions"]).length?(showNotification({id:"importing-images",message:"Currently importing images.",closeTimer:1e4}),$.post(Headway.ajaxURL,{action:"headway_visual_editor",method:"import_images",security:Headway.security,importFile:n},function(e){var t=e;if(typeof t["error"]!="undefined")return alert("Error while importing images for layout: "+t.error);importLayout(t)})):importLayout(n)},r.readAsText(n)}else alert("Cannot load layout file. Please insure that the selected file is a valid Headway layout export.")},importLayout=function(e){$i(".block").each(function(){deleteBlock(this)});var t=e.blocks,n=Object.keys(t).length;return $.each(t,function(){var e={type:this.type,top:this.position.top,left:this.position.left,width:this.dimensions.width,height:this.dimensions.height,settings:this.settings};$i(".ui-headway-grid").first().data("ui-headwayGrid").addBlock(e)}),showNotification({id:"layout-successfully-imported",message:"Layout successfully imported.<br /><br />Remember to save if you wish to keep the layout.",closeTimer:!1,closable:!0,success:!0}),closeBox("grid-wizard"),allowSaving(),!0},$("div#boxes").delegate("#grid-wizard-import-select-file","click",function(){$(this).siblings('input[type="file"]').trigger("click")}),$("div#boxes").delegate('#grid-wizard-import input[type="file"]',"change",function(e){if(e.target.files[0].name.split(".").slice(-1)[0]!="json")return $(this).val(null),alert("Invalid layout file. Please be sure that the layout is a valid JSON formatted file.");initiateLayoutImport($(this))}),$("div#boxes").delegate("#grid-wizard-export-download-file","click",function(){var e={action:"headway_visual_editor",security:Headway.security,method:"export_layout",layout:Headway.currentLayout},t=Headway.ajaxURL+"?"+$.param(e);return window.open(t)})},define("modules/grid/grid-wizard",function(){}),define("modules/grid/mode-grid",["jquery","modules/grid/grid","deps/itstylesheet","modules/grid/wrappers","modules/grid/wrapper-inputs","modules/grid/grid-wizard","deps/jquery.pep","helper.blocks","helper.wrappers"],function(e,t,n){var r={init:function(){bindGridWizard()},iframeCallback:function(){$i(".block").each(function(){updateBlockContentCover(e(this)),loadBlockContent({blockElement:e(this),blockOrigin:getBlockID(e(this))})}),gridStylesheet=new ITStylesheet({document:Headway.iframe.contents()[0],href:"/?headway-trigger=compiler&file=ve-iframe-grid-dynamic"},"find"),addEdgeInsertWrapperButtons(),addWrapperButtons($i("div.wrapper")),bindWrapperButtons(),setupWrapperSortables(),setupWrapperResizable(),setupWrapperContextMenu(),assignDefaultWrapperID(),$i(".grid-container").length===1&&!$i(".block").length&&$i(".grid-container").height(500),$i("div.wrapper").headwayGrid(),$i("div.wrapper-mirrored").headwayGrid("disable"),updateGridWidthInput("#sub-tab-grid-content"),setupBlockContextMenu(),bindBlockDimensionsTooltip()}};return updateGridCSS=function(e,t,n,r,s){var o=n*t+(t-1)*r,u=n*t/o,a=r*t/o,f=100/t*u,l=100/t*a,c=9,h=e+" ";gridStylesheet.update_rule(h+".grid-guides .grid-guide",{margin:"0 0 0 "+Math.round(l,c)+"%"});for(i=1;i<=t;i++)gridStylesheet.update_rule(h+".grid-width-"+i,{width:Math.round(f*i+(i-1)*l,c)+"%"}),gridStylesheet.update_rule(h+".grid-left-"+i,{left:"0 0 0 "+Math.round((f+l)*i,c)+"%"});gridStylesheet.update_rule(h+"div.grid-container",{width:o+1+"px"}),gridStylesheet.update_rule(e+".wrapper-fixed",{width:o+"px"}),typeof s!="undefined"&&s.length&&updateGridWidthInput(s)},r}),require.config({paths:{ko:"deps/knockout",underscore:"deps/underscore",jqueryUI:"deps/jquery.ui",qtip:"deps/jquery.qtip"},shim:{underscore:{exports:"_"}}}),require(["jquery","util.loader"],function(e){startTitleActivityIndicator(),Headway.blockTypeURLs=e.parseJSON(Headway.blockTypeURLs.replace(/"/g,'"')),Headway.allBlockTypes=e.parseJSON(Headway.allBlockTypes.replace(/"/g,'"')),Headway.ranTour=e.parseJSON(Headway.ranTour.replace(/"/g,'"')),Headway.designEditorProperties=e.parseJSON(Headway.designEditorProperties.replace(/"/g,'"')),require(["modules/layout-selector"],function(e){e.init()}),require(["modules/panel","modules/iframe"],function(e,t){e.init(),t.init()}),require(["modules/menu"],function(e){e.init()}),require(["modules/snapshots"],function(e){e.init()}),require(["util.tour"],function(e){Headway.ranTour[Headway.mode]==0&&Headway.ranTour.legacy==0&&e.start()}),require(["helper.data","helper.blocks","helper.wrappers","helper.context-menus","helper.notifications","helper.boxes","helper.history"],function(e,t,n,r,i,s,o){o.init()});switch(Headway.mode){case"grid":require(["modules/grid/mode-grid","modules/iframe"],function(e){Headway.instance=e,e.init(),waitForIframeLoad(e.iframeCallback)});break;case"design":require(["modules/design/mode-design","modules/iframe"],function(e){Headway.instance=e,e.init(),waitForIframeLoad(e.iframeCallback)})}e(document).ready(function(){e("body").addClass("show-ve")}),e(window).bind("load",function(){setTimeout(function(){e("div#ve-loading-overlay").remove()},1e3)})}),define("app",function(){});
\ No newline at end of file
--- /dev/null
+(function(){function e(e){var t=function(e,t){return i("",e,t)},s=n;e&&(n[e]||(n[e]={}),s=n[e]);if(!s.define||!s.define.packaged)r.original=s.define,s.define=r,s.define.packaged=!0;if(!s.require||!s.require.packaged)i.original=s.require,s.require=t,s.require.packaged=!0}var t="",n=function(){return this}();if(!t&&typeof requirejs!="undefined")return;var r=function(e,t,n){if(typeof e!="string"){r.original?r.original.apply(window,arguments):(console.error("dropping module because define wasn't a string."),console.trace());return}arguments.length==2&&(n=t),r.modules||(r.modules={},r.payloads={}),r.payloads[e]=n,r.modules[e]=null},i=function(e,t,n){if(Object.prototype.toString.call(t)==="[object Array]"){var r=[];for(var s=0,u=t.length;s<u;++s){var a=o(e,t[s]);if(!a&&i.original)return i.original.apply(window,arguments);r.push(a)}n&&n.apply(null,r)}else{if(typeof t=="string"){var f=o(e,t);return!f&&i.original?i.original.apply(window,arguments):(n&&n(),f)}if(i.original)return i.original.apply(window,arguments)}},s=function(e,t){if(t.indexOf("!")!==-1){var n=t.split("!");return s(e,n[0])+"!"+s(e,n[1])}if(t.charAt(0)=="."){var r=e.split("/").slice(0,-1).join("/");t=r+"/"+t;while(t.indexOf(".")!==-1&&i!=t){var i=t;t=t.replace(/\/\.\//,"/").replace(/[^\/]+\/\.\.\//,"")}}return t},o=function(e,t){t=s(e,t);var n=r.modules[t];if(!n){n=r.payloads[t];if(typeof n=="function"){var o={},u={id:t,uri:"",exports:o,packaged:!0},a=function(e,n){return i(t,e,n)},f=n(a,o,u);o=f||u.exports,r.modules[t]=o,delete r.payloads[t]}n=r.modules[t]=o||n}return n};e(t)})(),define("ace/ace",["require","exports","module","ace/lib/fixoldbrowsers","ace/lib/dom","ace/lib/event","ace/editor","ace/edit_session","ace/undomanager","ace/virtual_renderer","ace/multi_select","ace/worker/worker_client","ace/keyboard/hash_handler","ace/placeholder","ace/mode/folding/fold_mode","ace/theme/textmate","ace/ext/error_marker","ace/config"],function(e,t,n){e("./lib/fixoldbrowsers");var r=e("./lib/dom"),i=e("./lib/event"),s=e("./editor").Editor,o=e("./edit_session").EditSession,u=e("./undomanager").UndoManager,a=e("./virtual_renderer").VirtualRenderer,f=e("./multi_select").MultiSelect;e("./worker/worker_client"),e("./keyboard/hash_handler"),e("./placeholder"),e("./mode/folding/fold_mode"),e("./theme/textmate"),e("./ext/error_marker"),t.config=e("./config"),t.require=e,t.edit=function(e){if(typeof e=="string"){var n=e,e=document.getElementById(n);if(!e)throw new Error("ace.edit can't find div #"+n)}if(e.env&&e.env.editor instanceof s)return e.env.editor;var o=t.createEditSession(r.getInnerText(e));e.innerHTML="";var u=new s(new a(e));new f(u),u.setSession(o);var l={document:o,editor:u,onResize:u.resize.bind(u,null)};return i.addListener(window,"resize",l.onResize),u.on("destroy",function(){i.removeListener(window,"resize",l.onResize)}),e.env=u.env=l,u},t.createEditSession=function(e,t){var n=new o(e,t);return n.setUndoManager(new u),n},t.EditSession=o,t.UndoManager=u}),define("ace/mode/behaviour",["require","exports","module"],function(e,t,n){var r=function(){this.$behaviours={}};(function(){this.add=function(e,t,n){switch(undefined){case this.$behaviours:this.$behaviours={};case this.$behaviours[e]:this.$behaviours[e]={}}this.$behaviours[e][t]=n},this.addBehaviours=function(e){for(var t in e)for(var n in e[t])this.add(t,n,e[t][n])},this.remove=function(e){this.$behaviours&&this.$behaviours[e]&&delete this.$behaviours[e]},this.inherit=function(e,t){if(typeof e=="function")var n=(new e).getBehaviours(t);else var n=e.getBehaviours(t);this.addBehaviours(n)},this.getBehaviours=function(e){if(!e)return this.$behaviours;var t={};for(var n=0;n<e.length;n++)this.$behaviours[e[n]]&&(t[e[n]]=this.$behaviours[e[n]]);return t}}).call(r.prototype),t.Behaviour=r}),define("ace/unicode",["require","exports","module"],function(e,t,n){function r(e){var n=/\w{4}/g;for(var r in e)t.packages[r]=e[r].replace(n,"\\u$&")}t.packages={},r({L:"0041-005A0061-007A00AA00B500BA00C0-00D600D8-00F600F8-02C102C6-02D102E0-02E402EC02EE0370-037403760377037A-037D03860388-038A038C038E-03A103A3-03F503F7-0481048A-05250531-055605590561-058705D0-05EA05F0-05F20621-064A066E066F0671-06D306D506E506E606EE06EF06FA-06FC06FF07100712-072F074D-07A507B107CA-07EA07F407F507FA0800-0815081A082408280904-0939093D09500958-0961097109720979-097F0985-098C098F09900993-09A809AA-09B009B209B6-09B909BD09CE09DC09DD09DF-09E109F009F10A05-0A0A0A0F0A100A13-0A280A2A-0A300A320A330A350A360A380A390A59-0A5C0A5E0A72-0A740A85-0A8D0A8F-0A910A93-0AA80AAA-0AB00AB20AB30AB5-0AB90ABD0AD00AE00AE10B05-0B0C0B0F0B100B13-0B280B2A-0B300B320B330B35-0B390B3D0B5C0B5D0B5F-0B610B710B830B85-0B8A0B8E-0B900B92-0B950B990B9A0B9C0B9E0B9F0BA30BA40BA8-0BAA0BAE-0BB90BD00C05-0C0C0C0E-0C100C12-0C280C2A-0C330C35-0C390C3D0C580C590C600C610C85-0C8C0C8E-0C900C92-0CA80CAA-0CB30CB5-0CB90CBD0CDE0CE00CE10D05-0D0C0D0E-0D100D12-0D280D2A-0D390D3D0D600D610D7A-0D7F0D85-0D960D9A-0DB10DB3-0DBB0DBD0DC0-0DC60E01-0E300E320E330E40-0E460E810E820E840E870E880E8A0E8D0E94-0E970E99-0E9F0EA1-0EA30EA50EA70EAA0EAB0EAD-0EB00EB20EB30EBD0EC0-0EC40EC60EDC0EDD0F000F40-0F470F49-0F6C0F88-0F8B1000-102A103F1050-1055105A-105D106110651066106E-10701075-1081108E10A0-10C510D0-10FA10FC1100-1248124A-124D1250-12561258125A-125D1260-1288128A-128D1290-12B012B2-12B512B8-12BE12C012C2-12C512C8-12D612D8-13101312-13151318-135A1380-138F13A0-13F41401-166C166F-167F1681-169A16A0-16EA1700-170C170E-17111720-17311740-17511760-176C176E-17701780-17B317D717DC1820-18771880-18A818AA18B0-18F51900-191C1950-196D1970-19741980-19AB19C1-19C71A00-1A161A20-1A541AA71B05-1B331B45-1B4B1B83-1BA01BAE1BAF1C00-1C231C4D-1C4F1C5A-1C7D1CE9-1CEC1CEE-1CF11D00-1DBF1E00-1F151F18-1F1D1F20-1F451F48-1F4D1F50-1F571F591F5B1F5D1F5F-1F7D1F80-1FB41FB6-1FBC1FBE1FC2-1FC41FC6-1FCC1FD0-1FD31FD6-1FDB1FE0-1FEC1FF2-1FF41FF6-1FFC2071207F2090-209421022107210A-211321152119-211D212421262128212A-212D212F-2139213C-213F2145-2149214E218321842C00-2C2E2C30-2C5E2C60-2CE42CEB-2CEE2D00-2D252D30-2D652D6F2D80-2D962DA0-2DA62DA8-2DAE2DB0-2DB62DB8-2DBE2DC0-2DC62DC8-2DCE2DD0-2DD62DD8-2DDE2E2F300530063031-3035303B303C3041-3096309D-309F30A1-30FA30FC-30FF3105-312D3131-318E31A0-31B731F0-31FF3400-4DB54E00-9FCBA000-A48CA4D0-A4FDA500-A60CA610-A61FA62AA62BA640-A65FA662-A66EA67F-A697A6A0-A6E5A717-A71FA722-A788A78BA78CA7FB-A801A803-A805A807-A80AA80C-A822A840-A873A882-A8B3A8F2-A8F7A8FBA90A-A925A930-A946A960-A97CA984-A9B2A9CFAA00-AA28AA40-AA42AA44-AA4BAA60-AA76AA7AAA80-AAAFAAB1AAB5AAB6AAB9-AABDAAC0AAC2AADB-AADDABC0-ABE2AC00-D7A3D7B0-D7C6D7CB-D7FBF900-FA2DFA30-FA6DFA70-FAD9FB00-FB06FB13-FB17FB1DFB1F-FB28FB2A-FB36FB38-FB3CFB3EFB40FB41FB43FB44FB46-FBB1FBD3-FD3DFD50-FD8FFD92-FDC7FDF0-FDFBFE70-FE74FE76-FEFCFF21-FF3AFF41-FF5AFF66-FFBEFFC2-FFC7FFCA-FFCFFFD2-FFD7FFDA-FFDC",Ll:"0061-007A00AA00B500BA00DF-00F600F8-00FF01010103010501070109010B010D010F01110113011501170119011B011D011F01210123012501270129012B012D012F01310133013501370138013A013C013E014001420144014601480149014B014D014F01510153015501570159015B015D015F01610163016501670169016B016D016F0171017301750177017A017C017E-0180018301850188018C018D019201950199-019B019E01A101A301A501A801AA01AB01AD01B001B401B601B901BA01BD-01BF01C601C901CC01CE01D001D201D401D601D801DA01DC01DD01DF01E101E301E501E701E901EB01ED01EF01F001F301F501F901FB01FD01FF02010203020502070209020B020D020F02110213021502170219021B021D021F02210223022502270229022B022D022F02310233-0239023C023F0240024202470249024B024D024F-02930295-02AF037103730377037B-037D039003AC-03CE03D003D103D5-03D703D903DB03DD03DF03E103E303E503E703E903EB03ED03EF-03F303F503F803FB03FC0430-045F04610463046504670469046B046D046F04710473047504770479047B047D047F0481048B048D048F04910493049504970499049B049D049F04A104A304A504A704A904AB04AD04AF04B104B304B504B704B904BB04BD04BF04C204C404C604C804CA04CC04CE04CF04D104D304D504D704D904DB04DD04DF04E104E304E504E704E904EB04ED04EF04F104F304F504F704F904FB04FD04FF05010503050505070509050B050D050F05110513051505170519051B051D051F0521052305250561-05871D00-1D2B1D62-1D771D79-1D9A1E011E031E051E071E091E0B1E0D1E0F1E111E131E151E171E191E1B1E1D1E1F1E211E231E251E271E291E2B1E2D1E2F1E311E331E351E371E391E3B1E3D1E3F1E411E431E451E471E491E4B1E4D1E4F1E511E531E551E571E591E5B1E5D1E5F1E611E631E651E671E691E6B1E6D1E6F1E711E731E751E771E791E7B1E7D1E7F1E811E831E851E871E891E8B1E8D1E8F1E911E931E95-1E9D1E9F1EA11EA31EA51EA71EA91EAB1EAD1EAF1EB11EB31EB51EB71EB91EBB1EBD1EBF1EC11EC31EC51EC71EC91ECB1ECD1ECF1ED11ED31ED51ED71ED91EDB1EDD1EDF1EE11EE31EE51EE71EE91EEB1EED1EEF1EF11EF31EF51EF71EF91EFB1EFD1EFF-1F071F10-1F151F20-1F271F30-1F371F40-1F451F50-1F571F60-1F671F70-1F7D1F80-1F871F90-1F971FA0-1FA71FB0-1FB41FB61FB71FBE1FC2-1FC41FC61FC71FD0-1FD31FD61FD71FE0-1FE71FF2-1FF41FF61FF7210A210E210F2113212F21342139213C213D2146-2149214E21842C30-2C5E2C612C652C662C682C6A2C6C2C712C732C742C76-2C7C2C812C832C852C872C892C8B2C8D2C8F2C912C932C952C972C992C9B2C9D2C9F2CA12CA32CA52CA72CA92CAB2CAD2CAF2CB12CB32CB52CB72CB92CBB2CBD2CBF2CC12CC32CC52CC72CC92CCB2CCD2CCF2CD12CD32CD52CD72CD92CDB2CDD2CDF2CE12CE32CE42CEC2CEE2D00-2D25A641A643A645A647A649A64BA64DA64FA651A653A655A657A659A65BA65DA65FA663A665A667A669A66BA66DA681A683A685A687A689A68BA68DA68FA691A693A695A697A723A725A727A729A72BA72DA72F-A731A733A735A737A739A73BA73DA73FA741A743A745A747A749A74BA74DA74FA751A753A755A757A759A75BA75DA75FA761A763A765A767A769A76BA76DA76FA771-A778A77AA77CA77FA781A783A785A787A78CFB00-FB06FB13-FB17FF41-FF5A",Lu:"0041-005A00C0-00D600D8-00DE01000102010401060108010A010C010E01100112011401160118011A011C011E01200122012401260128012A012C012E01300132013401360139013B013D013F0141014301450147014A014C014E01500152015401560158015A015C015E01600162016401660168016A016C016E017001720174017601780179017B017D018101820184018601870189-018B018E-0191019301940196-0198019C019D019F01A001A201A401A601A701A901AC01AE01AF01B1-01B301B501B701B801BC01C401C701CA01CD01CF01D101D301D501D701D901DB01DE01E001E201E401E601E801EA01EC01EE01F101F401F6-01F801FA01FC01FE02000202020402060208020A020C020E02100212021402160218021A021C021E02200222022402260228022A022C022E02300232023A023B023D023E02410243-02460248024A024C024E03700372037603860388-038A038C038E038F0391-03A103A3-03AB03CF03D2-03D403D803DA03DC03DE03E003E203E403E603E803EA03EC03EE03F403F703F903FA03FD-042F04600462046404660468046A046C046E04700472047404760478047A047C047E0480048A048C048E04900492049404960498049A049C049E04A004A204A404A604A804AA04AC04AE04B004B204B404B604B804BA04BC04BE04C004C104C304C504C704C904CB04CD04D004D204D404D604D804DA04DC04DE04E004E204E404E604E804EA04EC04EE04F004F204F404F604F804FA04FC04FE05000502050405060508050A050C050E05100512051405160518051A051C051E0520052205240531-055610A0-10C51E001E021E041E061E081E0A1E0C1E0E1E101E121E141E161E181E1A1E1C1E1E1E201E221E241E261E281E2A1E2C1E2E1E301E321E341E361E381E3A1E3C1E3E1E401E421E441E461E481E4A1E4C1E4E1E501E521E541E561E581E5A1E5C1E5E1E601E621E641E661E681E6A1E6C1E6E1E701E721E741E761E781E7A1E7C1E7E1E801E821E841E861E881E8A1E8C1E8E1E901E921E941E9E1EA01EA21EA41EA61EA81EAA1EAC1EAE1EB01EB21EB41EB61EB81EBA1EBC1EBE1EC01EC21EC41EC61EC81ECA1ECC1ECE1ED01ED21ED41ED61ED81EDA1EDC1EDE1EE01EE21EE41EE61EE81EEA1EEC1EEE1EF01EF21EF41EF61EF81EFA1EFC1EFE1F08-1F0F1F18-1F1D1F28-1F2F1F38-1F3F1F48-1F4D1F591F5B1F5D1F5F1F68-1F6F1FB8-1FBB1FC8-1FCB1FD8-1FDB1FE8-1FEC1FF8-1FFB21022107210B-210D2110-211221152119-211D212421262128212A-212D2130-2133213E213F214521832C00-2C2E2C602C62-2C642C672C692C6B2C6D-2C702C722C752C7E-2C802C822C842C862C882C8A2C8C2C8E2C902C922C942C962C982C9A2C9C2C9E2CA02CA22CA42CA62CA82CAA2CAC2CAE2CB02CB22CB42CB62CB82CBA2CBC2CBE2CC02CC22CC42CC62CC82CCA2CCC2CCE2CD02CD22CD42CD62CD82CDA2CDC2CDE2CE02CE22CEB2CEDA640A642A644A646A648A64AA64CA64EA650A652A654A656A658A65AA65CA65EA662A664A666A668A66AA66CA680A682A684A686A688A68AA68CA68EA690A692A694A696A722A724A726A728A72AA72CA72EA732A734A736A738A73AA73CA73EA740A742A744A746A748A74AA74CA74EA750A752A754A756A758A75AA75CA75EA760A762A764A766A768A76AA76CA76EA779A77BA77DA77EA780A782A784A786A78BFF21-FF3A",Lt:"01C501C801CB01F21F88-1F8F1F98-1F9F1FA8-1FAF1FBC1FCC1FFC",Lm:"02B0-02C102C6-02D102E0-02E402EC02EE0374037A0559064006E506E607F407F507FA081A0824082809710E460EC610FC17D718431AA71C78-1C7D1D2C-1D611D781D9B-1DBF2071207F2090-20942C7D2D6F2E2F30053031-3035303B309D309E30FC-30FEA015A4F8-A4FDA60CA67FA717-A71FA770A788A9CFAA70AADDFF70FF9EFF9F",Lo:"01BB01C0-01C3029405D0-05EA05F0-05F20621-063F0641-064A066E066F0671-06D306D506EE06EF06FA-06FC06FF07100712-072F074D-07A507B107CA-07EA0800-08150904-0939093D09500958-096109720979-097F0985-098C098F09900993-09A809AA-09B009B209B6-09B909BD09CE09DC09DD09DF-09E109F009F10A05-0A0A0A0F0A100A13-0A280A2A-0A300A320A330A350A360A380A390A59-0A5C0A5E0A72-0A740A85-0A8D0A8F-0A910A93-0AA80AAA-0AB00AB20AB30AB5-0AB90ABD0AD00AE00AE10B05-0B0C0B0F0B100B13-0B280B2A-0B300B320B330B35-0B390B3D0B5C0B5D0B5F-0B610B710B830B85-0B8A0B8E-0B900B92-0B950B990B9A0B9C0B9E0B9F0BA30BA40BA8-0BAA0BAE-0BB90BD00C05-0C0C0C0E-0C100C12-0C280C2A-0C330C35-0C390C3D0C580C590C600C610C85-0C8C0C8E-0C900C92-0CA80CAA-0CB30CB5-0CB90CBD0CDE0CE00CE10D05-0D0C0D0E-0D100D12-0D280D2A-0D390D3D0D600D610D7A-0D7F0D85-0D960D9A-0DB10DB3-0DBB0DBD0DC0-0DC60E01-0E300E320E330E40-0E450E810E820E840E870E880E8A0E8D0E94-0E970E99-0E9F0EA1-0EA30EA50EA70EAA0EAB0EAD-0EB00EB20EB30EBD0EC0-0EC40EDC0EDD0F000F40-0F470F49-0F6C0F88-0F8B1000-102A103F1050-1055105A-105D106110651066106E-10701075-1081108E10D0-10FA1100-1248124A-124D1250-12561258125A-125D1260-1288128A-128D1290-12B012B2-12B512B8-12BE12C012C2-12C512C8-12D612D8-13101312-13151318-135A1380-138F13A0-13F41401-166C166F-167F1681-169A16A0-16EA1700-170C170E-17111720-17311740-17511760-176C176E-17701780-17B317DC1820-18421844-18771880-18A818AA18B0-18F51900-191C1950-196D1970-19741980-19AB19C1-19C71A00-1A161A20-1A541B05-1B331B45-1B4B1B83-1BA01BAE1BAF1C00-1C231C4D-1C4F1C5A-1C771CE9-1CEC1CEE-1CF12135-21382D30-2D652D80-2D962DA0-2DA62DA8-2DAE2DB0-2DB62DB8-2DBE2DC0-2DC62DC8-2DCE2DD0-2DD62DD8-2DDE3006303C3041-3096309F30A1-30FA30FF3105-312D3131-318E31A0-31B731F0-31FF3400-4DB54E00-9FCBA000-A014A016-A48CA4D0-A4F7A500-A60BA610-A61FA62AA62BA66EA6A0-A6E5A7FB-A801A803-A805A807-A80AA80C-A822A840-A873A882-A8B3A8F2-A8F7A8FBA90A-A925A930-A946A960-A97CA984-A9B2AA00-AA28AA40-AA42AA44-AA4BAA60-AA6FAA71-AA76AA7AAA80-AAAFAAB1AAB5AAB6AAB9-AABDAAC0AAC2AADBAADCABC0-ABE2AC00-D7A3D7B0-D7C6D7CB-D7FBF900-FA2DFA30-FA6DFA70-FAD9FB1DFB1F-FB28FB2A-FB36FB38-FB3CFB3EFB40FB41FB43FB44FB46-FBB1FBD3-FD3DFD50-FD8FFD92-FDC7FDF0-FDFBFE70-FE74FE76-FEFCFF66-FF6FFF71-FF9DFFA0-FFBEFFC2-FFC7FFCA-FFCFFFD2-FFD7FFDA-FFDC",M:"0300-036F0483-04890591-05BD05BF05C105C205C405C505C70610-061A064B-065E067006D6-06DC06DE-06E406E706E806EA-06ED07110730-074A07A6-07B007EB-07F30816-0819081B-08230825-08270829-082D0900-0903093C093E-094E0951-0955096209630981-098309BC09BE-09C409C709C809CB-09CD09D709E209E30A01-0A030A3C0A3E-0A420A470A480A4B-0A4D0A510A700A710A750A81-0A830ABC0ABE-0AC50AC7-0AC90ACB-0ACD0AE20AE30B01-0B030B3C0B3E-0B440B470B480B4B-0B4D0B560B570B620B630B820BBE-0BC20BC6-0BC80BCA-0BCD0BD70C01-0C030C3E-0C440C46-0C480C4A-0C4D0C550C560C620C630C820C830CBC0CBE-0CC40CC6-0CC80CCA-0CCD0CD50CD60CE20CE30D020D030D3E-0D440D46-0D480D4A-0D4D0D570D620D630D820D830DCA0DCF-0DD40DD60DD8-0DDF0DF20DF30E310E34-0E3A0E47-0E4E0EB10EB4-0EB90EBB0EBC0EC8-0ECD0F180F190F350F370F390F3E0F3F0F71-0F840F860F870F90-0F970F99-0FBC0FC6102B-103E1056-1059105E-10601062-10641067-106D1071-10741082-108D108F109A-109D135F1712-17141732-1734175217531772177317B6-17D317DD180B-180D18A91920-192B1930-193B19B0-19C019C819C91A17-1A1B1A55-1A5E1A60-1A7C1A7F1B00-1B041B34-1B441B6B-1B731B80-1B821BA1-1BAA1C24-1C371CD0-1CD21CD4-1CE81CED1CF21DC0-1DE61DFD-1DFF20D0-20F02CEF-2CF12DE0-2DFF302A-302F3099309AA66F-A672A67CA67DA6F0A6F1A802A806A80BA823-A827A880A881A8B4-A8C4A8E0-A8F1A926-A92DA947-A953A980-A983A9B3-A9C0AA29-AA36AA43AA4CAA4DAA7BAAB0AAB2-AAB4AAB7AAB8AABEAABFAAC1ABE3-ABEAABECABEDFB1EFE00-FE0FFE20-FE26",Mn:"0300-036F0483-04870591-05BD05BF05C105C205C405C505C70610-061A064B-065E067006D6-06DC06DF-06E406E706E806EA-06ED07110730-074A07A6-07B007EB-07F30816-0819081B-08230825-08270829-082D0900-0902093C0941-0948094D0951-095509620963098109BC09C1-09C409CD09E209E30A010A020A3C0A410A420A470A480A4B-0A4D0A510A700A710A750A810A820ABC0AC1-0AC50AC70AC80ACD0AE20AE30B010B3C0B3F0B41-0B440B4D0B560B620B630B820BC00BCD0C3E-0C400C46-0C480C4A-0C4D0C550C560C620C630CBC0CBF0CC60CCC0CCD0CE20CE30D41-0D440D4D0D620D630DCA0DD2-0DD40DD60E310E34-0E3A0E47-0E4E0EB10EB4-0EB90EBB0EBC0EC8-0ECD0F180F190F350F370F390F71-0F7E0F80-0F840F860F870F90-0F970F99-0FBC0FC6102D-10301032-10371039103A103D103E10581059105E-10601071-1074108210851086108D109D135F1712-17141732-1734175217531772177317B7-17BD17C617C9-17D317DD180B-180D18A91920-19221927192819321939-193B1A171A181A561A58-1A5E1A601A621A65-1A6C1A73-1A7C1A7F1B00-1B031B341B36-1B3A1B3C1B421B6B-1B731B801B811BA2-1BA51BA81BA91C2C-1C331C361C371CD0-1CD21CD4-1CE01CE2-1CE81CED1DC0-1DE61DFD-1DFF20D0-20DC20E120E5-20F02CEF-2CF12DE0-2DFF302A-302F3099309AA66FA67CA67DA6F0A6F1A802A806A80BA825A826A8C4A8E0-A8F1A926-A92DA947-A951A980-A982A9B3A9B6-A9B9A9BCAA29-AA2EAA31AA32AA35AA36AA43AA4CAAB0AAB2-AAB4AAB7AAB8AABEAABFAAC1ABE5ABE8ABEDFB1EFE00-FE0FFE20-FE26",Mc:"0903093E-09400949-094C094E0982098309BE-09C009C709C809CB09CC09D70A030A3E-0A400A830ABE-0AC00AC90ACB0ACC0B020B030B3E0B400B470B480B4B0B4C0B570BBE0BBF0BC10BC20BC6-0BC80BCA-0BCC0BD70C01-0C030C41-0C440C820C830CBE0CC0-0CC40CC70CC80CCA0CCB0CD50CD60D020D030D3E-0D400D46-0D480D4A-0D4C0D570D820D830DCF-0DD10DD8-0DDF0DF20DF30F3E0F3F0F7F102B102C10311038103B103C105610571062-10641067-106D108310841087-108C108F109A-109C17B617BE-17C517C717C81923-19261929-192B193019311933-193819B0-19C019C819C91A19-1A1B1A551A571A611A631A641A6D-1A721B041B351B3B1B3D-1B411B431B441B821BA11BA61BA71BAA1C24-1C2B1C341C351CE11CF2A823A824A827A880A881A8B4-A8C3A952A953A983A9B4A9B5A9BAA9BBA9BD-A9C0AA2FAA30AA33AA34AA4DAA7BABE3ABE4ABE6ABE7ABE9ABEAABEC",Me:"0488048906DE20DD-20E020E2-20E4A670-A672",N:"0030-003900B200B300B900BC-00BE0660-066906F0-06F907C0-07C90966-096F09E6-09EF09F4-09F90A66-0A6F0AE6-0AEF0B66-0B6F0BE6-0BF20C66-0C6F0C78-0C7E0CE6-0CEF0D66-0D750E50-0E590ED0-0ED90F20-0F331040-10491090-10991369-137C16EE-16F017E0-17E917F0-17F91810-18191946-194F19D0-19DA1A80-1A891A90-1A991B50-1B591BB0-1BB91C40-1C491C50-1C5920702074-20792080-20892150-21822185-21892460-249B24EA-24FF2776-27932CFD30073021-30293038-303A3192-31953220-32293251-325F3280-328932B1-32BFA620-A629A6E6-A6EFA830-A835A8D0-A8D9A900-A909A9D0-A9D9AA50-AA59ABF0-ABF9FF10-FF19",Nd:"0030-00390660-066906F0-06F907C0-07C90966-096F09E6-09EF0A66-0A6F0AE6-0AEF0B66-0B6F0BE6-0BEF0C66-0C6F0CE6-0CEF0D66-0D6F0E50-0E590ED0-0ED90F20-0F291040-10491090-109917E0-17E91810-18191946-194F19D0-19DA1A80-1A891A90-1A991B50-1B591BB0-1BB91C40-1C491C50-1C59A620-A629A8D0-A8D9A900-A909A9D0-A9D9AA50-AA59ABF0-ABF9FF10-FF19",Nl:"16EE-16F02160-21822185-218830073021-30293038-303AA6E6-A6EF",No:"00B200B300B900BC-00BE09F4-09F90BF0-0BF20C78-0C7E0D70-0D750F2A-0F331369-137C17F0-17F920702074-20792080-20892150-215F21892460-249B24EA-24FF2776-27932CFD3192-31953220-32293251-325F3280-328932B1-32BFA830-A835",P:"0021-00230025-002A002C-002F003A003B003F0040005B-005D005F007B007D00A100AB00B700BB00BF037E0387055A-055F0589058A05BE05C005C305C605F305F40609060A060C060D061B061E061F066A-066D06D40700-070D07F7-07F90830-083E0964096509700DF40E4F0E5A0E5B0F04-0F120F3A-0F3D0F850FD0-0FD4104A-104F10FB1361-13681400166D166E169B169C16EB-16ED1735173617D4-17D617D8-17DA1800-180A1944194519DE19DF1A1E1A1F1AA0-1AA61AA8-1AAD1B5A-1B601C3B-1C3F1C7E1C7F1CD32010-20272030-20432045-20512053-205E207D207E208D208E2329232A2768-277527C527C627E6-27EF2983-299829D8-29DB29FC29FD2CF9-2CFC2CFE2CFF2E00-2E2E2E302E313001-30033008-30113014-301F3030303D30A030FBA4FEA4FFA60D-A60FA673A67EA6F2-A6F7A874-A877A8CEA8CFA8F8-A8FAA92EA92FA95FA9C1-A9CDA9DEA9DFAA5C-AA5FAADEAADFABEBFD3EFD3FFE10-FE19FE30-FE52FE54-FE61FE63FE68FE6AFE6BFF01-FF03FF05-FF0AFF0C-FF0FFF1AFF1BFF1FFF20FF3B-FF3DFF3FFF5BFF5DFF5F-FF65",Pd:"002D058A05BE140018062010-20152E172E1A301C303030A0FE31FE32FE58FE63FF0D",Ps:"0028005B007B0F3A0F3C169B201A201E2045207D208D23292768276A276C276E27702772277427C527E627E827EA27EC27EE2983298529872989298B298D298F299129932995299729D829DA29FC2E222E242E262E283008300A300C300E3010301430163018301A301DFD3EFE17FE35FE37FE39FE3BFE3DFE3FFE41FE43FE47FE59FE5BFE5DFF08FF3BFF5BFF5FFF62",Pe:"0029005D007D0F3B0F3D169C2046207E208E232A2769276B276D276F27712773277527C627E727E927EB27ED27EF298429862988298A298C298E2990299229942996299829D929DB29FD2E232E252E272E293009300B300D300F3011301530173019301B301E301FFD3FFE18FE36FE38FE3AFE3CFE3EFE40FE42FE44FE48FE5AFE5CFE5EFF09FF3DFF5DFF60FF63",Pi:"00AB2018201B201C201F20392E022E042E092E0C2E1C2E20",Pf:"00BB2019201D203A2E032E052E0A2E0D2E1D2E21",Pc:"005F203F20402054FE33FE34FE4D-FE4FFF3F",Po:"0021-00230025-0027002A002C002E002F003A003B003F0040005C00A100B700BF037E0387055A-055F058905C005C305C605F305F40609060A060C060D061B061E061F066A-066D06D40700-070D07F7-07F90830-083E0964096509700DF40E4F0E5A0E5B0F04-0F120F850FD0-0FD4104A-104F10FB1361-1368166D166E16EB-16ED1735173617D4-17D617D8-17DA1800-18051807-180A1944194519DE19DF1A1E1A1F1AA0-1AA61AA8-1AAD1B5A-1B601C3B-1C3F1C7E1C7F1CD3201620172020-20272030-2038203B-203E2041-20432047-205120532055-205E2CF9-2CFC2CFE2CFF2E002E012E06-2E082E0B2E0E-2E162E182E192E1B2E1E2E1F2E2A-2E2E2E302E313001-3003303D30FBA4FEA4FFA60D-A60FA673A67EA6F2-A6F7A874-A877A8CEA8CFA8F8-A8FAA92EA92FA95FA9C1-A9CDA9DEA9DFAA5C-AA5FAADEAADFABEBFE10-FE16FE19FE30FE45FE46FE49-FE4CFE50-FE52FE54-FE57FE5F-FE61FE68FE6AFE6BFF01-FF03FF05-FF07FF0AFF0CFF0EFF0FFF1AFF1BFF1FFF20FF3CFF61FF64FF65",S:"0024002B003C-003E005E0060007C007E00A2-00A900AC00AE-00B100B400B600B800D700F702C2-02C502D2-02DF02E5-02EB02ED02EF-02FF03750384038503F604820606-0608060B060E060F06E906FD06FE07F609F209F309FA09FB0AF10B700BF3-0BFA0C7F0CF10CF20D790E3F0F01-0F030F13-0F170F1A-0F1F0F340F360F380FBE-0FC50FC7-0FCC0FCE0FCF0FD5-0FD8109E109F13601390-139917DB194019E0-19FF1B61-1B6A1B74-1B7C1FBD1FBF-1FC11FCD-1FCF1FDD-1FDF1FED-1FEF1FFD1FFE20442052207A-207C208A-208C20A0-20B8210021012103-21062108210921142116-2118211E-2123212521272129212E213A213B2140-2144214A-214D214F2190-2328232B-23E82400-24262440-244A249C-24E92500-26CD26CF-26E126E326E8-26FF2701-27042706-2709270C-27272729-274B274D274F-27522756-275E2761-276727942798-27AF27B1-27BE27C0-27C427C7-27CA27CC27D0-27E527F0-29822999-29D729DC-29FB29FE-2B4C2B50-2B592CE5-2CEA2E80-2E992E9B-2EF32F00-2FD52FF0-2FFB300430123013302030363037303E303F309B309C319031913196-319F31C0-31E33200-321E322A-32503260-327F328A-32B032C0-32FE3300-33FF4DC0-4DFFA490-A4C6A700-A716A720A721A789A78AA828-A82BA836-A839AA77-AA79FB29FDFCFDFDFE62FE64-FE66FE69FF04FF0BFF1C-FF1EFF3EFF40FF5CFF5EFFE0-FFE6FFE8-FFEEFFFCFFFD",Sm:"002B003C-003E007C007E00AC00B100D700F703F60606-060820442052207A-207C208A-208C2140-2144214B2190-2194219A219B21A021A321A621AE21CE21CF21D221D421F4-22FF2308-230B23202321237C239B-23B323DC-23E125B725C125F8-25FF266F27C0-27C427C7-27CA27CC27D0-27E527F0-27FF2900-29822999-29D729DC-29FB29FE-2AFF2B30-2B442B47-2B4CFB29FE62FE64-FE66FF0BFF1C-FF1EFF5CFF5EFFE2FFE9-FFEC",Sc:"002400A2-00A5060B09F209F309FB0AF10BF90E3F17DB20A0-20B8A838FDFCFE69FF04FFE0FFE1FFE5FFE6",Sk:"005E006000A800AF00B400B802C2-02C502D2-02DF02E5-02EB02ED02EF-02FF0375038403851FBD1FBF-1FC11FCD-1FCF1FDD-1FDF1FED-1FEF1FFD1FFE309B309CA700-A716A720A721A789A78AFF3EFF40FFE3",So:"00A600A700A900AE00B000B60482060E060F06E906FD06FE07F609FA0B700BF3-0BF80BFA0C7F0CF10CF20D790F01-0F030F13-0F170F1A-0F1F0F340F360F380FBE-0FC50FC7-0FCC0FCE0FCF0FD5-0FD8109E109F13601390-1399194019E0-19FF1B61-1B6A1B74-1B7C210021012103-21062108210921142116-2118211E-2123212521272129212E213A213B214A214C214D214F2195-2199219C-219F21A121A221A421A521A7-21AD21AF-21CD21D021D121D321D5-21F32300-2307230C-231F2322-2328232B-237B237D-239A23B4-23DB23E2-23E82400-24262440-244A249C-24E92500-25B625B8-25C025C2-25F72600-266E2670-26CD26CF-26E126E326E8-26FF2701-27042706-2709270C-27272729-274B274D274F-27522756-275E2761-276727942798-27AF27B1-27BE2800-28FF2B00-2B2F2B452B462B50-2B592CE5-2CEA2E80-2E992E9B-2EF32F00-2FD52FF0-2FFB300430123013302030363037303E303F319031913196-319F31C0-31E33200-321E322A-32503260-327F328A-32B032C0-32FE3300-33FF4DC0-4DFFA490-A4C6A828-A82BA836A837A839AA77-AA79FDFDFFE4FFE8FFEDFFEEFFFCFFFD",Z:"002000A01680180E2000-200A20282029202F205F3000",Zs:"002000A01680180E2000-200A202F205F3000",Zl:"2028",Zp:"2029",C:"0000-001F007F-009F00AD03780379037F-0383038B038D03A20526-05300557055805600588058B-059005C8-05CF05EB-05EF05F5-0605061C061D0620065F06DD070E070F074B074C07B2-07BF07FB-07FF082E082F083F-08FF093A093B094F095609570973-097809800984098D098E0991099209A909B109B3-09B509BA09BB09C509C609C909CA09CF-09D609D8-09DB09DE09E409E509FC-0A000A040A0B-0A0E0A110A120A290A310A340A370A3A0A3B0A3D0A43-0A460A490A4A0A4E-0A500A52-0A580A5D0A5F-0A650A76-0A800A840A8E0A920AA90AB10AB40ABA0ABB0AC60ACA0ACE0ACF0AD1-0ADF0AE40AE50AF00AF2-0B000B040B0D0B0E0B110B120B290B310B340B3A0B3B0B450B460B490B4A0B4E-0B550B58-0B5B0B5E0B640B650B72-0B810B840B8B-0B8D0B910B96-0B980B9B0B9D0BA0-0BA20BA5-0BA70BAB-0BAD0BBA-0BBD0BC3-0BC50BC90BCE0BCF0BD1-0BD60BD8-0BE50BFB-0C000C040C0D0C110C290C340C3A-0C3C0C450C490C4E-0C540C570C5A-0C5F0C640C650C70-0C770C800C810C840C8D0C910CA90CB40CBA0CBB0CC50CC90CCE-0CD40CD7-0CDD0CDF0CE40CE50CF00CF3-0D010D040D0D0D110D290D3A-0D3C0D450D490D4E-0D560D58-0D5F0D640D650D76-0D780D800D810D840D97-0D990DB20DBC0DBE0DBF0DC7-0DC90DCB-0DCE0DD50DD70DE0-0DF10DF5-0E000E3B-0E3E0E5C-0E800E830E850E860E890E8B0E8C0E8E-0E930E980EA00EA40EA60EA80EA90EAC0EBA0EBE0EBF0EC50EC70ECE0ECF0EDA0EDB0EDE-0EFF0F480F6D-0F700F8C-0F8F0F980FBD0FCD0FD9-0FFF10C6-10CF10FD-10FF1249124E124F12571259125E125F1289128E128F12B112B612B712BF12C112C612C712D7131113161317135B-135E137D-137F139A-139F13F5-13FF169D-169F16F1-16FF170D1715-171F1737-173F1754-175F176D17711774-177F17B417B517DE17DF17EA-17EF17FA-17FF180F181A-181F1878-187F18AB-18AF18F6-18FF191D-191F192C-192F193C-193F1941-1943196E196F1975-197F19AC-19AF19CA-19CF19DB-19DD1A1C1A1D1A5F1A7D1A7E1A8A-1A8F1A9A-1A9F1AAE-1AFF1B4C-1B4F1B7D-1B7F1BAB-1BAD1BBA-1BFF1C38-1C3A1C4A-1C4C1C80-1CCF1CF3-1CFF1DE7-1DFC1F161F171F1E1F1F1F461F471F4E1F4F1F581F5A1F5C1F5E1F7E1F7F1FB51FC51FD41FD51FDC1FF01FF11FF51FFF200B-200F202A-202E2060-206F20722073208F2095-209F20B9-20CF20F1-20FF218A-218F23E9-23FF2427-243F244B-245F26CE26E226E4-26E727002705270A270B2728274C274E2753-2755275F27602795-279727B027BF27CB27CD-27CF2B4D-2B4F2B5A-2BFF2C2F2C5F2CF2-2CF82D26-2D2F2D66-2D6E2D70-2D7F2D97-2D9F2DA72DAF2DB72DBF2DC72DCF2DD72DDF2E32-2E7F2E9A2EF4-2EFF2FD6-2FEF2FFC-2FFF3040309730983100-3104312E-3130318F31B8-31BF31E4-31EF321F32FF4DB6-4DBF9FCC-9FFFA48D-A48FA4C7-A4CFA62C-A63FA660A661A674-A67BA698-A69FA6F8-A6FFA78D-A7FAA82C-A82FA83A-A83FA878-A87FA8C5-A8CDA8DA-A8DFA8FC-A8FFA954-A95EA97D-A97FA9CEA9DA-A9DDA9E0-A9FFAA37-AA3FAA4EAA4FAA5AAA5BAA7C-AA7FAAC3-AADAAAE0-ABBFABEEABEFABFA-ABFFD7A4-D7AFD7C7-D7CAD7FC-F8FFFA2EFA2FFA6EFA6FFADA-FAFFFB07-FB12FB18-FB1CFB37FB3DFB3FFB42FB45FBB2-FBD2FD40-FD4FFD90FD91FDC8-FDEFFDFEFDFFFE1A-FE1FFE27-FE2FFE53FE67FE6C-FE6FFE75FEFD-FF00FFBF-FFC1FFC8FFC9FFD0FFD1FFD8FFD9FFDD-FFDFFFE7FFEF-FFFBFFFEFFFF",Cc:"0000-001F007F-009F",Cf:"00AD0600-060306DD070F17B417B5200B-200F202A-202E2060-2064206A-206FFEFFFFF9-FFFB",Co:"E000-F8FF",Cs:"D800-DFFF",Cn:"03780379037F-0383038B038D03A20526-05300557055805600588058B-059005C8-05CF05EB-05EF05F5-05FF06040605061C061D0620065F070E074B074C07B2-07BF07FB-07FF082E082F083F-08FF093A093B094F095609570973-097809800984098D098E0991099209A909B109B3-09B509BA09BB09C509C609C909CA09CF-09D609D8-09DB09DE09E409E509FC-0A000A040A0B-0A0E0A110A120A290A310A340A370A3A0A3B0A3D0A43-0A460A490A4A0A4E-0A500A52-0A580A5D0A5F-0A650A76-0A800A840A8E0A920AA90AB10AB40ABA0ABB0AC60ACA0ACE0ACF0AD1-0ADF0AE40AE50AF00AF2-0B000B040B0D0B0E0B110B120B290B310B340B3A0B3B0B450B460B490B4A0B4E-0B550B58-0B5B0B5E0B640B650B72-0B810B840B8B-0B8D0B910B96-0B980B9B0B9D0BA0-0BA20BA5-0BA70BAB-0BAD0BBA-0BBD0BC3-0BC50BC90BCE0BCF0BD1-0BD60BD8-0BE50BFB-0C000C040C0D0C110C290C340C3A-0C3C0C450C490C4E-0C540C570C5A-0C5F0C640C650C70-0C770C800C810C840C8D0C910CA90CB40CBA0CBB0CC50CC90CCE-0CD40CD7-0CDD0CDF0CE40CE50CF00CF3-0D010D040D0D0D110D290D3A-0D3C0D450D490D4E-0D560D58-0D5F0D640D650D76-0D780D800D810D840D97-0D990DB20DBC0DBE0DBF0DC7-0DC90DCB-0DCE0DD50DD70DE0-0DF10DF5-0E000E3B-0E3E0E5C-0E800E830E850E860E890E8B0E8C0E8E-0E930E980EA00EA40EA60EA80EA90EAC0EBA0EBE0EBF0EC50EC70ECE0ECF0EDA0EDB0EDE-0EFF0F480F6D-0F700F8C-0F8F0F980FBD0FCD0FD9-0FFF10C6-10CF10FD-10FF1249124E124F12571259125E125F1289128E128F12B112B612B712BF12C112C612C712D7131113161317135B-135E137D-137F139A-139F13F5-13FF169D-169F16F1-16FF170D1715-171F1737-173F1754-175F176D17711774-177F17DE17DF17EA-17EF17FA-17FF180F181A-181F1878-187F18AB-18AF18F6-18FF191D-191F192C-192F193C-193F1941-1943196E196F1975-197F19AC-19AF19CA-19CF19DB-19DD1A1C1A1D1A5F1A7D1A7E1A8A-1A8F1A9A-1A9F1AAE-1AFF1B4C-1B4F1B7D-1B7F1BAB-1BAD1BBA-1BFF1C38-1C3A1C4A-1C4C1C80-1CCF1CF3-1CFF1DE7-1DFC1F161F171F1E1F1F1F461F471F4E1F4F1F581F5A1F5C1F5E1F7E1F7F1FB51FC51FD41FD51FDC1FF01FF11FF51FFF2065-206920722073208F2095-209F20B9-20CF20F1-20FF218A-218F23E9-23FF2427-243F244B-245F26CE26E226E4-26E727002705270A270B2728274C274E2753-2755275F27602795-279727B027BF27CB27CD-27CF2B4D-2B4F2B5A-2BFF2C2F2C5F2CF2-2CF82D26-2D2F2D66-2D6E2D70-2D7F2D97-2D9F2DA72DAF2DB72DBF2DC72DCF2DD72DDF2E32-2E7F2E9A2EF4-2EFF2FD6-2FEF2FFC-2FFF3040309730983100-3104312E-3130318F31B8-31BF31E4-31EF321F32FF4DB6-4DBF9FCC-9FFFA48D-A48FA4C7-A4CFA62C-A63FA660A661A674-A67BA698-A69FA6F8-A6FFA78D-A7FAA82C-A82FA83A-A83FA878-A87FA8C5-A8CDA8DA-A8DFA8FC-A8FFA954-A95EA97D-A97FA9CEA9DA-A9DDA9E0-A9FFAA37-AA3FAA4EAA4FAA5AAA5BAA7C-AA7FAAC3-AADAAAE0-ABBFABEEABEFABFA-ABFFD7A4-D7AFD7C7-D7CAD7FC-D7FFFA2EFA2FFA6EFA6FFADA-FAFFFB07-FB12FB18-FB1CFB37FB3DFB3FFB42FB45FBB2-FBD2FD40-FD4FFD90FD91FDC8-FDEFFDFEFDFFFE1A-FE1FFE27-FE2FFE53FE67FE6C-FE6FFE75FEFDFEFEFF00FFBF-FFC1FFC8FFC9FFD0FFD1FFD8FFD9FFDD-FFDFFFE7FFEF-FFF8FFFEFFFF"})}),define("ace/token_iterator",["require","exports","module"],function(e,t,n){var r=function(e,t,n){this.$session=e,this.$row=t,this.$rowTokens=e.getTokens(t);var r=e.getTokenAt(t,n);this.$tokenIndex=r?r.index:-1};(function(){this.stepBackward=function(){this.$tokenIndex-=1;while(this.$tokenIndex<0){this.$row-=1;if(this.$row<0)return this.$row=0,null;this.$rowTokens=this.$session.getTokens(this.$row),this.$tokenIndex=this.$rowTokens.length-1}return this.$rowTokens[this.$tokenIndex]},this.stepForward=function(){this.$tokenIndex+=1;var e;while(this.$tokenIndex>=this.$rowTokens.length){this.$row+=1,e||(e=this.$session.getLength());if(this.$row>=e)return this.$row=e-1,null;this.$rowTokens=this.$session.getTokens(this.$row),this.$tokenIndex=0}return this.$rowTokens[this.$tokenIndex]},this.getCurrentToken=function(){return this.$rowTokens[this.$tokenIndex]},this.getCurrentTokenRow=function(){return this.$row},this.getCurrentTokenColumn=function(){var e=this.$rowTokens,t=this.$tokenIndex,n=e[t].start;if(n!==undefined)return n;n=0;while(t>0)t-=1,n+=e[t].value.length;return n}}).call(r.prototype),t.TokenIterator=r}),define("ace/mode/text_highlight_rules",["require","exports","module","ace/lib/lang"],function(e,t,n){var r=e("../lib/lang"),i=function(){this.$rules={start:[{token:"empty_line",regex:"^$"},{defaultToken:"text"}]}};(function(){this.addRules=function(e,t){if(!t){for(var n in e)this.$rules[n]=e[n];return}for(var n in e){var r=e[n];for(var i=0;i<r.length;i++){var s=r[i];s.next&&(typeof s.next!="string"?s.nextState&&s.nextState.indexOf(t)!==0&&(s.nextState=t+s.nextState):s.next.indexOf(t)!==0&&(s.next=t+s.next))}this.$rules[t+n]=r}},this.getRules=function(){return this.$rules},this.embedRules=function(e,t,n,i,s){var o=typeof e=="function"?(new e).getRules():e;if(i)for(var u=0;u<i.length;u++)i[u]=t+i[u];else{i=[];for(var a in o)i.push(t+a)}this.addRules(o,t);if(n){var f=Array.prototype[s?"push":"unshift"];for(var u=0;u<i.length;u++)f.apply(this.$rules[i[u]],r.deepCopy(n))}this.$embeds||(this.$embeds=[]),this.$embeds.push(t)},this.getEmbeds=function(){return this.$embeds};var e=function(e,t){return(e!="start"||t.length)&&t.unshift(this.nextState,e),this.nextState},t=function(e,t){return t.shift(),t.shift()||"start"};this.normalizeRules=function(){function n(s){var o=i[s];o.processed=!0;for(var u=0;u<o.length;u++){var a=o[u];!a.regex&&a.start&&(a.regex=a.start,a.next||(a.next=[]),a.next.push({defaultToken:a.token},{token:a.token+".end",regex:a.end||a.start,next:"pop"}),a.token=a.token+".start",a.push=!0);var f=a.next||a.push;if(f&&Array.isArray(f)){var l=a.stateName;l||(l=a.token,typeof l!="string"&&(l=l[0]||""),i[l]&&(l+=r++)),i[l]=f,a.next=l,n(l)}else f=="pop"&&(a.next=t);a.push&&(a.nextState=a.next||a.push,a.next=e,delete a.push);if(a.rules)for(var c in a.rules)i[c]?i[c].push&&i[c].push.apply(i[c],a.rules[c]):i[c]=a.rules[c];if(a.include||typeof a=="string")var h=a.include||a,p=i[h];else Array.isArray(a)&&(p=a);if(p){var d=[u,1].concat(p);a.noEscape&&(d=d.filter(function(e){return!e.next})),o.splice.apply(o,d),u--,p=null}a.keywordMap&&(a.token=this.createKeywordMapper(a.keywordMap,a.defaultToken||"text",a.caseInsensitive),delete a.defaultToken)}}var r=0,i=this.$rules;Object.keys(i).forEach(n,this)},this.createKeywordMapper=function(e,t,n,r){var i=Object.create(null);return Object.keys(e).forEach(function(t){var s=e[t];n&&(s=s.toLowerCase());var o=s.split(r||"|");for(var u=o.length;u--;)i[o[u]]=t}),Object.getPrototypeOf(i)&&(i.__proto__=null),this.$keywordList=Object.keys(i),e=null,n?function(e){return i[e.toLowerCase()]||t}:function(e){return i[e]||t}},this.getKeywords=function(){return this.$keywords}}).call(i.prototype),t.TextHighlightRules=i}),define("ace/anchor",["require","exports","module","ace/lib/oop","ace/lib/event_emitter"],function(e,t,n){var r=e("./lib/oop"),i=e("./lib/event_emitter").EventEmitter,s=t.Anchor=function(e,t,n){this.$onChange=this.onChange.bind(this),this.attach(e),typeof n=="undefined"?this.setPosition(t.row,t.column):this.setPosition(t,n)};(function(){r.implement(this,i),this.getPosition=function(){return this.$clipPositionToDocument(this.row,this.column)},this.getDocument=function(){return this.document},this.$insertRight=!1,this.onChange=function(e){var t=e.data,n=t.range;if(n.start.row==n.end.row&&n.start.row!=this.row)return;if(n.start.row>this.row)return;if(n.start.row==this.row&&n.start.column>this.column)return;var r=this.row,i=this.column,s=n.start,o=n.end;if(t.action==="insertText")if(s.row===r&&s.column<=i){if(s.column!==i||!this.$insertRight)s.row===o.row?i+=o.column-s.column:(i-=s.column,r+=o.row-s.row)}else s.row!==o.row&&s.row<r&&(r+=o.row-s.row);else t.action==="insertLines"?s.row<=r&&(r+=o.row-s.row):t.action==="removeText"?s.row===r&&s.column<i?o.column>=i?i=s.column:i=Math.max(0,i-(o.column-s.column)):s.row!==o.row&&s.row<r?(o.row===r&&(i=Math.max(0,i-o.column)+s.column),r-=o.row-s.row):o.row===r&&(r-=o.row-s.row,i=Math.max(0,i-o.column)+s.column):t.action=="removeLines"&&s.row<=r&&(o.row<=r?r-=o.row-s.row:(r=s.row,i=0));this.setPosition(r,i,!0)},this.setPosition=function(e,t,n){var r;n?r={row:e,column:t}:r=this.$clipPositionToDocument(e,t);if(this.row==r.row&&this.column==r.column)return;var i={row:this.row,column:this.column};this.row=r.row,this.column=r.column,this._signal("change",{old:i,value:r})},this.detach=function(){this.document.removeEventListener("change",this.$onChange)},this.attach=function(e){this.document=e||this.document,this.document.on("change",this.$onChange)},this.$clipPositionToDocument=function(e,t){var n={};return e>=this.document.getLength()?(n.row=Math.max(0,this.document.getLength()-1),n.column=this.document.getLine(n.row).length):e<0?(n.row=0,n.column=0):(n.row=e,n.column=Math.min(this.document.getLine(n.row).length,Math.max(0,t))),t<0&&(n.column=0),n}}).call(s.prototype)}),define("ace/background_tokenizer",["require","exports","module","ace/lib/oop","ace/lib/event_emitter"],function(e,t,n){var r=e("./lib/oop"),i=e("./lib/event_emitter").EventEmitter,s=function(e,t){this.running=!1,this.lines=[],this.states=[],this.currentLine=0,this.tokenizer=e;var n=this;this.$worker=function(){if(!n.running)return;var e=new Date,t=n.currentLine,r=-1,i=n.doc;while(n.lines[t])t++;var s=t,o=i.getLength(),u=0;n.running=!1;while(t<o){n.$tokenizeRow(t),r=t;do t++;while(n.lines[t]);u++;if(u%5==0&&new Date-e>20){n.running=setTimeout(n.$worker,20),n.currentLine=t;return}}n.currentLine=t,s<=r&&n.fireUpdateEvent(s,r)}};(function(){r.implement(this,i),this.setTokenizer=function(e){this.tokenizer=e,this.lines=[],this.states=[],this.start(0)},this.setDocument=function(e){this.doc=e,this.lines=[],this.states=[],this.stop()},this.fireUpdateEvent=function(e,t){var n={first:e,last:t};this._signal("update",{data:n})},this.start=function(e){this.currentLine=Math.min(e||0,this.currentLine,this.doc.getLength()),this.lines.splice(this.currentLine,this.lines.length),this.states.splice(this.currentLine,this.states.length),this.stop(),this.running=setTimeout(this.$worker,700)},this.scheduleStart=function(){this.running||(this.running=setTimeout(this.$worker,700))},this.$updateOnChange=function(e){var t=e.range,n=t.start.row,r=t.end.row-n;if(r===0)this.lines[n]=null;else if(e.action=="removeText"||e.action=="removeLines")this.lines.splice(n,r+1,null),this.states.splice(n,r+1,null);else{var i=Array(r+1);i.unshift(n,1),this.lines.splice.apply(this.lines,i),this.states.splice.apply(this.states,i)}this.currentLine=Math.min(n,this.currentLine,this.doc.getLength()),this.stop()},this.stop=function(){this.running&&clearTimeout(this.running),this.running=!1},this.getTokens=function(e){return this.lines[e]||this.$tokenizeRow(e)},this.getState=function(e){return this.currentLine==e&&this.$tokenizeRow(e),this.states[e]||"start"},this.$tokenizeRow=function(e){var t=this.doc.getLine(e),n=this.states[e-1],r=this.tokenizer.getLineTokens(t,n,e);return this.states[e]+""!=r.state+""?(this.states[e]=r.state,this.lines[e+1]=null,this.currentLine>e+1&&(this.currentLine=e+1)):this.currentLine==e&&(this.currentLine=e+1),this.lines[e]=r.tokens}}).call(s.prototype),t.BackgroundTokenizer=s}),define("ace/search_highlight",["require","exports","module","ace/lib/lang","ace/lib/oop","ace/range"],function(e,t,n){var r=e("./lib/lang"),i=e("./lib/oop"),s=e("./range").Range,o=function(e,t,n){this.setRegexp(e),this.clazz=t,this.type=n||"text"};(function(){this.MAX_RANGES=500,this.setRegexp=function(e){if(this.regExp+""==e+"")return;this.regExp=e,this.cache=[]},this.update=function(e,t,n,i){if(!this.regExp)return;var o=i.firstRow,u=i.lastRow;for(var a=o;a<=u;a++){var f=this.cache[a];f==null&&(f=r.getMatchOffsets(n.getLine(a),this.regExp),f.length>this.MAX_RANGES&&(f=f.slice(0,this.MAX_RANGES)),f=f.map(function(e){return new s(a,e.offset,a,e.offset+e.length)}),this.cache[a]=f.length?f:"");for(var l=f.length;l--;)t.drawSingleLineMarker(e,f[l].toScreenRange(n),this.clazz,i)}}}).call(o.prototype),t.SearchHighlight=o}),define("ace/edit_session/folding",["require","exports","module","ace/range","ace/edit_session/fold_line","ace/edit_session/fold","ace/token_iterator"],function(e,t,n){function r(){this.getFoldAt=function(e,t,n){var r=this.getFoldLine(e);if(!r)return null;var i=r.folds;for(var s=0;s<i.length;s++){var o=i[s];if(o.range.contains(e,t)){if(n==1&&o.range.isEnd(e,t))continue;if(n==-1&&o.range.isStart(e,t))continue;return o}}},this.getFoldsInRange=function(e){var t=e.start,n=e.end,r=this.$foldData,i=[];t.column+=1,n.column-=1;for(var s=0;s<r.length;s++){var o=r[s].range.compareRange(e);if(o==2)continue;if(o==-2)break;var u=r[s].folds;for(var a=0;a<u.length;a++){var f=u[a];o=f.range.compareRange(e);if(o==-2)break;if(o==2)continue;if(o==42)break;i.push(f)}}return t.column-=1,n.column+=1,i},this.getFoldsInRangeList=function(e){if(Array.isArray(e)){var t=[];e.forEach(function(e){t=t.concat(this.getFoldsInRange(e))},this)}else var t=this.getFoldsInRange(e);return t},this.getAllFolds=function(){var e=[],t=this.$foldData;for(var n=0;n<t.length;n++)for(var r=0;r<t[n].folds.length;r++)e.push(t[n].folds[r]);return e},this.getFoldStringAt=function(e,t,n,r){r=r||this.getFoldLine(e);if(!r)return null;var i={end:{column:0}},s,o;for(var u=0;u<r.folds.length;u++){o=r.folds[u];var a=o.range.compareEnd(e,t);if(a==-1){s=this.getLine(o.start.row).substring(i.end.column,o.start.column);break}if(a===0)return null;i=o}return s||(s=this.getLine(o.start.row).substring(i.end.column)),n==-1?s.substring(0,t-i.end.column):n==1?s.substring(t-i.end.column):s},this.getFoldLine=function(e,t){var n=this.$foldData,r=0;t&&(r=n.indexOf(t)),r==-1&&(r=0);for(r;r<n.length;r++){var i=n[r];if(i.start.row<=e&&i.end.row>=e)return i;if(i.end.row>e)return null}return null},this.getNextFoldLine=function(e,t){var n=this.$foldData,r=0;t&&(r=n.indexOf(t)),r==-1&&(r=0);for(r;r<n.length;r++){var i=n[r];if(i.end.row>=e)return i}return null},this.getFoldedRowCount=function(e,t){var n=this.$foldData,r=t-e+1;for(var i=0;i<n.length;i++){var s=n[i],o=s.end.row,u=s.start.row;if(o>=t){u<t&&(u>=e?r-=t-u:r=0);break}o>=e&&(u>=e?r-=o-u:r-=o-e+1)}return r},this.$addFoldLine=function(e){return this.$foldData.push(e),this.$foldData.sort(function(e,t){return e.start.row-t.start.row}),e},this.addFold=function(e,t){var n=this.$foldData,r=!1,i;e instanceof o?i=e:(i=new o(t,e),i.collapseChildren=t.collapseChildren),this.$clipRangeToDocument(i.range);var u=i.start.row,a=i.start.column,f=i.end.row,l=i.end.column;if(u<f||u==f&&a<=l-2){var c=this.getFoldAt(u,a,1),h=this.getFoldAt(f,l,-1);if(c&&h==c)return c.addSubFold(i);if(c&&!c.range.isStart(u,a)||h&&!h.range.isEnd(f,l))throw new Error("A fold can't intersect already existing fold"+i.range+c.range);var p=this.getFoldsInRange(i.range);p.length>0&&(this.removeFolds(p),p.forEach(function(e){i.addSubFold(e)}));for(var d=0;d<n.length;d++){var v=n[d];if(f==v.start.row){v.addFold(i),r=!0;break}if(u==v.end.row){v.addFold(i),r=!0;if(!i.sameRow){var m=n[d+1];if(m&&m.start.row==f){v.merge(m);break}}break}if(f<=v.start.row)break}return r||(v=this.$addFoldLine(new s(this.$foldData,i))),this.$useWrapMode?this.$updateWrapData(v.start.row,v.start.row):this.$updateRowLengthCache(v.start.row,v.start.row),this.$modified=!0,this._emit("changeFold",{data:i,action:"add"}),i}throw new Error("The range has to be at least 2 characters width")},this.addFolds=function(e){e.forEach(function(e){this.addFold(e)},this)},this.removeFold=function(e){var t=e.foldLine,n=t.start.row,r=t.end.row,i=this.$foldData,s=t.folds;if(s.length==1)i.splice(i.indexOf(t),1);else if(t.range.isEnd(e.end.row,e.end.column))s.pop(),t.end.row=s[s.length-1].end.row,t.end.column=s[s.length-1].end.column;else if(t.range.isStart(e.start.row,e.start.column))s.shift(),t.start.row=s[0].start.row,t.start.column=s[0].start.column;else if(e.sameRow)s.splice(s.indexOf(e),1);else{var o=t.split(e.start.row,e.start.column);s=o.folds,s.shift(),o.start.row=s[0].start.row,o.start.column=s[0].start.column}this.$updating||(this.$useWrapMode?this.$updateWrapData(n,r):this.$updateRowLengthCache(n,r)),this.$modified=!0,this._emit("changeFold",{data:e,action:"remove"})},this.removeFolds=function(e){var t=[];for(var n=0;n<e.length;n++)t.push(e[n]);t.forEach(function(e){this.removeFold(e)},this),this.$modified=!0},this.expandFold=function(e){this.removeFold(e),e.subFolds.forEach(function(t){e.restoreRange(t),this.addFold(t)},this),e.collapseChildren>0&&this.foldAll(e.start.row+1,e.end.row,e.collapseChildren-1),e.subFolds=[]},this.expandFolds=function(e){e.forEach(function(e){this.expandFold(e)},this)},this.unfold=function(e,t){var n,r;e==null?(n=new i(0,0,this.getLength(),0),t=!0):typeof e=="number"?n=new i(e,0,e,this.getLine(e).length):"row"in e?n=i.fromPoints(e,e):n=e,r=this.getFoldsInRangeList(n);if(t)this.removeFolds(r);else{var s=r;while(s.length)this.expandFolds(s),s=this.getFoldsInRangeList(n)}if(r.length)return r},this.isRowFolded=function(e,t){return!!this.getFoldLine(e,t)},this.getRowFoldEnd=function(e,t){var n=this.getFoldLine(e,t);return n?n.end.row:e},this.getRowFoldStart=function(e,t){var n=this.getFoldLine(e,t);return n?n.start.row:e},this.getFoldDisplayLine=function(e,t,n,r,i){r==null&&(r=e.start.row,i=0),t==null&&(t=e.end.row,n=this.getLine(t).length);var s=this.doc,o="";return e.walk(function(e,t,n,u){if(t<r)return;if(t==r){if(n<i)return;u=Math.max(i,u)}e!=null?o+=e:o+=s.getLine(t).substring(u,n)},t,n),o},this.getDisplayLine=function(e,t,n,r){var i=this.getFoldLine(e);if(!i){var s;return s=this.doc.getLine(e),s.substring(r||0,t||s.length)}return this.getFoldDisplayLine(i,e,t,n,r)},this.$cloneFoldData=function(){var e=[];return e=this.$foldData.map(function(t){var n=t.folds.map(function(e){return e.clone()});return new s(e,n)}),e},this.toggleFold=function(e){var t=this.selection,n=t.getRange(),r,i;if(n.isEmpty()){var s=n.start;r=this.getFoldAt(s.row,s.column);if(r){this.expandFold(r);return}(i=this.findMatchingBracket(s))?n.comparePoint(i)==1?n.end=i:(n.start=i,n.start.column++,n.end.column--):(i=this.findMatchingBracket({row:s.row,column:s.column+1}))?(n.comparePoint(i)==1?n.end=i:n.start=i,n.start.column++):n=this.getCommentFoldRange(s.row,s.column)||n}else{var o=this.getFoldsInRange(n);if(e&&o.length){this.expandFolds(o);return}o.length==1&&(r=o[0])}r||(r=this.getFoldAt(n.start.row,n.start.column));if(r&&r.range.toString()==n.toString()){this.expandFold(r);return}var u="...";if(!n.isMultiLine()){u=this.getTextRange(n);if(u.length<4)return;u=u.trim().substring(0,2)+".."}this.addFold(u,n)},this.getCommentFoldRange=function(e,t,n){var r=new u(this,e,t),s=r.getCurrentToken();if(s&&/^comment|string/.test(s.type)){var o=new i,a=new RegExp(s.type.replace(/\..*/,"\\."));if(n!=1){do s=r.stepBackward();while(s&&a.test(s.type));r.stepForward()}o.start.row=r.getCurrentTokenRow(),o.start.column=r.getCurrentTokenColumn()+2,r=new u(this,e,t);if(n!=-1){do s=r.stepForward();while(s&&a.test(s.type));s=r.stepBackward()}else s=r.getCurrentToken();return o.end.row=r.getCurrentTokenRow(),o.end.column=r.getCurrentTokenColumn()+s.value.length-2,o}},this.foldAll=function(e,t,n){n==undefined&&(n=1e5);var r=this.foldWidgets;if(!r)return;t=t||this.getLength(),e=e||0;for(var i=e;i<t;i++){r[i]==null&&(r[i]=this.getFoldWidget(i));if(r[i]!="start")continue;var s=this.getFoldWidgetRange(i);if(s&&s.isMultiLine()&&s.end.row<=t&&s.start.row>=e){i=s.end.row;try{var o=this.addFold("...",s);o&&(o.collapseChildren=n)}catch(u){}}}},this.$foldStyles={manual:1,markbegin:1,markbeginend:1},this.$foldStyle="markbegin",this.setFoldStyle=function(e){if(!this.$foldStyles[e])throw new Error("invalid fold style: "+e+"["+Object.keys(this.$foldStyles).join(", ")+"]");if(this.$foldStyle==e)return;this.$foldStyle=e,e=="manual"&&this.unfold();var t=this.$foldMode;this.$setFolding(null),this.$setFolding(t)},this.$setFolding=function(e){if(this.$foldMode==e)return;this.$foldMode=e,this.removeListener("change",this.$updateFoldWidgets),this._emit("changeAnnotation");if(!e||this.$foldStyle=="manual"){this.foldWidgets=null;return}this.foldWidgets=[],this.getFoldWidget=e.getFoldWidget.bind(e,this,this.$foldStyle),this.getFoldWidgetRange=e.getFoldWidgetRange.bind(e,this,this.$foldStyle),this.$updateFoldWidgets=this.updateFoldWidgets.bind(this),this.on("change",this.$updateFoldWidgets)},this.getParentFoldRangeData=function(e,t){var n=this.foldWidgets;if(!n||t&&n[e])return{};var r=e-1,i;while(r>=0){var s=n[r];s==null&&(s=n[r]=this.getFoldWidget(r));if(s=="start"){var o=this.getFoldWidgetRange(r);i||(i=o);if(o&&o.end.row>=e)break}r--}return{range:r!==-1&&o,firstRange:i}},this.onFoldWidgetClick=function(e,t){t=t.domEvent;var n={children:t.shiftKey,all:t.ctrlKey||t.metaKey,siblings:t.altKey},r=this.$toggleFoldWidget(e,n);if(!r){var i=t.target||t.srcElement;i&&/ace_fold-widget/.test(i.className)&&(i.className+=" ace_invalid")}},this.$toggleFoldWidget=function(e,t){if(!this.getFoldWidget)return;var n=this.getFoldWidget(e),r=this.getLine(e),i=n==="end"?-1:1,s=this.getFoldAt(e,i===-1?0:r.length,i);if(s){t.children||t.all?this.removeFold(s):this.expandFold(s);return}var o=this.getFoldWidgetRange(e,!0);if(o&&!o.isMultiLine()){s=this.getFoldAt(o.start.row,o.start.column,1);if(s&&o.isEqual(s.range)){this.removeFold(s);return}}if(t.siblings){var u=this.getParentFoldRangeData(e);if(u.range)var a=u.range.start.row+1,f=u.range.end.row;this.foldAll(a,f,t.all?1e4:0)}else t.children?(f=o?o.end.row:this.getLength(),this.foldAll(e+1,o.end.row,t.all?1e4:0)):o&&(t.all&&(o.collapseChildren=1e4),this.addFold("...",o));return o},this.toggleFoldWidget=function(e){var t=this.selection.getCursor().row;t=this.getRowFoldStart(t);var n=this.$toggleFoldWidget(t,{});if(n)return;var r=this.getParentFoldRangeData(t,!0);n=r.range||r.firstRange;if(n){t=n.start.row;var i=this.getFoldAt(t,this.getLine(t).length,1);i?this.removeFold(i):this.addFold("...",n)}},this.updateFoldWidgets=function(e){var t=e.data,n=t.range,r=n.start.row,i=n.end.row-r;if(i===0)this.foldWidgets[r]=null;else if(t.action=="removeText"||t.action=="removeLines")this.foldWidgets.splice(r,i+1,null);else{var s=Array(i+1);s.unshift(r,1),this.foldWidgets.splice.apply(this.foldWidgets,s)}}}var i=e("../range").Range,s=e("./fold_line").FoldLine,o=e("./fold").Fold,u=e("../token_iterator").TokenIterator;t.Folding=r}),define("ace/edit_session/fold_line",["require","exports","module","ace/range"],function(e,t,n){function r(e,t){this.foldData=e,Array.isArray(t)?this.folds=t:t=this.folds=[t];var n=t[t.length-1];this.range=new i(t[0].start.row,t[0].start.column,n.end.row,n.end.column),this.start=this.range.start,this.end=this.range.end,this.folds.forEach(function(e){e.setFoldLine(this)},this)}var i=e("../range").Range;(function(){this.shiftRow=function(e){this.start.row+=e,this.end.row+=e,this.folds.forEach(function(t){t.start.row+=e,t.end.row+=e})},this.addFold=function(e){if(e.sameRow){if(e.start.row<this.startRow||e.endRow>this.endRow)throw new Error("Can't add a fold to this FoldLine as it has no connection");this.folds.push(e),this.folds.sort(function(e,t){return-e.range.compareEnd(t.start.row,t.start.column)}),this.range.compareEnd(e.start.row,e.start.column)>0?(this.end.row=e.end.row,this.end.column=e.end.column):this.range.compareStart(e.end.row,e.end.column)<0&&(this.start.row=e.start.row,this.start.column=e.start.column)}else if(e.start.row==this.end.row)this.folds.push(e),this.end.row=e.end.row,this.end.column=e.end.column;else{if(e.end.row!=this.start.row)throw new Error("Trying to add fold to FoldRow that doesn't have a matching row");this.folds.unshift(e),this.start.row=e.start.row,this.start.column=e.start.column}e.foldLine=this},this.containsRow=function(e){return e>=this.start.row&&e<=this.end.row},this.walk=function(e,t,n){var r=0,i=this.folds,s,o,u,a=!0;t==null&&(t=this.end.row,n=this.end.column);for(var f=0;f<i.length;f++){s=i[f],o=s.range.compareStart(t,n);if(o==-1){e(null,t,n,r,a);return}u=e(null,s.start.row,s.start.column,r,a),u=!u&&e(s.placeholder,s.start.row,s.start.column,r);if(u||o==0)return;a=!s.sameRow,r=s.end.column}e(null,t,n,r,a)},this.getNextFoldTo=function(e,t){var n,r;for(var i=0;i<this.folds.length;i++){n=this.folds[i],r=n.range.compareEnd(e,t);if(r==-1)return{fold:n,kind:"after"};if(r==0)return{fold:n,kind:"inside"}}return null},this.addRemoveChars=function(e,t,n){var r=this.getNextFoldTo(e,t),i,s;if(r){i=r.fold;if(r.kind=="inside"&&i.start.column!=t&&i.start.row!=e)window.console&&window.console.log(e,t,i);else if(i.start.row==e){s=this.folds;var o=s.indexOf(i);o==0&&(this.start.column+=n);for(o;o<s.length;o++){i=s[o],i.start.column+=n;if(!i.sameRow)return;i.end.column+=n}this.end.column+=n}}},this.split=function(e,t){var n=this.getNextFoldTo(e,t).fold,i=this.folds,s=this.foldData;if(!n)return null;var o=i.indexOf(n),u=i[o-1];this.end.row=u.end.row,this.end.column=u.end.column,i=i.splice(o,i.length-o);var a=new r(s,i);return s.splice(s.indexOf(this)+1,0,a),a},this.merge=function(e){var t=e.folds;for(var n=0;n<t.length;n++)this.addFold(t[n]);var r=this.foldData;r.splice(r.indexOf(e),1)},this.toString=function(){var e=[this.range.toString()+": ["];return this.folds.forEach(function(t){e.push(" "+t.toString())}),e.push("]"),e.join("\n")},this.idxToPosition=function(e){var t=0,n;for(var r=0;r<this.folds.length;r++){var n=this.folds[r];e-=n.start.column-t;if(e<0)return{row:n.start.row,column:n.start.column+e};e-=n.placeholder.length;if(e<0)return n.start;t=n.end.column}return{row:this.end.row,column:this.end.column+e}}}).call(r.prototype),t.FoldLine=r}),define("ace/tokenizer",["require","exports","module"],function(e,t,n){var r=1e3,i=function(e){this.states=e,this.regExps={},this.matchMappings={};for(var t in this.states){var n=this.states[t],r=[],i=0,s=this.matchMappings[t]={defaultToken:"text"},o="g",u=[];for(var a=0;a<n.length;a++){var f=n[a];f.defaultToken&&(s.defaultToken=f.defaultToken),f.caseInsensitive&&(o="gi");if(f.regex==null)continue;f.regex instanceof RegExp&&(f.regex=f.regex.toString().slice(1,-1));var l=f.regex,c=(new RegExp("(?:("+l+")|(.))")).exec("a").length-2;if(Array.isArray(f.token))if(f.token.length==1||c==1)f.token=f.token[0];else{if(c-1!=f.token.length)throw new Error("number of classes and regexp groups in '"+f.token+"'\n'"+f.regex+"' doesn't match\n"+(c-1)+"!="+f.token.length);f.tokenArray=f.token,f.token=null,f.onMatch=this.$arrayTokens}else typeof f.token=="function"&&!f.onMatch&&(c>1?f.onMatch=this.$applyToken:f.onMatch=f.token);c>1&&(/\\\d/.test(f.regex)?l=f.regex.replace(/\\([0-9]+)/g,function(e,t){return"\\"+(parseInt(t,10)+i+1)}):(c=1,l=this.removeCapturingGroups(f.regex)),!f.splitRegex&&typeof f.token!="string"&&u.push(f)),s[i]=a,i+=c,r.push(l),f.onMatch||(f.onMatch=null),f.__proto__=null}u.forEach(function(e){e.splitRegex=this.createSplitterRegexp(e.regex,o)},this),this.regExps[t]=new RegExp("("+r.join(")|(")+")|($)",o)}};(function(){this.$setMaxTokenCount=function(e){r=e|0},this.$applyToken=function(e){var t=this.splitRegex.exec(e).slice(1),n=this.token.apply(this,t);if(typeof n=="string")return[{type:n,value:e}];var r=[];for(var i=0,s=n.length;i<s;i++)t[i]&&(r[r.length]={type:n[i],value:t[i]});return r},this.$arrayTokens=function(e){if(!e)return[];var t=this.splitRegex.exec(e);if(!t)return"text";var n=[],r=this.tokenArray;for(var i=0,s=r.length;i<s;i++)t[i+1]&&(n[n.length]={type:r[i],value:t[i+1]});return n},this.removeCapturingGroups=function(e){var t=e.replace(/\[(?:\\.|[^\]])*?\]|\\.|\(\?[:=!]|(\()/g,function(e,t){return t?"(?:":e});return t},this.createSplitterRegexp=function(e,t){if(e.indexOf("(?=")!=-1){var n=0,r=!1,i={};e.replace(/(\\.)|(\((?:\?[=!])?)|(\))|([\[\]])/g,function(e,t,s,o,u,a){return r?r=u!="]":u?r=!0:o?(n==i.stack&&(i.end=a+1,i.stack=-1),n--):s&&(n++,s.length!=1&&(i.stack=n,i.start=a)),e}),i.end!=null&&/^\)*$/.test(e.substr(i.end))&&(e=e.substring(0,i.start)+e.substr(i.end))}return new RegExp(e,(t||"").replace("g",""))},this.getLineTokens=function(e,t){if(t&&typeof t!="string"){var n=t.slice(0);t=n[0]}else var n=[];var i=t||"start",s=this.states[i];s||(i="start",s=this.states[i]);var o=this.matchMappings[i],u=this.regExps[i];u.lastIndex=0;var a,f=[],l=0,c={type:null,value:""};while(a=u.exec(e)){var h=o.defaultToken,p=null,d=a[0],v=u.lastIndex;if(v-d.length>l){var m=e.substring(l,v-d.length);c.type==h?c.value+=m:(c.type&&f.push(c),c={type:h,value:m})}for(var g=0;g<a.length-2;g++){if(a[g+1]===undefined)continue;p=s[o[g]],p.onMatch?h=p.onMatch(d,i,n):h=p.token,p.next&&(typeof p.next=="string"?i=p.next:i=p.next(i,n),s=this.states[i],s||(window.console&&console.error&&console.error(i,"doesn't exist"),i="start",s=this.states[i]),o=this.matchMappings[i],l=v,u=this.regExps[i],u.lastIndex=v);break}if(d)if(typeof h=="string")!!p&&p.merge===!1||c.type!==h?(c.type&&f.push(c),c={type:h,value:d}):c.value+=d;else if(h){c.type&&f.push(c),c={type:null,value:""};for(var g=0;g<h.length;g++)f.push(h[g])}if(l==e.length)break;l=v;if(f.length>r){while(l<e.length)c.type&&f.push(c),c={value:e.substring(l,l+=2e3),type:"overflow"};i="start",n=[];break}}return c.type&&f.push(c),n.length>1&&n[0]!==i&&n.unshift(i),{tokens:f,state:n.length?n:i}}}).call(i.prototype),t.Tokenizer=i}),define("ace/edit_session/fold",["require","exports","module","ace/range","ace/range_list","ace/lib/oop"],function(e,t,n){function r(e,t){e.row-=t.row,e.row==0&&(e.column-=t.column)}function i(e,t){r(e.start,t),r(e.end,t)}function s(e,t){e.row==0&&(e.column+=t.column),e.row+=t.row}function o(e,t){s(e.start,t),s(e.end,t)}var u=e("../range").Range,a=e("../range_list").RangeList,f=e("../lib/oop"),l=t.Fold=function(e,t){this.foldLine=null,this.placeholder=t,this.range=e,this.start=e.start,this.end=e.end,this.sameRow=e.start.row==e.end.row,this.subFolds=this.ranges=[]};f.inherits(l,a),function(){this.toString=function(){return'"'+this.placeholder+'" '+this.range.toString()},this.setFoldLine=function(e){this.foldLine=e,this.subFolds.forEach(function(t){t.setFoldLine(e)})},this.clone=function(){var e=this.range.clone(),t=new l(e,this.placeholder);return this.subFolds.forEach(function(e){t.subFolds.push(e.clone())}),t.collapseChildren=this.collapseChildren,t},this.addSubFold=function(e){if(this.range.isEqual(e))return;if(!this.range.containsRange(e))throw new Error("A fold can't intersect already existing fold"+e.range+this.range);i(e,this.start);var t=e.start.row,n=e.start.column;for(var r=0,s=-1;r<this.subFolds.length;r++){s=this.subFolds[r].range.compare(t,n);if(s!=1)break}var o=this.subFolds[r];if(s==0)return o.addSubFold(e);var t=e.range.end.row,n=e.range.end.column;for(var u=r,s=-1;u<this.subFolds.length;u++){s=this.subFolds[u].range.compare(t,n);if(s!=1)break}var a=this.subFolds[u];if(s==0)throw new Error("A fold can't intersect already existing fold"+e.range+this.range);var f=this.subFolds.splice(r,u-r,e);return e.setFoldLine(this.foldLine),e},this.restoreRange=function(e){return o(e,this.start)}}.call(l.prototype)}),define("ace/mode/text",["require","exports","module","ace/tokenizer","ace/mode/text_highlight_rules","ace/mode/behaviour","ace/unicode","ace/lib/lang","ace/token_iterator","ace/range"],function(e,t,n){var r=e("../tokenizer").Tokenizer,i=e("./text_highlight_rules").TextHighlightRules,s=e("./behaviour").Behaviour,o=e("../unicode"),u=e("../lib/lang"),a=e("../token_iterator").TokenIterator,f=e("../range").Range,l=function(){this.HighlightRules=i,this.$behaviour=new s};(function(){this.tokenRe=new RegExp("^["+o.packages.L+o.packages.Mn+o.packages.Mc+o.packages.Nd+o.packages.Pc+"\\$_]+","g"),this.nonTokenRe=new RegExp("^(?:[^"+o.packages.L+o.packages.Mn+o.packages.Mc+o.packages.Nd+o.packages.Pc+"\\$_]|\\s])+","g"),this.getTokenizer=function(){return this.$tokenizer||(this.$highlightRules=new this.HighlightRules,this.$tokenizer=new r(this.$highlightRules.getRules())),this.$tokenizer},this.lineCommentStart="",this.blockComment="",this.toggleCommentLines=function(e,t,n,r){function i(e){for(var t=n;t<=r;t++)e(s.getLine(t),t)}var s=t.doc,o=!0,a=!0,f=Infinity,l=t.getTabSize(),c=!1;if(!this.lineCommentStart){if(!this.blockComment)return!1;var h=this.blockComment.start,p=this.blockComment.end,d=new RegExp("^(\\s*)(?:"+u.escapeRegExp(h)+")"),v=new RegExp("(?:"+u.escapeRegExp(p)+")\\s*$"),m=function(e,t){if(y(e,t))return;if(!o||/\S/.test(e))s.insertInLine({row:t,column:e.length},p),s.insertInLine({row:t,column:f},h)},g=function(e,t){var n;(n=e.match(v))&&s.removeInLine(t,e.length-n[0].length,e.length),(n=e.match(d))&&s.removeInLine(t,n[1].length,n[0].length)},y=function(e,n){if(d.test(e))return!0;var r=t.getTokens(n);for(var i=0;i<r.length;i++)if(r[i].type==="comment")return!0}}else{if(Array.isArray(this.lineCommentStart))var d=this.lineCommentStart.map(u.escapeRegExp).join("|"),h=this.lineCommentStart[0];else var d=u.escapeRegExp(this.lineCommentStart),h=this.lineCommentStart;d=new RegExp("^(\\s*)(?:"+d+") ?"),c=t.getUseSoftTabs();var g=function(e,t){var n=e.match(d);if(!n)return;var r=n[1].length,i=n[0].length;!w(e,r,i)&&n[0][i-1]==" "&&i--,s.removeInLine(t,r,i)},b=h+" ",m=function(e,t){if(!o||/\S/.test(e))w(e,f,f)?s.insertInLine({row:t,column:f},b):s.insertInLine({row:t,column:f},h)},y=function(e,t){return d.test(e)},w=function(e,t,n){var r=0;while(t--&&e.charAt(t)==" ")r++;if(r%l!=0)return!1;var r=0;while(e.charAt(n++)==" ")r++;return l>2?r%l!=l-1:r%l==0}}var E=Infinity;i(function(e,t){var n=e.search(/\S/);n!==-1?(n<f&&(f=n),a&&!y(e,t)&&(a=!1)):E>e.length&&(E=e.length)}),f==Infinity&&(f=E,o=!1,a=!1),c&&f%l!=0&&(f=Math.floor(f/l)*l),i(a?g:m)},this.toggleBlockComment=function(e,t,n,r){var i=this.blockComment;if(!i)return;!i.start&&i[0]&&(i=i[0]);var s=new a(t,r.row,r.column),o=s.getCurrentToken(),u=t.selection,l=t.selection.toOrientedRange(),c,h;if(o&&/comment/.test(o.type)){var p,d;while(o&&/comment/.test(o.type)){var v=o.value.indexOf(i.start);if(v!=-1){var m=s.getCurrentTokenRow(),g=s.getCurrentTokenColumn()+v;p=new f(m,g,m,g+i.start.length);break}o=s.stepBackward()}var s=new a(t,r.row,r.column),o=s.getCurrentToken();while(o&&/comment/.test(o.type)){var v=o.value.indexOf(i.end);if(v!=-1){var m=s.getCurrentTokenRow(),g=s.getCurrentTokenColumn()+v;d=new f(m,g,m,g+i.end.length);break}o=s.stepForward()}d&&t.remove(d),p&&(t.remove(p),c=p.start.row,h=-i.start.length)}else h=i.start.length,c=n.start.row,t.insert(n.end,i.end),t.insert(n.start,i.start);l.start.row==c&&(l.start.column+=h),l.end.row==c&&(l.end.column+=h),t.selection.fromOrientedRange(l)},this.getNextLineIndent=function(e,t,n){return this.$getIndent(t)},this.checkOutdent=function(e,t,n){return!1},this.autoOutdent=function(e,t,n){},this.$getIndent=function(e){return e.match(/^\s*/)[0]},this.createWorker=function(e){return null},this.createModeDelegates=function(e){this.$embeds=[],this.$modes={};for(var t in e)e[t]&&(this.$embeds.push(t),this.$modes[t]=new e[t]);var n=["toggleBlockComment","toggleCommentLines","getNextLineIndent","checkOutdent","autoOutdent","transformAction","getCompletions"];for(var t=0;t<n.length;t++)(function(e){var r=n[t],i=e[r];e[n[t]]=function(){return this.$delegator(r,arguments,i)}})(this)},this.$delegator=function(e,t,n){var r=t[0];typeof r!="string"&&(r=r[0]);for(var i=0;i<this.$embeds.length;i++){if(!this.$modes[this.$embeds[i]])continue;var s=r.split(this.$embeds[i]);if(!s[0]&&s[1]){t[0]=s[1];var o=this.$modes[this.$embeds[i]];return o[e].apply(o,t)}}var u=n.apply(this,t);return n?u:undefined},this.transformAction=function(e,t,n,r,i){if(this.$behaviour){var s=this.$behaviour.getBehaviours();for(var o in s)if(s[o][t]){var u=s[o][t].apply(this,arguments);if(u)return u}}},this.getKeywords=function(e){if(!this.completionKeywords){var t=this.$tokenizer.rules,n=[];for(var r in t){var i=t[r];for(var s=0,o=i.length;s<o;s++)if(typeof i[s].token=="string")/keyword|support|storage/.test(i[s].token)&&n.push(i[s].regex);else if(typeof i[s].token=="object")for(var u=0,a=i[s].token.length;u<a;u++)if(/keyword|support|storage/.test(i[s].token[u])){var r=i[s].regex.match(/\(.+?\)/g)[u];n.push(r.substr(1,r.length-2))}}this.completionKeywords=n}return e?n.concat(this.$keywordList||[]):this.$keywordList},this.$createKeywordList=function(){return this.$highlightRules||this.getTokenizer(),this.$keywordList=this.$highlightRules.$keywordList||[]},this.getCompletions=function(e,t,n,r){var i=this.$keywordList||this.$createKeywordList();return i.map(function(e){return{name:e,value:e,score:0,meta:"keyword"}})},this.$id="ace/mode/text"}).call(l.prototype),t.Mode=l}),define("ace/range_list",["require","exports","module","ace/range"],function(e,t,n){var r=e("./range").Range,i=r.comparePoints,s=function(){this.ranges=[]};(function(){this.comparePoints=i,this.pointIndex=function(e,t,n){var r=this.ranges;for(var s=n||0;s<r.length;s++){var o=r[s],u=i(e,o.end);if(u>0)continue;var a=i(e,o.start);return u===0?t&&a!==0?-s-2:s:a>0||a===0&&!t?s:-s-1}return-s-1},this.add=function(e){var t=!e.isEmpty(),n=this.pointIndex(e.start,t);n<0&&(n=-n-1);var r=this.pointIndex(e.end,t,n);return r<0?r=-r-1:r++,this.ranges.splice(n,r-n,e)},this.addList=function(e){var t=[];for(var n=e.length;n--;)t.push.call(t,this.add(e[n]));return t},this.substractPoint=function(e){var t=this.pointIndex(e);if(t>=0)return this.ranges.splice(t,1)},this.merge=function(){var e=[],t=this.ranges;t=t.sort(function(e,t){return i(e.start,t.start)});var n=t[0],r;for(var s=1;s<t.length;s++){r=n,n=t[s];var o=i(r.end,n.start);if(o<0)continue;if(o==0&&!r.isEmpty()&&!n.isEmpty())continue;i(r.end,n.end)<0&&(r.end.row=n.end.row,r.end.column=n.end.column),t.splice(s,1),e.push(n),n=r,s--}return this.ranges=t,e},this.contains=function(e,t){return this.pointIndex({row:e,column:t})>=0},this.containsPoint=function(e){return this.pointIndex(e)>=0},this.rangeAtPoint=function(e){var t=this.pointIndex(e);if(t>=0)return this.ranges[t]},this.clipRows=function(e,t){var n=this.ranges;if(n[0].start.row>t||n[n.length-1].start.row<e)return[];var r=this.pointIndex({row:e,column:0});r<0&&(r=-r-1);var i=this.pointIndex({row:t,column:0},r);i<0&&(i=-i-1);var s=[];for(var o=r;o<i;o++)s.push(n[o]);return s},this.removeAll=function(){return this.ranges.splice(0,this.ranges.length)},this.attach=function(e){this.session&&this.detach(),this.session=e,this.onChange=this.$onChange.bind(this),this.session.on("change",this.onChange)},this.detach=function(){if(!this.session)return;this.session.removeListener("change",this.onChange),this.session=null},this.$onChange=function(e){var t=e.data.range;if(e.data.action[0]=="i")var n=t.start,r=t.end;else var r=t.start,n=t.end;var i=n.row,s=r.row,o=s-i,u=-n.column+r.column,a=this.ranges;for(var f=0,l=a.length;f<l;f++){var c=a[f];if(c.end.row<i)continue;if(c.start.row>i)break;c.start.row==i&&c.start.column>=n.column&&(c.start.column!=n.column||!this.$insertRight)&&(c.start.column+=u,c.start.row+=o);if(c.end.row==i&&c.end.column>=n.column){if(c.end.column==n.column&&this.$insertRight)continue;c.end.column==n.column&&u>0&&f<l-1&&c.end.column>c.start.column&&c.end.column==a[f+1].start.column&&(c.end.column-=u),c.end.column+=u,c.end.row+=o}}if(o!=0&&f<l)for(;f<l;f++){var c=a[f];c.start.row+=o,c.end.row+=o}}}).call(s.prototype),t.RangeList=s}),define("ace/range",["require","exports","module"],function(e,t,n){var r=function(e,t){return e.row-t.row||e.column-t.column},i=function(e,t,n,r){this.start={row:e,column:t},this.end={row:n,column:r}};(function(){this.isEqual=function(e){return this.start.row===e.start.row&&this.end.row===e.end.row&&this.start.column===e.start.column&&this.end.column===e.end.column},this.toString=function(){return"Range: ["+this.start.row+"/"+this.start.column+"] -> ["+this.end.row+"/"+this.end.column+"]"},this.contains=function(e,t){return this.compare(e,t)==0},this.compareRange=function(e){var t,n=e.end,r=e.start;return t=this.compare(n.row,n.column),t==1?(t=this.compare(r.row,r.column),t==1?2:t==0?1:0):t==-1?-2:(t=this.compare(r.row,r.column),t==-1?-1:t==1?42:0)},this.comparePoint=function(e){return this.compare(e.row,e.column)},this.containsRange=function(e){return this.comparePoint(e.start)==0&&this.comparePoint(e.end)==0},this.intersects=function(e){var t=this.compareRange(e);return t==-1||t==0||t==1},this.isEnd=function(e,t){return this.end.row==e&&this.end.column==t},this.isStart=function(e,t){return this.start.row==e&&this.start.column==t},this.setStart=function(e,t){typeof e=="object"?(this.start.column=e.column,this.start.row=e.row):(this.start.row=e,this.start.column=t)},this.setEnd=function(e,t){typeof e=="object"?(this.end.column=e.column,this.end.row=e.row):(this.end.row=e,this.end.column=t)},this.inside=function(e,t){return this.compare(e,t)==0?this.isEnd(e,t)||this.isStart(e,t)?!1:!0:!1},this.insideStart=function(e,t){return this.compare(e,t)==0?this.isEnd(e,t)?!1:!0:!1},this.insideEnd=function(e,t){return this.compare(e,t)==0?this.isStart(e,t)?!1:!0:!1},this.compare=function(e,t){return!this.isMultiLine()&&e===this.start.row?t<this.start.column?-1:t>this.end.column?1:0:e<this.start.row?-1:e>this.end.row?1:this.start.row===e?t>=this.start.column?0:-1:this.end.row===e?t<=this.end.column?0:1:0},this.compareStart=function(e,t){return this.start.row==e&&this.start.column==t?-1:this.compare(e,t)},this.compareEnd=function(e,t){return this.end.row==e&&this.end.column==t?1:this.compare(e,t)},this.compareInside=function(e,t){return this.end.row==e&&this.end.column==t?1:this.start.row==e&&this.start.column==t?-1:this.compare(e,t)},this.clipRows=function(e,t){if(this.end.row>t)var n={row:t+1,column:0};else if(this.end.row<e)var n={row:e,column:0};if(this.start.row>t)var r={row:t+1,column:0};else if(this.start.row<e)var r={row:e,column:0};return i.fromPoints(r||this.start,n||this.end)},this.extend=function(e,t){var n=this.compare(e,t);if(n==0)return this;if(n==-1)var r={row:e,column:t};else var s={row:e,column:t};return i.fromPoints(r||this.start,s||this.end)},this.isEmpty=function(){return this.start.row===this.end.row&&this.start.column===this.end.column},this.isMultiLine=function(){return this.start.row!==this.end.row},this.clone=function(){return i.fromPoints(this.start,this.end)},this.collapseRows=function(){return this.end.column==0?new i(this.start.row,0,Math.max(this.start.row,this.end.row-1),0):new i(this.start.row,0,this.end.row,0)},this.toScreenRange=function(e){var t=e.documentToScreenPosition(this.start),n=e.documentToScreenPosition(this.end);return new i(t.row,t.column,n.row,n.column)},this.moveBy=function(e,t){this.start.row+=e,this.start.column+=t,this.end.row+=e,this.end.column+=t}}).call(i.prototype),i.fromPoints=function(e,t){return new i(e.row,e.column,t.row,t.column)},i.comparePoints=r,i.comparePoints=function(e,t){return e.row-t.row||e.column-t.column},t.Range=i}),define("ace/edit_session/bracket_match",["require","exports","module","ace/token_iterator","ace/range"],function(e,t,n){function r(){this.findMatchingBracket=function(e,t){if(e.column==0)return null;var n=t||this.getLine(e.row).charAt(e.column-1);if(n=="")return null;var r=n.match(/([\(\[\{])|([\)\]\}])/);return r?r[1]?this.$findClosingBracket(r[1],e):this.$findOpeningBracket(r[2],e):null},this.getBracketRange=function(e){var t=this.getLine(e.row),n=!0,r,i=t.charAt(e.column-1),o=i&&i.match(/([\(\[\{])|([\)\]\}])/);o||(i=t.charAt(e.column),e={row:e.row,column:e.column+1},o=i&&i.match(/([\(\[\{])|([\)\]\}])/),n=!1);if(!o)return null;if(o[1]){var u=this.$findClosingBracket(o[1],e);if(!u)return null;r=s.fromPoints(e,u),n||(r.end.column++,r.start.column--),r.cursor=r.end}else{var u=this.$findOpeningBracket(o[2],e);if(!u)return null;r=s.fromPoints(u,e),n||(r.start.column++,r.end.column--),r.cursor=r.start}return r},this.$brackets={")":"(","(":")","]":"[","[":"]","{":"}","}":"{"},this.$findOpeningBracket=function(e,t,n){var r=this.$brackets[e],s=1,o=new i(this,t.row,t.column),u=o.getCurrentToken();u||(u=o.stepForward());if(!u)return;n||(n=new RegExp("(\\.?"+u.type.replace(".","\\.").replace("rparen",".paren")+")+"));var a=t.column-o.getCurrentTokenColumn()-2,f=u.value;for(;;){while(a>=0){var l=f.charAt(a);if(l==r){s-=1;if(s==0)return{row:o.getCurrentTokenRow(),column:a+o.getCurrentTokenColumn()}}else l==e&&(s+=1);a-=1}do u=o.stepBackward();while(u&&!n.test(u.type));if(u==null)break;f=u.value,a=f.length-1}return null},this.$findClosingBracket=function(e,t,n){var r=this.$brackets[e],s=1,o=new i(this,t.row,t.column),u=o.getCurrentToken();u||(u=o.stepForward());if(!u)return;n||(n=new RegExp("(\\.?"+u.type.replace(".","\\.").replace("lparen",".paren")+")+"));var a=t.column-o.getCurrentTokenColumn();for(;;){var f=u.value,l=f.length;while(a<l){var c=f.charAt(a);if(c==r){s-=1;if(s==0)return{row:o.getCurrentTokenRow(),column:a+o.getCurrentTokenColumn()}}else c==e&&(s+=1);a+=1}do u=o.stepForward();while(u&&!n.test(u.type));if(u==null)break;a=0}return null}}var i=e("../token_iterator").TokenIterator,s=e("../range").Range;t.BracketMatch=r}),define("ace/selection",["require","exports","module","ace/lib/oop","ace/lib/lang","ace/lib/event_emitter","ace/range"],function(e,t,n){var r=e("./lib/oop"),i=e("./lib/lang"),s=e("./lib/event_emitter").EventEmitter,o=e("./range").Range,u=function(e){this.session=e,this.doc=e.getDocument(),this.clearSelection(),this.lead=this.selectionLead=this.doc.createAnchor(0,0),this.anchor=this.selectionAnchor=this.doc.createAnchor(0,0);var t=this;this.lead.on("change",function(e){t._emit("changeCursor"),t.$isEmpty||t._emit("changeSelection"),!t.$keepDesiredColumnOnChange&&e.old.column!=e.value.column&&(t.$desiredColumn=null)}),this.selectionAnchor.on("change",function(){t.$isEmpty||t._emit("changeSelection")})};(function(){r.implement(this,s),this.isEmpty=function(){return this.$isEmpty||this.anchor.row==this.lead.row&&this.anchor.column==this.lead.column},this.isMultiLine=function(){return this.isEmpty()?!1:this.getRange().isMultiLine()},this.getCursor=function(){return this.lead.getPosition()},this.setSelectionAnchor=function(e,t){this.anchor.setPosition(e,t),this.$isEmpty&&(this.$isEmpty=!1,this._emit("changeSelection"))},this.getSelectionAnchor=function(){return this.$isEmpty?this.getSelectionLead():this.anchor.getPosition()},this.getSelectionLead=function(){return this.lead.getPosition()},this.shiftSelection=function(e){if(this.$isEmpty){this.moveCursorTo(this.lead.row,this.lead.column+e);return}var t=this.getSelectionAnchor(),n=this.getSelectionLead(),r=this.isBackwards();(!r||t.column!==0)&&this.setSelectionAnchor(t.row,t.column+e),(r||n.column!==0)&&this.$moveSelection(function(){this.moveCursorTo(n.row,n.column+e)})},this.isBackwards=function(){var e=this.anchor,t=this.lead;return e.row>t.row||e.row==t.row&&e.column>t.column},this.getRange=function(){var e=this.anchor,t=this.lead;return this.isEmpty()?o.fromPoints(t,t):this.isBackwards()?o.fromPoints(t,e):o.fromPoints(e,t)},this.clearSelection=function(){this.$isEmpty||(this.$isEmpty=!0,this._emit("changeSelection"))},this.selectAll=function(){var e=this.doc.getLength()-1;this.setSelectionAnchor(0,0),this.moveCursorTo(e,this.doc.getLine(e).length)},this.setRange=this.setSelectionRange=function(e,t){t?(this.setSelectionAnchor(e.end.row,e.end.column),this.selectTo(e.start.row,e.start.column)):(this.setSelectionAnchor(e.start.row,e.start.column),this.selectTo(e.end.row,e.end.column)),this.getRange().isEmpty()&&(this.$isEmpty=!0),this.$desiredColumn=null},this.$moveSelection=function(e){var t=this.lead;this.$isEmpty&&this.setSelectionAnchor(t.row,t.column),e.call(this)},this.selectTo=function(e,t){this.$moveSelection(function(){this.moveCursorTo(e,t)})},this.selectToPosition=function(e){this.$moveSelection(function(){this.moveCursorToPosition(e)})},this.moveTo=function(e,t){this.clearSelection(),this.moveCursorTo(e,t)},this.moveToPosition=function(e){this.clearSelection(),this.moveCursorToPosition(e)},this.selectUp=function(){this.$moveSelection(this.moveCursorUp)},this.selectDown=function(){this.$moveSelection(this.moveCursorDown)},this.selectRight=function(){this.$moveSelection(this.moveCursorRight)},this.selectLeft=function(){this.$moveSelection(this.moveCursorLeft)},this.selectLineStart=function(){this.$moveSelection(this.moveCursorLineStart)},this.selectLineEnd=function(){this.$moveSelection(this.moveCursorLineEnd)},this.selectFileEnd=function(){this.$moveSelection(this.moveCursorFileEnd)},this.selectFileStart=function(){this.$moveSelection(this.moveCursorFileStart)},this.selectWordRight=function(){this.$moveSelection(this.moveCursorWordRight)},this.selectWordLeft=function(){this.$moveSelection(this.moveCursorWordLeft)},this.getWordRange=function(e,t){if(typeof t=="undefined"){var n=e||this.lead;e=n.row,t=n.column}return this.session.getWordRange(e,t)},this.selectWord=function(){this.setSelectionRange(this.getWordRange())},this.selectAWord=function(){var e=this.getCursor(),t=this.session.getAWordRange(e.row,e.column);this.setSelectionRange(t)},this.getLineRange=function(e,t){var n=typeof e=="number"?e:this.lead.row,r,i=this.session.getFoldLine(n);return i?(n=i.start.row,r=i.end.row):r=n,t===!0?new o(n,0,r,this.session.getLine(r).length):new o(n,0,r+1,0)},this.selectLine=function(){this.setSelectionRange(this.getLineRange())},this.moveCursorUp=function(){this.moveCursorBy(-1,0)},this.moveCursorDown=function(){this.moveCursorBy(1,0)},this.moveCursorLeft=function(){var e=this.lead.getPosition(),t;if(t=this.session.getFoldAt(e.row,e.column,-1))this.moveCursorTo(t.start.row,t.start.column);else if(e.column==0)e.row>0&&this.moveCursorTo(e.row-1,this.doc.getLine(e.row-1).length);else{var n=this.session.getTabSize();this.session.isTabStop(e)&&this.doc.getLine(e.row).slice(e.column-n,e.column).split(" ").length-1==n?this.moveCursorBy(0,-n):this.moveCursorBy(0,-1)}},this.moveCursorRight=function(){var e=this.lead.getPosition(),t;if(t=this.session.getFoldAt(e.row,e.column,1))this.moveCursorTo(t.end.row,t.end.column);else if(this.lead.column==this.doc.getLine(this.lead.row).length)this.lead.row<this.doc.getLength()-1&&this.moveCursorTo(this.lead.row+1,0);else{var n=this.session.getTabSize(),e=this.lead;this.session.isTabStop(e)&&this.doc.getLine(e.row).slice(e.column,e.column+n).split(" ").length-1==n?this.moveCursorBy(0,n):this.moveCursorBy(0,1)}},this.moveCursorLineStart=function(){var e=this.lead.row,t=this.lead.column,n=this.session.documentToScreenRow(e,t),r=this.session.screenToDocumentPosition(n,0),i=this.session.getDisplayLine(e,null,r.row,r.column),s=i.match(/^\s*/);s[0].length!=t&&!this.session.$useEmacsStyleLineStart&&(r.column+=s[0].length),this.moveCursorToPosition(r)},this.moveCursorLineEnd=function(){var e=this.lead,t=this.session.getDocumentLastRowColumnPosition(e.row,e.column);if(this.lead.column==t.column){var n=this.session.getLine(t.row);if(t.column==n.length){var r=n.search(/\s+$/);r>0&&(t.column=r)}}this.moveCursorTo(t.row,t.column)},this.moveCursorFileEnd=function(){var e=this.doc.getLength()-1,t=this.doc.getLine(e).length;this.moveCursorTo(e,t)},this.moveCursorFileStart=function(){this.moveCursorTo(0,0)},this.moveCursorLongWordRight=function(){var e=this.lead.row,t=this.lead.column,n=this.doc.getLine(e),r=n.substring(t),i;this.session.nonTokenRe.lastIndex=0,this.session.tokenRe.lastIndex=0;var s=this.session.getFoldAt(e,t,1);if(s){this.moveCursorTo(s.end.row,s.end.column);return}if(i=this.session.nonTokenRe.exec(r))t+=this.session.nonTokenRe.lastIndex,this.session.nonTokenRe.lastIndex=0,r=n.substring(t);if(t>=n.length){this.moveCursorTo(e,n.length),this.moveCursorRight(),e<this.doc.getLength()-1&&this.moveCursorWordRight();return}if(i=this.session.tokenRe.exec(r))t+=this.session.tokenRe.lastIndex,this.session.tokenRe.lastIndex=0;this.moveCursorTo(e,t)},this.moveCursorLongWordLeft=function(){var e=this.lead.row,t=this.lead.column,n;if(n=this.session.getFoldAt(e,t,-1)){this.moveCursorTo(n.start.row,n.start.column);return}var r=this.session.getFoldStringAt(e,t,-1);r==null&&(r=this.doc.getLine(e).substring(0,t));var s=i.stringReverse(r),o;this.session.nonTokenRe.lastIndex=0,this.session.tokenRe.lastIndex=0;if(o=this.session.nonTokenRe.exec(s))t-=this.session.nonTokenRe.lastIndex,s=s.slice(this.session.nonTokenRe.lastIndex),this.session.nonTokenRe.lastIndex=0;if(t<=0){this.moveCursorTo(e,0),this.moveCursorLeft(),e>0&&this.moveCursorWordLeft();return}if(o=this.session.tokenRe.exec(s))t-=this.session.tokenRe.lastIndex,this.session.tokenRe.lastIndex=0;this.moveCursorTo(e,t)},this.$shortWordEndIndex=function(e){var t,n=0,r,i=/\s/,s=this.session.tokenRe;s.lastIndex=0;if(t=this.session.tokenRe.exec(e))n=this.session.tokenRe.lastIndex;else{while((r=e[n])&&i.test(r))n++;if(n<1){s.lastIndex=0;while((r=e[n])&&!s.test(r)){s.lastIndex=0,n++;if(i.test(r)){if(n>2){n--;break}while((r=e[n])&&i.test(r))n++;if(n>2)break}}}}return s.lastIndex=0,n},this.moveCursorShortWordRight=function(){var e=this.lead.row,t=this.lead.column,n=this.doc.getLine(e),r=n.substring(t),i=this.session.getFoldAt(e,t,1);if(i)return this.moveCursorTo(i.end.row,i.end.column);if(t==n.length){var s=this.doc.getLength();do e++,r=this.doc.getLine(e);while(e<s&&/^\s*$/.test(r));/^\s+/.test(r)||(r=""),t=0}var o=this.$shortWordEndIndex(r);this.moveCursorTo(e,t+o)},this.moveCursorShortWordLeft=function(){var e=this.lead.row,t=this.lead.column,n;if(n=this.session.getFoldAt(e,t,-1))return this.moveCursorTo(n.start.row,n.start.column);var r=this.session.getLine(e).substring(0,t);if(t==0){do e--,r=this.doc.getLine(e);while(e>0&&/^\s*$/.test(r));t=r.length,/\s+$/.test(r)||(r="")}var s=i.stringReverse(r),o=this.$shortWordEndIndex(s);return this.moveCursorTo(e,t-o)},this.moveCursorWordRight=function(){this.session.$selectLongWords?this.moveCursorLongWordRight():this.moveCursorShortWordRight()},this.moveCursorWordLeft=function(){this.session.$selectLongWords?this.moveCursorLongWordLeft():this.moveCursorShortWordLeft()},this.moveCursorBy=function(e,t){var n=this.session.documentToScreenPosition(this.lead.row,this.lead.column);t===0&&(this.$desiredColumn?n.column=this.$desiredColumn:this.$desiredColumn=n.column);var r=this.session.screenToDocumentPosition(n.row+e,n.column);e!==0&&t===0&&r.row===this.lead.row&&r.column===this.lead.column&&this.session.lineWidgets&&this.session.lineWidgets[r.row]&&r.row++,this.moveCursorTo(r.row,r.column+t,t===0)},this.moveCursorToPosition=function(e){this.moveCursorTo(e.row,e.column)},this.moveCursorTo=function(e,t,n){var r=this.session.getFoldAt(e,t,1);r&&(e=r.start.row,t=r.start.column),this.$keepDesiredColumnOnChange=!0,this.lead.setPosition(e,t),this.$keepDesiredColumnOnChange=!1,n||(this.$desiredColumn=null)},this.moveCursorToScreen=function(e,t,n){var r=this.session.screenToDocumentPosition(e,t);this.moveCursorTo(r.row,r.column,n)},this.detach=function(){this.lead.detach(),this.anchor.detach(),this.session=this.doc=null},this.fromOrientedRange=function(e){this.setSelectionRange(e,e.cursor==e.start),this.$desiredColumn=e.desiredColumn||this.$desiredColumn},this.toOrientedRange=function(e){var t=this.getRange();return e?(e.start.column=t.start.column,e.start.row=t.start.row,e.end.column=t.end.column,e.end.row=t.end.row):e=t,e.cursor=this.isBackwards()?e.start:e.end,e.desiredColumn=this.$desiredColumn,e},this.toJSON=function(){if(this.rangeCount)var e=this.ranges.map(function(e){var t=e.clone();return t.isBackwards=e.cursor==e.start,t});else{var e=this.getRange();e.isBackwards=this.isBackwards()}return e},this.fromJSON=function(e){if(e.start==undefined){if(this.rangeList){this.toSingleRange(e[0]);for(var t=e.length;t--;){var n=o.fromPoints(e[t].start,e[t].end);e.isBackwards&&(n.cursor=n.start),this.addRange(n,!0)}return}e=e[0]}this.rangeList&&this.toSingleRange(e),this.setSelectionRange(e,e.isBackwards)},this.isEqual=function(e){if((e.length||this.rangeCount)&&e.length!=this.rangeCount)return!1;if(!e.length||!this.ranges)return this.getRange().isEqual(e);for(var t=this.ranges.length;t--;)if(!this.ranges[t].isEqual(e[t]))return!1;return!0}}).call(u.prototype),t.Selection=u}),define("ace/search",["require","exports","module","ace/lib/lang","ace/lib/oop","ace/range"],function(e,t,n){var r=e("./lib/lang"),i=e("./lib/oop"),s=e("./range").Range,o=function(){this.$options={}};(function(){this.set=function(e){return i.mixin(this.$options,e),this},this.getOptions=function(){return r.copyObject(this.$options)},this.setOptions=function(e){this.$options=e},this.find=function(e){var t=this.$matchIterator(e,this.$options);if(!t)return!1;var n=null;return t.forEach(function(e,t,r){if(!e.start){var i=e.offset+(r||0);n=new s(t,i,t,i+e.length)}else n=e;return!0}),n},this.findAll=function(e){var t=this.$options;if(!t.needle)return[];this.$assembleRegExp(t);var n=t.range,i=n?e.getLines(n.start.row,n.end.row):e.doc.getAllLines(),o=[],u=t.re;if(t.$isMultiLine){var a=u.length,f=i.length-a,l;e:for(var c=u.offset||0;c<=f;c++){for(var h=0;h<a;h++)if(i[c+h].search(u[h])==-1)continue e;var p=i[c],d=i[c+a-1],v=p.length-p.match(u[0])[0].length,m=d.match(u[a-1])[0].length;if(l&&l.end.row===c&&l.end.column>v)continue;o.push(l=new s(c,v,c+a-1,m)),a>2&&(c=c+a-2)}}else for(var g=0;g<i.length;g++){var y=r.getMatchOffsets(i[g],u);for(var h=0;h<y.length;h++){var b=y[h];o.push(new s(g,b.offset,g,b.offset+b.length))}}if(n){var w=n.start.column,E=n.start.column,g=0,h=o.length-1;while(g<h&&o[g].start.column<w&&o[g].start.row==n.start.row)g++;while(g<h&&o[h].end.column>E&&o[h].end.row==n.end.row)h--;o=o.slice(g,h+1);for(g=0,h=o.length;g<h;g++)o[g].start.row+=n.start.row,o[g].end.row+=n.start.row}return o},this.replace=function(e,t){var n=this.$options,r=this.$assembleRegExp(n);if(n.$isMultiLine)return t;if(!r)return;var i=r.exec(e);if(!i||i[0].length!=e.length)return null;t=e.replace(r,t);if(n.preserveCase){t=t.split("");for(var s=Math.min(e.length,e.length);s--;){var o=e[s];o&&o.toLowerCase()!=o?t[s]=t[s].toUpperCase():t[s]=t[s].toLowerCase()}t=t.join("")}return t},this.$matchIterator=function(e,t){var n=this.$assembleRegExp(t);if(!n)return!1;var i=this,o,u=t.backwards;if(t.$isMultiLine)var a=n.length,f=function(t,r,i){var u=t.search(n[0]);if(u==-1)return;for(var f=1;f<a;f++){t=e.getLine(r+f);if(t.search(n[f])==-1)return}var l=t.match(n[a-1])[0].length,c=new s(r,u,r+a-1,l);n.offset==1?(c.start.row--,c.start.column=Number.MAX_VALUE):i&&(c.start.column+=i);if(o(c))return!0};else if(u)var f=function(e,t,i){var s=r.getMatchOffsets(e,n);for(var u=s.length-1;u>=0;u--)if(o(s[u],t,i))return!0};else var f=function(e,t,i){var s=r.getMatchOffsets(e,n);for(var u=0;u<s.length;u++)if(o(s[u],t,i))return!0};return{forEach:function(n){o=n,i.$lineIterator(e,t).forEach(f)}}},this.$assembleRegExp=function(e,t){if(e.needle instanceof RegExp)return e.re=e.needle;var n=e.needle;if(!e.needle)return e.re=!1;e.regExp||(n=r.escapeRegExp(n)),e.wholeWord&&(n="\\b"+n+"\\b");var i=e.caseSensitive?"g":"gi";e.$isMultiLine=!t&&/[\n\r]/.test(n);if(e.$isMultiLine)return e.re=this.$assembleMultilineRegExp(n,i);try{var s=new RegExp(n,i)}catch(o){s=!1}return e.re=s},this.$assembleMultilineRegExp=function(e,t){var n=e.replace(/\r\n|\r|\n/g,"$\n^").split("\n"),r=[];for(var i=0;i<n.length;i++)try{r.push(new RegExp(n[i],t))}catch(s){return!1}return n[0]==""?(r.shift(),r.offset=1):r.offset=0,r},this.$lineIterator=function(e,t){var n=t.backwards==1,r=t.skipCurrent!=0,i=t.range,s=t.start;s||(s=i?i[n?"end":"start"]:e.selection.getRange()),s.start&&(s=s[r!=n?"end":"start"]);var o=i?i.start.row:0,u=i?i.end.row:e.getLength()-1,a=n?function(n){var r=s.row,i=e.getLine(r).substring(0,s.column);if(n(i,r))return;for(r--;r>=o;r--)if(n(e.getLine(r),r))return;if(t.wrap==0)return;for(r=u,o=s.row;r>=o;r--)if(n(e.getLine(r),r))return}:function(n){var r=s.row,i=e.getLine(r).substr(s.column);if(n(i,r,s.column))return;for(r+=1;r<=u;r++)if(n(e.getLine(r),r))return;if(t.wrap==0)return;for(r=o,u=s.row;r<=u;r++)if(n(e.getLine(r),r))return};return{forEach:a}}}).call(o.prototype),t.Search=o}),define("ace/edit_session",["require","exports","module","ace/lib/oop","ace/lib/lang","ace/config","ace/lib/event_emitter","ace/selection","ace/mode/text","ace/range","ace/document","ace/background_tokenizer","ace/search_highlight","ace/edit_session/folding","ace/edit_session/bracket_match"],function(e,t,n){var r=e("./lib/oop"),i=e("./lib/lang"),s=e("./config"),o=e("./lib/event_emitter").EventEmitter,u=e("./selection").Selection,a=e("./mode/text").Mode,f=e("./range").Range,l=e("./document").Document,c=e("./background_tokenizer").BackgroundTokenizer,h=e("./search_highlight").SearchHighlight,p=function(e,t){this.$breakpoints=[],this.$decorations=[],this.$frontMarkers={},this.$backMarkers={},this.$markerId=1,this.$undoSelect=!0,this.$foldData=[],this.$foldData.toString=function(){return this.join("\n")},this.on("changeFold",this.onChangeFold.bind(this)),this.$onChange=this.onChange.bind(this);if(typeof e!="object"||!e.getLine)e=new l(e);this.setDocument(e),this.selection=new u(this),s.resetOptions(this),this.setMode(t),s._signal("session",this)};(function(){function t(e){return e<4352?!1:e>=4352&&e<=4447||e>=4515&&e<=4519||e>=4602&&e<=4607||e>=9001&&e<=9002||e>=11904&&e<=11929||e>=11931&&e<=12019||e>=12032&&e<=12245||e>=12272&&e<=12283||e>=12288&&e<=12350||e>=12353&&e<=12438||e>=12441&&e<=12543||e>=12549&&e<=12589||e>=12593&&e<=12686||e>=12688&&e<=12730||e>=12736&&e<=12771||e>=12784&&e<=12830||e>=12832&&e<=12871||e>=12880&&e<=13054||e>=13056&&e<=19903||e>=19968&&e<=42124||e>=42128&&e<=42182||e>=43360&&e<=43388||e>=44032&&e<=55203||e>=55216&&e<=55238||e>=55243&&e<=55291||e>=63744&&e<=64255||e>=65040&&e<=65049||e>=65072&&e<=65106||e>=65108&&e<=65126||e>=65128&&e<=65131||e>=65281&&e<=65376||e>=65504&&e<=65510}r.implement(this,o),this.setDocument=function(e){this.doc&&this.doc.removeListener("change",this.$onChange),this.doc=e,e.on("change",this.$onChange),this.bgTokenizer&&this.bgTokenizer.setDocument(this.getDocument()),this.resetCaches()},this.getDocument=function(){return this.doc},this.$resetRowCache=function(e){if(!e){this.$docRowCache=[],this.$screenRowCache=[];return}var t=this.$docRowCache.length,n=this.$getRowCacheIndex(this.$docRowCache,e)+1;t>n&&(this.$docRowCache.splice(n,t),this.$screenRowCache.splice(n,t))},this.$getRowCacheIndex=function(e,t){var n=0,r=e.length-1;while(n<=r){var i=n+r>>1,s=e[i];if(t>s)n=i+1;else{if(!(t<s))return i;r=i-1}}return n-1},this.resetCaches=function(){this.$modified=!0,this.$wrapData=[],this.$rowLengthCache=[],this.$resetRowCache(0),this.bgTokenizer&&this.bgTokenizer.start(0)},this.onChangeFold=function(e){var t=e.data;this.$resetRowCache(t.start.row)},this.onChange=function(e){var t=e.data;this.$modified=!0,this.$resetRowCache(t.range.start.row);var n=this.$updateInternalDataOnChange(e);!this.$fromUndo&&this.$undoManager&&!t.ignore&&(this.$deltasDoc.push(t),n&&n.length!=0&&this.$deltasFold.push({action:"removeFolds",folds:n}),this.$informUndoManager.schedule()),this.bgTokenizer.$updateOnChange(t),this._signal("change",e)},this.setValue=function(e){this.doc.setValue(e),this.selection.moveTo(0,0),this.$resetRowCache(0),this.$deltas=[],this.$deltasDoc=[],this.$deltasFold=[],this.setUndoManager(this.$undoManager),this.getUndoManager().reset()},this.getValue=this.toString=function(){return this.doc.getValue()},this.getSelection=function(){return this.selection},this.getState=function(e){return this.bgTokenizer.getState(e)},this.getTokens=function(e){return this.bgTokenizer.getTokens(e)},this.getTokenAt=function(e,t){var n=this.bgTokenizer.getTokens(e),r,i=0;if(t==null)s=n.length-1,i=this.getLine(e).length;else for(var s=0;s<n.length;s++){i+=n[s].value.length;if(i>=t)break}return r=n[s],r?(r.index=s,r.start=i-r.value.length,r):null},this.setUndoManager=function(e){this.$undoManager=e,this.$deltas=[],this.$deltasDoc=[],this.$deltasFold=[],this.$informUndoManager&&this.$informUndoManager.cancel();if(e){var t=this;this.$syncInformUndoManager=function(){t.$informUndoManager.cancel(),t.$deltasFold.length&&(t.$deltas.push({group:"fold",deltas:t.$deltasFold}),t.$deltasFold=[]),t.$deltasDoc.length&&(t.$deltas.push({group:"doc",deltas:t.$deltasDoc}),t.$deltasDoc=[]),t.$deltas.length>0&&e.execute({action:"aceupdate",args:[t.$deltas,t],merge:t.mergeUndoDeltas}),t.mergeUndoDeltas=!1,t.$deltas=[]},this.$informUndoManager=i.delayedCall(this.$syncInformUndoManager)}},this.markUndoGroup=function(){this.$syncInformUndoManager&&this.$syncInformUndoManager()},this.$defaultUndoManager={undo:function(){},redo:function(){},reset:function(){}},this.getUndoManager=function(){return this.$undoManager||this.$defaultUndoManager},this.getTabString=function(){return this.getUseSoftTabs()?i.stringRepeat(" ",this.getTabSize()):" "},this.setUseSoftTabs=function(e){this.setOption("useSoftTabs",e)},this.getUseSoftTabs=function(){return this.$useSoftTabs&&!this.$mode.$indentWithTabs},this.setTabSize=function(e){this.setOption("tabSize",e)},this.getTabSize=function(){return this.$tabSize},this.isTabStop=function(e){return this.$useSoftTabs&&e.column%this.$tabSize===0},this.$overwrite=!1,this.setOverwrite=function(e){this.setOption("overwrite",e)},this.getOverwrite=function(){return this.$overwrite},this.toggleOverwrite=function(){this.setOverwrite(!this.$overwrite)},this.addGutterDecoration=function(e,t){this.$decorations[e]||(this.$decorations[e]=""),this.$decorations[e]+=" "+t,this._signal("changeBreakpoint",{})},this.removeGutterDecoration=function(e,t){this.$decorations[e]=(this.$decorations[e]||"").replace(" "+t,""),this._signal("changeBreakpoint",{})},this.getBreakpoints=function(){return this.$breakpoints},this.setBreakpoints=function(e){this.$breakpoints=[];for(var t=0;t<e.length;t++)this.$breakpoints[e[t]]="ace_breakpoint";this._signal("changeBreakpoint",{})},this.clearBreakpoints=function(){this.$breakpoints=[],this._signal("changeBreakpoint",{})},this.setBreakpoint=function(e,t){t===undefined&&(t="ace_breakpoint"),t?this.$breakpoints[e]=t:delete this.$breakpoints[e],this._signal("changeBreakpoint",{})},this.clearBreakpoint=function(e){delete this.$breakpoints[e],this._signal("changeBreakpoint",{})},this.addMarker=function(e,t,n,r){var i=this.$markerId++,s={range:e,type:n||"line",renderer:typeof n=="function"?n:null,clazz:t,inFront:!!r,id:i};return r?(this.$frontMarkers[i]=s,this._signal("changeFrontMarker")):(this.$backMarkers[i]=s,this._signal("changeBackMarker")),i},this.addDynamicMarker=function(e,t){if(!e.update)return;var n=this.$markerId++;return e.id=n,e.inFront=!!t,t?(this.$frontMarkers[n]=e,this._signal("changeFrontMarker")):(this.$backMarkers[n]=e,this._signal("changeBackMarker")),e},this.removeMarker=function(e){var t=this.$frontMarkers[e]||this.$backMarkers[e];if(!t)return;var n=t.inFront?this.$frontMarkers:this.$backMarkers;t&&(delete n[e],this._signal(t.inFront?"changeFrontMarker":"changeBackMarker"))},this.getMarkers=function(e){return e?this.$frontMarkers:this.$backMarkers},this.highlight=function(e){if(!this.$searchHighlight){var t=new h(null,"ace_selected-word","text");this.$searchHighlight=this.addDynamicMarker(t)}this.$searchHighlight.setRegexp(e)},this.highlightLines=function(e,t,n,r){typeof t!="number"&&(n=t,t=e),n||(n="ace_step");var i=new f(e,0,t,Infinity);return i.id=this.addMarker(i,n,"fullLine",r),i},this.setAnnotations=function(e){this.$annotations=e,this._signal("changeAnnotation",{})},this.getAnnotations=function(){return this.$annotations||[]},this.clearAnnotations=function(){this.setAnnotations([])},this.$detectNewLine=function(e){var t=e.match(/^.*?(\r?\n)/m);t?this.$autoNewLine=t[1]:this.$autoNewLine="\n"},this.getWordRange=function(e,t){var n=this.getLine(e),r=!1;t>0&&(r=!!n.charAt(t-1).match(this.tokenRe)),r||(r=!!n.charAt(t).match(this.tokenRe));if(r)var i=this.tokenRe;else if(/^\s+$/.test(n.slice(t-1,t+1)))var i=/\s/;else var i=this.nonTokenRe;var s=t;if(s>0){do s--;while(s>=0&&n.charAt(s).match(i));s++}var o=t;while(o<n.length&&n.charAt(o).match(i))o++;return new f(e,s,e,o)},this.getAWordRange=function(e,t){var n=this.getWordRange(e,t),r=this.getLine(n.end.row);while(r.charAt(n.end.column).match(/[ \t]/))n.end.column+=1;return n},this.setNewLineMode=function(e){this.doc.setNewLineMode(e)},this.getNewLineMode=function(){return this.doc.getNewLineMode()},this.setUseWorker=function(e){this.setOption("useWorker",e)},this.getUseWorker=function(){return this.$useWorker},this.onReloadTokenizer=function(e){var t=e.data;this.bgTokenizer.start(t.first),this._signal("tokenizerUpdate",e)},this.$modes={},this.$mode=null,this.$modeId=null,this.setMode=function(e,t){if(e&&typeof e=="object"){if(e.getTokenizer)return this.$onChangeMode(e);var n=e,r=n.path}else r=e||"ace/mode/text";this.$modes["ace/mode/text"]||(this.$modes["ace/mode/text"]=new a);if(this.$modes[r]&&!n){this.$onChangeMode(this.$modes[r]),t&&t();return}this.$modeId=r,s.loadModule(["mode",r],function(e){if(this.$modeId!==r)return t&&t();if(this.$modes[r]&&!n)return this.$onChangeMode(this.$modes[r]);e&&e.Mode&&(e=new e.Mode(n),n||(this.$modes[r]=e,e.$id=r),this.$onChangeMode(e),t&&t())}.bind(this)),this.$mode||this.$onChangeMode(this.$modes["ace/mode/text"],!0)},this.$onChangeMode=function(e,t){t||(this.$modeId=e.$id);if(this.$mode===e)return;this.$mode=e,this.$stopWorker(),this.$useWorker&&this.$startWorker();var n=e.getTokenizer();if(n.addEventListener!==undefined){var r=this.onReloadTokenizer.bind(this);n.addEventListener("update",r)}if(!this.bgTokenizer){this.bgTokenizer=new c(n);var i=this;this.bgTokenizer.addEventListener("update",function(e){i._signal("tokenizerUpdate",e)})}else this.bgTokenizer.setTokenizer(n);this.bgTokenizer.setDocument(this.getDocument()),this.tokenRe=e.tokenRe,this.nonTokenRe=e.nonTokenRe,t||(this.$options.wrapMethod.set.call(this,this.$wrapMethod),this.$setFolding(e.foldingRules),this.bgTokenizer.start(0),this._emit("changeMode"))},this.$stopWorker=function(){this.$worker&&this.$worker.terminate(),this.$worker=null},this.$startWorker=function(){if(typeof Worker!="undefined"&&!e.noWorker)try{this.$worker=this.$mode.createWorker(this)}catch(t){console.log("Could not load worker"),console.log(t),this.$worker=null}else this.$worker=null},this.getMode=function(){return this.$mode},this.$scrollTop=0,this.setScrollTop=function(e){if(this.$scrollTop===e||isNaN(e))return;this.$scrollTop=e,this._signal("changeScrollTop",e)},this.getScrollTop=function(){return this.$scrollTop},this.$scrollLeft=0,this.setScrollLeft=function(e){if(this.$scrollLeft===e||isNaN(e))return;this.$scrollLeft=e,this._signal("changeScrollLeft",e)},this.getScrollLeft=function(){return this.$scrollLeft},this.getScreenWidth=function(){return this.$computeWidth(),this.lineWidgets?Math.max(this.getLineWidgetMaxWidth(),this.screenWidth):this.screenWidth},this.getLineWidgetMaxWidth=function(){if(this.lineWidgetsWidth!=null)return this.lineWidgetsWidth;var e=0;return this.lineWidgets.forEach(function(t){t&&t.screenWidth>e&&(e=t.screenWidth)}),this.lineWidgetWidth=e},this.$computeWidth=function(e){if(this.$modified||e){this.$modified=!1;if(this.$useWrapMode)return this.screenWidth=this.$wrapLimit;var t=this.doc.getAllLines(),n=this.$rowLengthCache,r=0,i=0,s=this.$foldData[i],o=s?s.start.row:Infinity,u=t.length;for(var a=0;a<u;a++){if(a>o){a=s.end.row+1;if(a>=u)break;s=this.$foldData[i++],o=s?s.start.row:Infinity}n[a]==null&&(n[a]=this.$getStringScreenWidth(t[a])[0]),n[a]>r&&(r=n[a])}this.screenWidth=r}},this.getLine=function(e){return this.doc.getLine(e)},this.getLines=function(e,t){return this.doc.getLines(e,t)},this.getLength=function(){return this.doc.getLength()},this.getTextRange=function(e){return this.doc.getTextRange(e||this.selection.getRange())},this.insert=function(e,t){return this.doc.insert(e,t)},this.remove=function(e){return this.doc.remove(e)},this.undoChanges=function(e,t){if(!e.length)return;this.$fromUndo=!0;var n=null;for(var r=e.length-1;r!=-1;r--){var i=e[r];i.group=="doc"?(this.doc.revertDeltas(i.deltas),n=this.$getUndoSelection(i.deltas,!0,n)):i.deltas.forEach(function(e){this.addFolds(e.folds)},this)}return this.$fromUndo=!1,n&&this.$undoSelect&&!t&&this.selection.setSelectionRange(n),n},this.redoChanges=function(e,t){if(!e.length)return;this.$fromUndo=!0;var n=null;for(var r=0;r<e.length;r++){var i=e[r];i.group=="doc"&&(this.doc.applyDeltas(i.deltas),n=this.$getUndoSelection(i.deltas,!1,n))}return this.$fromUndo=!1,n&&this.$undoSelect&&!t&&this.selection.setSelectionRange(n),n},this.setUndoSelect=function(e){this.$undoSelect=e},this.$getUndoSelection=function(e,t,n){function r(e){var n=e.action==="insertText"||e.action==="insertLines";return t?!n:n}var i=e[0],s,o,u=!1;r(i)?(s=f.fromPoints(i.range.start,i.range.end),u=!0):(s=f.fromPoints(i.range.start,i.range.start),u=!1);for(var a=1;a<e.length;a++)i=e[a],r(i)?(o=i.range.start,s.compare(o.row,o.column)==-1&&s.setStart(i.range.start),o=i.range.end,s.compare(o.row,o.column)==1&&s.setEnd(i.range.end),u=!0):(o=i.range.start,s.compare(o.row,o.column)==-1&&(s=f.fromPoints(i.range.start,i.range.start)),u=!1);if(n!=null){f.comparePoints(n.start,s.start)===0&&(n.start.column+=s.end.column-s.start.column,n.end.column+=s.end.column-s.start.column);var l=n.compareRange(s);l==1?s.setStart(n.start):l==-1&&s.setEnd(n.end)}return s},this.replace=function(e,t){return this.doc.replace(e,t)},this.moveText=function(e,t,n){var r=this.getTextRange(e),i=this.getFoldsInRange(e),s=f.fromPoints(t,t);if(!n){this.remove(e);var o=e.start.row-e.end.row,u=o?-e.end.column:e.start.column-e.end.column;u&&(s.start.row==e.end.row&&s.start.column>e.end.column&&(s.start.column+=u),s.end.row==e.end.row&&s.end.column>e.end.column&&(s.end.column+=u)),o&&s.start.row>=e.end.row&&(s.start.row+=o,s.end.row+=o)}s.end=this.insert(s.start,r);if(i.length){var a=e.start,l=s.start,o=l.row-a.row,u=l.column-a.column;this.addFolds(i.map(function(e){return e=e.clone(),e.start.row==a.row&&(e.start.column+=u),e.end.row==a.row&&(e.end.column+=u),e.start.row+=o,e.end.row+=o,e}))}return s},this.indentRows=function(e,t,n){n=n.replace(/\t/g,this.getTabString());for(var r=e;r<=t;r++)this.insert({row:r,column:0},n)},this.outdentRows=function(e){var t=e.collapseRows(),n=new f(0,0,0,0),r=this.getTabSize();for(var i=t.start.row;i<=t.end.row;++i){var s=this.getLine(i);n.start.row=i,n.end.row=i;for(var o=0;o<r;++o)if(s.charAt(o)!=" ")break;o<r&&s.charAt(o)==" "?(n.start.column=o,n.end.column=o+1):(n.start.column=0,n.end.column=o),this.remove(n)}},this.$moveLines=function(e,t,n){e=this.getRowFoldStart(e),t=this.getRowFoldEnd(t);if(n<0){var r=this.getRowFoldStart(e+n);if(r<0)return 0;var i=r-e}else if(n>0){var r=this.getRowFoldEnd(t+n);if(r>this.doc.getLength()-1)return 0;var i=r-t}else{e=this.$clipRowToDocument(e),t=this.$clipRowToDocument(t);var i=t-e+1}var s=new f(e,0,t,Number.MAX_VALUE),o=this.getFoldsInRange(s).map(function(e){return e=e.clone(),e.start.row+=i,e.end.row+=i,e}),u=n==0?this.doc.getLines(e,t):this.doc.removeLines(e,t);return this.doc.insertLines(e+i,u),o.length&&this.addFolds(o),i},this.moveLinesUp=function(e,t){return this.$moveLines(e,t,-1)},this.moveLinesDown=function(e,t){return this.$moveLines(e,t,1)},this.duplicateLines=function(e,t){return this.$moveLines(e,t,0)},this.$clipRowToDocument=function(e){return Math.max(0,Math.min(e,this.doc.getLength()-1))},this.$clipColumnToRow=function(e,t){return t<0?0:Math.min(this.doc.getLine(e).length,t)},this.$clipPositionToDocument=function(e,t){t=Math.max(0,t);if(e<0)e=0,t=0;else{var n=this.doc.getLength();e>=n?(e=n-1,t=this.doc.getLine(n-1).length):t=Math.min(this.doc.getLine(e).length,t)}return{row:e,column:t}},this.$clipRangeToDocument=function(e){e.start.row<0?(e.start.row=0,e.start.column=0):e.start.column=this.$clipColumnToRow(e.start.row,e.start.column);var t=this.doc.getLength()-1;return e.end.row>t?(e.end.row=t,e.end.column=this.doc.getLine(t).length):e.end.column=this.$clipColumnToRow(e.end.row,e.end.column),e},this.$wrapLimit=80,this.$useWrapMode=!1,this.$wrapLimitRange={min:null,max:null},this.setUseWrapMode=function(e){if(e!=this.$useWrapMode){this.$useWrapMode=e,this.$modified=!0,this.$resetRowCache(0);if(e){var t=this.getLength();this.$wrapData=Array(t),this.$updateWrapData(0,t-1)}this._signal("changeWrapMode")}},this.getUseWrapMode=function(){return this.$useWrapMode},this.setWrapLimitRange=function(e,t){if(this.$wrapLimitRange.min!==e||this.$wrapLimitRange.max!==t)this.$wrapLimitRange={min:e,max:t},this.$modified=!0,this._signal("changeWrapMode")},this.adjustWrapLimit=function(e,t){var n=this.$wrapLimitRange;n.max<0&&(n={min:t,max:t});var r=this.$constrainWrapLimit(e,n.min,n.max);return r!=this.$wrapLimit&&r>1?(this.$wrapLimit=r,this.$modified=!0,this.$useWrapMode&&(this.$updateWrapData(0,this.getLength()-1),this.$resetRowCache(0),this._signal("changeWrapLimit")),!0):!1},this.$constrainWrapLimit=function(e,t,n){return t&&(e=Math.max(t,e)),n&&(e=Math.min(n,e)),e},this.getWrapLimit=function(){return this.$wrapLimit},this.setWrapLimit=function(e){this.setWrapLimitRange(e,e)},this.getWrapLimitRange=function(){return{min:this.$wrapLimitRange.min,max:this.$wrapLimitRange.max}},this.$updateInternalDataOnChange=function(e){var t=this.$useWrapMode,n,r=e.data.action,i=e.data.range.start.row,s=e.data.range.end.row,o=e.data.range.start,u=e.data.range.end,a=null;r.indexOf("Lines")!=-1?(r=="insertLines"?s=i+e.data.lines.length:s=i,n=e.data.lines?e.data.lines.length:s-i):n=s-i,this.$updating=!0;if(n!=0)if(r.indexOf("remove")!=-1){this[t?"$wrapData":"$rowLengthCache"].splice(i,n);var f=this.$foldData;a=this.getFoldsInRange(e.data.range),this.removeFolds(a);var l=this.getFoldLine(u.row),c=0;if(l){l.addRemoveChars(u.row,u.column,o.column-u.column),l.shiftRow(-n);var h=this.getFoldLine(i);h&&h!==l&&(h.merge(l),l=h),c=f.indexOf(l)+1}for(c;c<f.length;c++){var l=f[c];l.start.row>=u.row&&l.shiftRow(-n)}s=i}else{var p=Array(n);p.unshift(i,0);var d=t?this.$wrapData:this.$rowLengthCache;d.splice.apply(d,p);var f=this.$foldData,l=this.getFoldLine(i),c=0;if(l){var v=l.range.compareInside(o.row,o.column);v==0?(l=l.split(o.row,o.column),l.shiftRow(n),l.addRemoveChars(s,0,u.column-o.column)):v==-1&&(l.addRemoveChars(i,0,u.column-o.column),l.shiftRow(n)),c=f.indexOf(l)+1}for(c;c<f.length;c++){var l=f[c];l.start.row>=i&&l.shiftRow(n)}}else{n=Math.abs(e.data.range.start.column-e.data.range.end.column),r.indexOf("remove")!=-1&&(a=this.getFoldsInRange(e.data.range),this.removeFolds(a),n=-n);var l=this.getFoldLine(i);l&&l.addRemoveChars(i,o.column,n)}return t&&this.$wrapData.length!=this.doc.getLength()&&console.error("doc.getLength() and $wrapData.length have to be the same!"),this.$updating=!1,t?this.$updateWrapData(i,s):this.$updateRowLengthCache(i,s),a},this.$updateRowLengthCache=function(e,t,n){this.$rowLengthCache[e]=null,this.$rowLengthCache[t]=null},this.$updateWrapData=function(e,t){var n=this.doc.getAllLines(),r=this.getTabSize(),i=this.$wrapData,s=this.$wrapLimit,o,u,a=e;t=Math.min(t,n.length-1);while(a<=t)u=this.getFoldLine(a,u),u?(o=[],u.walk(function(e,t,r,i){var s;if(e!=null){s=this.$getDisplayTokens(e,o.length),s[0]=l;for(var u=1;u<s.length;u++)s[u]=p}else s=this.$getDisplayTokens(n[t].substring(i,r),o.length);o=o.concat(s)}.bind(this),u.end.row,n[u.end.row].length+1),i[u.start.row]=this.$computeWrapSplits(o,s,r),a=u.end.row+1):(o=this.$getDisplayTokens(n[a]),i[a]=this.$computeWrapSplits(o,s,r),a++)};var n=1,u=2,l=3,p=4,d=9,v=10,m=11,g=12;this.$computeWrapSplits=function(e,t){function n(t){var n=e.slice(s,t),i=n.length;n.join("").replace(/12/g,function(){i-=1}).replace(/2/g,function(){i-=1}),o+=i,r.push(o),s=t}if(e.length==0)return[];var r=[],i=e.length,s=0,o=0,u=this.$wrapAsCode;while(i-s>t){var a=s+t;if(e[a-1]>=v&&e[a]>=v){n(a);continue}if(e[a]==l||e[a]==p){for(a;a!=s-1;a--)if(e[a]==l)break;if(a>s){n(a);continue}a=s+t;for(a;a<e.length;a++)if(e[a]!=p)break;if(a==e.length)break;n(a);continue}var f=Math.max(a-(u?10:t-(t>>2)),s-1);while(a>f&&e[a]<l)a--;if(u){while(a>f&&e[a]<l)a--;while(a>f&&e[a]==d)a--}else while(a>f&&e[a]<v)a--;if(a>f){n(++a);continue}a=s+t,n(a)}return r},this.$getDisplayTokens=function(e,r){var i=[],s;r=r||0;for(var o=0;o<e.length;o++){var a=e.charCodeAt(o);if(a==9){s=this.getScreenTabSize(i.length+r),i.push(m);for(var f=1;f<s;f++)i.push(g)}else a==32?i.push(v):a>39&&a<48||a>57&&a<64?i.push(d):a>=4352&&t(a)?i.push(n,u):i.push(n)}return i},this.$getStringScreenWidth=function(e,n,r){if(n==0)return[0,0];n==null&&(n=Infinity),r=r||0;var i,s;for(s=0;s<e.length;s++){i=e.charCodeAt(s),i==9?r+=this.getScreenTabSize(r):i>=4352&&t(i)?r+=2:r+=1;if(r>n)break}return[r,s]},this.lineWidgets=null,this.getRowLength=function(e){if(this.lineWidgets)var t=this.lineWidgets[e]&&this.lineWidgets[e].rowCount||0;else t=0;return!this.$useWrapMode||!this.$wrapData[e]?1+t:this.$wrapData[e].length+1+t},this.getRowLineCount=function(e){return!this.$useWrapMode||!this.$wrapData[e]?1:this.$wrapData[e].length+1},this.getScreenLastRowColumn=function(e){var t=this.screenToDocumentPosition(e,Number.MAX_VALUE);return this.documentToScreenColumn(t.row,t.column)},this.getDocumentLastRowColumn=function(e,t){var n=this.documentToScreenRow(e,t);return this.getScreenLastRowColumn(n)},this.getDocumentLastRowColumnPosition=function(e,t){var n=this.documentToScreenRow(e,t);return this.screenToDocumentPosition(n,Number.MAX_VALUE/10)},this.getRowSplitData=function(e){return this.$useWrapMode?this.$wrapData[e]:undefined},this.getScreenTabSize=function(e){return this.$tabSize-e%this.$tabSize},this.screenToDocumentRow=function(e,t){return this.screenToDocumentPosition(e,t).row},this.screenToDocumentColumn=function(e,t){return this.screenToDocumentPosition(e,t).column},this.screenToDocumentPosition=function(e,t){if(e<0)return{row:0,column:0};var n,r=0,i=0,s,o=0,u=0,a=this.$screenRowCache,f=this.$getRowCacheIndex(a,e),l=a.length;if(l&&f>=0)var o=a[f],r=this.$docRowCache[f],c=e>a[l-1];else var c=!l;var h=this.getLength()-1,p=this.getNextFoldLine(r),d=p?p.start.row:Infinity;while(o<=e){u=this.getRowLength(r);if(o+u>e||r>=h)break;o+=u,r++,r>d&&(r=p.end.row+1,p=this.getNextFoldLine(r,p),d=p?p.start.row:Infinity),c&&(this.$docRowCache.push(r),this.$screenRowCache.push(o))}if(p&&p.start.row<=r)n=this.getFoldDisplayLine(p),r=p.start.row;else{if(o+u<=e||r>h)return{row:h,column:this.getLine(h).length};n=this.getLine(r),p=null}if(this.$useWrapMode){var v=this.$wrapData[r];if(v){var m=Math.floor(e-o);s=v[m],m>0&&v.length&&(i=v[m-1]||v[v.length-1],n=n.substring(i))}}return i+=this.$getStringScreenWidth(n,t)[1],this.$useWrapMode&&i>=s&&(i=s-1),p?p.idxToPosition(i):{row:r,column:i}},this.documentToScreenPosition=function(e,t){if(typeof t=="undefined")var n=this.$clipPositionToDocument(e.row,e.column);else n=this.$clipPositionToDocument(e,t);e=n.row,t=n.column;var r=0,i=null,s=null;s=this.getFoldAt(e,t,1),s&&(e=s.start.row,t=s.start.column);var o,u=0,a=this.$docRowCache,f=this.$getRowCacheIndex(a,e),l=a.length;if(l&&f>=0)var u=a[f],r=this.$screenRowCache[f],c=e>a[l-1];else var c=!l;var h=this.getNextFoldLine(u),p=h?h.start.row:Infinity;while(u<e){if(u>=p){o=h.end.row+1;if(o>e)break;h=this.getNextFoldLine(o,h),p=h?h.start.row:Infinity}else o=u+1;r+=this.getRowLength(u),u=o,c&&(this.$docRowCache.push(u),this.$screenRowCache.push(r))}var d="";h&&u>=p?(d=this.getFoldDisplayLine(h,e,t),i=h.start.row):(d=this.getLine(e).substring(0,t),i=e);if(this.$useWrapMode){var v=this.$wrapData[i];if(v){var m=0;while(d.length>=v[m])r++,m++;d=d.substring(v[m-1]||0,d.length)}}return{row:r,column:this.$getStringScreenWidth(d)[0]}},this.documentToScreenColumn=function(e,t){return this.documentToScreenPosition(e,t).column},this.documentToScreenRow=function(e,t){return this.documentToScreenPosition(e,t).row},this.getScreenLength=function(){var e=0,t=null;if(!this.$useWrapMode){e=this.getLength();var n=this.$foldData;for(var r=0;r<n.length;r++)t=n[r],e-=t.end.row-t.start.row}else{var i=this.$wrapData.length,s=0,r=0,t=this.$foldData[r++],o=t?t.start.row:Infinity;while(s<i){var u=this.$wrapData[s];e+=u?u.length+1:1,s++,s>o&&(s=t.end.row+1,t=this.$foldData[r++],o=t?t.start.row:Infinity)}}return this.lineWidgets&&(e+=this.$getWidgetScreenLength()),e},this.$setFontMetrics=function(e){}}).call(p.prototype),e("./edit_session/folding").Folding.call(p.prototype),e("./edit_session/bracket_match").BracketMatch.call(p.prototype),s.defineOptions(p.prototype,"session",{wrap:{set:function(e){!e||e=="off"?e=!1:e=="free"?e=!0:e=="printMargin"?e=-1:typeof e=="string"&&(e=parseInt(e,10)||!1);if(this.$wrap==e)return;if(!e)this.setUseWrapMode(!1);else{var t=typeof e=="number"?e:null;this.setWrapLimitRange(t,t),this.setUseWrapMode(!0)}this.$wrap=e},get:function(){return this.getUseWrapMode()?this.$wrap==-1?"printMargin":this.getWrapLimitRange().min?this.$wrap:"free":"off"},handlesSet:!0},wrapMethod:{set:function(e){e=e=="auto"?this.$mode.type!="text":e!="text",e!=this.$wrapAsCode&&(this.$wrapAsCode=e,this.$useWrapMode&&(this.$modified=!0,this.$resetRowCache(0),this.$updateWrapData(0,this.getLength()-1)))},initialValue:"auto"},firstLineNumber:{set:function(){this._signal("changeBreakpoint")},initialValue:1},useWorker:{set:function(e){this.$useWorker=e,this.$stopWorker(),e&&this.$startWorker()},initialValue:!0},useSoftTabs:{initialValue:!0},tabSize:{set:function(e){if(isNaN(e)||this.$tabSize===e)return;this.$modified=!0,this.$rowLengthCache=[],this.$tabSize=e,this._signal("changeTabSize")},initialValue:4,handlesSet:!0},overwrite:{set:function(e){this._signal("changeOverwrite")},initialValue:!1},newLineMode:{set:function(e){this.doc.setNewLineMode(e)},get:function(){return this.doc.getNewLineMode()},handlesSet:!0},mode:{set:function(e){this.setMode(e)},get:function(){return this.$modeId}}}),t.EditSession=p}),define("ace/commands/command_manager",["require","exports","module","ace/lib/oop","ace/keyboard/hash_handler","ace/lib/event_emitter"],function(e,t,n){var r=e("../lib/oop"),i=e("../keyboard/hash_handler").HashHandler,s=e("../lib/event_emitter").EventEmitter,o=function(e,t){i.call(this,t,e),this.byName=this.commands,this.setDefaultHandler("exec",function(e){return e.command.exec(e.editor,e.args||{})})};r.inherits(o,i),function(){r.implement(this,s),this.exec=function(e,t,n){typeof e=="string"&&(e=this.commands[e]);if(!e)return!1;if(t&&t.$readOnly&&!e.readOnly)return!1;var r={editor:t,command:e,args:n},i=this._emit("exec",r);return this._signal("afterExec",r),i===!1?!1:!0},this.toggleRecording=function(e){if(this.$inReplay)return;return e&&e._emit("changeStatus"),this.recording?(this.macro.pop(),this.removeEventListener("exec",this.$addCommandToMacro),this.macro.length||(this.macro=this.oldMacro),this.recording=!1):(this.$addCommandToMacro||(this.$addCommandToMacro=function(e){this.macro.push([e.command,e.args])}.bind(this)),this.oldMacro=this.macro,this.macro=[],this.on("exec",this.$addCommandToMacro),this.recording=!0)},this.replay=function(e){if(this.$inReplay||!this.macro)return;if(this.recording)return this.toggleRecording(e);try{this.$inReplay=!0,this.macro.forEach(function(t){typeof t=="string"?this.exec(t,e):this.exec(t[0],e,t[1])},this)}finally{this.$inReplay=!1}},this.trimMacro=function(e){return e.map(function(e){return typeof e[0]!="string"&&(e[0]=e[0].name),e[1]||(e=e[0]),e})}}.call(o.prototype),t.CommandManager=o}),define("ace/keyboard/keybinding",["require","exports","module","ace/lib/keys","ace/lib/event"],function(e,t,n){var r=e("../lib/keys"),i=e("../lib/event"),s=function(e){this.$editor=e,this.$data={},this.$handlers=[],this.setDefaultHandler(e.commands)};(function(){this.setDefaultHandler=function(e){this.removeKeyboardHandler(this.$defaultHandler),this.$defaultHandler=e,this.addKeyboardHandler(e,0),this.$data={editor:this.$editor}},this.setKeyboardHandler=function(e){var t=this.$handlers;if(t[t.length-1]==e)return;while(t[t.length-1]&&t[t.length-1]!=this.$defaultHandler)this.removeKeyboardHandler(t[t.length-1]);this.addKeyboardHandler(e,1)},this.addKeyboardHandler=function(e,t){if(!e)return;typeof e=="function"&&!e.handleKeyboard&&(e.handleKeyboard=e);var n=this.$handlers.indexOf(e);n!=-1&&this.$handlers.splice(n,1),t==undefined?this.$handlers.push(e):this.$handlers.splice(t,0,e),n==-1&&e.attach&&e.attach(this.$editor)},this.removeKeyboardHandler=function(e){var t=this.$handlers.indexOf(e);return t==-1?!1:(this.$handlers.splice(t,1),e.detach&&e.detach(this.$editor),!0)},this.getKeyboardHandler=function(){return this.$handlers[this.$handlers.length-1]},this.$callKeyboardHandlers=function(e,t,n,r){var s,o=!1,u=this.$editor.commands;for(var a=this.$handlers.length;a--;){s=this.$handlers[a].handleKeyboard(this.$data,e,t,n,r);if(!s||!s.command)continue;s.command=="null"?o=!0:o=u.exec(s.command,this.$editor,s.args,r),o&&r&&e!=-1&&s.passEvent!=1&&s.command.passEvent!=1&&i.stopEvent(r);if(o)break}return o},this.onCommandKey=function(e,t,n){var i=r.keyCodeToString(n);this.$callKeyboardHandlers(t,i,n,e)},this.onTextInput=function(e){var t=this.$callKeyboardHandlers(-1,e);t||this.$editor.commands.exec("insertstring",this.$editor,e)}}).call(s.prototype),t.KeyBinding=s}),define("ace/keyboard/hash_handler",["require","exports","module","ace/lib/keys","ace/lib/useragent"],function(e,t,n){function r(e,t){this.platform=t||(s.isMac?"mac":"win"),this.commands={},this.commandKeyBinding={};if(this.__defineGetter__&&this.__defineSetter__&&typeof console!="undefined"&&console.error){var n=!1,r=function(){n||(n=!0,console.error("commmandKeyBinding has too many m's. use commandKeyBinding"))};this.__defineGetter__("commmandKeyBinding",function(){return r(),this.commandKeyBinding}),this.__defineSetter__("commmandKeyBinding",function(e){return r(),this.commandKeyBinding=e})}else this.commmandKeyBinding=this.commandKeyBinding;this.addCommands(e)}var i=e("../lib/keys"),s=e("../lib/useragent");(function(){this.addCommand=function(e){this.commands[e.name]&&this.removeCommand(e),this.commands[e.name]=e,e.bindKey&&this._buildKeyHash(e)},this.removeCommand=function(e){var t=typeof e=="string"?e:e.name;e=this.commands[t],delete this.commands[t];var n=this.commandKeyBinding;for(var r in n)for(var i in n[r])n[r][i]==e&&delete n[r][i]},this.bindKey=function(e,t){if(!e)return;if(typeof t=="function"){this.addCommand({exec:t,bindKey:e,name:t.name||e});return}var n=this.commandKeyBinding;e.split("|").forEach(function(e){var r=this.parseKeys(e,t),i=r.hashId;(n[i]||(n[i]={}))[r.key]=t},this)},this.addCommands=function(e){e&&Object.keys(e).forEach(function(t){var n=e[t];if(!n)return;if(typeof n=="string")return this.bindKey(n,t);typeof n=="function"&&(n={exec:n});if(typeof n!="object")return;n.name||(n.name=t),this.addCommand(n)},this)},this.removeCommands=function(e){Object.keys(e).forEach(function(t){this.removeCommand(e[t])},this)},this.bindKeys=function(e){Object.keys(e).forEach(function(t){this.bindKey(t,e[t])},this)},this._buildKeyHash=function(e){var t=e.bindKey;if(!t)return;var n=typeof t=="string"?t:t[this.platform];this.bindKey(n,e)},this.parseKeys=function(e){e.indexOf(" ")!=-1&&(e=e.split(/\s+/).pop());var t=e.toLowerCase().split(/[\-\+]([\-\+])?/).filter(function(e){return e}),n=t.pop(),r=i[n];if(i.FUNCTION_KEYS[r])n=i.FUNCTION_KEYS[r].toLowerCase();else{if(!t.length)return{key:n,hashId:-1};if(t.length==1&&t[0]=="shift")return{key:n.toUpperCase(),hashId:-1}}var s=0;for(var o=t.length;o--;){var u=i.KEY_MODS[t[o]];if(u==null)return typeof console!="undefined"&&console.error("invalid modifier "+t[o]+" in "+e),!1;s|=u}return{key:n,hashId:s}},this.findKeyCommand=function(e,t){var n=this.commandKeyBinding;return n[e]&&n[e][t]},this.handleKeyboard=function(e,t,n,r){return{command:this.findKeyCommand(t,n)}}}).call(r.prototype),t.HashHandler=r}),define("ace/mouse/fold_handler",["require","exports","module"],function(e,t,n){function r(e){e.on("click",function(t){var n=t.getDocumentPosition(),r=e.session,i=r.getFoldAt(n.row,n.column,1);i&&(t.getAccelKey()?r.removeFold(i):r.expandFold(i),t.stop())}),e.on("gutterclick",function(t){var n=e.renderer.$gutterLayer.getRegion(t);if(n=="foldWidgets"){var r=t.getDocumentPosition().row,i=e.session;i.foldWidgets&&i.foldWidgets[r]&&e.session.onFoldWidgetClick(r,t),e.isFocused()||e.focus(),t.stop()}}),e.on("gutterdblclick",function(t){var n=e.renderer.$gutterLayer.getRegion(t);if(n=="foldWidgets"){var r=t.getDocumentPosition().row,i=e.session,s=i.getParentFoldRangeData(r,!0),o=s.range||s.firstRange;if(o){r=o.start.row;var u=i.getFoldAt(r,i.getLine(r).length,1);u?i.removeFold(u):(i.addFold("...",o),e.renderer.scrollCursorIntoView({row:o.start.row,column:0}))}t.stop()}})}t.FoldHandler=r}),define("ace/commands/default_commands",["require","exports","module","ace/lib/lang","ace/config"],function(e,t,n){function r(e,t){return{win:e,mac:t}}var i=e("../lib/lang"),s=e("../config");t.commands=[{name:"showSettingsMenu",bindKey:r("Ctrl-,","Command-,"),exec:function(e){s.loadModule("ace/ext/settings_menu",function(t){t.init(e),e.showSettingsMenu()})},readOnly:!0},{name:"goToNextError",bindKey:r("Alt-E","Ctrl-E"),exec:function(e){s.loadModule("ace/ext/error_marker",function(t){t.showErrorMarker(e,1)})},scrollIntoView:"animate",readOnly:!0},{name:"goToPreviousError",bindKey:r("Alt-Shift-E","Ctrl-Shift-E"),exec:function(e){s.loadModule("ace/ext/error_marker",function(t){t.showErrorMarker(e,-1)})},scrollIntoView:"animate",readOnly:!0},{name:"selectall",bindKey:r("Ctrl-A","Command-A"),exec:function(e){e.selectAll()},readOnly:!0},{name:"centerselection",bindKey:r(null,"Ctrl-L"),exec:function(e){e.centerSelection()},readOnly:!0},{name:"gotoline",bindKey:r("Ctrl-L","Command-L"),exec:function(e){var t=parseInt(prompt("Enter line number:"),10);isNaN(t)||e.gotoLine(t)},readOnly:!0},{name:"fold",bindKey:r("Alt-L|Ctrl-F1","Command-Alt-L|Command-F1"),exec:function(e){e.session.toggleFold(!1)},scrollIntoView:"center",readOnly:!0},{name:"unfold",bindKey:r("Alt-Shift-L|Ctrl-Shift-F1","Command-Alt-Shift-L|Command-Shift-F1"),exec:function(e){e.session.toggleFold(!0)},scrollIntoView:"center",readOnly:!0},{name:"toggleFoldWidget",bindKey:r("F2","F2"),exec:function(e){e.session.toggleFoldWidget()},scrollIntoView:"center",readOnly:!0},{name:"toggleParentFoldWidget",bindKey:r("Alt-F2","Alt-F2"),exec:function(e){e.session.toggleFoldWidget(!0)},scrollIntoView:"center",readOnly:!0},{name:"foldall",bindKey:r("Ctrl-Alt-0","Ctrl-Command-Option-0"),exec:function(e){e.session.foldAll()},scrollIntoView:"center",readOnly:!0},{name:"foldOther",bindKey:r("Alt-0","Command-Option-0"),exec:function(e){e.session.foldAll(),e.session.unfold(e.selection.getAllRanges())},scrollIntoView:"center",readOnly:!0},{name:"unfoldall",bindKey:r("Alt-Shift-0","Command-Option-Shift-0"),exec:function(e){e.session.unfold()},scrollIntoView:"center",readOnly:!0},{name:"findnext",bindKey:r("Ctrl-K","Command-G"),exec:function(e){e.findNext()},readOnly:!0},{name:"findprevious",bindKey:r("Ctrl-Shift-K","Command-Shift-G"),exec:function(e){e.findPrevious()},readOnly:!0},{name:"selectOrFindNext",bindKey:r("ALt-K","Ctrl-G"),exec:function(e){e.selection.isEmpty()?e.selection.selectWord():e.findNext()},readOnly:!0},{name:"selectOrFindPrevious",bindKey:r("Alt-Shift-K","Ctrl-Shift-G"),exec:function(e){e.selection.isEmpty()?e.selection.selectWord():e.findPrevious()},readOnly:!0},{name:"find",bindKey:r("Ctrl-F","Command-F"),exec:function(e){s.loadModule("ace/ext/searchbox",function(t){t.Search(e)})},readOnly:!0},{name:"overwrite",bindKey:"Insert",exec:function(e){e.toggleOverwrite()},readOnly:!0},{name:"selecttostart",bindKey:r("Ctrl-Shift-Home","Command-Shift-Up"),exec:function(e){e.getSelection().selectFileStart()},multiSelectAction:"forEach",readOnly:!0,scrollIntoView:"animate",aceCommandGroup:"fileJump"},{name:"gotostart",bindKey:r("Ctrl-Home","Command-Home|Command-Up"),exec:function(e){e.navigateFileStart()},multiSelectAction:"forEach",readOnly:!0,scrollIntoView:"animate",aceCommandGroup:"fileJump"},{name:"selectup",bindKey:r("Shift-Up","Shift-Up"),exec:function(e){e.getSelection().selectUp()},multiSelectAction:"forEach",readOnly:!0},{name:"golineup",bindKey:r("Up","Up|Ctrl-P"),exec:function(e,t){e.navigateUp(t.times)},multiSelectAction:"forEach",readOnly:!0},{name:"selecttoend",bindKey:r("Ctrl-Shift-End","Command-Shift-Down"),exec:function(e){e.getSelection().selectFileEnd()},multiSelectAction:"forEach",readOnly:!0,scrollIntoView:"animate",aceCommandGroup:"fileJump"},{name:"gotoend",bindKey:r("Ctrl-End","Command-End|Command-Down"),exec:function(e){e.navigateFileEnd()},multiSelectAction:"forEach",readOnly:!0,scrollIntoView:"animate",aceCommandGroup:"fileJump"},{name:"selectdown",bindKey:r("Shift-Down","Shift-Down"),exec:function(e){e.getSelection().selectDown()},multiSelectAction:"forEach",scrollIntoView:"cursor",readOnly:!0},{name:"golinedown",bindKey:r("Down","Down|Ctrl-N"),exec:function(e,t){e.navigateDown(t.times)},multiSelectAction:"forEach",scrollIntoView:"cursor",readOnly:!0},{name:"selectwordleft",bindKey:r("Ctrl-Shift-Left","Option-Shift-Left"),exec:function(e){e.getSelection().selectWordLeft()},multiSelectAction:"forEach",scrollIntoView:"cursor",readOnly:!0},{name:"gotowordleft",bindKey:r("Ctrl-Left","Option-Left"),exec:function(e){e.navigateWordLeft()},multiSelectAction:"forEach",scrollIntoView:"cursor",readOnly:!0},{name:"selecttolinestart",bindKey:r("Alt-Shift-Left","Command-Shift-Left"),exec:function(e){e.getSelection().selectLineStart()},multiSelectAction:"forEach",scrollIntoView:"cursor",readOnly:!0},{name:"gotolinestart",bindKey:r("Alt-Left|Home","Command-Left|Home|Ctrl-A"),exec:function(e){e.navigateLineStart()},multiSelectAction:"forEach",scrollIntoView:"cursor",readOnly:!0},{name:"selectleft",bindKey:r("Shift-Left","Shift-Left"),exec:function(e){e.getSelection().selectLeft()},multiSelectAction:"forEach",scrollIntoView:"cursor",readOnly:!0},{name:"gotoleft",bindKey:r("Left","Left|Ctrl-B"),exec:function(e,t){e.navigateLeft(t.times)},multiSelectAction:"forEach",scrollIntoView:"cursor",readOnly:!0},{name:"selectwordright",bindKey:r("Ctrl-Shift-Right","Option-Shift-Right"),exec:function(e){e.getSelection().selectWordRight()},multiSelectAction:"forEach",scrollIntoView:"cursor",readOnly:!0},{name:"gotowordright",bindKey:r("Ctrl-Right","Option-Right"),exec:function(e){e.navigateWordRight()},multiSelectAction:"forEach",scrollIntoView:"cursor",readOnly:!0},{name:"selecttolineend",bindKey:r("Alt-Shift-Right","Command-Shift-Right"),exec:function(e){e.getSelection().selectLineEnd()},multiSelectAction:"forEach",scrollIntoView:"cursor",readOnly:!0},{name:"gotolineend",bindKey:r("Alt-Right|End","Command-Right|End|Ctrl-E"),exec:function(e){e.navigateLineEnd()},multiSelectAction:"forEach",scrollIntoView:"cursor",readOnly:!0},{name:"selectright",bindKey:r("Shift-Right","Shift-Right"),exec:function(e){e.getSelection().selectRight()},multiSelectAction:"forEach",scrollIntoView:"cursor",readOnly:!0},{name:"gotoright",bindKey:r("Right","Right|Ctrl-F"),exec:function(e,t){e.navigateRight(t.times)},multiSelectAction:"forEach",scrollIntoView:"cursor",readOnly:!0},{name:"selectpagedown",bindKey:"Shift-PageDown",exec:function(e){e.selectPageDown()},readOnly:!0},{name:"pagedown",bindKey:r(null,"Option-PageDown"),exec:function(e){e.scrollPageDown()},readOnly:!0},{name:"gotopagedown",bindKey:r("PageDown","PageDown|Ctrl-V"),exec:function(e){e.gotoPageDown()},readOnly:!0},{name:"selectpageup",bindKey:"Shift-PageUp",exec:function(e){e.selectPageUp()},readOnly:!0},{name:"pageup",bindKey:r(null,"Option-PageUp"),exec:function(e){e.scrollPageUp()},readOnly:!0},{name:"gotopageup",bindKey:"PageUp",exec:function(e){e.gotoPageUp()},readOnly:!0},{name:"scrollup",bindKey:r("Ctrl-Up",null),exec:function(e){e.renderer.scrollBy(0,-2*e.renderer.layerConfig.lineHeight)},readOnly:!0},{name:"scrolldown",bindKey:r("Ctrl-Down",null),exec:function(e){e.renderer.scrollBy(0,2*e.renderer.layerConfig.lineHeight)},readOnly:!0},{name:"selectlinestart",bindKey:"Shift-Home",exec:function(e){e.getSelection().selectLineStart()},multiSelectAction:"forEach",scrollIntoView:"cursor",readOnly:!0},{name:"selectlineend",bindKey:"Shift-End",exec:function(e){e.getSelection().selectLineEnd()},multiSelectAction:"forEach",scrollIntoView:"cursor",readOnly:!0},{name:"togglerecording",bindKey:r("Ctrl-Alt-E","Command-Option-E"),exec:function(e){e.commands.toggleRecording(e)},readOnly:!0},{name:"replaymacro",bindKey:r("Ctrl-Shift-E","Command-Shift-E"),exec:function(e){e.commands.replay(e)},readOnly:!0},{name:"jumptomatching",bindKey:r("Ctrl-P","Ctrl-Shift-P"),exec:function(e){e.jumpToMatching()},multiSelectAction:"forEach",readOnly:!0},{name:"selecttomatching",bindKey:r("Ctrl-Shift-P",null),exec:function(e){e.jumpToMatching(!0)},multiSelectAction:"forEach",readOnly:!0},{name:"cut",exec:function(e){var t=e.getSelectionRange();e._emit("cut",t),e.selection.isEmpty()||(e.session.remove(t),e.clearSelection())},scrollIntoView:"cursor",multiSelectAction:"forEach"},{name:"removeline",bindKey:r("Ctrl-D","Command-D"),exec:function(e){e.removeLines()},scrollIntoView:"cursor",multiSelectAction:"forEachLine"},{name:"duplicateSelection",bindKey:r("Ctrl-Shift-D","Command-Shift-D"),exec:function(e){e.duplicateSelection()},scrollIntoView:"cursor",multiSelectAction:"forEach"},{name:"sortlines",bindKey:r("Ctrl-Alt-S","Command-Alt-S"),exec:function(e){e.sortLines()},scrollIntoView:"selection",multiSelectAction:"forEachLine"},{name:"togglecomment",bindKey:r("Ctrl-/","Command-/"),exec:function(e){e.toggleCommentLines()},multiSelectAction:"forEachLine",scrollIntoView:"selectionPart"},{name:"toggleBlockComment",bindKey:r("Ctrl-Shift-/","Command-Shift-/"),exec:function(e){e.toggleBlockComment()},multiSelectAction:"forEach",scrollIntoView:"selectionPart"},{name:"modifyNumberUp",bindKey:r("Ctrl-Shift-Up","Alt-Shift-Up"),exec:function(e){e.modifyNumber(1)},multiSelectAction:"forEach"},{name:"modifyNumberDown",bindKey:r("Ctrl-Shift-Down","Alt-Shift-Down"),exec:function(e){e.modifyNumber(-1)},multiSelectAction:"forEach"},{name:"replace",bindKey:r("Ctrl-H","Command-Option-F"),exec:function(e){s.loadModule("ace/ext/searchbox",function(t){t.Search(e,!0)})}},{name:"undo",bindKey:r("Ctrl-Z","Command-Z"),exec:function(e){e.undo()}},{name:"redo",bindKey:r("Ctrl-Shift-Z|Ctrl-Y","Command-Shift-Z|Command-Y"),exec:function(e){e.redo()}},{name:"copylinesup",bindKey:r("Alt-Shift-Up","Command-Option-Up"),exec:function(e){e.copyLinesUp()},scrollIntoView:"cursor"},{name:"movelinesup",bindKey:r("Alt-Up","Option-Up"),exec:function(e){e.moveLinesUp()},scrollIntoView:"cursor"},{name:"copylinesdown",bindKey:r("Alt-Shift-Down","Command-Option-Down"),exec:function(e){e.copyLinesDown()},scrollIntoView:"cursor"},{name:"movelinesdown",bindKey:r("Alt-Down","Option-Down"),exec:function(e){e.moveLinesDown()},scrollIntoView:"cursor"},{name:"del",bindKey:r("Delete","Delete|Ctrl-D|Shift-Delete"),exec:function(e){e.remove("right")},multiSelectAction:"forEach",scrollIntoView:"cursor"},{name:"backspace",bindKey:r("Shift-Backspace|Backspace","Ctrl-Backspace|Shift-Backspace|Backspace|Ctrl-H"),exec:function(e){e.remove("left")},multiSelectAction:"forEach",scrollIntoView:"cursor"},{name:"cut_or_delete",bindKey:r("Shift-Delete",null),exec:function(e){if(!e.selection.isEmpty())return!1;e.remove("left")},multiSelectAction:"forEach",scrollIntoView:"cursor"},{name:"removetolinestart",bindKey:r("Alt-Backspace","Command-Backspace"),exec:function(e){e.removeToLineStart()},multiSelectAction:"forEach",scrollIntoView:"cursor"},{name:"removetolineend",bindKey:r("Alt-Delete","Ctrl-K"),exec:function(e){e.removeToLineEnd()},multiSelectAction:"forEach",scrollIntoView:"cursor"},{name:"removewordleft",bindKey:r("Ctrl-Backspace","Alt-Backspace|Ctrl-Alt-Backspace"),exec:function(e){e.removeWordLeft()},multiSelectAction:"forEach",scrollIntoView:"cursor"},{name:"removewordright",bindKey:r("Ctrl-Delete","Alt-Delete"),exec:function(e){e.removeWordRight()},multiSelectAction:"forEach",scrollIntoView:"cursor"},{name:"outdent",bindKey:r("Shift-Tab","Shift-Tab"),exec:function(e){e.blockOutdent()},multiSelectAction:"forEach",scrollIntoView:"selectionPart"},{name:"indent",bindKey:r("Tab","Tab"),exec:function(e){e.indent()},multiSelectAction:"forEach",scrollIntoView:"selectionPart"},{name:"blockoutdent",bindKey:r("Ctrl-[","Ctrl-["),exec:function(e){e.blockOutdent()},multiSelectAction:"forEachLine",scrollIntoView:"selectionPart"},{name:"blockindent",bindKey:r("Ctrl-]","Ctrl-]"),exec:function(e){e.blockIndent()},multiSelectAction:"forEachLine",scrollIntoView:"selectionPart"},{name:"insertstring",exec:function(e,t){e.insert(t)},multiSelectAction:"forEach",scrollIntoView:"cursor"},{name:"inserttext",exec:function(e,t){e.insert(i.stringRepeat(t.text||"",t.times||1))},multiSelectAction:"forEach",scrollIntoView:"cursor"},{name:"splitline",bindKey:r(null,"Ctrl-O"),exec:function(e){e.splitLine()},multiSelectAction:"forEach",scrollIntoView:"cursor"},{name:"transposeletters",bindKey:r("Ctrl-T","Ctrl-T"),exec:function(e){e.transposeLetters()},multiSelectAction:function(e){e.transposeSelections(1)},scrollIntoView:"cursor"},{name:"touppercase",bindKey:r("Ctrl-U","Ctrl-U"),exec:function(e){e.toUpperCase()},multiSelectAction:"forEach",scrollIntoView:"cursor"},{name:"tolowercase",bindKey:r("Ctrl-Shift-U","Ctrl-Shift-U"),exec:function(e){e.toLowerCase()},multiSelectAction:"forEach",scrollIntoView:"cursor"}]}),define("ace/lib/event_emitter",["require","exports","module"],function(e,t,n){var r={},i=function(){this.propagationStopped=!0},s=function(){this.defaultPrevented=!0};r._emit=r._dispatchEvent=function(e,t){this._eventRegistry||(this._eventRegistry={}),this._defaultHandlers||(this._defaultHandlers={});var n=this._eventRegistry[e]||[],r=this._defaultHandlers[e];if(!n.length&&!r)return;if(typeof t!="object"||!t)t={};t.type||(t.type=e),t.stopPropagation||(t.stopPropagation=i),t.preventDefault||(t.preventDefault=s),n=n.slice();for(var o=0;o<n.length;o++){n[o](t,this);if(t.propagationStopped)break}if(r&&!t.defaultPrevented)return r(t,this)},r._signal=function(e,t){var n=(this._eventRegistry||{})[e];if(!n)return;n=n.slice();for(var r=0;r<n.length;r++)n[r](t,this)},r.once=function(e,t){var n=this;t&&this.addEventListener(e,function r(){n.removeEventListener(e,r),t.apply(null,arguments)})},r.setDefaultHandler=function(e,t){var n=this._defaultHandlers;n||(n=this._defaultHandlers={_disabled_:{}});if(n[e]){var r=n[e],i=n._disabled_[e];i||(n._disabled_[e]=i=[]),i.push(r);var s=i.indexOf(t);s!=-1&&i.splice(s,1)}n[e]=t},r.removeDefaultHandler=function(e,t){var n=this._defaultHandlers;if(!n)return;var r=n._disabled_[e];if(n[e]==t){var i=n[e];r&&this.setDefaultHandler(e,r.pop())}else if(r){var s=r.indexOf(t);s!=-1&&r.splice(s,1)}},r.on=r.addEventListener=function(e,t,n){this._eventRegistry=this._eventRegistry||{};var r=this._eventRegistry[e];return r||(r=this._eventRegistry[e]=[]),r.indexOf(t)==-1&&r[n?"unshift":"push"](t),t},r.off=r.removeListener=r.removeEventListener=function(e,t){this._eventRegistry=this._eventRegistry||{};var n=this._eventRegistry[e];if(!n)return;var r=n.indexOf(t);r!==-1&&n.splice(r,1)},r.removeAllListeners=function(e){this._eventRegistry&&(this._eventRegistry[e]=[])},t.EventEmitter=r}),define("ace/undomanager",["require","exports","module"],function(e,t,n){var r=function(){this.reset()};(function(){this.execute=function(e){var t=e.args[0];this.$doc=e.args[1],e.merge&&this.hasUndo()&&(this.dirtyCounter--,t=this.$undoStack.pop().concat(t)),this.$undoStack.push(t),this.$redoStack=[],this.dirtyCounter<0&&(this.dirtyCounter=NaN),this.dirtyCounter++},this.undo=function(e){var t=this.$undoStack.pop(),n=null;return t&&(n=this.$doc.undoChanges(t,e),this.$redoStack.push(t),this.dirtyCounter--),n},this.redo=function(e){var t=this.$redoStack.pop(),n=null;return t&&(n=this.$doc.redoChanges(t,e),this.$undoStack.push(t),this.dirtyCounter++),n},this.reset=function(){this.$undoStack=[],this.$redoStack=[],this.dirtyCounter=0},this.hasUndo=function(){return this.$undoStack.length>0},this.hasRedo=function(){return this.$redoStack.length>0},this.markClean=function(){this.dirtyCounter=0},this.isClean=function(){return this.dirtyCounter===0}}).call(r.prototype),t.UndoManager=r}),define("ace/lib/net",["require","exports","module","ace/lib/dom"],function(e,t,n){var r=e("./dom");t.get=function(e,t){var n=new XMLHttpRequest;n.open("GET",e,!0),n.onreadystatechange=function(){n.readyState===4&&t(n.responseText)},n.send(null)},t.loadScript=function(e,t){var n=r.getDocumentHead(),i=document.createElement("script");i.src=e,n.appendChild(i),i.onload=i.onreadystatechange=function(e,n){if(n||!i.readyState||i.readyState=="loaded"||i.readyState=="complete")i=i.onload=i.onreadystatechange=null,n||t()}}}),define("ace/virtual_renderer",["require","exports","module","ace/lib/oop","ace/lib/dom","ace/config","ace/layer/gutter","ace/layer/marker","ace/layer/text","ace/layer/cursor","ace/scrollbar","ace/renderloop","ace/layer/font_metrics","ace/lib/event_emitter"],function(e,t,n){var r=e("./lib/oop"),i=e("./lib/dom"),s=e("./config"),o=e("./layer/gutter").Gutter,u=e("./layer/marker").Marker,a=e("./layer/text").Text,f=e("./layer/cursor").Cursor,l=e("./scrollbar").HScrollBar,c=e("./scrollbar").VScrollBar,h=e("./renderloop").RenderLoop,p=e("./layer/font_metrics").FontMetrics,d=e("./lib/event_emitter").EventEmitter,v='.ace_editor {position: relative;overflow: hidden;font-family: \'Monaco\', \'Menlo\', \'Ubuntu Mono\', \'Consolas\', \'source-code-pro\', monospace;font-size: 12px;line-height: normal;direction: ltr;}.ace_scroller {position: absolute;overflow: hidden;top: 0;bottom: 0;background-color: inherit;-ms-user-select: none;-moz-user-select: none;-webkit-user-select: none;user-select: none;}.ace_content {position: absolute;-moz-box-sizing: border-box;-webkit-box-sizing: border-box;box-sizing: border-box;cursor: text;min-width: 100%;}.ace_dragging, .ace_dragging * {cursor: move !important;}.ace_dragging .ace_scroller:before{position: absolute;top: 0;left: 0;right: 0;bottom: 0;content: \'\';background: rgba(250, 250, 250, 0.01);z-index: 1000;}.ace_dragging.ace_dark .ace_scroller:before{background: rgba(0, 0, 0, 0.01);}.ace_selecting, .ace_selecting * {cursor: text !important;}.ace_gutter {position: absolute;overflow : hidden;width: auto;top: 0;bottom: 0;left: 0;cursor: default;z-index: 4;-ms-user-select: none;-moz-user-select: none;-webkit-user-select: none;user-select: none;}.ace_gutter-active-line {position: absolute;left: 0;right: 0;}.ace_scroller.ace_scroll-left {box-shadow: 17px 0 16px -16px rgba(0, 0, 0, 0.4) inset;}.ace_gutter-cell {padding-left: 19px;padding-right: 6px;background-repeat: no-repeat;}.ace_gutter-cell.ace_error {background-image: url("data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAMAAAAoLQ9TAAABOFBMVEX/////////QRswFAb/Ui4wFAYwFAYwFAaWGAfDRymzOSH/PxswFAb/SiUwFAYwFAbUPRvjQiDllog5HhHdRybsTi3/Tyv9Tir+Syj/UC3////XurebMBIwFAb/RSHbPx/gUzfdwL3kzMivKBAwFAbbvbnhPx66NhowFAYwFAaZJg8wFAaxKBDZurf/RB6mMxb/SCMwFAYwFAbxQB3+RB4wFAb/Qhy4Oh+4QifbNRcwFAYwFAYwFAb/QRzdNhgwFAYwFAbav7v/Uy7oaE68MBK5LxLewr/r2NXewLswFAaxJw4wFAbkPRy2PyYwFAaxKhLm1tMwFAazPiQwFAaUGAb/QBrfOx3bvrv/VC/maE4wFAbRPBq6MRO8Qynew8Dp2tjfwb0wFAbx6eju5+by6uns4uH9/f36+vr/GkHjAAAAYnRSTlMAGt+64rnWu/bo8eAA4InH3+DwoN7j4eLi4xP99Nfg4+b+/u9B/eDs1MD1mO7+4PHg2MXa347g7vDizMLN4eG+Pv7i5evs/v79yu7S3/DV7/498Yv24eH+4ufQ3Ozu/v7+y13sRqwAAADLSURBVHjaZc/XDsFgGIBhtDrshlitmk2IrbHFqL2pvXf/+78DPokj7+Fz9qpU/9UXJIlhmPaTaQ6QPaz0mm+5gwkgovcV6GZzd5JtCQwgsxoHOvJO15kleRLAnMgHFIESUEPmawB9ngmelTtipwwfASilxOLyiV5UVUyVAfbG0cCPHig+GBkzAENHS0AstVF6bacZIOzgLmxsHbt2OecNgJC83JERmePUYq8ARGkJx6XtFsdddBQgZE2nPR6CICZhawjA4Fb/chv+399kfR+MMMDGOQAAAABJRU5ErkJggg==");background-repeat: no-repeat;background-position: 2px center;}.ace_gutter-cell.ace_warning {background-image: url("data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAMAAAAoLQ9TAAAAmVBMVEX///8AAAD///8AAAAAAABPSzb/5sAAAAB/blH/73z/ulkAAAAAAAD85pkAAAAAAAACAgP/vGz/rkDerGbGrV7/pkQICAf////e0IsAAAD/oED/qTvhrnUAAAD/yHD/njcAAADuv2r/nz//oTj/p064oGf/zHAAAAA9Nir/tFIAAAD/tlTiuWf/tkIAAACynXEAAAAAAAAtIRW7zBpBAAAAM3RSTlMAABR1m7RXO8Ln31Z36zT+neXe5OzooRDfn+TZ4p3h2hTf4t3k3ucyrN1K5+Xaks52Sfs9CXgrAAAAjklEQVR42o3PbQ+CIBQFYEwboPhSYgoYunIqqLn6/z8uYdH8Vmdnu9vz4WwXgN/xTPRD2+sgOcZjsge/whXZgUaYYvT8QnuJaUrjrHUQreGczuEafQCO/SJTufTbroWsPgsllVhq3wJEk2jUSzX3CUEDJC84707djRc5MTAQxoLgupWRwW6UB5fS++NV8AbOZgnsC7BpEAAAAABJRU5ErkJggg==");background-position: 2px center;}.ace_gutter-cell.ace_info {background-image: url("data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAAAAAA6mKC9AAAAGXRFWHRTb2Z0d2FyZQBBZG9iZSBJbWFnZVJlYWR5ccllPAAAAAJ0Uk5TAAB2k804AAAAPklEQVQY02NgIB68QuO3tiLznjAwpKTgNyDbMegwisCHZUETUZV0ZqOquBpXj2rtnpSJT1AEnnRmL2OgGgAAIKkRQap2htgAAAAASUVORK5CYII=");background-position: 2px center;}.ace_dark .ace_gutter-cell.ace_info {background-image: url("data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABAAAAAQBAMAAADt3eJSAAAAJFBMVEUAAAChoaGAgIAqKiq+vr6tra1ZWVmUlJSbm5s8PDxubm56enrdgzg3AAAAAXRSTlMAQObYZgAAAClJREFUeNpjYMAPdsMYHegyJZFQBlsUlMFVCWUYKkAZMxZAGdxlDMQBAG+TBP4B6RyJAAAAAElFTkSuQmCC");}.ace_scrollbar {position: absolute;right: 0;bottom: 0;z-index: 6;}.ace_scrollbar-inner {position: absolute;cursor: text;left: 0;top: 0;}.ace_scrollbar-v{overflow-x: hidden;overflow-y: scroll;top: 0;}.ace_scrollbar-h {overflow-x: scroll;overflow-y: hidden;left: 0;}.ace_print-margin {position: absolute;height: 100%;}.ace_text-input {position: absolute;z-index: 0;width: 0.5em;height: 1em;opacity: 0;background: transparent;-moz-appearance: none;appearance: none;border: none;resize: none;outline: none;overflow: hidden;font: inherit;padding: 0 1px;margin: 0 -1px;text-indent: -1em;-ms-user-select: text;-moz-user-select: text;-webkit-user-select: text;user-select: text;}.ace_text-input.ace_composition {background: #f8f8f8;color: #111;z-index: 1000;opacity: 1;text-indent: 0;}.ace_layer {z-index: 1;position: absolute;overflow: hidden;white-space: pre;height: 100%;width: 100%;-moz-box-sizing: border-box;-webkit-box-sizing: border-box;box-sizing: border-box;/* setting pointer-events: auto; on node under the mouse, which changesduring scroll, will break mouse wheel scrolling in Safari */pointer-events: none;}.ace_gutter-layer {position: relative;width: auto;text-align: right;pointer-events: auto;}.ace_text-layer {font: inherit !important;}.ace_cjk {display: inline-block;text-align: center;}.ace_cursor-layer {z-index: 4;}.ace_cursor {z-index: 4;position: absolute;-moz-box-sizing: border-box;-webkit-box-sizing: border-box;box-sizing: border-box;border-left: 2px solid}.ace_slim-cursors .ace_cursor {border-left-width: 1px;}.ace_overwrite-cursors .ace_cursor {border-left-width: 0px;border-bottom: 1px solid;}.ace_hidden-cursors .ace_cursor {opacity: 0.2;}.ace_smooth-blinking .ace_cursor {-moz-transition: opacity 0.18s;-webkit-transition: opacity 0.18s;-o-transition: opacity 0.18s;-ms-transition: opacity 0.18s;transition: opacity 0.18s;}.ace_editor.ace_multiselect .ace_cursor {border-left-width: 1px;}.ace_marker-layer .ace_step, .ace_marker-layer .ace_stack {position: absolute;z-index: 3;}.ace_marker-layer .ace_selection {position: absolute;z-index: 5;}.ace_marker-layer .ace_bracket {position: absolute;z-index: 6;}.ace_marker-layer .ace_active-line {position: absolute;z-index: 2;}.ace_marker-layer .ace_selected-word {position: absolute;z-index: 4;-moz-box-sizing: border-box;-webkit-box-sizing: border-box;box-sizing: border-box;}.ace_line .ace_fold {-moz-box-sizing: border-box;-webkit-box-sizing: border-box;box-sizing: border-box;display: inline-block;height: 11px;margin-top: -2px;vertical-align: middle;background-image:url("data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABEAAAAJCAYAAADU6McMAAAAGXRFWHRTb2Z0d2FyZQBBZG9iZSBJbWFnZVJlYWR5ccllPAAAAJpJREFUeNpi/P//PwOlgAXGYGRklAVSokD8GmjwY1wasKljQpYACtpCFeADcHVQfQyMQAwzwAZI3wJKvCLkfKBaMSClBlR7BOQikCFGQEErIH0VqkabiGCAqwUadAzZJRxQr/0gwiXIal8zQQPnNVTgJ1TdawL0T5gBIP1MUJNhBv2HKoQHHjqNrA4WO4zY0glyNKLT2KIfIMAAQsdgGiXvgnYAAAAASUVORK5CYII="),url("data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAA3CAYAAADNNiA5AAAAGXRFWHRTb2Z0d2FyZQBBZG9iZSBJbWFnZVJlYWR5ccllPAAAACJJREFUeNpi+P//fxgTAwPDBxDxD078RSX+YeEyDFMCIMAAI3INmXiwf2YAAAAASUVORK5CYII=");background-repeat: no-repeat, repeat-x;background-position: center center, top left;color: transparent;border: 1px solid black;-moz-border-radius: 2px;-webkit-border-radius: 2px;border-radius: 2px;cursor: pointer;pointer-events: auto;}.ace_dark .ace_fold {}.ace_fold:hover{background-image:url("data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABEAAAAJCAYAAADU6McMAAAAGXRFWHRTb2Z0d2FyZQBBZG9iZSBJbWFnZVJlYWR5ccllPAAAAJpJREFUeNpi/P//PwOlgAXGYGRklAVSokD8GmjwY1wasKljQpYACtpCFeADcHVQfQyMQAwzwAZI3wJKvCLkfKBaMSClBlR7BOQikCFGQEErIH0VqkabiGCAqwUadAzZJRxQr/0gwiXIal8zQQPnNVTgJ1TdawL0T5gBIP1MUJNhBv2HKoQHHjqNrA4WO4zY0glyNKLT2KIfIMAAQsdgGiXvgnYAAAAASUVORK5CYII="),url("data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAA3CAYAAADNNiA5AAAAGXRFWHRTb2Z0d2FyZQBBZG9iZSBJbWFnZVJlYWR5ccllPAAAACBJREFUeNpi+P//fz4TAwPDZxDxD5X4i5fLMEwJgAADAEPVDbjNw87ZAAAAAElFTkSuQmCC");}.ace_tooltip {background-color: #FFF;background-image: -webkit-linear-gradient(top, transparent, rgba(0, 0, 0, 0.1));background-image: linear-gradient(to bottom, transparent, rgba(0, 0, 0, 0.1));border: 1px solid gray;border-radius: 1px;box-shadow: 0 1px 2px rgba(0, 0, 0, 0.3);color: black;display: block;max-width: 100%;padding: 3px 4px;position: fixed;z-index: 999999;-moz-box-sizing: border-box;-webkit-box-sizing: border-box;box-sizing: border-box;cursor: default;white-space: pre;word-wrap: break-word;line-height: normal;font-style: normal;font-weight: normal;letter-spacing: normal;pointer-events: none;}.ace_folding-enabled > .ace_gutter-cell {padding-right: 13px;}.ace_fold-widget {-moz-box-sizing: border-box;-webkit-box-sizing: border-box;box-sizing: border-box;margin: 0 -12px 0 1px;display: none;width: 11px;vertical-align: top;background-image: url("data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAUAAAAFCAYAAACNbyblAAAANElEQVR42mWKsQ0AMAzC8ixLlrzQjzmBiEjp0A6WwBCSPgKAXoLkqSot7nN3yMwR7pZ32NzpKkVoDBUxKAAAAABJRU5ErkJggg==");background-repeat: no-repeat;background-position: center;border-radius: 3px;border: 1px solid transparent;cursor: pointer;}.ace_folding-enabled .ace_fold-widget {display: inline-block; }.ace_fold-widget.ace_end {background-image: url("data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAUAAAAFCAYAAACNbyblAAAANElEQVR42m3HwQkAMAhD0YzsRchFKI7sAikeWkrxwScEB0nh5e7KTPWimZki4tYfVbX+MNl4pyZXejUO1QAAAABJRU5ErkJggg==");}.ace_fold-widget.ace_closed {background-image: url("data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAMAAAAGCAYAAAAG5SQMAAAAOUlEQVR42jXKwQkAMAgDwKwqKD4EwQ26sSOkVWjgIIHAzPiCgaqiqnJHZnKICBERHN194O5b9vbLuAVRL+l0YWnZAAAAAElFTkSuQmCCXA==");}.ace_fold-widget:hover {border: 1px solid rgba(0, 0, 0, 0.3);background-color: rgba(255, 255, 255, 0.2);-moz-box-shadow: 0 1px 1px rgba(255, 255, 255, 0.7);-webkit-box-shadow: 0 1px 1px rgba(255, 255, 255, 0.7);box-shadow: 0 1px 1px rgba(255, 255, 255, 0.7);}.ace_fold-widget:active {border: 1px solid rgba(0, 0, 0, 0.4);background-color: rgba(0, 0, 0, 0.05);-moz-box-shadow: 0 1px 1px rgba(255, 255, 255, 0.8);-webkit-box-shadow: 0 1px 1px rgba(255, 255, 255, 0.8);box-shadow: 0 1px 1px rgba(255, 255, 255, 0.8);}/*** Dark version for fold widgets*/.ace_dark .ace_fold-widget {background-image: url("data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAUAAAAFCAYAAACNbyblAAAAHklEQVQIW2P4//8/AzoGEQ7oGCaLLAhWiSwB146BAQCSTPYocqT0AAAAAElFTkSuQmCC");}.ace_dark .ace_fold-widget.ace_end {background-image: url("data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAUAAAAFCAYAAACNbyblAAAAH0lEQVQIW2P4//8/AxQ7wNjIAjDMgC4AxjCVKBirIAAF0kz2rlhxpAAAAABJRU5ErkJggg==");}.ace_dark .ace_fold-widget.ace_closed {background-image: url("data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAMAAAAFCAYAAACAcVaiAAAAHElEQVQIW2P4//+/AxAzgDADlOOAznHAKgPWAwARji8UIDTfQQAAAABJRU5ErkJggg==");}.ace_dark .ace_fold-widget:hover {box-shadow: 0 1px 1px rgba(255, 255, 255, 0.2);background-color: rgba(255, 255, 255, 0.1);}.ace_dark .ace_fold-widget:active {-moz-box-shadow: 0 1px 1px rgba(255, 255, 255, 0.2);-webkit-box-shadow: 0 1px 1px rgba(255, 255, 255, 0.2);box-shadow: 0 1px 1px rgba(255, 255, 255, 0.2);}.ace_fold-widget.ace_invalid {background-color: #FFB4B4;border-color: #DE5555;}.ace_fade-fold-widgets .ace_fold-widget {-moz-transition: opacity 0.4s ease 0.05s;-webkit-transition: opacity 0.4s ease 0.05s;-o-transition: opacity 0.4s ease 0.05s;-ms-transition: opacity 0.4s ease 0.05s;transition: opacity 0.4s ease 0.05s;opacity: 0;}.ace_fade-fold-widgets:hover .ace_fold-widget {-moz-transition: opacity 0.05s ease 0.05s;-webkit-transition: opacity 0.05s ease 0.05s;-o-transition: opacity 0.05s ease 0.05s;-ms-transition: opacity 0.05s ease 0.05s;transition: opacity 0.05s ease 0.05s;opacity:1;}.ace_underline {text-decoration: underline;}.ace_bold {font-weight: bold;}.ace_nobold .ace_bold {font-weight: normal;}.ace_italic {font-style: italic;}.ace_error-marker {background-color: rgba(255, 0, 0,0.2);position: absolute;z-index: 9;}.ace_highlight-marker {background-color: rgba(255, 255, 0,0.2);position: absolute;z-index: 8;}';i.importCssString(v,"ace_editor");var m=function(e,t){var n=this;this.container=e||i.createElement("div"),this.$keepTextAreaAtCursor=!0,i.addCssClass(this.container,"ace_editor"),this.setTheme(t),this.$gutter=i.createElement("div"),this.$gutter.className="ace_gutter",this.container.appendChild(this.$gutter),this.scroller=i.createElement("div"),this.scroller.className="ace_scroller",this.container.appendChild(this.scroller),this.content=i.createElement("div"),this.content.className="ace_content",this.scroller.appendChild(this.content),this.$gutterLayer=new o(this.$gutter),this.$gutterLayer.on("changeGutterWidth",this.onGutterResize.bind(this)),this.$markerBack=new u(this.content);var r=this.$textLayer=new a(this.content);this.canvas=r.element,this.$markerFront=new u(this.content),this.$cursorLayer=new f(this.content),this.$horizScroll=!1,this.$vScroll=!1,this.scrollBar=this.scrollBarV=new c(this.container,this),this.scrollBarH=new l(this.container,this),this.scrollBarV.addEventListener("scroll",function(e){n.$scrollAnimation||n.session.setScrollTop(e.data-n.scrollMargin.top)}),this.scrollBarH.addEventListener("scroll",function(e){n.$scrollAnimation||n.session.setScrollLeft(e.data-n.scrollMargin.left)}),this.scrollTop=0,this.scrollLeft=0,this.cursorPos={row:0,column:0},this.$fontMetrics=new p(this.container,500),this.$textLayer.$setFontMetrics(this.$fontMetrics),this.$textLayer.addEventListener("changeCharacterSize",function(e){n.updateCharacterSize(),n.onResize(!0,n.gutterWidth,n.$size.width,n.$size.height),n._signal("changeCharacterSize",e)}),this.$size={width:0,height:0,scrollerHeight:0,scrollerWidth:0,$dirty:!0},this.layerConfig={width:1,padding:0,firstRow:0,firstRowScreen:0,lastRow:0,lineHeight:0,characterWidth:0,minHeight:1,maxHeight:1,offset:0,height:1,gutterOffset:1},this.scrollMargin={left:0,right:0,top:0,bottom:0,v:0,h:0},this.$loop=new h(this.$renderChanges.bind(this),this.container.ownerDocument.defaultView),this.$loop.schedule(this.CHANGE_FULL),this.updateCharacterSize(),this.setPadding(4),s.resetOptions(this),s._emit("renderer",this)};(function(){this.CHANGE_CURSOR=1,this.CHANGE_MARKER=2,this.CHANGE_GUTTER=4,this.CHANGE_SCROLL=8,this.CHANGE_LINES=16,this.CHANGE_TEXT=32,this.CHANGE_SIZE=64,this.CHANGE_MARKER_BACK=128,this.CHANGE_MARKER_FRONT=256,this.CHANGE_FULL=512,this.CHANGE_H_SCROLL=1024,r.implement(this,d),this.updateCharacterSize=function(){this.$textLayer.allowBoldFonts!=this.$allowBoldFonts&&(this.$allowBoldFonts=this.$textLayer.allowBoldFonts,this.setStyle("ace_nobold",!this.$allowBoldFonts)),this.layerConfig.characterWidth=this.characterWidth=this.$textLayer.getCharacterWidth(),this.layerConfig.lineHeight=this.lineHeight=this.$textLayer.getLineHeight(),this.$updatePrintMargin()},this.setSession=function(e){this.session&&this.session.doc.off("changeNewLineMode",this.onChangeNewLineMode),this.session=e;if(!e)return;this.scrollMargin.top&&e.getScrollTop()<=0&&e.setScrollTop(-this.scrollMargin.top),this.$cursorLayer.setSession(e),this.$markerBack.setSession(e),this.$markerFront.setSession(e),this.$gutterLayer.setSession(e),this.$textLayer.setSession(e),this.$loop.schedule(this.CHANGE_FULL),this.session.$setFontMetrics(this.$fontMetrics),this.onChangeNewLineMode=this.onChangeNewLineMode.bind(this),this.onChangeNewLineMode(),this.session.doc.on("changeNewLineMode",this.onChangeNewLineMode)},this.updateLines=function(e,t){t===undefined&&(t=Infinity),this.$changedLines?(this.$changedLines.firstRow>e&&(this.$changedLines.firstRow=e),this.$changedLines.lastRow<t&&(this.$changedLines.lastRow=t)):this.$changedLines={firstRow:e,lastRow:t};if(this.$changedLines.firstRow>this.layerConfig.lastRow||this.$changedLines.lastRow<this.layerConfig.firstRow)return;this.$loop.schedule(this.CHANGE_LINES)},this.onChangeNewLineMode=function(){this.$loop.schedule(this.CHANGE_TEXT),this.$textLayer.$updateEolChar()},this.onChangeTabSize=function(){this.$loop.schedule(this.CHANGE_TEXT|this.CHANGE_MARKER),this.$textLayer.onChangeTabSize()},this.updateText=function(){this.$loop.schedule(this.CHANGE_TEXT)},this.updateFull=function(e){e?this.$renderChanges(this.CHANGE_FULL,!0):this.$loop.schedule(this.CHANGE_FULL)},this.updateFontSize=function(){this.$textLayer.checkForSizeChanges()},this.$changes=0,this.$updateSizeAsync=function(){this.$loop.pending?this.$size.$dirty=!0:this.onResize()},this.onResize=function(e,t,n,r){if(this.resizing>2)return;this.resizing>0?this.resizing++:this.resizing=e?1:0;var i=this.container;r||(r=i.clientHeight||i.scrollHeight),n||(n=i.clientWidth||i.scrollWidth);var s=this.$updateCachedSize(e,t,n,r);if(!this.$size.scrollerHeight||!n&&!r)return this.resizing=0;e&&(this.$gutterLayer.$padding=null),e?this.$renderChanges(s|this.$changes,!0):this.$loop.schedule(s|this.$changes),this.resizing&&(this.resizing=0)},this.$updateCachedSize=function(e,t,n,r){r-=this.$extraHeight||0;var i=0,s=this.$size,o={width:s.width,height:s.height,scrollerHeight:s.scrollerHeight,scrollerWidth:s.scrollerWidth};r&&(e||s.height!=r)&&(s.height=r,i|=this.CHANGE_SIZE,s.scrollerHeight=s.height,this.$horizScroll&&(s.scrollerHeight-=this.scrollBarH.getHeight()),this.scrollBarV.element.style.bottom=this.scrollBarH.getHeight()+"px",i|=this.CHANGE_SCROLL);if(n&&(e||s.width!=n)){i|=this.CHANGE_SIZE,s.width=n,t==null&&(t=this.$showGutter?this.$gutter.offsetWidth:0),this.gutterWidth=t,this.scrollBarH.element.style.left=this.scroller.style.left=t+"px",s.scrollerWidth=Math.max(0,n-t-this.scrollBarV.getWidth()),this.scrollBarH.element.style.right=this.scroller.style.right=this.scrollBarV.getWidth()+"px",this.scroller.style.bottom=this.scrollBarH.getHeight()+"px";if(this.session&&this.session.getUseWrapMode()&&this.adjustWrapLimit()||e)i|=this.CHANGE_FULL}return s.$dirty=!n||!r,i&&this._signal("resize",o),i},this.onGutterResize=function(){var e=this.$showGutter?this.$gutter.offsetWidth:0;e!=this.gutterWidth&&(this.$changes|=this.$updateCachedSize(!0,e,this.$size.width,this.$size.height)),this.session.getUseWrapMode()&&this.adjustWrapLimit()?this.$loop.schedule(this.CHANGE_FULL):this.$size.$dirty?this.$loop.schedule(this.CHANGE_FULL):(this.$computeLayerConfig(),this.$loop.schedule(this.CHANGE_MARKER))},this.adjustWrapLimit=function(){var e=this.$size.scrollerWidth-this.$padding*2,t=Math.floor(e/this.characterWidth);return this.session.adjustWrapLimit(t,this.$showPrintMargin&&this.$printMarginColumn)},this.setAnimatedScroll=function(e){this.setOption("animatedScroll",e)},this.getAnimatedScroll=function(){return this.$animatedScroll},this.setShowInvisibles=function(e){this.setOption("showInvisibles",e)},this.getShowInvisibles=function(){return this.getOption("showInvisibles")},this.getDisplayIndentGuides=function(){return this.getOption("displayIndentGuides")},this.setDisplayIndentGuides=function(e){this.setOption("displayIndentGuides",e)},this.setShowPrintMargin=function(e){this.setOption("showPrintMargin",e)},this.getShowPrintMargin=function(){return this.getOption("showPrintMargin")},this.setPrintMarginColumn=function(e){this.setOption("printMarginColumn",e)},this.getPrintMarginColumn=function(){return this.getOption("printMarginColumn")},this.getShowGutter=function(){return this.getOption("showGutter")},this.setShowGutter=function(e){return this.setOption("showGutter",e)},this.getFadeFoldWidgets=function(){return this.getOption("fadeFoldWidgets")},this.setFadeFoldWidgets=function(e){this.setOption("fadeFoldWidgets",e)},this.setHighlightGutterLine=function(e){this.setOption("highlightGutterLine",e)},this.getHighlightGutterLine=function(){return this.getOption("highlightGutterLine")},this.$updateGutterLineHighlight=function(){var e=this.$cursorLayer.$pixelPos,t=this.layerConfig.lineHeight;if(this.session.getUseWrapMode()){var n=this.session.selection.getCursor();n.column=0,e=this.$cursorLayer.getPixelPosition(n,!0),t*=this.session.getRowLength(n.row)}this.$gutterLineHighlight.style.top=e.top-this.layerConfig.offset+"px",this.$gutterLineHighlight.style.height=t+"px"},this.$updatePrintMargin=function(){if(!this.$showPrintMargin&&!this.$printMarginEl)return;if(!this.$printMarginEl){var e=i.createElement("div");e.className="ace_layer ace_print-margin-layer",this.$printMarginEl=i.createElement("div"),this.$printMarginEl.className="ace_print-margin",e.appendChild(this.$printMarginEl),this.content.insertBefore(e,this.content.firstChild)}var t=this.$printMarginEl.style;t.left=this.characterWidth*this.$printMarginColumn+this.$padding+"px",t.visibility=this.$showPrintMargin?"visible":"hidden",this.session&&this.session.$wrap==-1&&this.adjustWrapLimit()},this.getContainerElement=function(){return this.container},this.getMouseEventTarget=function(){return this.content},this.getTextAreaContainer=function(){return this.container},this.$moveTextAreaToCursor=function(){if(!this.$keepTextAreaAtCursor)return;var e=this.layerConfig,t=this.$cursorLayer.$pixelPos.top,n=this.$cursorLayer.$pixelPos.left;t-=e.offset;var r=this.lineHeight;if(t<0||t>e.height-r)return;var i=this.characterWidth;if(this.$composition){var s=this.textarea.value.replace(/^\x01+/,"");i*=this.session.$getStringScreenWidth(s)[0]+2,r+=2,t-=1}n-=this.scrollLeft,n>this.$size.scrollerWidth-i&&(n=this.$size.scrollerWidth-i),n-=this.scrollBar.width,this.textarea.style.height=r+"px",this.textarea.style.width=i+"px",this.textarea.style.right=Math.max(0,this.$size.scrollerWidth-n-i)+"px",this.textarea.style.bottom=Math.max(0,this.$size.height-t-r)+"px"},this.getFirstVisibleRow=function(){return this.layerConfig.firstRow},this.getFirstFullyVisibleRow=function(){return this.layerConfig.firstRow+(this.layerConfig.offset===0?0:1)},this.getLastFullyVisibleRow=function(){var e=Math.floor((this.layerConfig.height+this.layerConfig.offset)/this.layerConfig.lineHeight);return this.layerConfig.firstRow-1+e},this.getLastVisibleRow=function(){return this.layerConfig.lastRow},this.$padding=null,this.setPadding=function(e){this.$padding=e,this.$textLayer.setPadding(e),this.$cursorLayer.setPadding(e),this.$markerFront.setPadding(e),this.$markerBack.setPadding(e),this.$loop.schedule(this.CHANGE_FULL),this.$updatePrintMargin()},this.setScrollMargin=function(e,t,n,r){var i=this.scrollMargin;i.top=e|0,i.bottom=t|0,i.right=r|0,i.left=n|0,i.v=i.top+i.bottom,i.h=i.left+i.right,i.top&&this.scrollTop<=0&&this.session&&this.session.setScrollTop(-i.top),this.updateFull()},this.getHScrollBarAlwaysVisible=function(){return this.$hScrollBarAlwaysVisible},this.setHScrollBarAlwaysVisible=function(e){this.setOption("hScrollBarAlwaysVisible",e)},this.getVScrollBarAlwaysVisible=function(){return this.$hScrollBarAlwaysVisible},this.setVScrollBarAlwaysVisible=function(e){this.setOption("vScrollBarAlwaysVisible",e)},this.$updateScrollBarV=function(){this.scrollBarV.setScrollHeight(this.layerConfig.maxHeight+this.scrollMargin.v),this.scrollBarV.setScrollTop(this.scrollTop+this.scrollMargin.top)},this.$updateScrollBarH=function(){this.scrollBarH.setScrollWidth(this.layerConfig.width+2*this.$padding+this.scrollMargin.h),this.scrollBarH.setScrollLeft(this.scrollLeft+this.scrollMargin.left)},this.$frozen=!1,this.freeze=function(){this.$frozen=!0},this.unfreeze=function(){this.$frozen=!1},this.$renderChanges=function(e,t){this.$changes&&(e|=this.$changes,this.$changes=0);if(!this.session||!this.container.offsetWidth||this.$frozen||!e&&!t){this.$changes|=e;return}if(this.$size.$dirty)return this.$changes|=e,this.onResize(!0);this.lineHeight||this.$textLayer.checkForSizeChanges(),this._signal("beforeRender");var n=this.layerConfig;if(e&this.CHANGE_FULL||e&this.CHANGE_SIZE||e&this.CHANGE_TEXT||e&this.CHANGE_LINES||e&this.CHANGE_SCROLL||e&this.CHANGE_H_SCROLL)e|=this.$computeLayerConfig(),n=this.layerConfig,this.$updateScrollBarV(),e&this.CHANGE_H_SCROLL&&this.$updateScrollBarH(),this.$gutterLayer.element.style.marginTop=-n.offset+"px",this.content.style.marginTop=-n.offset+"px",this.content.style.width=n.width+2*this.$padding+"px",this.content.style.height=n.minHeight+"px";e&this.CHANGE_H_SCROLL&&(this.content.style.marginLeft=-this.scrollLeft+"px",this.scroller.className=this.scrollLeft<=0?"ace_scroller":"ace_scroller ace_scroll-left");if(e&this.CHANGE_FULL){this.$textLayer.update(n),this.$showGutter&&this.$gutterLayer.update(n),this.$markerBack.update(n),this.$markerFront.update(n),this.$cursorLayer.update(n),this.$moveTextAreaToCursor(),this.$highlightGutterLine&&this.$updateGutterLineHighlight(),this._signal("afterRender");return}if(e&this.CHANGE_SCROLL){e&this.CHANGE_TEXT||e&this.CHANGE_LINES?this.$textLayer.update(n):this.$textLayer.scrollLines(n),this.$showGutter&&this.$gutterLayer.update(n),this.$markerBack.update(n),this.$markerFront.update(n),this.$cursorLayer.update(n),this.$highlightGutterLine&&this.$updateGutterLineHighlight(),this.$moveTextAreaToCursor(),this._signal("afterRender");return}e&this.CHANGE_TEXT?(this.$textLayer.update(n),this.$showGutter&&this.$gutterLayer.update(n)):e&this.CHANGE_LINES?(this.$updateLines()||e&this.CHANGE_GUTTER&&this.$showGutter)&&this.$gutterLayer.update(n):(e&this.CHANGE_TEXT||e&this.CHANGE_GUTTER)&&this.$showGutter&&this.$gutterLayer.update(n),e&this.CHANGE_CURSOR&&(this.$cursorLayer.update(n),this.$moveTextAreaToCursor(),this.$highlightGutterLine&&this.$updateGutterLineHighlight()),e&(this.CHANGE_MARKER|this.CHANGE_MARKER_FRONT)&&this.$markerFront.update(n),e&(this.CHANGE_MARKER|this.CHANGE_MARKER_BACK)&&this.$markerBack.update(n),this._signal("afterRender")},this.$autosize=function(){var e=this.session.getScreenLength()*this.lineHeight,t=this.$maxLines*this.lineHeight,n=Math.max((this.$minLines||1)*this.lineHeight,Math.min(t,e))+this.scrollMargin.v+(this.$extraHeight||0),r=e>t;if(n!=this.desiredHeight||this.$size.height!=this.desiredHeight||r!=this.$vScroll){r!=this.$vScroll&&(this.$vScroll=r,this.scrollBarV.setVisible(r));var i=this.container.clientWidth;this.container.style.height=n+"px",this.$updateCachedSize(!0,this.$gutterWidth,i,n),this.desiredHeight=n}},this.$computeLayerConfig=function(){this.$maxLines&&this.lineHeight>1&&this.$autosize();var e=this.session,t=this.$size,n=t.height<=2*this.lineHeight,r=this.session.getScreenLength(),i=r*this.lineHeight,s=this.scrollTop%this.lineHeight,o=t.scrollerHeight+this.lineHeight,u=this.$getLongestLine(),a=!n&&(this.$hScrollBarAlwaysVisible||t.scrollerWidth-u-2*this.$padding<0),f=this.$horizScroll!==a;f&&(this.$horizScroll=a,this.scrollBarH.setVisible(a)),!this.$maxLines&&this.$scrollPastEnd&&this.scrollTop>i-t.scrollerHeight&&(i+=Math.min((t.scrollerHeight-this.lineHeight)*this.$scrollPastEnd,this.scrollTop-i+t.scrollerHeight));var l=!n&&(this.$vScrollBarAlwaysVisible||t.scrollerHeight-i<0),c=this.$vScroll!==l;c&&(this.$vScroll=l,this.scrollBarV.setVisible(l)),this.session.setScrollTop(Math.max(-this.scrollMargin.top,Math.min(this.scrollTop,i-t.scrollerHeight+this.scrollMargin.bottom))),this.session.setScrollLeft(Math.max(-this.scrollMargin.left,Math.min(this.scrollLeft,u+2*this.$padding-t.scrollerWidth+this.scrollMargin.right)));var h=Math.ceil(o/this.lineHeight)-1,p=Math.max(0,Math.round((this.scrollTop-s)/this.lineHeight)),d=p+h,v,m,g=this.lineHeight;p=e.screenToDocumentRow(p,0);var y=e.getFoldLine(p);y&&(p=y.start.row),v=e.documentToScreenRow(p,0),m=e.getRowLength(p)*g,d=Math.min(e.screenToDocumentRow(d,0),e.getLength()-1),o=t.scrollerHeight+e.getRowLength(d)*g+m,s=this.scrollTop-v*g;var b=0;this.layerConfig.width!=u&&(b=this.CHANGE_H_SCROLL);if(f||c)b=this.$updateCachedSize(!0,this.gutterWidth,t.width,t.height),this._signal("scrollbarVisibilityChanged"),c&&(u=this.$getLongestLine());return this.layerConfig={width:u,padding:this.$padding,firstRow:p,firstRowScreen:v,lastRow:d,lineHeight:g,characterWidth:this.characterWidth,minHeight:o,maxHeight:i,offset:s,gutterOffset:Math.max(0,Math.ceil((s+t.height-t.scrollerHeight)/g)),height:this.$size.scrollerHeight},b},this.$updateLines=function(){var e=this.$changedLines.firstRow,t=this.$changedLines.lastRow;this.$changedLines=null;var n=this.layerConfig;if(e>n.lastRow+1)return;if(t<n.firstRow)return;if(t===Infinity){this.$showGutter&&this.$gutterLayer.update(n),this.$textLayer.update(n);return}return this.$textLayer.updateLines(n,e,t),!0},this.$getLongestLine=function(){var e=this.session.getScreenWidth();return this.showInvisibles&&!this.session.$useWrapMode&&(e+=1),Math.max(this.$size.scrollerWidth-2*this.$padding,Math.round(e*this.characterWidth))},this.updateFrontMarkers=function(){this.$markerFront.setMarkers(this.session.getMarkers(!0)),this.$loop.schedule(this.CHANGE_MARKER_FRONT)},this.updateBackMarkers=function(){this.$markerBack.setMarkers(this.session.getMarkers()),this.$loop.schedule(this.CHANGE_MARKER_BACK)},this.addGutterDecoration=function(e,t){this.$gutterLayer.addGutterDecoration(e,t)},this.removeGutterDecoration=function(e,t){this.$gutterLayer.removeGutterDecoration(e,t)},this.updateBreakpoints=function(e){this.$loop.schedule(this.CHANGE_GUTTER)},this.setAnnotations=function(e){this.$gutterLayer.setAnnotations(e),this.$loop.schedule(this.CHANGE_GUTTER)},this.updateCursor=function(){this.$loop.schedule(this.CHANGE_CURSOR)},this.hideCursor=function(){this.$cursorLayer.hideCursor()},this.showCursor=function(){this.$cursorLayer.showCursor()},this.scrollSelectionIntoView=function(e,t,n){this.scrollCursorIntoView(e,n),this.scrollCursorIntoView(t,n)},this.scrollCursorIntoView=function(e,t,n){if(this.$size.scrollerHeight===0)return;var r=this.$cursorLayer.getPixelPosition(e),i=r.left,s=r.top,o=n&&n.top||0,u=n&&n.bottom||0,a=this.$scrollAnimation?this.session.getScrollTop():this.scrollTop;a+o>s?(t&&(s-=t*this.$size.scrollerHeight),s===0&&(s=-this.scrollMargin.top),this.session.setScrollTop(s)):a+this.$size.scrollerHeight-u<s+this.lineHeight&&(t&&(s+=t*this.$size.scrollerHeight),this.session.setScrollTop(s+this.lineHeight-this.$size.scrollerHeight));var f=this.scrollLeft;f>i?(i<this.$padding+2*this.layerConfig.characterWidth&&(i=-this.scrollMargin.left),this.session.setScrollLeft(i)):f+this.$size.scrollerWidth<i+this.characterWidth?this.session.setScrollLeft(Math.round(i+this.characterWidth-this.$size.scrollerWidth)):f<=this.$padding&&i-f<this.characterWidth&&this.session.setScrollLeft(0)},this.getScrollTop=function(){return this.session.getScrollTop()},this.getScrollLeft=function(){return this.session.getScrollLeft()},this.getScrollTopRow=function(){return this.scrollTop/this.lineHeight},this.getScrollBottomRow=function(){return Math.max(0,Math.floor((this.scrollTop+this.$size.scrollerHeight)/this.lineHeight)-1)},this.scrollToRow=function(e){this.session.setScrollTop(e*this.lineHeight)},this.alignCursor=function(e,t){typeof e=="number"&&(e={row:e,column:0});var n=this.$cursorLayer.getPixelPosition(e),r=this.$size.scrollerHeight-this.lineHeight,i=n.top-r*(t||0);return this.session.setScrollTop(i),i},this.STEPS=8,this.$calcSteps=function(e,t){var n=0,r=this.STEPS,i=[],s=function(e,t,n){return n*(Math.pow(e-1,3)+1)+t};for(n=0;n<r;++n)i.push(s(n/this.STEPS,e,t-e));return i},this.scrollToLine=function(e,t,n,r){var i=this.$cursorLayer.getPixelPosition({row:e,column:0}),s=i.top;t&&(s-=this.$size.scrollerHeight/2);var o=this.scrollTop;this.session.setScrollTop(s),n!==!1&&this.animateScrolling(o,r)},this.animateScrolling=function(e,t){var n=this.scrollTop;if(!this.$animatedScroll)return;var r=this;if(e==n)return;if(this.$scrollAnimation){var i=this.$scrollAnimation.steps;if(i.length){e=i[0];if(e==n)return}}var s=r.$calcSteps(e,n);this.$scrollAnimation={from:e,to:n,steps:s},clearInterval(this.$timer),r.session.setScrollTop(s.shift()),r.session.$scrollTop=n,this.$timer=setInterval(function(){s.length?(r.session.setScrollTop(s.shift()),r.session.$scrollTop=n):n!=null?(r.session.$scrollTop=-1,r.session.setScrollTop(n),n=null):(r.$timer=clearInterval(r.$timer),r.$scrollAnimation=null,t&&t())},10)},this.scrollToY=function(e){this.scrollTop!==e&&(this.$loop.schedule(this.CHANGE_SCROLL),this.scrollTop=e)},this.scrollToX=function(e){this.scrollLeft!==e&&(this.scrollLeft=e),this.$loop.schedule(this.CHANGE_H_SCROLL)},this.scrollTo=function(e,t){this.session.setScrollTop(t),this.session.setScrollLeft(t)},this.scrollBy=function(e,t){t&&this.session.setScrollTop(this.session.getScrollTop()+t),e&&this.session.setScrollLeft(this.session.getScrollLeft()+e)},this.isScrollableBy=function(e,t){if(t<0&&this.session.getScrollTop()>=1-this.scrollMargin.top)return!0;if(t>0&&this.session.getScrollTop()+this.$size.scrollerHeight-this.layerConfig.maxHeight-(this.$size.scrollerHeight-this.lineHeight)*this.$scrollPastEnd<-1+this.scrollMargin.bottom)return!0;if(e<0&&this.session.getScrollLeft()>=1-this.scrollMargin.left)return!0;if(e>0&&this.session.getScrollLeft()+this.$size.scrollerWidth-this.layerConfig.width<-1+this.scrollMargin.right)return!0},this.pixelToScreenCoordinates=function(e,t){var n=this.scroller.getBoundingClientRect(),r=(e+this.scrollLeft-n.left-this.$padding)/this.characterWidth,i=Math.floor((t+this.scrollTop-n.top)/this.lineHeight),s=Math.round(r);return{row:i,column:s,side:r-s>0?1:-1}},this.screenToTextCoordinates=function(e,t){var n=this.scroller.getBoundingClientRect(),r=Math.round((e+this.scrollLeft-n.left-this.$padding)/this.characterWidth),i=(t+this.scrollTop-n.top)/this.lineHeight;return this.session.screenToDocumentPosition(i,Math.max(r,0))},this.textToScreenCoordinates=function(e,t){var n=this.scroller.getBoundingClientRect(),r=this.session.documentToScreenPosition(e,t),i=this.$padding+Math.round(r.column*this.characterWidth),s=r.row*this.lineHeight;return{pageX:n.left+i-this.scrollLeft,pageY:n.top+s-this.scrollTop}},this.visualizeFocus=function(){i.addCssClass(this.container,"ace_focus")},this.visualizeBlur=function(){i.removeCssClass(this.container,"ace_focus")},this.showComposition=function(e){this.$composition||(this.$composition={keepTextAreaAtCursor:this.$keepTextAreaAtCursor,cssText:this.textarea.style.cssText}),this.$keepTextAreaAtCursor=!0,i.addCssClass(this.textarea,"ace_composition"),this.textarea.style.cssText="",this.$moveTextAreaToCursor()},this.setCompositionText=function(e){this.$moveTextAreaToCursor()},this.hideComposition=function(){if(!this.$composition)return;i.removeCssClass(this.textarea,"ace_composition"),this.$keepTextAreaAtCursor=this.$composition.keepTextAreaAtCursor,this.textarea.style.cssText=this.$composition.cssText,this.$composition=null},this.setTheme=function(e,t){function n(n){if(r.$themeId!=e)return t&&t();if(!n.cssClass)return;i.importCssString(n.cssText,n.cssClass,r.container.ownerDocument),r.theme&&i.removeCssClass(r.container,r.theme.cssClass);var s="padding"in n?n.padding:"padding"in(r.theme||{})?4:r.$padding;r.$padding&&s!=r.$padding&&r.setPadding(s),r.$theme=n.cssClass,r.theme=n,i.addCssClass(r.container,n.cssClass),i.setCssClass(r.container,"ace_dark",n.isDark),r.$size&&(r.$size.width=0,r.$updateSizeAsync()),r._dispatchEvent("themeLoaded",{theme:n}),t&&t()}var r=this;this.$themeId=e,r._dispatchEvent("themeChange",{theme:e});if(!e||typeof e=="string"){var o=e||this.$options.theme.initialValue;s.loadModule(["theme",o],n)}else n(e)},this.getTheme=function(){return this.$themeId},this.setStyle=function(e,t){i.setCssClass(this.container,e,t!==!1)},this.unsetStyle=function(e){i.removeCssClass(this.container,e)},this.setCursorStyle=function(e){this.content.style.cursor!=e&&(this.content.style.cursor=e)},this.setMouseCursor=function(e){this.content.style.cursor=e},this.destroy=function(){this.$textLayer.destroy(),this.$cursorLayer.destroy()}}).call(m.prototype),s.defineOptions(m.prototype,"renderer",{animatedScroll:{initialValue:!1},showInvisibles:{set:function(e){this.$textLayer.setShowInvisibles(e)&&this.$loop.schedule(this.CHANGE_TEXT)},initialValue:!1},showPrintMargin:{set:function(){this.$updatePrintMargin()},initialValue:!0},printMarginColumn:{set:function(){this.$updatePrintMargin()},initialValue:80},printMargin:{set:function(e){typeof e=="number"&&(this.$printMarginColumn=e),this.$showPrintMargin=!!e,this.$updatePrintMargin()},get:function(){return this.$showPrintMargin&&this.$printMarginColumn}},showGutter:{set:function(e){this.$gutter.style.display=e?"block":"none",this.$loop.schedule(this.CHANGE_FULL),this.onGutterResize()},initialValue:!0},fadeFoldWidgets:{set:function(e){i.setCssClass(this.$gutter,"ace_fade-fold-widgets",e)},initialValue:!1},showFoldWidgets:{set:function(e){this.$gutterLayer.setShowFoldWidgets(e)},initialValue:!0},showLineNumbers:{set:function(e){this.$gutterLayer.setShowLineNumbers(e),this.$loop.schedule(this.CHANGE_GUTTER)},initialValue:!0},displayIndentGuides:{set:function(e){this.$textLayer.setDisplayIndentGuides(e)&&this.$loop.schedule(this.CHANGE_TEXT)},initialValue:!0},highlightGutterLine:{set:function(e){if(!this.$gutterLineHighlight){this.$gutterLineHighlight=i.createElement("div"),this.$gutterLineHighlight.className="ace_gutter-active-line",this.$gutter.appendChild(this.$gutterLineHighlight);return}this.$gutterLineHighlight.style.display=e?"":"none",this.$cursorLayer.$pixelPos&&this.$updateGutterLineHighlight()},initialValue:!1,value:!0},hScrollBarAlwaysVisible:{set:function(e){(!this.$hScrollBarAlwaysVisible||!this.$horizScroll)&&this.$loop.schedule(this.CHANGE_SCROLL)},initialValue:!1},vScrollBarAlwaysVisible:{set:function(e){(!this.$vScrollBarAlwaysVisible||!this.$vScroll)&&this.$loop.schedule(this.CHANGE_SCROLL)},initialValue:!1},fontSize:{set:function(e){typeof e=="number"&&(e+="px"),this.container.style.fontSize=e,this.updateFontSize()},initialValue:12},fontFamily:{set:function(e){this.container.style.fontFamily=e,this.updateFontSize()}},maxLines:{set:function(e){this.updateFull()}},minLines:{set:function(e){this.updateFull()}},scrollPastEnd:{set:function(e){e=+e||0;if(this.$scrollPastEnd==e)return;this.$scrollPastEnd=e,this.$loop.schedule(this.CHANGE_SCROLL)},initialValue:0,handlesSet:!0},fixedWidthGutter:{set:function(e){this.$gutterLayer.$fixedWidth=!!e,this.$loop.schedule(this.CHANGE_GUTTER)}},theme:{set:function(e){this.setTheme(e)},get:function(){return this.$themeId||this.theme},initialValue:"./theme/textmate",handlesSet:!0}}),t.VirtualRenderer=m}),define("ace/config",["require","exports","module","ace/lib/lang","ace/lib/oop","ace/lib/net","ace/lib/event_emitter"],function(e,t,n){"no use strict";function r(r){l.packaged=r||e.packaged||n.packaged||f.define&&define.packaged;if(!f.document)return"";var s={},o="",u=document.getElementsByTagName("script");for(var a=0;a<u.length;a++){var c=u[a],h=c.src||c.getAttribute("src");if(!h)continue;var p=c.attributes;for(var d=0,v=p.length;d<v;d++){var m=p[d];m.name.indexOf("data-ace-")===0&&(s[i(m.name.replace(/^data-ace-/,""))]=m.value)}var g=h.match(/^(.*)\/ace(\-\w+)?\.js(\?|$)/);g&&(o=g[1])}o&&(s.base=s.base||o,s.packaged=!0),s.basePath=s.base,s.workerPath=s.workerPath||s.base,s.modePath=s.modePath||s.base,s.themePath=s.themePath||s.base,delete s.base;for(var y in s)typeof s[y]!="undefined"&&t.set(y,s[y])}function i(e){return e.replace(/-(.)/g,function(e,t){return t.toUpperCase()})}var s=e("./lib/lang"),o=e("./lib/oop"),u=e("./lib/net"),a=e("./lib/event_emitter").EventEmitter,f=function(){return this}(),l={packaged:!1,workerPath:null,modePath:null,themePath:null,basePath:"",suffix:".js",$moduleUrls:{}};t.get=function(e){if(!l.hasOwnProperty(e))throw new Error("Unknown config key: "+e);return l[e]},t.set=function(e,t){if(!l.hasOwnProperty(e))throw new Error("Unknown config key: "+e);l[e]=t},t.all=function(){return s.copyObject(l)},o.implement(t,a),t.moduleUrl=function(e,t){if(l.$moduleUrls[e])return l.$moduleUrls[e];var n=e.split("/");t=t||n[n.length-2]||"";var r=t=="snippets"?"/":"-",i=n[n.length-1];if(r=="-"){var s=new RegExp("^"+t+"[\\-_]|[\\-_]"+t+"$","g");i=i.replace(s,"")}(!i||i==t)&&n.length>1&&(i=n[n.length-2]);var o=l[t+"Path"];return o==null?o=l.basePath:r=="/"&&(t=r=""),o&&o.slice(-1)!="/"&&(o+="/"),o+t+r+i+this.get("suffix")},t.setModuleUrl=function(e,t){return l.$moduleUrls[e]=t},t.$loading={},t.loadModule=function(n,r){var i,s;Array.isArray(n)&&(s=n[0],n=n[1]);try{i=e(n)}catch(o){}if(i&&!t.$loading[n])return r&&r(i);t.$loading[n]||(t.$loading[n]=[]),t.$loading[n].push(r);if(t.$loading[n].length>1)return;var a=function(){e([n],function(e){t._emit("load.module",{name:n,module:e});var r=t.$loading[n];t.$loading[n]=null,r.forEach(function(t){t&&t(e)})})};if(!t.get("packaged"))return a();u.loadScript(t.moduleUrl(n,s),a)},r(!0),t.init=r;var c={setOptions:function(e){Object.keys(e).forEach(function(t){this.setOption(t,e[t])},this)},getOptions:function(e){var t={};return e?Array.isArray(e)||(t=e,e=Object.keys(t)):e=Object.keys(this.$options),e.forEach(function(e){t[e]=this.getOption(e)},this),t},setOption:function(e,t){if(this["$"+e]===t)return;var n=this.$options[e];if(!n)return typeof console!="undefined"&&console.warn&&console.warn('misspelled option "'+e+'"'),undefined;if(n.forwardTo)return this[n.forwardTo]&&this[n.forwardTo].setOption(e,t);n.handlesSet||(this["$"+e]=t),n&&n.set&&n.set.call(this,t)},getOption:function(e){var t=this.$options[e];return t?t.forwardTo?this[t.forwardTo]&&this[t.forwardTo].getOption(e):t&&t.get?t.get.call(this):this["$"+e]:(typeof console!="undefined"&&console.warn&&console.warn('misspelled option "'+e+'"'),undefined)}},h={};t.defineOptions=function(e,t,n){return e.$options||(h[t]=e.$options={}),Object.keys(n).forEach(function(t){var r=n[t];typeof r=="string"&&(r={forwardTo:r}),r.name||(r.name=t),e.$options[r.name]=r,"initialValue"in r&&(e["$"+r.name]=r.initialValue)}),o.implement(e,c),this},t.resetOptions=function(e){Object.keys(e.$options).forEach(function(t){var n=e.$options[t];"value"in n&&e.setOption(t,n.value)})},t.setDefaultValue=function(e,n,r){var i=h[e]||(h[e]={});i[n]&&(i.forwardTo?t.setDefaultValue(i.forwardTo,n,r):i[n].value=r)},t.setDefaultValues=function(e,n){Object.keys(n).forEach(function(r){t.setDefaultValue(e,r,n[r])})}}),define("ace/layer/gutter",["require","exports","module","ace/lib/dom","ace/lib/oop","ace/lib/lang","ace/lib/event_emitter"],function(e,t,n){var r=e("../lib/dom"),i=e("../lib/oop"),s=e("../lib/lang"),o=e("../lib/event_emitter").EventEmitter,u=function(e){this.element=r.createElement("div"),this.element.className="ace_layer ace_gutter-layer",e.appendChild(this.element),this.setShowFoldWidgets(this.$showFoldWidgets),this.gutterWidth=0,this.$annotations=[],this.$updateAnnotations=this.$updateAnnotations.bind(this),this.$cells=[]};(function(){i.implement(this,o),this.setSession=function(e){this.session&&this.session.removeEventListener("change",this.$updateAnnotations),this.session=e,e.on("change",this.$updateAnnotations)},this.addGutterDecoration=function(e,t){window.console&&console.warn&&console.warn("deprecated use session.addGutterDecoration"),this.session.addGutterDecoration(e,t)},this.removeGutterDecoration=function(e,t){window.console&&console.warn&&console.warn("deprecated use session.removeGutterDecoration"),this.session.removeGutterDecoration(e,t)},this.setAnnotations=function(e){this.$annotations=[];for(var t=0;t<e.length;t++){var n=e[t],r=n.row,i=this.$annotations[r];i||(i=this.$annotations[r]={text:[]});var o=n.text;o=o?s.escapeHTML(o):n.html||"",i.text.indexOf(o)===-1&&i.text.push(o);var u=n.type;u=="error"?i.className=" ace_error":u=="warning"&&i.className!=" ace_error"?i.className=" ace_warning":u=="info"&&!i.className&&(i.className=" ace_info")}},this.$updateAnnotations=function(e){if(!this.$annotations.length)return;var t=e.data,n=t.range,r=n.start.row,i=n.end.row-r;if(i!==0)if(t.action=="removeText"||t.action=="removeLines")this.$annotations.splice(r,i+1,null);else{var s=new Array(i+1);s.unshift(r,1),this.$annotations.splice.apply(this.$annotations,s)}},this.update=function(e){var t=this.session,n=e.firstRow,i=Math.min(e.lastRow+e.gutterOffset,t.getLength()-1),s=t.getNextFoldLine(n),o=s?s.start.row:Infinity,u=this.$showFoldWidgets&&t.foldWidgets,a=t.$breakpoints,f=t.$decorations,l=t.$firstLineNumber,c=0,h=t.gutterRenderer||this.$renderer,p=null,d=-1,v=n;for(;;){v>o&&(v=s.end.row+1,s=t.getNextFoldLine(v,s),o=s?s.start.row:Infinity);if(v>i){while(this.$cells.length>d+1)p=this.$cells.pop(),this.element.removeChild(p.element);break}p=this.$cells[++d],p||(p={element:null,textNode:null,foldWidget:null},p.element=r.createElement("div"),p.textNode=document.createTextNode(""),p.element.appendChild(p.textNode),this.element.appendChild(p.element),this.$cells[d]=p);var m="ace_gutter-cell ";a[v]&&(m+=a[v]),f[v]&&(m+=f[v]),this.$annotations[v]&&(m+=this.$annotations[v].className),p.element.className!=m&&(p.element.className=m);var g=t.getRowLength(v)*e.lineHeight+"px";g!=p.element.style.height&&(p.element.style.height=g);if(u){var y=u[v];y==null&&(y=u[v]=t.getFoldWidget(v))}if(y){p.foldWidget||(p.foldWidget=r.createElement("span"),p.element.appendChild(p.foldWidget));var m="ace_fold-widget ace_"+y;y=="start"&&v==o&&v<s.end.row?m+=" ace_closed":m+=" ace_open",p.foldWidget.className!=m&&(p.foldWidget.className=m);var g=e.lineHeight+"px";p.foldWidget.style.height!=g&&(p.foldWidget.style.height=g)}else p.foldWidget&&(p.element.removeChild(p.foldWidget),p.foldWidget=null);var b=c=h?h.getText(t,v):v+l;b!=p.textNode.data&&(p.textNode.data=b),v++}this.element.style.height=e.minHeight+"px";if(this.$fixedWidth||t.$useWrapMode)c=t.getLength()+l;var w=h?h.getWidth(t,c,e):c.toString().length*e.characterWidth,E=this.$padding||this.$computePadding();w+=E.left+E.right,w!==this.gutterWidth&&!isNaN(w)&&(this.gutterWidth=w,this.element.style.width=Math.ceil(this.gutterWidth)+"px",this._emit("changeGutterWidth",w))},this.$fixedWidth=!1,this.$showLineNumbers=!0,this.$renderer="",this.setShowLineNumbers=function(e){this.$renderer=!e&&{getWidth:function(){return""},getText:function(){return""}}},this.getShowLineNumbers=function(){return this.$showLineNumbers},this.$showFoldWidgets=!0,this.setShowFoldWidgets=function(e){e?r.addCssClass(this.element,"ace_folding-enabled"):r.removeCssClass(this.element,"ace_folding-enabled"),this.$showFoldWidgets=e,this.$padding=null},this.getShowFoldWidgets=function(){return this.$showFoldWidgets},this.$computePadding=function(){if(!this.element.firstChild)return{left:0,right:0};var e=r.computedStyle(this.element.firstChild);return this.$padding={},this.$padding.left=parseInt(e.paddingLeft)+1||0,this.$padding.right=parseInt(e.paddingRight)||0,this.$padding},this.getRegion=function(e){var t=this.$padding||this.$computePadding(),n=this.element.getBoundingClientRect();if(e.x<t.left+n.left)return"markers";if(this.$showFoldWidgets&&e.x>n.right-t.right)return"foldWidgets"}}).call(u.prototype),t.Gutter=u}),define("ace/mouse/dragdrop_handler",["require","exports","module","ace/lib/dom","ace/lib/event","ace/lib/useragent"],function(e,t,n){function r(e){function t(e,t){var n=Date.now(),r=!t||e.row!=t.row,s=!t||e.column!=t.column;if(!O||r||s)m.$blockScrolling+=1,m.moveCursorToPosition(e),m.$blockScrolling-=1,O=n,M={x:E,y:S};else{var o=i(M.x,M.y,E,S);o>l?O=null:n-O>=f&&(m.renderer.scrollCursorIntoView(),O=null)}}function n(e,t){var n=Date.now(),r=m.renderer.layerConfig.lineHeight,i=m.renderer.layerConfig.characterWidth,s=m.renderer.scroller.getBoundingClientRect(),o={x:{left:E-s.left,right:s.right-E},y:{top:S-s.top,bottom:s.bottom-S}},u=Math.min(o.x.left,o.x.right),f=Math.min(o.y.top,o.y.bottom),l={row:e.row,column:e.column};u/i<=2&&(l.column+=o.x.left<o.x.right?-3:2),f/r<=1&&(l.row+=o.y.top<o.y.bottom?-1:1);var c=e.row!=l.row,h=e.column!=l.column,p=!t||e.row!=t.row;c||h&&!p?A?n-A>=a&&m.renderer.scrollCursorIntoView(l):A=n:A=null}function r(){var e=N;N=m.renderer.screenToTextCoordinates(E,S),t(N,e),n(N,e)}function c(){T=m.selection.toOrientedRange(),w=m.session.addMarker(T,"ace_selection",m.getSelectionStyle()),m.clearSelection(),m.isFocused()&&m.renderer.$cursorLayer.setBlinking(!1),clearInterval(x),x=setInterval(r,20),C=0,o.addListener(document,"mousemove",p)}function h(){clearInterval(x),m.session.removeMarker(w),w=null,m.$blockScrolling+=1,m.selection.fromOrientedRange(T),m.$blockScrolling-=1,m.isFocused()&&!L&&m.renderer.$cursorLayer.setBlinking(!m.getReadOnly()),T=null,C=0,A=null,O=null,o.removeListener(document,"mousemove",p)}function p(){_==null&&(_=setTimeout(function(){_!=null&&w&&h()},20))}function d(e){var t=e.types;return!t||Array.prototype.some.call(t,function(e){return e=="text/plain"||e=="Text"})}function v(e){var t=["copy","copymove","all","uninitialized"],n=["move","copymove","linkmove","all","uninitialized"],r=u.isMac?e.altKey:e.ctrlKey,i="uninitialized";try{i=e.dataTransfer.effectAllowed.toLowerCase()}catch(e){}var s="none";return r&&t.indexOf(i)>=0?s="copy":n.indexOf(i)>=0?s="move":t.indexOf(i)>=0&&(s="copy"),s}var m=e.editor,g=s.createElement("img");g.src="data:image/gif;base64,R0lGODlhAQABAAAAACH5BAEKAAEALAAAAAABAAEAAAICTAEAOw==",u.isOpera&&(g.style.cssText="width:1px;height:1px;position:fixed;top:0;left:0;z-index:2147483647;opacity:0;");var y=["dragWait","dragWaitEnd","startDrag","dragReadyEnd","onMouseDrag"];y.forEach(function(t){e[t]=this[t]},this),m.addEventListener("mousedown",this.onMouseDown.bind(e));var b=m.container,w,E,S,x,T,N,C=0,k,L,A,O,M;this.onDragStart=function(e){if(this.cancelDrag||!b.draggable){var t=this;return setTimeout(function(){t.startSelect(),t.captureMouse(e)},0),e.preventDefault()}T=m.getSelectionRange();var n=e.dataTransfer;n.effectAllowed=m.getReadOnly()?"copy":"copyMove",u.isOpera&&(m.container.appendChild(g),g._top=g.offsetTop),n.setDragImage&&n.setDragImage(g,0,0),u.isOpera&&m.container.removeChild(g),n.clearData(),n.setData("Text",m.session.getTextRange()),L=!0,this.setState("drag")},this.onDragEnd=function(e){b.draggable=!1,L=!1,this.setState(null);if(!m.getReadOnly()){var t=e.dataTransfer.dropEffect;!k&&t=="move"&&m.session.remove(m.getSelectionRange()),m.renderer.$cursorLayer.setBlinking(!0)}this.editor.unsetStyle("ace_dragging")},this.onDragEnter=function(e){if(m.getReadOnly()||!d(e.dataTransfer))return;return w||c(),C++,e.dataTransfer.dropEffect=k=v(e),o.preventDefault(e)},this.onDragOver=function(e){if(m.getReadOnly()||!d(e.dataTransfer))return;return w||(c(),C++),_!==null&&(_=null),E=e.clientX,S=e.clientY,e.dataTransfer.dropEffect=k=v(e),o.preventDefault(e)},this.onDragLeave=function(e){C--;if(C<=0&&w)return h(),k=null,o.preventDefault(e)},this.onDrop=function(e){if(!w)return;var t=e.dataTransfer;if(L)switch(k){case"move":T.contains(N.row,N.column)?T={start:N,end:N}:T=m.moveText(T,N);break;case"copy":T=m.moveText(T,N,!0)}else{var n=t.getData("Text");T={start:N,end:m.session.insert(N,n)},m.focus(),k=null}return h(),o.preventDefault(e)},o.addListener(b,"dragstart",this.onDragStart.bind(e)),o.addListener(b,"dragend",this.onDragEnd.bind(e)),o.addListener(b,"dragenter",this.onDragEnter.bind(e)),o.addListener(b,"dragover",this.onDragOver.bind(e)),o.addListener(b,"dragleave",this.onDragLeave.bind(e)),o.addListener(b,"drop",this.onDrop.bind(e));var _=null}function i(e,t,n,r){return Math.sqrt(Math.pow(n-e,2)+Math.pow(r-t,2))}var s=e("../lib/dom"),o=e("../lib/event"),u=e("../lib/useragent"),a=200,f=200,l=5;(function(){this.dragWait=function(){var e=Date.now()-this.mousedownEvent.time;e>this.editor.getDragDelay()&&this.startDrag()},this.dragWaitEnd=function(){var e=this.editor.container;e.draggable=!1,this.startSelect(this.mousedownEvent.getDocumentPosition()),this.selectEnd()},this.dragReadyEnd=function(e){this.editor.renderer.$cursorLayer.setBlinking(!this.editor.getReadOnly()),this.editor.unsetStyle("ace_dragging"),this.dragWaitEnd()},this.startDrag=function(){this.cancelDrag=!1;var e=this.editor.container;e.draggable=!0,this.editor.renderer.$cursorLayer.setBlinking(!1),this.editor.setStyle("ace_dragging"),this.setState("dragReady")},this.onMouseDrag=function(e){var t=this.editor.container;if(u.isIE&&this.state=="dragReady"){var n=i(this.mousedownEvent.x,this.mousedownEvent.y,this.x,this.y);n>3&&t.dragDrop()}if(this.state==="dragWait"){var n=i(this.mousedownEvent.x,this.mousedownEvent.y,this.x,this.y);n>0&&(t.draggable=!1,this.startSelect(this.mousedownEvent.getDocumentPosition()))}},this.onMouseDown=function(e){if(!this.$dragEnabled)return;this.mousedownEvent=e;var t=this.editor,n=e.inSelection(),r=e.getButton(),i=e.domEvent.detail||1;if(i===1&&r===0&&n){if(e.editor.inMultiSelectMode&&(e.getAccelKey()||e.getShiftKey()))return;this.mousedownEvent.time=Date.now();var s=e.domEvent.target||e.domEvent.srcElement;"unselectable"in s&&(s.unselectable="on");if(t.getDragDelay()){if(u.isWebKit){this.cancelDrag=!0;var o=t.container;o.draggable=!0}this.setState("dragWait")}else this.startDrag();this.captureMouse(e,this.onMouseDrag.bind(this)),e.defaultPrevented=!0}}}).call(r.prototype),t.DragdropHandler=r}),define("ace/layer/marker",["require","exports","module","ace/range","ace/lib/dom"],function(e,t,n){var r=e("../range").Range,i=e("../lib/dom"),s=function(e){this.element=i.createElement("div"),this.element.className="ace_layer ace_marker-layer",e.appendChild(this.element)};(function(){this.$padding=0,this.setPadding=function(e){this.$padding=e},this.setSession=function(e){this.session=e},this.setMarkers=function(e){this.markers=e},this.update=function(e){var e=e||this.config;if(!e)return;this.config=e;var t=[];for(var n in this.markers){var r=this.markers[n];if(!r.range){r.update(t,this,this.session,e);continue}var s=r.range.clipRows(e.firstRow,e.lastRow);if(s.isEmpty())continue;s=s.toScreenRange(this.session);if(r.renderer){var o=this.$getTop(s.start.row,e),u=this.$padding+s.start.column*e.characterWidth;r.renderer(t,s,u,o,e)}else r.type=="fullLine"?this.drawFullLineMarker(t,s,r.clazz,e):r.type=="screenLine"?this.drawScreenLineMarker(t,s,r.clazz,e):s.isMultiLine()?r.type=="text"?this.drawTextMarker(t,s,r.clazz,e):this.drawMultiLineMarker(t,s,r.clazz,e):this.drawSingleLineMarker(t,s,r.clazz+" ace_start",e)}this.element=i.setInnerHtml(this.element,t.join(""))},this.$getTop=function(e,t){return(e-t.firstRowScreen)*t.lineHeight},this.drawTextMarker=function(e,t,n,i,s){var o=t.start.row,u=new r(o,t.start.column,o,this.session.getScreenLastRowColumn(o));this.drawSingleLineMarker(e,u,n+" ace_start",i,1,s),o=t.end.row,u=new r(o,0,o,t.end.column),this.drawSingleLineMarker(e,u,n,i,0,s);for(o=t.start.row+1;o<t.end.row;o++)u.start.row=o,u.end.row=o,u.end.column=this.session.getScreenLastRowColumn(o),this.drawSingleLineMarker(e,u,n,i,1,s)},this.drawMultiLineMarker=function(e,t,n,r,i){var s=this.$padding,o=r.lineHeight,u=this.$getTop(t.start.row,r),a=s+t.start.column*r.characterWidth;i=i||"",e.push("<div class='",n," ace_start' style='","height:",o,"px;","right:0;","top:",u,"px;","left:",a,"px;",i,"'></div>"),u=this.$getTop(t.end.row,r);var f=t.end.column*r.characterWidth;e.push("<div class='",n,"' style='","height:",o,"px;","width:",f,"px;","top:",u,"px;","left:",s,"px;",i,"'></div>"),o=(t.end.row-t.start.row-1)*r.lineHeight;if(o<0)return;u=this.$getTop(t.start.row+1,r),e.push("<div class='",n,"' style='","height:",o,"px;","right:0;","top:",u,"px;","left:",s,"px;",i,"'></div>")},this.drawSingleLineMarker=function(e,t,n,r,i,s){var o=r.lineHeight,u=(t.end.column+(i||0)-t.start.column)*r.characterWidth,a=this.$getTop(t.start.row,r),f=this.$padding+t.start.column*r.characterWidth;e.push("<div class='",n,"' style='","height:",o,"px;","width:",u,"px;","top:",a,"px;","left:",f,"px;",s||"","'></div>")},this.drawFullLineMarker=function(e,t,n,r,i){var s=this.$getTop(t.start.row,r),o=r.lineHeight;t.start.row!=t.end.row&&(o+=this.$getTop(t.end.row,r)-s),e.push("<div class='",n,"' style='","height:",o,"px;","top:",s,"px;","left:0;right:0;",i||"","'></div>")},this.drawScreenLineMarker=function(e,t,n,r,i){var s=this.$getTop(t.start.row,r),o=r.lineHeight;e.push("<div class='",n,"' style='","height:",o,"px;","top:",s,"px;","left:0;right:0;",i||"","'></div>")}}).call(s.prototype),t.Marker=s}),define("ace/mouse/mouse_event",["require","exports","module","ace/lib/event","ace/lib/useragent"],function(e,t,n){var r=e("../lib/event"),i=e("../lib/useragent"),s=t.MouseEvent=function(e,t){this.domEvent=e,this.editor=t,this.x=this.clientX=e.clientX,this.y=this.clientY=e.clientY,this.$pos=null,this.$inSelection=null,this.propagationStopped=!1,this.defaultPrevented=!1};(function(){this.stopPropagation=function(){r.stopPropagation(this.domEvent),this.propagationStopped=!0},this.preventDefault=function(){r.preventDefault(this.domEvent),this.defaultPrevented=!0},this.stop=function(){this.stopPropagation(),this.preventDefault()},this.getDocumentPosition=function(){return this.$pos?this.$pos:(this.$pos=this.editor.renderer.screenToTextCoordinates(this.clientX,this.clientY),this.$pos)},this.inSelection=function(){if(this.$inSelection!==null)return this.$inSelection;var e=this.editor,t=e.getSelectionRange();if(t.isEmpty())this.$inSelection=!1;else{var n=this.getDocumentPosition();this.$inSelection=t.contains(n.row,n.column)}return this.$inSelection},this.getButton=function(){return r.getButton(this.domEvent)},this.getShiftKey=function(){return this.domEvent.shiftKey},this.getAccelKey=i.isMac?function(){return this.domEvent.metaKey}:function(){return this.domEvent.ctrlKey}}).call(s.prototype)}),define("ace/layer/text",["require","exports","module","ace/lib/oop","ace/lib/dom","ace/lib/lang","ace/lib/useragent","ace/lib/event_emitter"],function(e,t,n){var r=e("../lib/oop"),i=e("../lib/dom"),s=e("../lib/lang"),o=e("../lib/useragent"),u=e("../lib/event_emitter").EventEmitter,a=function(e){this.element=i.createElement("div"),this.element.className="ace_layer ace_text-layer",e.appendChild(this.element),this.$updateEolChar=this.$updateEolChar.bind(this)};(function(){r.implement(this,u),this.EOF_CHAR="¶",this.EOL_CHAR_LF="¬",this.EOL_CHAR_CRLF="¤",this.EOL_CHAR=this.EOL_CHAR_LF,this.TAB_CHAR="→",this.SPACE_CHAR="·",this.$padding=0,this.$updateEolChar=function(){var e=this.session.doc.getNewLineCharacter()=="\n"?this.EOL_CHAR_LF:this.EOL_CHAR_CRLF;if(this.EOL_CHAR!=e)return this.EOL_CHAR=e,!0},this.setPadding=function(e){this.$padding=e,this.element.style.padding="0 "+e+"px"},this.getLineHeight=function(){return this.$fontMetrics.$characterSize.height||0},this.getCharacterWidth=function(){return this.$fontMetrics.$characterSize.width||0},this.$setFontMetrics=function(e){this.$fontMetrics=e,this.$fontMetrics.on("changeCharacterSize",function(e){this._signal("changeCharacterSize",e)}.bind(this)),this.$pollSizeChanges()},this.checkForSizeChanges=function(){this.$fontMetrics.checkForSizeChanges()},this.$pollSizeChanges=function(){return this.$pollSizeChangesTimer=this.$fontMetrics.$pollSizeChanges()},this.setSession=function(e){this.session=e,this.$computeTabString()},this.showInvisibles=!1,this.setShowInvisibles=function(e){return this.showInvisibles==e?!1:(this.showInvisibles=e,this.$computeTabString(),!0)},this.displayIndentGuides=!0,this.setDisplayIndentGuides=function(e){return this.displayIndentGuides==e?!1:(this.displayIndentGuides=e,this.$computeTabString(),!0)},this.$tabStrings=[],this.onChangeTabSize=this.$computeTabString=function(){var e=this.session.getTabSize();this.tabSize=e;var t=this.$tabStrings=[0];for(var n=1;n<e+1;n++)this.showInvisibles?t.push("<span class='ace_invisible'>"+this.TAB_CHAR+s.stringRepeat(" ",n-1)+"</span>"):t.push(s.stringRepeat(" ",n));if(this.displayIndentGuides){this.$indentGuideRe=/\s\S| \t|\t |\s$/;var r="ace_indent-guide";if(this.showInvisibles){r+=" ace_invisible";var i=s.stringRepeat(this.SPACE_CHAR,this.tabSize),o=this.TAB_CHAR+s.stringRepeat(" ",this.tabSize-1)}else var i=s.stringRepeat(" ",this.tabSize),o=i;this.$tabStrings[" "]="<span class='"+r+"'>"+i+"</span>",this.$tabStrings[" "]="<span class='"+r+"'>"+o+"</span>"}},this.updateLines=function(e,t,n){(this.config.lastRow!=e.lastRow||this.config.firstRow!=e.firstRow)&&this.scrollLines(e),this.config=e;var r=Math.max(t,e.firstRow),s=Math.min(n,e.lastRow),o=this.element.childNodes,u=0;for(var a=e.firstRow;a<r;a++){var f=this.session.getFoldLine(a);if(f){if(f.containsRow(r)){r=f.start.row;break}a=f.end.row}u++}var a=r,f=this.session.getNextFoldLine(a),l=f?f.start.row:Infinity;for(;;){a>l&&(a=f.end.row+1,f=this.session.getNextFoldLine(a,f),l=f?f.start.row:Infinity);if(a>s)break;var c=o[u++];if(c){var h=[];this.$renderLine(h,a,!this.$useLineGroups(),a==l?f:!1),c.style.height=e.lineHeight*this.session.getRowLength(a)+"px",i.setInnerHtml(c,h.join(""))}a++}},this.scrollLines=function(e){var t=this.config;this.config=e;if(!t||t.lastRow<e.firstRow)return this.update(e);if(e.lastRow<t.firstRow)return this.update(e);var n=this.element;if(t.firstRow<e.firstRow)for(var r=this.session.getFoldedRowCount(t.firstRow,e.firstRow-1);r>0;r--)n.removeChild(n.firstChild);if(t.lastRow>e.lastRow)for(var r=this.session.getFoldedRowCount(e.lastRow+1,t.lastRow);r>0;r--)n.removeChild(n.lastChild);if(e.firstRow<t.firstRow){var i=this.$renderLinesFragment(e,e.firstRow,t.firstRow-1);n.firstChild?n.insertBefore(i,n.firstChild):n.appendChild(i)}if(e.lastRow>t.lastRow){var i=this.$renderLinesFragment(e,t.lastRow+1,e.lastRow);n.appendChild(i)}},this.$renderLinesFragment=function(e,t,n){var r=this.element.ownerDocument.createDocumentFragment(),s=t,o=this.session.getNextFoldLine(s),u=o?o.start.row:Infinity;for(;;){s>u&&(s=o.end.row+1,o=this.session.getNextFoldLine(s,o),u=o?o.start.row:Infinity);if(s>n)break;var a=i.createElement("div"),f=[];this.$renderLine(f,s,!1,s==u?o:!1),a.innerHTML=f.join("");if(this.$useLineGroups())a.className="ace_line_group",r.appendChild(a),a.style.height=e.lineHeight*this.session.getRowLength(s)+"px";else while(a.firstChild)r.appendChild(a.firstChild);s++}return r},this.update=function(e){this.config=e;var t=[],n=e.firstRow,r=e.lastRow,s=n,o=this.session.getNextFoldLine(s),u=o?o.start.row:Infinity;for(;;){s>u&&(s=o.end.row+1,o=this.session.getNextFoldLine(s,o),u=o?o.start.row:Infinity);if(s>r)break;this.$useLineGroups()&&t.push("<div class='ace_line_group' style='height:",e.lineHeight*this.session.getRowLength(s),"px'>"),this.$renderLine(t,s,!1,s==u?o:!1),this.$useLineGroups()&&t.push("</div>"),s++}this.element=i.setInnerHtml(this.element,t.join(""))},this.$textToken={text:!0,rparen:!0,lparen:!0},this.$renderToken=function(e,t,n,r){var i=this,o=/\t|&|<|( +)|([\x00-\x1f\x80-\xa0\u1680\u180E\u2000-\u200f\u2028\u2029\u202F\u205F\u3000\uFEFF])|[\u1100-\u115F\u11A3-\u11A7\u11FA-\u11FF\u2329-\u232A\u2E80-\u2E99\u2E9B-\u2EF3\u2F00-\u2FD5\u2FF0-\u2FFB\u3000-\u303E\u3041-\u3096\u3099-\u30FF\u3105-\u312D\u3131-\u318E\u3190-\u31BA\u31C0-\u31E3\u31F0-\u321E\u3220-\u3247\u3250-\u32FE\u3300-\u4DBF\u4E00-\uA48C\uA490-\uA4C6\uA960-\uA97C\uAC00-\uD7A3\uD7B0-\uD7C6\uD7CB-\uD7FB\uF900-\uFAFF\uFE10-\uFE19\uFE30-\uFE52\uFE54-\uFE66\uFE68-\uFE6B\uFF01-\uFF60\uFFE0-\uFFE6]/g,u=function(e,n,r,o,u){if(n)return i.showInvisibles?"<span class='ace_invisible'>"+s.stringRepeat(i.SPACE_CHAR,e.length)+"</span>":s.stringRepeat(" ",e.length);if(e=="&")return"&";if(e=="<")return"<";if(e==" "){var a=i.session.getScreenTabSize(t+o);return t+=a-1,i.$tabStrings[a]}if(e==" "){var f=i.showInvisibles?"ace_cjk ace_invisible":"ace_cjk",l=i.showInvisibles?i.SPACE_CHAR:"";return t+=1,"<span class='"+f+"' style='width:"+i.config.characterWidth*2+"px'>"+l+"</span>"}return r?"<span class='ace_invisible ace_invalid'>"+i.SPACE_CHAR+"</span>":(t+=1,"<span class='ace_cjk' style='width:"+i.config.characterWidth*2+"px'>"+e+"</span>")},a=r.replace(o,u);if(!this.$textToken[n.type]){var f="ace_"+n.type.replace(/\./g," ace_"),l="";n.type=="fold"&&(l=" style='width:"+n.value.length*this.config.characterWidth+"px;' "),e.push("<span class='",f,"'",l,">",a,"</span>")}else e.push(a);return t+r.length},this.renderIndentGuide=function(e,t,n){var r=t.search(this.$indentGuideRe);return r<=0||r>=n?t:t[0]==" "?(r-=r%this.tabSize,e.push(s.stringRepeat(this.$tabStrings[" "],r/this.tabSize)),t.substr(r)):t[0]==" "?(e.push(s.stringRepeat(this.$tabStrings[" "],r)),t.substr(r)):t},this.$renderWrappedLine=function(e,t,n,r){var i=0,s=0,o=n[0],u=0;for(var a=0;a<t.length;a++){var f=t[a],l=f.value;if(a==0&&this.displayIndentGuides){i=l.length,l=this.renderIndentGuide(e,l,o);if(!l)continue;i-=l.length}if(i+l.length<o)u=this.$renderToken(e,u,f,l),i+=l.length;else{while(i+l.length>=o)u=this.$renderToken(e,u,f,l.substring(0,o-i)),l=l.substring(o-i),i=o,r||e.push("</div>","<div class='ace_line' style='height:",this.config.lineHeight,"px'>"),s++,u=0,o=n[s]||Number.MAX_VALUE;l.length!=0&&(i+=l.length,u=this.$renderToken(e,u,f,l))}}},this.$renderSimpleLine=function(e,t){var n=0,r=t[0],i=r.value;this.displayIndentGuides&&(i=this.renderIndentGuide(e,i)),i&&(n=this.$renderToken(e,n,r,i));for(var s=1;s<t.length;s++)r=t[s],i=r.value,n=this.$renderToken(e,n,r,i)},this.$renderLine=function(e,t,n,r){!r&&r!=0&&(r=this.session.getFoldLine(t));if(r)var i=this.$getFoldLineTokens(t,r);else var i=this.session.getTokens(t);n||e.push("<div class='ace_line' style='height:",this.config.lineHeight*(this.$useLineGroups()?1:this.session.getRowLength(t)),"px'>");if(i.length){var s=this.session.getRowSplitData(t);s&&s.length?this.$renderWrappedLine(e,i,s,n):this.$renderSimpleLine(e,i)}this.showInvisibles&&(r&&(t=r.end.row),e.push("<span class='ace_invisible'>",t==this.session.getLength()-1?this.EOF_CHAR:this.EOL_CHAR,"</span>")),n||e.push("</div>")},this.$getFoldLineTokens=function(e,t){function n(e,t,n){var r=0,s=0;while(s+e[r].value.length<t){s+=e[r].value.length,r++;if(r==e.length)return}if(s!=t){var o=e[r].value.substring(t-s);o.length>n-t&&(o=o.substring(0,n-t)),i.push({type:e[r].type,value:o}),s=t+o.length,r+=1}while(s<n&&r<e.length){var o=e[r].value;o.length+s>n?i.push({type:e[r].type,value:o.substring(0,n-s)}):i.push(e[r]),s+=o.length,r+=1}}var r=this.session,i=[],s=r.getTokens(e);return t.walk(function(e,t,o,u,a){e!=null?i.push({type:"fold",value:e}):(a&&(s=r.getTokens(t)),s.length&&n(s,u,o))},t.end.row,this.session.getLine(t.end.row).length),i},this.$useLineGroups=function(){return this.session.getUseWrapMode()},this.destroy=function(){clearInterval(this.$pollSizeChangesTimer),this.$measureNode&&this.$measureNode.parentNode.removeChild(this.$measureNode),delete this.$measureNode}}).call(a.prototype),t.Text=a}),define("ace/tooltip",["require","exports","module","ace/lib/oop","ace/lib/dom"],function(e,t,n){function r(e){this.isOpen=!1,this.$element=null,this.$parentNode=e}var i=e("./lib/oop"),s=e("./lib/dom");(function(){this.$init=function(){return this.$element=s.createElement("div"),this.$element.className="ace_tooltip",this.$element.style.display="none",this.$parentNode.appendChild(this.$element),this.$element},this.getElement=function(){return this.$element||this.$init()},this.setText=function(e){s.setInnerText(this.getElement(),e)},this.setHtml=function(e){this.getElement().innerHTML=e},this.setPosition=function(e,t){this.getElement().style.left=e+"px",this.getElement().style.top=t+"px"},this.setClassName=function(e){s.addCssClass(this.getElement(),e)},this.show=function(e,t,n){e!=null&&this.setText(e),t!=null&&n!=null&&this.setPosition(t,n),this.isOpen||(this.getElement().style.display="block",this.isOpen=!0)},this.hide=function(){this.isOpen&&(this.getElement().style.display="none",this.isOpen=!1)},this.getHeight=function(){return this.getElement().offsetHeight},this.getWidth=function(){return this.getElement().offsetWidth}}).call(r.prototype),t.Tooltip=r}),define("ace/layer/cursor",["require","exports","module","ace/lib/dom"],function(e,t,n){var r=e("../lib/dom"),i,s=function(e){this.element=r.createElement("div"),this.element.className="ace_layer ace_cursor-layer",e.appendChild(this.element),i===undefined&&(i="opacity"in this.element),this.isVisible=!1,this.isBlinking=!0,this.blinkInterval=1e3,this.smoothBlinking=!1,this.cursors=[],this.cursor=this.addCursor(),r.addCssClass(this.element,"ace_hidden-cursors"),this.$updateCursors=this.$updateVisibility.bind(this)};(function(){this.$updateVisibility=function(e){var t=this.cursors;for(var n=t.length;n--;)t[n].style.visibility=e?"":"hidden"},this.$updateOpacity=function(e){var t=this.cursors;for(var n=t.length;n--;)t[n].style.opacity=e?"":"0"},this.$padding=0,this.setPadding=function(e){this.$padding=e},this.setSession=function(e){this.session=e},this.setBlinking=function(e){e!=this.isBlinking&&(this.isBlinking=e,this.restartTimer())},this.setBlinkInterval=function(e){e!=this.blinkInterval&&(this.blinkInterval=e,this.restartTimer())},this.setSmoothBlinking=function(e){e!=this.smoothBlinking&&!i&&(this.smoothBlinking=e,r.setCssClass(this.element,"ace_smooth-blinking",e),this.$updateCursors(!0),this.$updateCursors=(e?this.$updateOpacity:this.$updateVisibility).bind(this),this.restartTimer())},this.addCursor=function(){var e=r.createElement("div");return e.className="ace_cursor",this.element.appendChild(e),this.cursors.push(e),e},this.removeCursor=function(){if(this.cursors.length>1){var e=this.cursors.pop();return e.parentNode.removeChild(e),e}},this.hideCursor=function(){this.isVisible=!1,r.addCssClass(this.element,"ace_hidden-cursors"),this.restartTimer()},this.showCursor=function(){this.isVisible=!0,r.removeCssClass(this.element,"ace_hidden-cursors"),this.restartTimer()},this.restartTimer=function(){var e=this.$updateCursors;clearInterval(this.intervalId),clearTimeout(this.timeoutId),this.smoothBlinking&&r.removeCssClass(this.element,"ace_smooth-blinking"),e(!0);if(!this.isBlinking||!this.blinkInterval||!this.isVisible)return;this.smoothBlinking&&setTimeout(function(){r.addCssClass(this.element,"ace_smooth-blinking")}.bind(this));var t=function(){this.timeoutId=setTimeout(function(){e(!1)},.6*this.blinkInterval)}.bind(this);this.intervalId=setInterval(function(){e(!0),t()},this.blinkInterval),t()},this.getPixelPosition=function(e,t){if(!this.config||!this.session)return{left:0,top:0};e||(e=this.session.selection.getCursor());var n=this.session.documentToScreenPosition(e),r=this.$padding+n.column*this.config.characterWidth,i=(n.row-(t?this.config.firstRowScreen:0))*this.config.lineHeight;return{left:r,top:i}},this.update=function(e){this.config=e;var t=this.session.$selectionMarkers,n=0,r=0;if(t===undefined||t.length===0)t=[{cursor:null}];for(var n=0,i=t.length;n<i;n++){var s=this.getPixelPosition(t[n].cursor,!0);if((s.top>e.height+e.offset||s.top<0)&&n>1)continue;var o=(this.cursors[r++]||this.addCursor()).style;o.left=s.left+"px",o.top=s.top+"px",o.width=e.characterWidth+"px",o.height=e.lineHeight+"px"}while(this.cursors.length>r)this.removeCursor();var u=this.session.getOverwrite();this.$setOverwrite(u),this.$pixelPos=s,this.restartTimer()},this.$setOverwrite=function(e){e!=this.overwrite&&(this.overwrite=e,e?r.addCssClass(this.element,"ace_overwrite-cursors"):r.removeCssClass(this.element,"ace_overwrite-cursors"))},this.destroy=function(){clearInterval(this.intervalId),clearTimeout(this.timeoutId)}}).call(s.prototype),t.Cursor=s}),define("ace/mouse/default_gutter_handler",["require","exports","module","ace/lib/dom","ace/lib/oop","ace/lib/event","ace/tooltip"],function(e,t,n){function r(e){function t(){var t=c.getDocumentPosition().row,i=a.$annotations[t];if(!i)return n();var s=o.session.getLength();if(t==s){var u=o.renderer.pixelToScreenCoordinates(0,c.y).row,l=c.$pos;if(u>o.session.documentToScreenRow(l.row,l.column))return n()}if(h==i)return;h=i.text.join("<br/>"),f.setHtml(h),f.show(),o.on("mousewheel",n);if(e.$tooltipFollowsMouse)r(c);else{var p=a.$cells[t].element,d=p.getBoundingClientRect(),v=f.getElement().style;v.left=d.right+"px",v.top=d.bottom+"px"}}function n(){l&&(l=clearTimeout(l)),h&&(f.hide(),h=null,o.removeEventListener("mousewheel",n))}function r(e){f.setPosition(e.x,e.y)}var o=e.editor,a=o.renderer.$gutterLayer,f=new i(o.container);e.editor.setDefaultHandler("guttermousedown",function(t){if(!o.isFocused()||t.getButton()!=0)return;var n=a.getRegion(t);if(n=="foldWidgets")return;var r=t.getDocumentPosition().row,i=o.session.selection;if(t.getShiftKey())i.selectTo(r,0);else{if(t.domEvent.detail==2)return o.selectAll(),t.preventDefault();e.$clickSelection=o.selection.getLineRange(r)}return e.setState("selectByLines"),e.captureMouse(t),t.preventDefault()});var l,c,h;e.editor.setDefaultHandler("guttermousemove",function(i){var o=i.domEvent.target||i.domEvent.srcElement;if(s.hasCssClass(o,"ace_fold-widget"))return n();h&&e.$tooltipFollowsMouse&&r(i),c=i;if(l)return;l=setTimeout(function(){l=null,c&&!e.isMousePressed?t():n()},50)}),u.addListener(o.renderer.$gutter,"mouseout",function(e){c=null;if(!h||l)return;l=setTimeout(function(){l=null,n()},50)}),o.on("changeSession",n)}function i(e){a.call(this,e)}var s=e("../lib/dom"),o=e("../lib/oop"),u=e("../lib/event"),a=e("../tooltip").Tooltip;o.inherits(i,a),function(){this.setPosition=function(e,t){var n=window.innerWidth||document.documentElement.clientWidth,r=window.innerHeight||document.documentElement.clientHeight,i=this.getWidth(),s=this.getHeight();e+=15,t+=15,e+i>n&&(e-=e+i-n),t+s>r&&(t-=20+s),a.prototype.setPosition.call(this,e,t)}}.call(i.prototype),t.GutterHandler=r}),define("ace/scrollbar",["require","exports","module","ace/lib/oop","ace/lib/dom","ace/lib/event","ace/lib/event_emitter"],function(e,t,n){var r=e("./lib/oop"),i=e("./lib/dom"),s=e("./lib/event"),o=e("./lib/event_emitter").EventEmitter,u=function(e){this.element=i.createElement("div"),this.element.className="ace_scrollbar ace_scrollbar"+this.classSuffix,this.inner=i.createElement("div"),this.inner.className="ace_scrollbar-inner",this.element.appendChild(this.inner),e.appendChild(this.element),this.setVisible(!1),this.skipEvent=!1,s.addListener(this.element,"scroll",this.onScroll.bind(this)),s.addListener(this.element,"mousedown",s.preventDefault)};(function(){r.implement(this,o),this.setVisible=function(e){this.element.style.display=e?"":"none",this.isVisible=e}}).call(u.prototype);var a=function(e,t){u.call(this,e),this.scrollTop=0,t.$scrollbarWidth=this.width=i.scrollbarWidth(e.ownerDocument),this.inner.style.width=this.element.style.width=(this.width||15)+5+"px"};r.inherits(a,u),function(){this.classSuffix="-v",this.onScroll=function(){this.skipEvent||(this.scrollTop=this.element.scrollTop,this._emit("scroll",{data:this.scrollTop})),this.skipEvent=!1},this.getWidth=function(){return this.isVisible?this.width:0},this.setHeight=function(e){this.element.style.height=e+"px"},this.setInnerHeight=function(e){this.inner.style.height=e+"px"},this.setScrollHeight=function(e){this.inner.style.height=e+"px"},this.setScrollTop=function(e){this.scrollTop!=e&&(this.skipEvent=!0,this.scrollTop=this.element.scrollTop=e)}}.call(a.prototype);var f=function(e,t){u.call(this,e),this.scrollLeft=0,this.height=t.$scrollbarWidth,this.inner.style.height=this.element.style.height=(this.height||15)+5+"px"};r.inherits(f,u),function(){this.classSuffix="-h",this.onScroll=function(){this.skipEvent||(this.scrollLeft=this.element.scrollLeft,this._emit("scroll",{data:this.scrollLeft})),this.skipEvent=!1},this.getHeight=function(){return this.isVisible?this.height:0},this.setWidth=function(e){this.element.style.width=e+"px"},this.setInnerWidth=function(e){this.inner.style.width=e+"px"},this.setScrollWidth=function(e){this.inner.style.width=e+"px"},this.setScrollLeft=function(e){this.scrollLeft!=e&&(this.skipEvent=!0,this.scrollLeft=this.element.scrollLeft=e)}}.call(f.prototype),t.ScrollBar=a,t.ScrollBarV=a,t.ScrollBarH=f,t.VScrollBar=a,t.HScrollBar=f}),define("ace/mouse/default_handlers",["require","exports","module","ace/lib/dom","ace/lib/event","ace/lib/useragent"],function(e,t,n){function r(e){e.$clickSelection=null;var t=e.editor;t.setDefaultHandler("mousedown",this.onMouseDown.bind(e)),t.setDefaultHandler("dblclick",this.onDoubleClick.bind(e)),t.setDefaultHandler("tripleclick",this.onTripleClick.bind(e)),t.setDefaultHandler("quadclick",this.onQuadClick.bind(e)),t.setDefaultHandler("mousewheel",this.onMouseWheel.bind(e));var n=["select","startSelect","selectEnd","selectAllEnd","selectByWordsEnd","selectByLinesEnd","dragWait","dragWaitEnd","focusWait"];n.forEach(function(t){e[t]=this[t]},this),e.selectByLines=this.extendSelectionBy.bind(e,"getLineRange"),e.selectByWords=this.extendSelectionBy.bind(e,"getWordRange")}function i(e,t,n,r){return Math.sqrt(Math.pow(n-e,2)+Math.pow(r-t,2))}function s(e,t){if(e.start.row==e.end.row)var n=2*t.column-e.start.column-e.end.column;else if(e.start.row==e.end.row-1&&!e.start.column&&!e.end.column)var n=t.column-4;else var n=2*t.row-e.start.row-e.end.row;return n<0?{cursor:e.start,anchor:e.end}:{cursor:e.end,anchor:e.start}}var o=e("../lib/dom"),u=e("../lib/event"),a=e("../lib/useragent"),f=0;(function(){this.onMouseDown=function(e){var t=e.inSelection(),n=e.getDocumentPosition();this.mousedownEvent=e;var r=this.editor,i=e.getButton();if(i!==0){var s=r.getSelectionRange(),o=s.isEmpty();o&&r.selection.moveToPosition(n),r.textInput.onContextMenu(e.domEvent);return}if(t&&!r.isFocused()){r.focus();if(this.$focusTimout&&!this.$clickSelection&&!r.inMultiSelectMode){this.mousedownEvent.time=Date.now(),this.setState("focusWait"),this.captureMouse(e);return}}return this.captureMouse(e),!t||this.$clickSelection||e.getShiftKey()||r.inMultiSelectMode?this.startSelect(n):t&&(this.mousedownEvent.time=Date.now(),this.startSelect(n)),e.preventDefault()},this.startSelect=function(e){e=e||this.editor.renderer.screenToTextCoordinates(this.x,this.y);var t=this.editor,n=this.mousedownEvent.getShiftKey();n?t.selection.selectToPosition(e):this.$clickSelection||t.selection.moveToPosition(e),t.renderer.scroller.setCapture&&t.renderer.scroller.setCapture(),t.setStyle("ace_selecting"),this.setState("select")},this.select=function(){var e,t=this.editor,n=t.renderer.screenToTextCoordinates(this.x,this.y);if(this.$clickSelection){var r=this.$clickSelection.comparePoint(n);if(r==-1)e=this.$clickSelection.end;else if(r==1)e=this.$clickSelection.start;else{var i=s(this.$clickSelection,n);n=i.cursor,e=i.anchor}t.selection.setSelectionAnchor(e.row,e.column)}t.selection.selectToPosition(n),t.renderer.scrollCursorIntoView()},this.extendSelectionBy=function(e){var t,n=this.editor,r=n.renderer.screenToTextCoordinates(this.x,this.y),i=n.selection[e](r.row,r.column);if(this.$clickSelection){var o=this.$clickSelection.comparePoint(i.start),u=this.$clickSelection.comparePoint(i.end);if(o==-1&&u<=0){t=this.$clickSelection.end;if(i.end.row!=r.row||i.end.column!=r.column)r=i.start}else if(u==1&&o>=0){t=this.$clickSelection.start;if(i.start.row!=r.row||i.start.column!=r.column)r=i.end}else if(o==-1&&u==1)r=i.end,t=i.start;else{var a=s(this.$clickSelection,r);r=a.cursor,t=a.anchor}n.selection.setSelectionAnchor(t.row,t.column)}n.selection.selectToPosition(r),n.renderer.scrollCursorIntoView()},this.selectEnd=this.selectAllEnd=this.selectByWordsEnd=this.selectByLinesEnd=function(){this.editor.unsetStyle("ace_selecting"),this.editor.renderer.scroller.releaseCapture&&this.editor.renderer.scroller.releaseCapture()},this.focusWait=function(){var e=i(this.mousedownEvent.x,this.mousedownEvent.y,this.x,this.y),t=Date.now();(e>f||t-this.mousedownEvent.time>this.$focusTimout)&&this.startSelect(this.mousedownEvent.getDocumentPosition())},this.onDoubleClick=function(e){var t=e.getDocumentPosition(),n=this.editor,r=n.session,i=r.getBracketRange(t);i?(i.isEmpty()&&(i.start.column--,i.end.column++),this.setState("select")):(i=n.selection.getWordRange(t.row,t.column),this.setState("selectByWords")),this.$clickSelection=i,this[this.state]&&this[this.state](e)},this.onTripleClick=function(e){var t=e.getDocumentPosition(),n=this.editor;this.setState("selectByLines"),this.$clickSelection=n.selection.getLineRange(t.row),this[this.state]&&this[this.state](e)},this.onQuadClick=function(e){var t=this.editor;t.selectAll(),this.$clickSelection=t.getSelectionRange(),this.setState("selectAll")},this.onMouseWheel=function(e){if(e.getAccelKey())return;e.getShiftKey()&&e.wheelY&&!e.wheelX&&(e.wheelX=e.wheelY,e.wheelY=0);var t=e.domEvent.timeStamp,n=t-(this.$lastScrollTime||0),r=this.editor,i=r.renderer.isScrollableBy(e.wheelX*e.speed,e.wheelY*e.speed);if(i||n<200)return this.$lastScrollTime=t,r.renderer.scrollBy(e.wheelX*e.speed,e.wheelY*e.speed),e.stop()}}).call(r.prototype),t.DefaultHandlers=r}),define("ace/renderloop",["require","exports","module","ace/lib/event"],function(e,t,n){var r=e("./lib/event"),i=function(e,t){this.onRender=e,this.pending=!1,this.changes=0,this.window=t||window};(function(){this.schedule=function(e){this.changes=this.changes|e;if(!this.pending&&this.changes){this.pending=!0;var t=this;r.nextFrame(function(){t.pending=!1;var e;while(e=t.changes)t.changes=0,t.onRender(e)},this.window)}}}).call(i.prototype),t.RenderLoop=i}),define("ace/mouse/mouse_handler",["require","exports","module","ace/lib/event","ace/lib/useragent","ace/mouse/default_handlers","ace/mouse/default_gutter_handler","ace/mouse/mouse_event","ace/mouse/dragdrop_handler","ace/config"],function(e,t,n){var r=e("../lib/event"),i=e("../lib/useragent"),s=e("./default_handlers").DefaultHandlers,o=e("./default_gutter_handler").GutterHandler,u=e("./mouse_event").MouseEvent,a=e("./dragdrop_handler").DragdropHandler,f=e("../config"),l=function(e){this.editor=e,new s(this),new o(this),new a(this);var t=e.renderer.getMouseEventTarget();r.addListener(t,"click",this.onMouseEvent.bind(this,"click")),r.addListener(t,"mousemove",this.onMouseMove.bind(this,"mousemove")),r.addMultiMouseDownListener(t,[300,300,250],this,"onMouseEvent"),e.renderer.scrollBarV&&(r.addMultiMouseDownListener(e.renderer.scrollBarV.inner,[300,300,250],this,"onMouseEvent"),r.addMultiMouseDownListener(e.renderer.scrollBarH.inner,[300,300,250],this,"onMouseEvent")),r.addMouseWheelListener(e.container,this.onMouseWheel.bind(this,"mousewheel"));var n=e.renderer.$gutter;r.addListener(n,"mousedown",this.onMouseEvent.bind(this,"guttermousedown")),r.addListener(n,"click",this.onMouseEvent.bind(this,"gutterclick")),r.addListener(n,"dblclick",this.onMouseEvent.bind(this,"gutterdblclick")),r.addListener(n,"mousemove",this.onMouseEvent.bind(this,"guttermousemove")),r.addListener(t,"mousedown",function(t){e.focus()}),r.addListener(n,"mousedown",function(t){return e.focus(),r.preventDefault(t)})};(function(){this.onMouseEvent=function(e,t){this.editor._emit(e,new u(t,this.editor))},this.onMouseMove=function(e,t){var n=this.editor._eventRegistry&&this.editor._eventRegistry.mousemove;if(!n||!n.length)return;this.editor._emit(e,new u(t,this.editor))},this.onMouseWheel=function(e,t){var n=new u(t,this.editor);n.speed=this.$scrollSpeed*2,n.wheelX=t.wheelX,n.wheelY=t.wheelY,this.editor._emit(e,n)},this.setState=function(e){this.state=e},this.captureMouse=function(e,t){this.x=e.x,this.y=e.y,this.isMousePressed=!0;var n=this.editor.renderer;n.$keepTextAreaAtCursor&&(n.$keepTextAreaAtCursor=null);var s=this,o=function(e){s.x=e.clientX,s.y=e.clientY,t&&t(e),s.mouseEvent=new u(e,s.editor),s.$mouseMoved=!0},a=function(e){clearInterval(l),f(),s[s.state+"End"]&&s[s.state+"End"](e),s.$clickSelection=null,n.$keepTextAreaAtCursor==null&&(n.$keepTextAreaAtCursor=!0,n.$moveTextAreaToCursor()),s.isMousePressed=!1,s.$onCaptureMouseMove=s.releaseMouse=null,s.onMouseEvent("mouseup",e)},f=function(){s[s.state]&&s[s.state](),s.$mouseMoved=!1};if(i.isOldIE&&e.domEvent.type=="dblclick")return setTimeout(function(){a(e)});s.$onCaptureMouseMove=o,s.releaseMouse=r.capture(this.editor.container,o,a);var l=setInterval(f,20)},this.releaseMouse=null}).call(l.prototype),f.defineOptions(l.prototype,"mouseHandler",{scrollSpeed:{initialValue:2},dragDelay:{initialValue:150},dragEnabled:{initialValue:!0},focusTimout:{initialValue:0},tooltipFollowsMouse:{initialValue:!0}}),t.MouseHandler=l}),define("ace/layer/font_metrics",["require","exports","module","ace/lib/oop","ace/lib/dom","ace/lib/lang","ace/lib/event_emitter"],function(e,t,n){var r=e("../lib/oop"),i=e("../lib/dom"),s=e("../lib/lang"),o=e("../lib/event_emitter").EventEmitter,u=0,a=t.FontMetrics=function(e,t){this.el=i.createElement("div"),this.$setMeasureNodeStyles(this.el.style,!0),this.$main=i.createElement("div"),this.$setMeasureNodeStyles(this.$main.style),this.$measureNode=i.createElement("div"),this.$setMeasureNodeStyles(this.$measureNode.style),this.el.appendChild(this.$main),this.el.appendChild(this.$measureNode),e.appendChild(this.el),u||this.$testFractionalRect(),this.$measureNode.textContent=s.stringRepeat("X",u),this.$characterSize={width:0,height:0},this.checkForSizeChanges()};(function(){r.implement(this,o),this.$characterSize={width:0,height:0},this.$testFractionalRect=function(){var e=i.createElement("div");this.$setMeasureNodeStyles(e.style),e.style.width="0.2px",document.documentElement.appendChild(e);var t=e.getBoundingClientRect().width;t>0&&t<1?u=1:u=100,e.parentNode.removeChild(e)},this.$setMeasureNodeStyles=function(e,t){e.width=e.height="auto",e.left=e.top="-100px",e.visibility="hidden",e.position="fixed",e.whiteSpace="pre",e.font="inherit",e.overflow=t?"hidden":"visible"},this.checkForSizeChanges=function(){var e=this.$measureSizes();if(e&&(this.$characterSize.width!==e.width||this.$characterSize.height!==e.height)){this.$measureNode.style.fontWeight="bold";var t=this.$measureSizes();this.$measureNode.style.fontWeight="",this.$characterSize=e,this.charSizes=Object.create(null),this.allowBoldFonts=t&&t.width===e.width&&t.height===e.height,this._emit("changeCharacterSize",{data:e})}},this.$pollSizeChanges=function(){if(this.$pollSizeChangesTimer)return this.$pollSizeChangesTimer;var e=this;return this.$pollSizeChangesTimer=setInterval(function(){e.checkForSizeChanges()},500)},this.setPolling=function(e){e?this.$pollSizeChanges():this.$pollSizeChangesTimer&&this.$pollSizeChangesTimer},this.$measureSizes=function(){var e=this.$measureNode.getBoundingClientRect(),t={height:e.height,width:e.width/u};return t.width===0||t.height===0?null:t},this.$measureCharWidth=function(e){this.$main.textContent=s.stringRepeat(e,u);var t=this.$main.getBoundingClientRect();return t.width/u},this.getCharacterWidth=function(e){var t=this.charSizes[e];return t===undefined&&(this.charSizes[e]=this.$measureCharWidth(e)/this.$characterSize.width),t},this.destroy=function(){clearInterval(this.$pollSizeChangesTimer),this.el&&this.el.parentNode&&this.el.parentNode.removeChild(this.el)}}).call(a.prototype)}),define("ace/keyboard/textinput",["require","exports","module","ace/lib/event","ace/lib/useragent","ace/lib/dom","ace/lib/lang"],function(e,t,n){var r=e("../lib/event"),i=e("../lib/useragent"),s=e("../lib/dom"),o=e("../lib/lang"),u=i.isChrome<18,a=function(e,t){function n(e){if(v)return;if(L)t=0,n=e?0:l.value.length-1;else var t=e?2:1,n=2;try{l.setSelectionRange(t,n)}catch(r){}}function a(){if(v)return;l.value=c,i.isWebKit&&E.schedule()}function f(){setTimeout(function(){m&&(l.style.cssText=m,m=""),t.renderer.$keepTextAreaAtCursor==null&&(t.renderer.$keepTextAreaAtCursor=!0,t.renderer.$moveTextAreaToCursor())},0)}var l=s.createElement("textarea");l.className="ace_text-input",i.isTouchPad&&l.setAttribute("x-palm-disable-auto-cap",!0),l.wrap="off",l.autocorrect="off",l.autocapitalize="off",l.spellcheck=!1,l.style.opacity="0",e.insertBefore(l,e.firstChild);var c="\ 1\ 1",h=!1,p=!1,d=!1,v=!1,m="",g=!0;try{var y=document.activeElement===l}catch(b){}r.addListener(l,"blur",function(){t.onBlur(),y=!1}),r.addListener(l,"focus",function(){y=!0,t.onFocus(),n()}),this.focus=function(){l.focus()},this.blur=function(){l.blur()},this.isFocused=function(){return y};var w=o.delayedCall(function(){y&&n(g)}),E=o.delayedCall(function(){v||(l.value=c,y&&n())});i.isWebKit||t.addEventListener("changeSelection",function(){t.selection.isEmpty()!=g&&(g=!g,w.schedule())}),a(),y&&t.onFocus();var S=function(e){return e.selectionStart===0&&e.selectionEnd===e.value.length};!l.setSelectionRange&&l.createTextRange&&(l.setSelectionRange=function(e,t){var n=this.createTextRange();n.collapse(!0),n.moveStart("character",e),n.moveEnd("character",t),n.select()},S=function(e){try{var t=e.ownerDocument.selection.createRange()}catch(n){}return!t||t.parentElement()!=e?!1:t.text==e.value});if(i.isOldIE){var x=!1,T=function(e){if(x)return;var t=l.value;if(v||!t||t==c)return;if(e&&t==c[0])return N.schedule();O(t),x=!0,a(),x=!1},N=o.delayedCall(T);r.addListener(l,"propertychange",T);var C={13:1,27:1};r.addListener(l,"keyup",function(e){v&&(!l.value||C[e.keyCode])&&setTimeout(j,0);if((l.value.charCodeAt(0)||0)<129)return N.call();v?B():H()}),r.addListener(l,"keydown",function(e){N.schedule(50)})}var k=function(e){h?h=!1:p?p=!1:S(l)?(t.selectAll(),n()):L&&n(t.selection.isEmpty())},L=null;this.setInputHandler=function(e){L=e},this.getInputHandler=function(){return L};var A=!1,O=function(e){L&&(e=L(e),L=null),d?(n(),e&&t.onPaste(e),d=!1):e==c.charAt(0)?A?t.execCommand("del",{source:"ace"}):t.execCommand("backspace",{source:"ace"}):(e.substring(0,2)==c?e=e.substr(2):e.charAt(0)==c.charAt(0)?e=e.substr(1):e.charAt(e.length-1)==c.charAt(0)&&(e=e.slice(0,-1)),e.charAt(e.length-1)==c.charAt(0)&&(e=e.slice(0,-1)),e&&t.onTextInput(e)),A&&(A=!1)},M=function(e){if(v)return;var t=l.value;O(t),a()},_=function(e){var i=t.getCopyText();if(!i){r.preventDefault(e);return}var s=e.clipboardData||window.clipboardData;if(s&&!u){var o=s.setData("Text",i);o&&(t.onCut(),r.preventDefault(e))}o||(h=!0,l.value=i,l.select(),setTimeout(function(){h=!1,a(),n(),t.onCut()}))},D=function(e){var i=t.getCopyText();if(!i){r.preventDefault(e);return}var s=e.clipboardData||window.clipboardData;if(s&&!u){var o=s.setData("Text",i);o&&(t.onCopy(),r.preventDefault(e))}o||(p=!0,l.value=i,l.select(),setTimeout(function(){p=!1,a(),n(),t.onCopy()}))},P=function(e){var s=e.clipboardData||window.clipboardData;if(s){var o=s.getData("Text");o&&t.onPaste(o),i.isIE&&setTimeout(n),r.preventDefault(e)}else l.value="",d=!0};r.addCommandKeyListener(l,t.onCommandKey.bind(t)),r.addListener(l,"select",k),r.addListener(l,"input",M),r.addListener(l,"cut",_),r.addListener(l,"copy",D),r.addListener(l,"paste",P),(!("oncut"in l)||!("oncopy"in l)||!("onpaste"in l))&&r.addListener(e,"keydown",function(e){if(i.isMac&&!e.metaKey||!e.ctrlKey)return;switch(e.keyCode){case 67:D(e);break;case 86:P(e);break;case 88:_(e)}});var H=function(e){if(v||!t.onCompositionStart)return;v={},t.onCompositionStart(),setTimeout(B,0),t.on("mousedown",j),t.selection.isEmpty()||(t.insert(""),t.session.markUndoGroup(),t.selection.clearSelection()),t.session.markUndoGroup()},B=function(){if(!v||!t.onCompositionUpdate)return;var e=l.value.replace(/\x01/g,"");if(v.lastValue===e)return;t.onCompositionUpdate(e),v.lastValue&&t.undo(),v.lastValue=e;if(v.lastValue){var n=t.selection.getRange();t.insert(v.lastValue),t.session.markUndoGroup(),v.range=t.selection.getRange(),t.selection.setRange(n),t.selection.clearSelection()}},j=function(e){if(!t.onCompositionEnd)return;var n=v;v=!1;var r=setTimeout(function(){r=null;var e=l.value.replace(/\x01/g,"");if(v)return;e==n.lastValue?a():!n.lastValue&&e&&(a(),O(e))});L=function(e){return r&&clearTimeout(r),e=e.replace(/\x01/g,""),e==n.lastValue?"":(n.lastValue&&r&&t.undo(),e)},t.onCompositionEnd(),t.removeListener("mousedown",j),e.type=="compositionend"&&n.range&&t.selection.setRange(n.range)},F=o.delayedCall(B,50);r.addListener(l,"compositionstart",H),i.isGecko?r.addListener(l,"text",function(){F.schedule()}):(r.addListener(l,"keyup",function(){F.schedule()}),r.addListener(l,"keydown",function(){F.schedule()})),r.addListener(l,"compositionend",j),this.getElement=function(){return l},this.setReadOnly=function(e){l.readOnly=e},this.onContextMenu=function(e){A=!0,m||(m=l.style.cssText),l.style.cssText="z-index:100000;"+(i.isIE?"opacity:0.1;":""),n(t.selection.isEmpty()),t._emit("nativecontextmenu",{target:t,domEvent:e});var o=t.container.getBoundingClientRect(),u=s.computedStyle(t.container),a=o.top+(parseInt(u.borderTopWidth)||0),c=o.left+(parseInt(o.borderLeftWidth)||0),h=o.bottom-a-l.clientHeight,p=function(e){l.style.left=e.clientX-c-2+"px",l.style.top=Math.min(e.clientY-a-2,h)+"px"};p(e);if(e.type!="mousedown")return;t.renderer.$keepTextAreaAtCursor&&(t.renderer.$keepTextAreaAtCursor=null),i.isWin&&r.capture(t.container,p,f)},this.onContextMenuClose=f;if(!i.isGecko||i.isMac){var I=function(e){t.textInput.onContextMenu(e),f()};r.addListener(t.renderer.scroller,"contextmenu",I),r.addListener(l,"contextmenu",I)}};t.TextInput=a}),define("ace/lib/lang",["require","exports","module"],function(e,t,n){t.last=function(e){return e[e.length-1]},t.stringReverse=function(e){return e.split("").reverse().join("")},t.stringRepeat=function(e,t){var n="";while(t>0){t&1&&(n+=e);if(t>>=1)e+=e}return n};var r=/^\s\s*/,i=/\s\s*$/;t.stringTrimLeft=function(e){return e.replace(r,"")},t.stringTrimRight=function(e){return e.replace(i,"")},t.copyObject=function(e){var t={};for(var n in e)t[n]=e[n];return t},t.copyArray=function(e){var t=[];for(var n=0,r=e.length;n<r;n++)e[n]&&typeof e[n]=="object"?t[n]=this.copyObject(e[n]):t[n]=e[n];return t},t.deepCopy=function(e){if(typeof e!="object"||!e)return e;var n=e.constructor;if(n===RegExp)return e;var r=n();for(var i in e)typeof e[i]=="object"?r[i]=t.deepCopy(e[i]):r[i]=e[i];return r},t.arrayToMap=function(e){var t={};for(var n=0;n<e.length;n++)t[e[n]]=1;return t},t.createMap=function(e){var t=Object.create(null);for(var n in e)t[n]=e[n];return t},t.arrayRemove=function(e,t){for(var n=0;n<=e.length;n++)t===e[n]&&e.splice(n,1)},t.escapeRegExp=function(e){return e.replace(/([.*+?^${}()|[\]\/\\])/g,"\\$1")},t.escapeHTML=function(e){return e.replace(/&/g,"&").replace(/"/g,""").replace(/'/g,"'").replace(/</g,"<")},t.getMatchOffsets=function(e,t){var n=[];return e.replace(t,function(e){n.push({offset:arguments[arguments.length-2],length:e.length})}),n},t.deferredCall=function(e){var t=null,n=function(){t=null,e()},r=function(e){return r.cancel(),t=setTimeout(n,e||0),r};return r.schedule=r,r.call=function(){return this.cancel(),e(),r},r.cancel=function(){return clearTimeout(t),t=null,r},r.isPending=function(){return t},r},t.delayedCall=function(e,t){var n=null,r=function(){n=null,e()},i=function(e){n==null&&(n=setTimeout(r,e||t))};return i.delay=function(e){n&&clearTimeout(n),n=setTimeout(r,e||t)},i.schedule=i,i.call=function(){this.cancel(),e()},i.cancel=function(){n&&clearTimeout(n),n=null},i.isPending=function(){return n},i}}),define("ace/multi_select",["require","exports","module","ace/range_list","ace/range","ace/selection","ace/mouse/multi_select_handler","ace/lib/event","ace/lib/lang","ace/commands/multi_select_commands","ace/search","ace/edit_session","ace/editor","ace/config"],function(e,t,n){function r(e,t,n){return v.$options.wrap=!0,v.$options.needle=t,v.$options.backwards=n==-1,v.find(e)}function i(e,t){return e.row==t.row&&e.column==t.column}function s(e){if(e.$multiselectOnSessionChange)return;e.$onAddRange=e.$onAddRange.bind(e),e.$onRemoveRange=e.$onRemoveRange.bind(e),e.$onMultiSelect=e.$onMultiSelect.bind(e),e.$onSingleSelect=e.$onSingleSelect.bind(e),e.$multiselectOnSessionChange=t.onSessionChange.bind(e),e.$multiselectOnSessionChange(e),e.on("changeSession",e.$multiselectOnSessionChange),e.on("mousedown",l),e.commands.addCommands(p.defaultCommands),o(e)}function o(e){function t(t){r&&(e.renderer.setMouseCursor(""),r=!1)}var n=e.textInput.getElement(),r=!1;c.addListener(n,"keydown",function(n){n.keyCode==18&&!(n.ctrlKey||n.shiftKey||n.metaKey)?r||(e.renderer.setMouseCursor("crosshair"),r=!0):r&&t()}),c.addListener(n,"keyup",t),c.addListener(n,"blur",t)}var u=e("./range_list").RangeList,a=e("./range").Range,f=e("./selection").Selection,l=e("./mouse/multi_select_handler").onMouseDown,c=e("./lib/event"),h=e("./lib/lang"),p=e("./commands/multi_select_commands");t.commands=p.defaultCommands.concat(p.multiSelectCommands);var d=e("./search").Search,v=new d,m=e("./edit_session").EditSession;(function(){this.getSelectionMarkers=function(){return this.$selectionMarkers}}).call(m.prototype),function(){this.ranges=null,this.rangeList=null,this.addRange=function(e,t){if(!e)return;if(!this.inMultiSelectMode&&this.rangeCount==0){var n=this.toOrientedRange();this.rangeList.add(n),this.rangeList.add(e);if(this.rangeList.ranges.length!=2)return this.rangeList.removeAll(),t||this.fromOrientedRange(e);this.rangeList.removeAll(),this.rangeList.add(n),this.$onAddRange(n)}e.cursor||(e.cursor=e.end);var r=this.rangeList.add(e);return this.$onAddRange(e),r.length&&this.$onRemoveRange(r),this.rangeCount>1&&!this.inMultiSelectMode&&(this._signal("multiSelect"),this.inMultiSelectMode=!0,this.session.$undoSelect=!1,this.rangeList.attach(this.session)),t||this.fromOrientedRange(e)},this.toSingleRange=function(e){e=e||this.ranges[0];var t=this.rangeList.removeAll();t.length&&this.$onRemoveRange(t),e&&this.fromOrientedRange(e)},this.substractPoint=function(e){var t=this.rangeList.substractPoint(e);if(t)return this.$onRemoveRange(t),t[0]},this.mergeOverlappingRanges=function(){var e=this.rangeList.merge();e.length?this.$onRemoveRange(e):this.ranges[0]&&this.fromOrientedRange(this.ranges[0])},this.$onAddRange=function(e){this.rangeCount=this.rangeList.ranges.length,this.ranges.unshift(e),this._signal("addRange",{range:e})},this.$onRemoveRange=function(e){this.rangeCount=this.rangeList.ranges.length;if(this.rangeCount==1&&this.inMultiSelectMode){var t=this.rangeList.ranges.pop();e.push(t),this.rangeCount=0}for(var n=e.length;n--;){var r=this.ranges.indexOf(e[n]);this.ranges.splice(r,1)}this._signal("removeRange",{ranges:e}),this.rangeCount==0&&this.inMultiSelectMode&&(this.inMultiSelectMode=!1,this._signal("singleSelect"),this.session.$undoSelect=!0,this.rangeList.detach(this.session)),t=t||this.ranges[0],t&&!t.isEqual(this.getRange())&&this.fromOrientedRange(t)},this.$initRangeList=function(){if(this.rangeList)return;this.rangeList=new u,this.ranges=[],this.rangeCount=0},this.getAllRanges=function(){return this.rangeCount?this.rangeList.ranges.concat():[this.getRange()]},this.splitIntoLines=function(){if(this.rangeCount>1){var e=this.rangeList.ranges,t=e[e.length-1],n=a.fromPoints(e[0].start,t.end);this.toSingleRange(),this.setSelectionRange(n,t.cursor==t.start)}else{var n=this.getRange(),r=this.isBackwards(),i=n.start.row,s=n.end.row;if(i==s){if(r)var o=n.end,u=n.start;else var o=n.start,u=n.end;this.addRange(a.fromPoints(u,u)),this.addRange(a.fromPoints(o,o));return}var f=[],l=this.getLineRange(i,!0);l.start.column=n.start.column,f.push(l);for(var c=i+1;c<s;c++)f.push(this.getLineRange(c,!0));l=this.getLineRange(s,!0),l.end.column=n.end.column,f.push(l),f.forEach(this.addRange,this)}},this.toggleBlockSelection=function(){if(this.rangeCount>1){var e=this.rangeList.ranges,t=e[e.length-1],n=a.fromPoints(e[0].start,t.end);this.toSingleRange(),this.setSelectionRange(n,t.cursor==t.start)}else{var r=this.session.documentToScreenPosition(this.selectionLead),i=this.session.documentToScreenPosition(this.selectionAnchor),s=this.rectangularRangeBlock(r,i);s.forEach(this.addRange,this)}},this.rectangularRangeBlock=function(e,t,n){var r=[],s=e.column<t.column;if(s)var o=e.column,u=t.column;else var o=t.column,u=e.column;var f=e.row<t.row;if(f)var l=e.row,c=t.row;else var l=t.row,c=e.row;o<0&&(o=0),l<0&&(l=0),l==c&&(n=!0);for(var h=l;h<=c;h++){var p=a.fromPoints(this.session.screenToDocumentPosition(h,o),this.session.screenToDocumentPosition(h,u));if(p.isEmpty()){if(d&&i(p.end,d))break;var d=p.end}p.cursor=s?p.start:p.end,r.push(p)}f&&r.reverse();if(!n){var v=r.length-1;while(r[v].isEmpty()&&v>0)v--;if(v>0){var m=0;while(r[m].isEmpty())m++}for(var g=v;g>=m;g--)r[g].isEmpty()&&r.splice(g,1)}return r}}.call(f.prototype);var g=e("./editor").Editor;(function(){this.updateSelectionMarkers=function(){this.renderer.updateCursor(),this.renderer.updateBackMarkers()},this.addSelectionMarker=function(e){e.cursor||(e.cursor=e.end);var t=this.getSelectionStyle();return e.marker=this.session.addMarker(e,"ace_selection",t),this.session.$selectionMarkers.push(e),this.session.selectionMarkerCount=this.session.$selectionMarkers.length,e},this.removeSelectionMarker=function(e){if(!e.marker)return;this.session.removeMarker(e.marker);var t=this.session.$selectionMarkers.indexOf(e);t!=-1&&this.session.$selectionMarkers.splice(t,1),this.session.selectionMarkerCount=this.session.$selectionMarkers.length},this.removeSelectionMarkers=function(e){var t=this.session.$selectionMarkers;for(var n=e.length;n--;){var r=e[n];if(!r.marker)continue;this.session.removeMarker(r.marker);var i=t.indexOf(r);i!=-1&&t.splice(i,1)}this.session.selectionMarkerCount=t.length},this.$onAddRange=function(e){this.addSelectionMarker(e.range),this.renderer.updateCursor(),this.renderer.updateBackMarkers()},this.$onRemoveRange=function(e){this.removeSelectionMarkers(e.ranges),this.renderer.updateCursor(),this.renderer.updateBackMarkers()},this.$onMultiSelect=function(e){if(this.inMultiSelectMode)return;this.inMultiSelectMode=!0,this.setStyle("ace_multiselect"),this.keyBinding.addKeyboardHandler(p.keyboardHandler),this.commands.setDefaultHandler("exec",this.$onMultiSelectExec),this.renderer.updateCursor(),this.renderer.updateBackMarkers()},this.$onSingleSelect=function(e){if(this.session.multiSelect.inVirtualMode)return;this.inMultiSelectMode=!1,this.unsetStyle("ace_multiselect"),this.keyBinding.removeKeyboardHandler(p.keyboardHandler),this.commands.removeDefaultHandler("exec",this.$onMultiSelectExec),this.renderer.updateCursor(),this.renderer.updateBackMarkers(),this._emit("changeSelection")},this.$onMultiSelectExec=function(e){var t=e.command,n=e.editor;if(!n.multiSelect)return;if(!t.multiSelectAction){var r=t.exec(n,e.args||{});n.multiSelect.addRange(n.multiSelect.toOrientedRange()),n.multiSelect.mergeOverlappingRanges()}else t.multiSelectAction=="forEach"?r=n.forEachSelection(t,e.args):t.multiSelectAction=="forEachLine"?r=n.forEachSelection(t,e.args,!0):t.multiSelectAction=="single"?(n.exitMultiSelectMode(),r=t.exec(n,e.args||{})):r=t.multiSelectAction(n,e.args||{});return r},this.forEachSelection=function(e,t,n){if(this.inVirtualSelectionMode)return;var r=this.session,i=this.selection,s=i.rangeList,o,u=i._eventRegistry;i._eventRegistry={};var a=new f(r);this.inVirtualSelectionMode=!0;for(var l=s.ranges.length;l--;){if(n)while(l>0&&s.ranges[l].start.row==s.ranges[l-1].end.row)l--;a.fromOrientedRange(s.ranges[l]),a.id=s.ranges[l].marker,this.selection=r.selection=a;var c=e.exec(this,t||{});o!==undefined&&(o=c),a.toOrientedRange(s.ranges[l])}a.detach(),this.selection=r.selection=i,this.inVirtualSelectionMode=!1,i._eventRegistry=u,i.mergeOverlappingRanges();var h=this.renderer.$scrollAnimation;return this.onCursorChange(),this.onSelectionChange(),h&&h.from==h.to&&this.renderer.animateScrolling(h.from),o},this.exitMultiSelectMode=function(){if(!this.inMultiSelectMode||this.inVirtualSelectionMode)return;this.multiSelect.toSingleRange()},this.getSelectedText=function(){var e="";if(this.inMultiSelectMode&&!this.inVirtualSelectionMode){var t=this.multiSelect.rangeList.ranges,n=[];for(var r=0;r<t.length;r++)n.push(this.session.getTextRange(t[r]));var i=this.session.getDocument().getNewLineCharacter();e=n.join(i),e.length==(n.length-1)*i.length&&(e="")}else this.selection.isEmpty()||(e=this.session.getTextRange(this.getSelectionRange()));return e},this.onPaste=function(e){if(this.$readOnly)return;var t={text:e};this._signal("paste",t),e=t.text;if(!this.inMultiSelectMode||this.inVirtualSelectionMode)return this.insert(e);var n=e.split(/\r\n|\r|\n/),r=this.selection.rangeList.ranges;if(n.length>r.length||n.length<2||!n[1])return this.commands.exec("insertstring",this,e);for(var i=r.length;i--;){var s=r[i];s.isEmpty()||this.session.remove(s),this.session.insert(s.start,n[i])}},this.findAll=function(e,t,n){t=t||{},t.needle=e||t.needle,this.$search.set(t);var r=this.$search.findAll(this.session);if(!r.length)return 0;this.$blockScrolling+=1;var i=this.multiSelect;n||i.toSingleRange(r[0]);for(var s=r.length;s--;)i.addRange(r[s],!0);return this.$blockScrolling-=1,r.length},this.selectMoreLines=function(e,t){var n=this.selection.toOrientedRange(),r=n.cursor==n.end,i=this.session.documentToScreenPosition(n.cursor);this.selection.$desiredColumn&&(i.column=this.selection.$desiredColumn);var s=this.session.screenToDocumentPosition(i.row+e,i.column);if(!n.isEmpty())var o=this.session.documentToScreenPosition(r?n.end:n.start),u=this.session.screenToDocumentPosition(o.row+e,o.column);else var u=s;if(r){var f=a.fromPoints(s,u);f.cursor=f.start}else{var f=a.fromPoints(u,s);f.cursor=f.end}f.desiredColumn=i.column;if(!this.selection.inMultiSelectMode)this.selection.addRange(n);else if(t)var l=n.cursor;this.selection.addRange(f),l&&this.selection.substractPoint(l)},this.transposeSelections=function(e){var t=this.session,n=t.multiSelect,r=n.ranges;for(var i=r.length;i--;){var s=r[i];if(s.isEmpty()){var o=t.getWordRange(s.start.row,s.start.column);s.start.row=o.start.row,s.start.column=o.start.column,s.end.row=o.end.row,s.end.column=o.end.column}}n.mergeOverlappingRanges();var u=[];for(var i=r.length;i--;){var s=r[i];u.unshift(t.getTextRange(s))}e<0?u.unshift(u.pop()):u.push(u.shift());for(var i=r.length;i--;){var s=r[i],o=s.clone();t.replace(s,u[i]),s.start.row=o.start.row,s.start.column=o.start.column}},this.selectMore=function(e,t){var n=this.session,i=n.multiSelect,s=i.toOrientedRange();s.isEmpty()&&(s=n.getWordRange(s.start.row,s.start.column),s.cursor=e==-1?s.start:s.end,this.multiSelect.addRange(s));var o=n.getTextRange(s),u=r(n,o,e);u&&(u.cursor=e==-1?u.start:u.end,this.$blockScrolling+=1,this.session.unfold(u),this.multiSelect.addRange(u),this.$blockScrolling-=1,this.renderer.scrollCursorIntoView(null,.5)),t&&this.multiSelect.substractPoint(s.cursor)},this.alignCursors=function(){var e=this.session,t=e.multiSelect,n=t.ranges;if(!n.length){var r=this.selection.getRange(),i=r.start.row,s=r.end.row,o=i==s;if(o){var u=this.session.getLength(),f;do f=this.session.getLine(s);while(/[=:]/.test(f)&&++s<u);do f=this.session.getLine(i);while(/[=:]/.test(f)&&--i>0);i<0&&(i=0),s>=u&&(s=u-1)}var l=this.session.doc.removeLines(i,s);l=this.$reAlignText(l,o),this.session.doc.insert({row:i,column:0},l.join("\n")+"\n"),o||(r.start.column=0,r.end.column=l[l.length-1].length),this.selection.setRange(r)}else{var c=-1,p=n.filter(function(e){if(e.cursor.row==c)return!0;c=e.cursor.row});t.$onRemoveRange(p);var d=0,v=Infinity,m=n.map(function(t){var n=t.cursor,r=e.getLine(n.row),i=r.substr(n.column).search(/\S/g);return i==-1&&(i=0),n.column>d&&(d=n.column),i<v&&(v=i),i});n.forEach(function(t,n){var r=t.cursor,i=d-r.column,s=m[n]-v;i>s?e.insert(r,h.stringRepeat(" ",i-s)):e.remove(new a(r.row,r.column,r.row,r.column-i+s)),t.start.column=t.end.column=d,t.start.row=t.end.row=r.row,t.cursor=t.end}),t.fromOrientedRange(n[0]),this.renderer.updateCursor(),this.renderer.updateBackMarkers()}},this.$reAlignText=function(e,t){function n(e){return h.stringRepeat(" ",e)}function r(e){return e[2]?n(a)+e[2]+n(f-e[2].length+l)+e[4].replace(/^([=:])\s+/,"$1 "):e[0]}function i(e){return e[2]?n(a+f-e[2].length)+e[2]+n(l," ")+e[4].replace(/^([=:])\s+/,"$1 "):e[0]}function s(e){return e[2]?n(a)+e[2]+n(l)+e[4].replace(/^([=:])\s+/,"$1 "):e[0]}var o=!0,u=!0,a,f,l;return e.map(function(e){var t=e.match(/(\s*)(.*?)(\s*)([=:].*)/);return t?a==null?(a=t[1].length,f=t[2].length,l=t[3].length,t):(a+f+l!=t[1].length+t[2].length+t[3].length&&(u=!1),a!=t[1].length&&(o=!1),a>t[1].length&&(a=t[1].length),f<t[2].length&&(f=t[2].length),l>t[3].length&&(l=t[3].length),t):[e]}).map(t?r:o?u?i:r:s)}}).call(g.prototype),t.onSessionChange=function(e){var t=e.session;t.multiSelect||(t.$selectionMarkers=[],t.selection.$initRangeList(),t.multiSelect=t.selection),this.multiSelect=t.multiSelect;var n=e.oldSession;n&&(n.multiSelect.removeEventListener("addRange",this.$onAddRange),n.multiSelect.removeEventListener("removeRange",this.$onRemoveRange),n.multiSelect.removeEventListener("multiSelect",this.$onMultiSelect),n.multiSelect.removeEventListener("singleSelect",this.$onSingleSelect)),t.multiSelect.on("addRange",this.$onAddRange),t.multiSelect.on("removeRange",this.$onRemoveRange),t.multiSelect.on("multiSelect",this.$onMultiSelect),t.multiSelect.on("singleSelect",this.$onSingleSelect),this.inMultiSelectMode!=t.selection.inMultiSelectMode&&(t.selection.inMultiSelectMode?this.$onMultiSelect():this.$onSingleSelect())},t.MultiSelect=s,e("./config").defineOptions(g.prototype,"editor",{enableMultiselect:{set:function(e){s(this),e?(this.on("changeSession",this.$multiselectOnSessionChange),this.on("mousedown",l)):(this.off("changeSession",this.$multiselectOnSessionChange),this.off("mousedown",l))},value:!0}})}),define("ace/editor",["require","exports","module","ace/lib/fixoldbrowsers","ace/lib/oop","ace/lib/dom","ace/lib/lang","ace/lib/useragent","ace/keyboard/textinput","ace/mouse/mouse_handler","ace/mouse/fold_handler","ace/keyboard/keybinding","ace/edit_session","ace/search","ace/range","ace/lib/event_emitter","ace/commands/command_manager","ace/commands/default_commands","ace/config"],function(e,t,n){e("./lib/fixoldbrowsers");var r=e("./lib/oop"),i=e("./lib/dom"),s=e("./lib/lang"),o=e("./lib/useragent"),u=e("./keyboard/textinput").TextInput,a=e("./mouse/mouse_handler").MouseHandler,f=e("./mouse/fold_handler").FoldHandler,l=e("./keyboard/keybinding").KeyBinding,c=e("./edit_session").EditSession,h=e("./search").Search,p=e("./range").Range,d=e("./lib/event_emitter").EventEmitter,v=e("./commands/command_manager").CommandManager,m=e("./commands/default_commands").commands,g=e("./config"),y=function(e,t){var n=e.getContainerElement();this.container=n,this.renderer=e,this.commands=new v(o.isMac?"mac":"win",m),this.textInput=new u(e.getTextAreaContainer(),this),this.renderer.textarea=this.textInput.getElement(),this.keyBinding=new l(this),this.$mouseHandler=new a(this),new f(this),this.$blockScrolling=0,this.$search=(new h).set({wrap:!0}),this.$historyTracker=this.$historyTracker.bind(this),this.commands.on("exec",this.$historyTracker),this.$initOperationListeners(),this._$emitInputEvent=s.delayedCall(function(){this._signal("input",{}),this.session.bgTokenizer&&this.session.bgTokenizer.scheduleStart()}.bind(this)),this.on("change",function(e,t){t._$emitInputEvent.schedule(31)}),this.setSession(t||new c("")),g.resetOptions(this),g._signal("editor",this)};(function(){r.implement(this,d),this.$initOperationListeners=function(){function e(e){return e[e.length-1]}this.selections=[],this.commands.on("exec",function(t){this.startOperation(t);var n=t.command;if(n.aceCommandGroup=="fileJump"){var r=this.prevOp;if(!r||r.command.aceCommandGroup!="fileJump")this.lastFileJumpPos=e(this.selections)}else this.lastFileJumpPos=null}.bind(this),!0),this.commands.on("afterExec",function(e){var t=e.command;t.aceCommandGroup=="fileJump"&&this.lastFileJumpPos&&!this.curOp.selectionChanged&&this.selection.fromJSON(this.lastFileJumpPos),this.endOperation(e)}.bind(this),!0),this.$opResetTimer=s.delayedCall(this.endOperation.bind(this)),this.on("change",function(){this.curOp||this.startOperation(),this.curOp.docChanged=!0}.bind(this),!0),this.on("changeSelection",function(){this.curOp||this.startOperation(),this.curOp.selectionChanged=!0}.bind(this),!0)},this.curOp=null,this.prevOp={},this.startOperation=function(e){if(this.curOp){if(!e||this.curOp.command)return;this.prevOp=this.curOp}e||(this.previousCommand=null,e={}),this.$opResetTimer.schedule(),this.curOp={command:e.command||{},args:e.args,scrollTop:this.renderer.scrollTop};var t=this.curOp.command;t&&t.scrollIntoView&&this.$blockScrolling++,this.selections.push(this.selection.toJSON())},this.endOperation=function(){if(this.curOp){var e=this.curOp.command;if(e&&e.scrollIntoView){this.$blockScrolling--;switch(e.scrollIntoView){case"center":this.renderer.scrollCursorIntoView(null,.5);break;case"animate":case"cursor":this.renderer.scrollCursorIntoView();break;case"selectionPart":var t=this.selection.getRange(),n=this.renderer.layerConfig;(t.start.row>=n.lastRow||t.end.row<=n.firstRow)&&this.renderer.scrollSelectionIntoView(this.selection.anchor,this.selection.lead);break;default:}e.scrollIntoView=="animate"&&this.renderer.animateScrolling(this.curOp.scrollTop)}this.prevOp=this.curOp,this.curOp=null}},this.$historyTracker=function(e){if(!this.$mergeUndoDeltas)return;var t=this.prevOp,n=["backspace","del","insertstring"],r=t.command&&e.command.name==t.command.name;if(e.command.name=="insertstring"){var i=e.args;this.mergeNextCommand===undefined&&(this.mergeNextCommand=!0),r=r&&this.mergeNextCommand&&(!/\s/.test(i)||/\s/.test(t.args)),this.mergeNextCommand=!0}else r=r&&n.indexOf(e.command.name)!==-1;this.$mergeUndoDeltas!="always"&&Date.now()-this.sequenceStartTime>2e3&&(r=!1),r?this.session.mergeUndoDeltas=!0:n.indexOf(e.command.name)!==-1&&(this.sequenceStartTime=Date.now())},this.setKeyboardHandler=function(e){if(!e)this.keyBinding.setKeyboardHandler(null);else if(typeof e=="string"){this.$keybindingId=e;var t=this;g.loadModule(["keybinding",e],function(n){t.$keybindingId==e&&t.keyBinding.setKeyboardHandler(n&&n.handler)})}else this.$keybindingId=null,this.keyBinding.setKeyboardHandler(e)},this.getKeyboardHandler=function(){return this.keyBinding.getKeyboardHandler()},this.setSession=function(e){if(this.session==e)return;var t=this.session;if(t){this.session.removeEventListener("change",this.$onDocumentChange),this.session.removeEventListener("changeMode",this.$onChangeMode),this.session.removeEventListener("tokenizerUpdate",this.$onTokenizerUpdate),this.session.removeEventListener("changeTabSize",this.$onChangeTabSize),this.session.removeEventListener("changeWrapLimit",this.$onChangeWrapLimit),this.session.removeEventListener("changeWrapMode",this.$onChangeWrapMode),this.session.removeEventListener("onChangeFold",this.$onChangeFold),this.session.removeEventListener("changeFrontMarker",this.$onChangeFrontMarker),this.session.removeEventListener("changeBackMarker",this.$onChangeBackMarker),this.session.removeEventListener("changeBreakpoint",this.$onChangeBreakpoint),this.session.removeEventListener("changeAnnotation",this.$onChangeAnnotation),this.session.removeEventListener("changeOverwrite",this.$onCursorChange),this.session.removeEventListener("changeScrollTop",this.$onScrollTopChange),this.session.removeEventListener("changeScrollLeft",this.$onScrollLeftChange);var n=this.session.getSelection();n.removeEventListener("changeCursor",this.$onCursorChange),n.removeEventListener("changeSelection",this.$onSelectionChange)}this.session=e,e&&(this.$onDocumentChange=this.onDocumentChange.bind(this),e.addEventListener("change",this.$onDocumentChange),this.renderer.setSession(e),this.$onChangeMode=this.onChangeMode.bind(this),e.addEventListener("changeMode",this.$onChangeMode),this.$onTokenizerUpdate=this.onTokenizerUpdate.bind(this),e.addEventListener("tokenizerUpdate",this.$onTokenizerUpdate),this.$onChangeTabSize=this.renderer.onChangeTabSize.bind(this.renderer),e.addEventListener("changeTabSize",this.$onChangeTabSize),this.$onChangeWrapLimit=this.onChangeWrapLimit.bind(this),e.addEventListener("changeWrapLimit",this.$onChangeWrapLimit),this.$onChangeWrapMode=this.onChangeWrapMode.bind(this),e.addEventListener("changeWrapMode",this.$onChangeWrapMode),this.$onChangeFold=this.onChangeFold.bind(this),e.addEventListener("changeFold",this.$onChangeFold),this.$onChangeFrontMarker=this.onChangeFrontMarker.bind(this),this.session.addEventListener("changeFrontMarker",this.$onChangeFrontMarker),this.$onChangeBackMarker=this.onChangeBackMarker.bind(this),this.session.addEventListener("changeBackMarker",this.$onChangeBackMarker),this.$onChangeBreakpoint=this.onChangeBreakpoint.bind(this),this.session.addEventListener("changeBreakpoint",this.$onChangeBreakpoint),this.$onChangeAnnotation=this.onChangeAnnotation.bind(this),this.session.addEventListener("changeAnnotation",this.$onChangeAnnotation),this.$onCursorChange=this.onCursorChange.bind(this),this.session.addEventListener("changeOverwrite",this.$onCursorChange),this.$onScrollTopChange=this.onScrollTopChange.bind(this),this.session.addEventListener("changeScrollTop",this.$onScrollTopChange),this.$onScrollLeftChange=this.onScrollLeftChange.bind(this),this.session.addEventListener("changeScrollLeft",this.$onScrollLeftChange),this.selection=e.getSelection(),this.selection.addEventListener("changeCursor",this.$onCursorChange),this.$onSelectionChange=this.onSelectionChange.bind(this),this.selection.addEventListener("changeSelection",this.$onSelectionChange),this.onChangeMode(),this.$blockScrolling+=1,this.onCursorChange(),this.$blockScrolling-=1,this.onScrollTopChange(),this.onScrollLeftChange(),this.onSelectionChange(),this.onChangeFrontMarker(),this.onChangeBackMarker(),this.onChangeBreakpoint(),this.onChangeAnnotation(),this.session.getUseWrapMode()&&this.renderer.adjustWrapLimit(),this.renderer.updateFull()),this._signal("changeSession",{session:e,oldSession:t}),t&&t._signal("changeEditor",{oldEditor:this}),e&&e._signal("changeEditor",{editor:this})},this.getSession=function(){return this.session},this.setValue=function(e,t){return this.session.doc.setValue(e),t?t==1?this.navigateFileEnd():t==-1&&this.navigateFileStart():this.selectAll(),e},this.getValue=function(){return this.session.getValue()},this.getSelection=function(){return this.selection},this.resize=function(e){this.renderer.onResize(e)},this.setTheme=function(e,t){this.renderer.setTheme(e,t)},this.getTheme=function(){return this.renderer.getTheme()},this.setStyle=function(e){this.renderer.setStyle(e)},this.unsetStyle=function(e){this.renderer.unsetStyle(e)},this.getFontSize=function(){return this.getOption("fontSize")||i.computedStyle(this.container,"fontSize")},this.setFontSize=function(e){this.setOption("fontSize",e)},this.$highlightBrackets=function(){this.session.$bracketHighlight&&(this.session.removeMarker(this.session.$bracketHighlight),this.session.$bracketHighlight=null);if(this.$highlightPending)return;var e=this;this.$highlightPending=!0,setTimeout(function(){e.$highlightPending=!1;var t=e.session.findMatchingBracket(e.getCursorPosition());if(t)var n=new p(t.row,t.column,t.row,t.column+1);else if(e.session.$mode.getMatching)var n=e.session.$mode.getMatching(e.session);n&&(e.session.$bracketHighlight=e.session.addMarker(n,"ace_bracket","text"))},50)},this.focus=function(){var e=this;setTimeout(function(){e.textInput.focus()}),this.textInput.focus()},this.isFocused=function(){return this.textInput.isFocused()},this.blur=function(){this.textInput.blur()},this.onFocus=function(){if(this.$isFocused)return;this.$isFocused=!0,this.renderer.showCursor(),this.renderer.visualizeFocus(),this._emit("focus")},this.onBlur=function(){if(!this.$isFocused)return;this.$isFocused=!1,this.renderer.hideCursor(),this.renderer.visualizeBlur(),this._emit("blur")},this.$cursorChange=function(){this.renderer.updateCursor()},this.onDocumentChange=function(e){var t=e.data,n=t.range,r;n.start.row==n.end.row&&t.action!="insertLines"&&t.action!="removeLines"?r=n.end.row:r=Infinity,this.renderer.updateLines(n.start.row,r),this._signal("change",e),this.$cursorChange()},this.onTokenizerUpdate=function(e){var t=e.data;this.renderer.updateLines(t.first,t.last)},this.onScrollTopChange=function(){this.renderer.scrollToY(this.session.getScrollTop())},this.onScrollLeftChange=function(){this.renderer.scrollToX(this.session.getScrollLeft())},this.onCursorChange=function(){this.$cursorChange(),this.$blockScrolling||this.renderer.scrollCursorIntoView(),this.$highlightBrackets(),this.$updateHighlightActiveLine(),this._signal("changeSelection")},this.$updateHighlightActiveLine=function(){var e=this.getSession(),t;if(this.$highlightActiveLine){if(this.$selectionStyle!="line"||!this.selection.isMultiLine())t=this.getCursorPosition();this.renderer.$maxLines&&this.session.getLength()===1&&!(this.renderer.$minLines>1)&&(t=!1)}if(e.$highlightLineMarker&&!t)e.removeMarker(e.$highlightLineMarker.id),e.$highlightLineMarker=null;else if(!e.$highlightLineMarker&&t){var n=new p(t.row,t.column,t.row,Infinity);n.id=e.addMarker(n,"ace_active-line","screenLine"),e.$highlightLineMarker=n}else t&&(e.$highlightLineMarker.start.row=t.row,e.$highlightLineMarker.end.row=t.row,e.$highlightLineMarker.start.column=t.column,e._signal("changeBackMarker"))},this.onSelectionChange=function(e){var t=this.session;t.$selectionMarker&&t.removeMarker(t.$selectionMarker),t.$selectionMarker=null;if(!this.selection.isEmpty()){var n=this.selection.getRange(),r=this.getSelectionStyle();t.$selectionMarker=t.addMarker(n,"ace_selection",r)}else this.$updateHighlightActiveLine();var i=this.$highlightSelectedWord&&this.$getSelectionHighLightRegexp();this.session.highlight(i),this._signal("changeSelection")},this.$getSelectionHighLightRegexp=function(){var e=this.session,t=this.getSelectionRange();if(t.isEmpty()||t.isMultiLine())return;var n=t.start.column-1,r=t.end.column+1,i=e.getLine(t.start.row),s=i.length,o=i.substring(Math.max(n,0),Math.min(r,s));if(n>=0&&/^[\w\d]/.test(o)||r<=s&&/[\w\d]$/.test(o))return;o=i.substring(t.start.column,t.end.column);if(!/^[\w\d]+$/.test(o))return;var u=this.$search.$assembleRegExp({wholeWord:!0,caseSensitive:!0,needle:o});return u},this.onChangeFrontMarker=function(){this.renderer.updateFrontMarkers()},this.onChangeBackMarker=function(){this.renderer.updateBackMarkers()},this.onChangeBreakpoint=function(){this.renderer.updateBreakpoints()},this.onChangeAnnotation=function(){this.renderer.setAnnotations(this.session.getAnnotations())},this.onChangeMode=function(e){this.renderer.updateText(),this._emit("changeMode",e)},this.onChangeWrapLimit=function(){this.renderer.updateFull()},this.onChangeWrapMode=function(){this.renderer.onResize(!0)},this.onChangeFold=function(){this.$updateHighlightActiveLine(),this.renderer.updateFull()},this.getSelectedText=function(){return this.session.getTextRange(this.getSelectionRange())},this.getCopyText=function(){var e=this.getSelectedText();return this._signal("copy",e),e},this.onCopy=function(){this.commands.exec("copy",this)},this.onCut=function(){this.commands.exec("cut",this)},this.onPaste=function(e){if(this.$readOnly)return;var t={text:e};this._signal("paste",t),this.insert(t.text,!0)},this.execCommand=function(e,t){this.commands.exec(e,this,t)},this.insert=function(e,t){var n=this.session,r=n.getMode(),i=this.getCursorPosition();if(this.getBehavioursEnabled()&&!t){var s=r.transformAction(n.getState(i.row),"insertion",this,n,e);s&&(e!==s.text&&(this.session.mergeUndoDeltas=!1,this.$mergeNextCommand=!1),e=s.text)}e==" "&&(e=this.session.getTabString());if(!this.selection.isEmpty()){var o=this.getSelectionRange();i=this.session.remove(o),this.clearSelection()}else if(this.session.getOverwrite()){var o=new p.fromPoints(i,i);o.end.column+=e.length,this.session.remove(o)}if(e=="\n"||e=="\r\n"){var u=n.getLine(i.row);if(i.column>u.search(/\S|$/)){var a=u.substr(i.column).search(/\S|$/);n.doc.removeInLine(i.row,i.column,i.column+a)}}this.clearSelection();var f=i.column,l=n.getState(i.row),u=n.getLine(i.row),c=r.checkOutdent(l,u,e),h=n.insert(i,e);s&&s.selection&&(s.selection.length==2?this.selection.setSelectionRange(new p(i.row,f+s.selection[0],i.row,f+s.selection[1])):this.selection.setSelectionRange(new p(i.row+s.selection[0],s.selection[1],i.row+s.selection[2],s.selection[3])));if(n.getDocument().isNewLine(e)){var d=r.getNextLineIndent(l,u.slice(0,i.column),n.getTabString());n.insert({row:i.row+1,column:0},d)}c&&r.autoOutdent(l,n,i.row)},this.onTextInput=function(e){this.keyBinding.onTextInput(e)},this.onCommandKey=function(e,t,n){this.keyBinding.onCommandKey(e,t,n)},this.setOverwrite=function(e){this.session.setOverwrite(e)},this.getOverwrite=function(){return this.session.getOverwrite()},this.toggleOverwrite=function(){this.session.toggleOverwrite()},this.setScrollSpeed=function(e){this.setOption("scrollSpeed",e)},this.getScrollSpeed=function(){return this.getOption("scrollSpeed")},this.setDragDelay=function(e){this.setOption("dragDelay",e)},this.getDragDelay=function(){return this.getOption("dragDelay")},this.setSelectionStyle=function(e){this.setOption("selectionStyle",e)},this.getSelectionStyle=function(){return this.getOption("selectionStyle")},this.setHighlightActiveLine=function(e){this.setOption("highlightActiveLine",e)},this.getHighlightActiveLine=function(){return this.getOption("highlightActiveLine")},this.setHighlightGutterLine=function(e){this.setOption("highlightGutterLine",e)},this.getHighlightGutterLine=function(){return this.getOption("highlightGutterLine")},this.setHighlightSelectedWord=function(e){this.setOption("highlightSelectedWord",e)},this.getHighlightSelectedWord=function(){return this.$highlightSelectedWord},this.setAnimatedScroll=function(e){this.renderer.setAnimatedScroll(e)},this.getAnimatedScroll=function(){return this.renderer.getAnimatedScroll()},this.setShowInvisibles=function(e){this.renderer.setShowInvisibles(e)},this.getShowInvisibles=function(){return this.renderer.getShowInvisibles()},this.setDisplayIndentGuides=function(e){this.renderer.setDisplayIndentGuides(e)},this.getDisplayIndentGuides=function(){return this.renderer.getDisplayIndentGuides()},this.setShowPrintMargin=function(e){this.renderer.setShowPrintMargin(e)},this.getShowPrintMargin=function(){return this.renderer.getShowPrintMargin()},this.setPrintMarginColumn=function(e){this.renderer.setPrintMarginColumn(e)},this.getPrintMarginColumn=function(){return this.renderer.getPrintMarginColumn()},this.setReadOnly=function(e){this.setOption("readOnly",e)},this.getReadOnly=function(){return this.getOption("readOnly")},this.setBehavioursEnabled=function(e){this.setOption("behavioursEnabled",e)},this.getBehavioursEnabled=function(){return this.getOption("behavioursEnabled")},this.setWrapBehavioursEnabled=function(e){this.setOption("wrapBehavioursEnabled",e)},this.getWrapBehavioursEnabled=function(){return this.getOption("wrapBehavioursEnabled")},this.setShowFoldWidgets=function(e){this.setOption("showFoldWidgets",e)},this.getShowFoldWidgets=function(){return this.getOption("showFoldWidgets")},this.setFadeFoldWidgets=function(e){this.setOption("fadeFoldWidgets",e)},this.getFadeFoldWidgets=function(){return this.getOption("fadeFoldWidgets")},this.remove=function(e){this.selection.isEmpty()&&(e=="left"?this.selection.selectLeft():this.selection.selectRight());var t=this.getSelectionRange();if(this.getBehavioursEnabled()){var n=this.session,r=n.getState(t.start.row),i=n.getMode().transformAction(r,"deletion",this,n,t);if(t.end.column===0){var s=n.getTextRange(t);if(s[s.length-1]=="\n"){var o=n.getLine(t.end.row);/^\s+$/.test(o)&&(t.end.column=o.length)}}i&&(t=i)}this.session.remove(t),this.clearSelection()},this.removeWordRight=function(){this.selection.isEmpty()&&this.selection.selectWordRight(),this.session.remove(this.getSelectionRange()),this.clearSelection()},this.removeWordLeft=function(){this.selection.isEmpty()&&this.selection.selectWordLeft(),this.session.remove(this.getSelectionRange()),this.clearSelection()},this.removeToLineStart=function(){this.selection.isEmpty()&&this.selection.selectLineStart(),this.session.remove(this.getSelectionRange()),this.clearSelection()},this.removeToLineEnd=function(){this.selection.isEmpty()&&this.selection.selectLineEnd();var e=this.getSelectionRange();e.start.column==e.end.column&&e.start.row==e.end.row&&(e.end.column=0,e.end.row++),this.session.remove(e),this.clearSelection()},this.splitLine=function(){this.selection.isEmpty()||(this.session.remove(this.getSelectionRange()),this.clearSelection());var e=this.getCursorPosition();this.insert("\n"),this.moveCursorToPosition(e)},this.transposeLetters=function(){if(!this.selection.isEmpty())return;var e=this.getCursorPosition(),t=e.column;if(t===0)return;var n=this.session.getLine(e.row),r,i;t<n.length?(r=n.charAt(t)+n.charAt(t-1),i=new p(e.row,t-1,e.row,t+1)):(r=n.charAt(t-1)+n.charAt(t-2),i=new p(e.row,t-2,e.row,t)),this.session.replace(i,r)},this.toLowerCase=function(){var e=this.getSelectionRange();this.selection.isEmpty()&&this.selection.selectWord();var t=this.getSelectionRange(),n=this.session.getTextRange(t);this.session.replace(t,n.toLowerCase()),this.selection.setSelectionRange(e)},this.toUpperCase=function(){var e=this.getSelectionRange();this.selection.isEmpty()&&this.selection.selectWord();var t=this.getSelectionRange(),n=this.session.getTextRange(t);this.session.replace(t,n.toUpperCase()),this.selection.setSelectionRange(e)},this.indent=function(){var e=this.session,t=this.getSelectionRange();if(t.start.row<t.end.row){var n=this.$getSelectedRows();e.indentRows(n.first,n.last," ");return}if(t.start.column<t.end.column){var r=e.getTextRange(t);if(!/^\s+$/.test(r)){var n=this.$getSelectedRows();e.indentRows(n.first,n.last," ");return}}var i=e.getLine(t.start.row),o=t.start,u=e.getTabSize(),a=e.documentToScreenColumn(o.row,o.column);if(this.session.getUseSoftTabs())var f=u-a%u,l=s.stringRepeat(" ",f);else{var f=a%u;while(i[t.start.column]==" "&&f)t.start.column--,f--;this.selection.setSelectionRange(t),l=" "}return this.insert(l)},this.blockIndent=function(){var e=this.$getSelectedRows();this.session.indentRows(e.first,e.last," ")},this.blockOutdent=function(){var e=this.session.getSelection();this.session.outdentRows(e.getRange())},this.sortLines=function(){var e=this.$getSelectedRows(),t=this.session,n=[];for(i=e.first;i<=e.last;i++)n.push(t.getLine(i));n.sort(function(e,t){return e.toLowerCase()<t.toLowerCase()?-1:e.toLowerCase()>t.toLowerCase()?1:0});var r=new p(0,0,0,0);for(var i=e.first;i<=e.last;i++){var s=t.getLine(i);r.start.row=i,r.end.row=i,r.end.column=s.length,t.replace(r,n[i-e.first])}},this.toggleCommentLines=function(){var e=this.session.getState(this.getCursorPosition().row),t=this.$getSelectedRows();this.session.getMode().toggleCommentLines(e,this.session,t.first,t.last)},this.toggleBlockComment=function(){var e=this.getCursorPosition(),t=this.session.getState(e.row),n=this.getSelectionRange();this.session.getMode().toggleBlockComment(t,this.session,n,e)},this.getNumberAt=function(e,t){var n=/[\-]?[0-9]+(?:\.[0-9]+)?/g;n.lastIndex=0;var r=this.session.getLine(e);while(n.lastIndex<t){var i=n.exec(r);if(i.index<=t&&i.index+i[0].length>=t){var s={value:i[0],start:i.index,end:i.index+i[0].length};return s}}return null},this.modifyNumber=function(e){var t=this.selection.getCursor().row,n=this.selection.getCursor().column,r=new p(t,n-1,t,n),i=this.session.getTextRange(r);if(!isNaN(parseFloat(i))&&isFinite(i)){var s=this.getNumberAt(t,n);if(s){var o=s.value.indexOf(".")>=0?s.start+s.value.indexOf(".")+1:s.end,u=s.start+s.value.length-o,a=parseFloat(s.value);a*=Math.pow(10,u),o!==s.end&&n<o?e*=Math.pow(10,s.end-n-1):e*=Math.pow(10,s.end-n),a+=e,a/=Math.pow(10,u);var f=a.toFixed(u),l=new p(t,s.start,t,s.end);this.session.replace(l,f),this.moveCursorTo(t,Math.max(s.start+1,n+f.length-s.value.length))}}},this.removeLines=function(){var e=this.$getSelectedRows(),t;e.first===0||e.last+1<this.session.getLength()?t=new p(e.first,0,e.last+1,0):t=new p(e.first-1,this.session.getLine(e.first-1).length,e.last,this.session.getLine(e.last).length),this.session.remove(t),this.clearSelection()},this.duplicateSelection=function(){var e=this.selection,t=this.session,n=e.getRange(),r=e.isBackwards();if(n.isEmpty()){var i=n.start.row;t.duplicateLines(i,i)}else{var s=r?n.start:n.end,o=t.insert(s,t.getTextRange(n),!1);n.start=s,n.end=o,e.setSelectionRange(n,r)}},this.moveLinesDown=function(){this.$moveLines(function(e,t){return this.session.moveLinesDown(e,t)})},this.moveLinesUp=function(){this.$moveLines(function(e,t){return this.session.moveLinesUp(e,t)})},this.moveText=function(e,t,n){return this.session.moveText(e,t,n)},this.copyLinesUp=function(){this.$moveLines(function(e,t){return this.session.duplicateLines(e,t),0})},this.copyLinesDown=function(){this.$moveLines(function(e,t){return this.session.duplicateLines(e,t)})},this.$moveLines=function(e){var t=this.selection;if(!t.inMultiSelectMode||this.inVirtualSelectionMode){var n=t.toOrientedRange(),r=this.$getSelectedRows(n),i=e.call(this,r.first,r.last);n.moveBy(i,0),t.fromOrientedRange(n)}else{var s=t.rangeList.ranges;t.rangeList.detach(this.session);for(var o=s.length;o--;){var u=o,r=s[o].collapseRows(),a=r.end.row,f=r.start.row;while(o--){r=s[o].collapseRows();if(!(f-r.end.row<=1))break;f=r.end.row}o++;var i=e.call(this,f,a);while(u>=o)s[u].moveBy(i,0),u--}t.fromOrientedRange(t.ranges[0]),t.rangeList.attach(this.session)}},this.$getSelectedRows=function(){var e=this.getSelectionRange().collapseRows();return{first:this.session.getRowFoldStart(e.start.row),last:this.session.getRowFoldEnd(e.end.row)}},this.onCompositionStart=function(e){this.renderer.showComposition(this.getCursorPosition())},this.onCompositionUpdate=function(e){this.renderer.setCompositionText(e)},this.onCompositionEnd=function(){this.renderer.hideComposition()},this.getFirstVisibleRow=function(){return this.renderer.getFirstVisibleRow()},this.getLastVisibleRow=function(){return this.renderer.getLastVisibleRow()},this.isRowVisible=function(e){return e>=this.getFirstVisibleRow()&&e<=this.getLastVisibleRow()},this.isRowFullyVisible=function(e){return e>=this.renderer.getFirstFullyVisibleRow()&&e<=this.renderer.getLastFullyVisibleRow()},this.$getVisibleRowCount=function(){return this.renderer.getScrollBottomRow()-this.renderer.getScrollTopRow()+1},this.$moveByPage=function(e,t){var n=this.renderer,r=this.renderer.layerConfig,i=e*Math.floor(r.height/r.lineHeight);this.$blockScrolling++,t===!0?this.selection.$moveSelection(function(){this.moveCursorBy(i,0)}):t===!1&&(this.selection.moveCursorBy(i,0),this.selection.clearSelection()),this.$blockScrolling--;var s=n.scrollTop;n.scrollBy(0,i*r.lineHeight),t!=null&&n.scrollCursorIntoView(null,.5),n.animateScrolling(s)},this.selectPageDown=function(){this.$moveByPage(1,!0)},this.selectPageUp=function(){this.$moveByPage(-1,!0)},this.gotoPageDown=function(){this.$moveByPage(1,!1)},this.gotoPageUp=function(){this.$moveByPage(-1,!1)},this.scrollPageDown=function(){this.$moveByPage(1)},this.scrollPageUp=function(){this.$moveByPage(-1)},this.scrollToRow=function(e){this.renderer.scrollToRow(e)},this.scrollToLine=function(e,t,n,r){this.renderer.scrollToLine(e,t,n,r)},this.centerSelection=function(){var e=this.getSelectionRange(),t={row:Math.floor(e.start.row+(e.end.row-e.start.row)/2),column:Math.floor(e.start.column+(e.end.column-e.start.column)/2)};this.renderer.alignCursor(t,.5)},this.getCursorPosition=function(){return this.selection.getCursor()},this.getCursorPositionScreen=function(){return this.session.documentToScreenPosition(this.getCursorPosition())},this.getSelectionRange=function(){return this.selection.getRange()},this.selectAll=function(){this.$blockScrolling+=1,this.selection.selectAll(),this.$blockScrolling-=1},this.clearSelection=function(){this.selection.clearSelection()},this.moveCursorTo=function(e,t){this.selection.moveCursorTo(e,t)},this.moveCursorToPosition=function(e){this.selection.moveCursorToPosition(e)},this.jumpToMatching=function(e){var t=this.getCursorPosition(),n=this.session.getBracketRange(t);if(!n){n=this.find({needle:/[{}()\[\]]/g,preventScroll:!0,start:{row:t.row,column:t.column-1}});if(!n)return;var r=n.start;r.row==t.row&&Math.abs(r.column-t.column)<2&&(n=this.session.getBracketRange(r))}r=n&&n.cursor||r,r&&(e?n&&n.isEqual(this.getSelectionRange())?this.clearSelection():this.selection.selectTo(r.row,r.column):this.selection.moveTo(r.row,r.column))},this.gotoLine=function(e,t,n){this.selection.clearSelection(),this.session.unfold({row:e-1,column:t||0}),this.$blockScrolling+=1,this.exitMultiSelectMode&&this.exitMultiSelectMode(),this.moveCursorTo(e-1,t||0),this.$blockScrolling-=1,this.isRowFullyVisible(e-1)||this.scrollToLine(e-1,!0,n)},this.navigateTo=function(e,t){this.selection.moveTo(e,t)},this.navigateUp=function(e){if(this.selection.isMultiLine()&&!this.selection.isBackwards()){var t=this.selection.anchor.getPosition();return this.moveCursorToPosition(t)}this.selection.clearSelection(),this.selection.moveCursorBy(-e||-1,0)},this.navigateDown=function(e){if(this.selection.isMultiLine()&&this.selection.isBackwards()){var t=this.selection.anchor.getPosition();return this.moveCursorToPosition(t)}this.selection.clearSelection(),this.selection.moveCursorBy(e||1,0)},this.navigateLeft=function(e){if(!this.selection.isEmpty()){var t=this.getSelectionRange().start;this.moveCursorToPosition(t)}else{e=e||1;while(e--)this.selection.moveCursorLeft()}this.clearSelection()},this.navigateRight=function(e){if(!this.selection.isEmpty()){var t=this.getSelectionRange().end;this.moveCursorToPosition(t)}else{e=e||1;while(e--)this.selection.moveCursorRight()}this.clearSelection()},this.navigateLineStart=function(){this.selection.moveCursorLineStart(),this.clearSelection()},this.navigateLineEnd=function(){this.selection.moveCursorLineEnd(),this.clearSelection()},this.navigateFileEnd=function(){this.selection.moveCursorFileEnd(),this.clearSelection()},this.navigateFileStart=function(){this.selection.moveCursorFileStart(),this.clearSelection()},this.navigateWordRight=function(){this.selection.moveCursorWordRight(),this.clearSelection()},this.navigateWordLeft=function(){this.selection.moveCursorWordLeft(),this.clearSelection()},this.replace=function(e,t){t&&this.$search.set(t);var n=this.$search.find(this.session),r=0;return n?(this.$tryReplace(n,e)&&(r=1),n!==null&&(this.selection.setSelectionRange(n),this.renderer.scrollSelectionIntoView(n.start,n.end)),r):r},this.replaceAll=function(e,t){t&&this.$search.set(t);var n=this.$search.findAll(this.session),r=0;if(!n.length)return r;this.$blockScrolling+=1;var i=this.getSelectionRange();this.selection.moveTo(0,0);for(var s=n.length-1;s>=0;--s)this.$tryReplace(n[s],e)&&r++;return this.selection.setSelectionRange(i),this.$blockScrolling-=1,r},this.$tryReplace=function(e,t){var n=this.session.getTextRange(e);return t=this.$search.replace(n,t),t!==null?(e.end=this.session.replace(e,t),e):null},this.getLastSearchOptions=function(){return this.$search.getOptions()},this.find=function(e,t,n){t||(t={}),typeof e=="string"||e instanceof RegExp?t.needle=e:typeof e=="object"&&r.mixin(t,e);var i=this.selection.getRange();t.needle==null&&(e=this.session.getTextRange(i)||this.$search.$options.needle,e||(i=this.session.getWordRange(i.start.row,i.start.column),e=this.session.getTextRange(i)),this.$search.set({needle:e})),this.$search.set(t),t.start||this.$search.set({start:i});var s=this.$search.find(this.session);if(t.preventScroll)return s;if(s)return this.revealRange(s,n),s;t.backwards?i.start=i.end:i.end=i.start,this.selection.setRange(i)},this.findNext=function(e,t){this.find({skipCurrent:!0,backwards:!1},e,t)},this.findPrevious=function(e,t){this.find(e,{skipCurrent:!0,backwards:!0},t)},this.revealRange=function(e,t){this.$blockScrolling+=1,this.session.unfold(e),this.selection.setSelectionRange(e),this.$blockScrolling-=1;var n=this.renderer.scrollTop;this.renderer.scrollSelectionIntoView(e.start,e.end,.5),t!==!1&&this.renderer.animateScrolling(n)},this.undo=function(){this.$blockScrolling++,this.session.getUndoManager().undo(),this.$blockScrolling--,this.renderer.scrollCursorIntoView(null,.5)},this.redo=function(){this.$blockScrolling++,this.session.getUndoManager().redo(),this.$blockScrolling--,this.renderer.scrollCursorIntoView(null,.5)},this.destroy=function(){this.renderer.destroy(),this._signal("destroy",this)},this.setAutoScrollEditorIntoView=function(e){if(!e)return;var t,n=this,r=!1;this.$scrollAnchor||(this.$scrollAnchor=document.createElement("div"));var i=this.$scrollAnchor;i.style.cssText="position:absolute",this.container.insertBefore(i,this.container.firstChild);var s=this.on("changeSelection",function(){r=!0}),o=this.renderer.on("beforeRender",function(){r&&(t=n.renderer.container.getBoundingClientRect())}),u=this.renderer.on("afterRender",function(){if(r&&t&&n.isFocused()){var e=n.renderer,s=e.$cursorLayer.$pixelPos,o=e.layerConfig,u=s.top-o.offset;s.top>=0&&u+t.top<0?r=!0:s.top<o.height&&s.top+t.top+o.lineHeight>window.innerHeight?r=!1:r=null,r!=null&&(i.style.top=u+"px",i.style.left=s.left+"px",i.style.height=o.lineHeight+"px",i.scrollIntoView(r)),r=t=null}});this.setAutoScrollEditorIntoView=function(e){if(e)return;delete this.setAutoScrollEditorIntoView,this.removeEventListener("changeSelection",s),this.renderer.removeEventListener("afterRender",u),this.renderer.removeEventListener("beforeRender",o)}},this.$resetCursorStyle=function(){var e=this.$cursorStyle||"ace",t=this.renderer.$cursorLayer;if(!t)return;t.setSmoothBlinking(e=="smooth"),t.isBlinking=!this.$readOnly&&e!="wide"}}).call(y.prototype),g.defineOptions(y.prototype,"editor",{selectionStyle:{set:function(e){this.onSelectionChange(),this._signal("changeSelectionStyle",{data:e})},initialValue:"line"},highlightActiveLine:{set:function(){this.$updateHighlightActiveLine()},initialValue:!0},highlightSelectedWord:{set:function(e){this.$onSelectionChange()},initialValue:!0},readOnly:{set:function(e){this.textInput.setReadOnly(e),this.$resetCursorStyle()},initialValue:!1},cursorStyle:{set:function(e){this.$resetCursorStyle()},values:["ace","slim","smooth","wide"],initialValue:"ace"},mergeUndoDeltas:{values:[!1,!0,"always"],initialValue:!0},behavioursEnabled:{initialValue:!0},wrapBehavioursEnabled:{initialValue:!0},autoScrollEditorIntoView:{set:function(e){this.setAutoScrollEditorIntoView(e)}},hScrollBarAlwaysVisible:"renderer",vScrollBarAlwaysVisible:"renderer",highlightGutterLine:"renderer",animatedScroll:"renderer",showInvisibles:"renderer",showPrintMargin:"renderer",printMarginColumn:"renderer",printMargin:"renderer",fadeFoldWidgets:"renderer",showFoldWidgets:"renderer",showLineNumbers:"renderer",showGutter:"renderer",displayIndentGuides:"renderer",fontSize:"renderer",fontFamily:"renderer",maxLines:"renderer",minLines:"renderer",scrollPastEnd:"renderer",fixedWidthGutter:"renderer",theme:"renderer",scrollSpeed:"$mouseHandler",dragDelay:"$mouseHandler",dragEnabled:"$mouseHandler",focusTimout:"$mouseHandler",tooltipFollowsMouse:"$mouseHandler",firstLineNumber:"session",overwrite:"session",newLineMode:"session",useWorker:"session",useSoftTabs:"session",tabSize:"session",wrap:"session",foldStyle:"session",mode:"session"}),t.Editor=y}),define("ace/mouse/multi_select_handler",["require","exports","module","ace/lib/event"],function(e,t,n){function r(e,t){return e.row==t.row&&e.column==t.column}function i(e){var t=e.domEvent,n=t.altKey,i=t.shiftKey,o=e.getAccelKey(),u=e.getButton();if(e.editor.inMultiSelectMode&&u==2){e.editor.textInput.onContextMenu(e.domEvent);return}if(!o&&!n){u===0&&e.editor.inMultiSelectMode&&e.editor.exitMultiSelectMode();return}var a=e.editor,f=a.selection,l=a.inMultiSelectMode,c=e.getDocumentPosition(),h=f.getCursor(),p=e.inSelection()||f.isEmpty()&&r(c,h),d=e.x,v=e.y,m=function(e){d=e.clientX,v=e.clientY},g=function(){var e=a.renderer.pixelToScreenCoordinates(d,v),t=y.screenToDocumentPosition(e.row,e.column);if(r(w,e)&&r(t,f.selectionLead))return;w=e,a.selection.moveToPosition(t),a.renderer.scrollCursorIntoView(),a.removeSelectionMarkers(x),x=f.rectangularRangeBlock(w,b),x.forEach(a.addSelectionMarker,a),a.updateSelectionMarkers()},y=a.session,b=a.renderer.pixelToScreenCoordinates(d,v),w=b;if(o&&!n&&!i&&u===0){if(!l&&p)return;if(!l){var E=f.toOrientedRange();a.addSelectionMarker(E)}var S=f.rangeList.rangeAtPoint(c);a.$blockScrolling++,a.once("mouseup",function(){var e=f.toOrientedRange();S&&e.isEmpty()&&r(S.cursor,e.cursor)?f.substractPoint(e.cursor):(E&&(a.removeSelectionMarker(E),f.addRange(E)),f.addRange(e)),a.$blockScrolling--})}else if(n&&u===0){e.stop(),l&&!o?f.toSingleRange():!l&&o&&f.addRange();var x=[];i?(b=y.documentToScreenPosition(f.lead),g()):f.moveToPosition(c);var T=function(e){clearInterval(C),a.removeSelectionMarkers(x);for(var t=0;t<x.length;t++)f.addRange(x[t])},N=g;s.capture(a.container,m,T);var C=setInterval(function(){N()},20);return e.preventDefault()}}var s=e("../lib/event");t.onMouseDown=i}),define("ace/lib/useragent",["require","exports","module"],function(e,t,n){t.OS={LINUX:"LINUX",MAC:"MAC",WINDOWS:"WINDOWS"},t.getOS=function(){return t.isMac?t.OS.MAC:t.isLinux?t.OS.LINUX:t.OS.WINDOWS};if(typeof navigator!="object")return;var r=(navigator.platform.match(/mac|win|linux/i)||["other"])[0].toLowerCase(),i=navigator.userAgent;t.isWin=r=="win",t.isMac=r=="mac",t.isLinux=r=="linux",t.isIE=(navigator.appName=="Microsoft Internet Explorer"||navigator.appName.indexOf("MSAppHost")>=0)&&parseFloat(navigator.userAgent.match(/(?:Trident\/[0-9]+[\.0-9]+;.*rv:|MSIE )([0-9]+[\.0-9]+)/)[1]),t.isOldIE=t.isIE&&t.isIE<9,t.isGecko=t.isMozilla=window.controllers&&window.navigator.product==="Gecko",t.isOldGecko=t.isGecko&&parseInt((navigator.userAgent.match(/rv\:(\d+)/)||[])[1],10)<4,t.isOpera=window.opera&&Object.prototype.toString.call(window.opera)=="[object Opera]",t.isWebKit=parseFloat(i.split("WebKit/")[1])||undefined,t.isChrome=parseFloat(i.split(" Chrome/")[1])||undefined,t.isAIR=i.indexOf("AdobeAIR")>=0,t.isIPad=i.indexOf("iPad")>=0,t.isTouchPad=i.indexOf("TouchPad")>=0}),define("ace/commands/multi_select_commands",["require","exports","module","ace/keyboard/hash_handler"],function(e,t,n){t.defaultCommands=[{name:"addCursorAbove",exec:function(e){e.selectMoreLines(-1)},bindKey:{win:"Ctrl-Alt-Up",mac:"Ctrl-Alt-Up"},readonly:!0},{name:"addCursorBelow",exec:function(e){e.selectMoreLines(1)},bindKey:{win:"Ctrl-Alt-Down",mac:"Ctrl-Alt-Down"},readonly:!0},{name:"addCursorAboveSkipCurrent",exec:function(e){e.selectMoreLines(-1,!0)},bindKey:{win:"Ctrl-Alt-Shift-Up",mac:"Ctrl-Alt-Shift-Up"},readonly:!0},{name:"addCursorBelowSkipCurrent",exec:function(e){e.selectMoreLines(1,!0)},bindKey:{win:"Ctrl-Alt-Shift-Down",mac:"Ctrl-Alt-Shift-Down"},readonly:!0},{name:"selectMoreBefore",exec:function(e){e.selectMore(-1)},bindKey:{win:"Ctrl-Alt-Left",mac:"Ctrl-Alt-Left"},readonly:!0},{name:"selectMoreAfter",exec:function(e){e.selectMore(1)},bindKey:{win:"Ctrl-Alt-Right",mac:"Ctrl-Alt-Right"},readonly:!0},{name:"selectNextBefore",exec:function(e){e.selectMore(-1,!0)},bindKey:{win:"Ctrl-Alt-Shift-Left",mac:"Ctrl-Alt-Shift-Left"},readonly:!0},{name:"selectNextAfter",exec:function(e){e.selectMore(1,!0)},bindKey:{win:"Ctrl-Alt-Shift-Right",mac:"Ctrl-Alt-Shift-Right"},readonly:!0},{name:"splitIntoLines",exec:function(e){e.multiSelect.splitIntoLines()},bindKey:{win:"Ctrl-Alt-L",mac:"Ctrl-Alt-L"},readonly:!0},{name:"alignCursors",exec:function(e){e.alignCursors()},bindKey:{win:"Ctrl-Alt-A",mac:"Ctrl-Alt-A"}}],t.multiSelectCommands=[{name:"singleSelection",bindKey:"esc",exec:function(e){e.exitMultiSelectMode()},readonly:!0,isAvailable:function(e){return e&&e.inMultiSelectMode}}];var r=e("../keyboard/hash_handler").HashHandler;t.keyboardHandler=new r(t.multiSelectCommands)}),define("ace/lib/oop",["require","exports","module"],function(e,t,n){t.inherits=function(e,t){e.super_=t,e.prototype=Object.create(t.prototype,{constructor:{value:e,enumerable:!1,writable:!0,configurable:!0}})},t.mixin=function(e,t){for(var n in t)e[n]=t[n];return e},t.implement=function(e,n){t.mixin(e,n)}}),define("ace/worker/worker_client",["require","exports","module","ace/lib/oop","ace/lib/event_emitter","ace/config"],function(e,t,n){var r=e("../lib/oop"),i=e("../lib/event_emitter").EventEmitter,s=e("../config"),o=function(t,n,r,i){this.$sendDeltaQueue=this.$sendDeltaQueue.bind(this),this.changeListener=this.changeListener.bind(this),this.onMessage=this.onMessage.bind(this),e.nameToUrl&&!e.toUrl&&(e.toUrl=e.nameToUrl);if(s.get("packaged")||!e.toUrl)i=i||s.moduleUrl(n,"worker");else{var o=this.$normalizePath;i=i||o(e.toUrl("ace/worker/worker.js",null,"_"));var u={};t.forEach(function(t){u[t]=o(e.toUrl(t,null,"_").replace(/(\.js)?(\?.*)?$/,""))})}try{this.$worker=new Worker(i)}catch(a){if(!(a instanceof window.DOMException))throw a;var f=this.$workerBlob(i),l=window.URL||window.webkitURL,c=l.createObjectURL(f);this.$worker=new Worker(c),l.revokeObjectURL(c)}this.$worker.postMessage({init:!0,tlns:u,module:n,classname:r}),this.callbackId=1,this.callbacks={},this.$worker.onmessage=this.onMessage};(function(){r.implement(this,i),this.onMessage=function(e){var t=e.data;switch(t.type){case"log":window.console&&console.log&&console.log.apply(console,t.data);break;case"event":this._signal(t.name,{data:t.data});break;case"call":var n=this.callbacks[t.id];n&&(n(t.data),delete this.callbacks[t.id])}},this.$normalizePath=function(e){return location.host?(e=e.replace(/^[a-z]+:\/\/[^\/]+/,""),e=location.protocol+"//"+location.host+(e.charAt(0)=="/"?"":location.pathname.replace(/\/[^\/]*$/,""))+"/"+e.replace(/^[\/]+/,""),e):e},this.terminate=function(){this._signal("terminate",{}),this.deltaQueue=null,this.$worker.terminate(),this.$worker=null,this.$doc.removeEventListener("change",this.changeListener),this.$doc=null},this.send=function(e,t){this.$worker.postMessage({command:e,args:t})},this.call=function(e,t,n){if(n){var r=this.callbackId++;this.callbacks[r]=n,t.push(r)}this.send(e,t)},this.emit=function(e,t){try{this.$worker.postMessage({event:e,data:{data:t.data}})}catch(n){}},this.attachToDocument=function(e){this.$doc&&this.terminate(),this.$doc=e,this.call("setValue",[e.getValue()]),e.on("change",this.changeListener)},this.changeListener=function(e){this.deltaQueue?this.deltaQueue.push(e.data):(this.deltaQueue=[e.data],setTimeout(this.$sendDeltaQueue,0))},this.$sendDeltaQueue=function(){var e=this.deltaQueue;if(!e)return;this.deltaQueue=null,e.length>20&&e.length>this.$doc.getLength()>>1?this.call("setValue",[this.$doc.getValue()]):this.emit("change",{data:e})},this.$workerBlob=function(e){var t="importScripts('"+e+"');";try{return new Blob([t],{type:"application/javascript"})}catch(n){var r=window.BlobBuilder||window.WebKitBlobBuilder||window.MozBlobBuilder,i=new r;return i.append(t),i.getBlob("application/javascript")}}}).call(o.prototype);var u=function(e,t,n){this.$sendDeltaQueue=this.$sendDeltaQueue.bind(this),this.changeListener=this.changeListener.bind(this),this.callbackId=1,this.callbacks={},this.messageBuffer=[];var r=null,o=!1,u=Object.create(i),a=this;this.$worker={},this.$worker.terminate=function(){},this.$worker.postMessage=function(e){a.messageBuffer.push(e),r&&(o?setTimeout(f):f())},this.setEmitSync=function(e){o=e};var f=function(){var e=a.messageBuffer.shift();e.command?r[e.command].apply(r,e.args):e.event&&u._signal(e.event,e.data)};u.postMessage=function(e){a.onMessage({data:e})},u.callback=function(e,t){this.postMessage({type:"call",id:t,data:e})},u.emit=function(e,t){this.postMessage({type:"event",name:e,data:t})},s.loadModule(["worker",t],function(e){r=new e[n](u);while(a.messageBuffer.length)f()})};u.prototype=o.prototype,t.UIWorkerClient=u,t.WorkerClient=o}),define("ace/lib/keys",["require","exports","module","ace/lib/oop"],function(e,t,n){var r=e("./oop"),i=function(){var e={MODIFIER_KEYS:{16:"Shift",17:"Ctrl",18:"Alt",224:"Meta"},KEY_MODS:{ctrl:1,alt:2,option:2,shift:4,"super":8,meta:8,command:8,cmd:8},FUNCTION_KEYS:{8:"Backspace",9:"Tab",13:"Return",19:"Pause",27:"Esc",32:"Space",33:"PageUp",34:"PageDown",35:"End",36:"Home",37:"Left",38:"Up",39:"Right",40:"Down",44:"Print",45:"Insert",46:"Delete",96:"Numpad0",97:"Numpad1",98:"Numpad2",99:"Numpad3",100:"Numpad4",101:"Numpad5",102:"Numpad6",103:"Numpad7",104:"Numpad8",105:"Numpad9","-13":"NumpadEnter",112:"F1",113:"F2",114:"F3",115:"F4",116:"F5",117:"F6",118:"F7",119:"F8",120:"F9",121:"F10",122:"F11",123:"F12",144:"Numlock",145:"Scrolllock"},PRINTABLE_KEYS:{32:" ",48:"0",49:"1",50:"2",51:"3",52:"4",53:"5",54:"6",55:"7",56:"8",57:"9",59:";",61:"=",65:"a",66:"b",67:"c",68:"d",69:"e",70:"f",71:"g",72:"h",73:"i",74:"j",75:"k",76:"l",77:"m",78:"n",79:"o",80:"p",81:"q",82:"r",83:"s",84:"t",85:"u",86:"v",87:"w",88:"x",89:"y",90:"z",107:"+",109:"-",110:".",188:",",190:".",191:"/",192:"`",219:"[",220:"\\",221:"]",222:"'"}},t,n;for(n in e.FUNCTION_KEYS)t=e.FUNCTION_KEYS[n].toLowerCase(),e[t]=parseInt(n,10);for(n in e.PRINTABLE_KEYS)t=e.PRINTABLE_KEYS[n].toLowerCase(),e[t]=parseInt(n,10);return r.mixin(e,e.MODIFIER_KEYS),r.mixin(e,e.PRINTABLE_KEYS),r.mixin(e,e.FUNCTION_KEYS),e.enter=e["return"],e.escape=e.esc,e.del=e["delete"],e[173]="-",function(){var t=["cmd","ctrl","alt","shift"];for(var n=Math.pow(2,t.length);n--;)e.KEY_MODS[n]=t.filter(function(t){return n&e.KEY_MODS[t]}).join("-")+"-"}(),e}();r.mixin(t,i),t.keyCodeToString=function(e){return(i[e]||String.fromCharCode(e)).toLowerCase()}}),define("ace/placeholder",["require","exports","module","ace/range","ace/lib/event_emitter","ace/lib/oop"],function(e,t,n){var r=e("./range").Range,i=e("./lib/event_emitter").EventEmitter,s=e("./lib/oop"),o=function(e,t,n,r,i,s){var o=this;this.length=t,this.session=e,this.doc=e.getDocument(),this.mainClass=i,this.othersClass=s,this.$onUpdate=this.onUpdate.bind(this),this.doc.on("change",this.$onUpdate),this.$others=r,this.$onCursorChange=function(){setTimeout(function(){o.onCursorChange()})},this.$pos=n;var u=e.getUndoManager().$undoStack||e.getUndoManager().$undostack||{length:-1};this.$undoStackDepth=u.length,this.setup(),e.selection.on("changeCursor",this.$onCursorChange)};(function(){s.implement(this,i),this.setup=function(){var e=this,t=this.doc,n=this.session,i=this.$pos;this.pos=t.createAnchor(i.row,i.column),this.markerId=n.addMarker(new r(i.row,i.column,i.row,i.column+this.length),this.mainClass,null,!1),this.pos.on("change",function(t){n.removeMarker(e.markerId),e.markerId=n.addMarker(new r(t.value.row,t.value.column,t.value.row,t.value.column+e.length),e.mainClass,null,!1)}),this.others=[],this.$others.forEach(function(n){var r=t.createAnchor(n.row,n.column);e.others.push(r)}),n.setUndoSelect(!1)},this.showOtherMarkers=function(){if(this.othersActive)return;var e=this.session,t=this;this.othersActive=!0,this.others.forEach(function(n){n.markerId=e.addMarker(new r(n.row,n.column,n.row,n.column+t.length),t.othersClass,null,!1),n.on("change",function(i){e.removeMarker(n.markerId),n.markerId=e.addMarker(new r(i.value.row,i.value.column,i.value.row,i.value.column+t.length),t.othersClass,null,!1)})})},this.hideOtherMarkers=function(){if(!this.othersActive)return;this.othersActive=!1;for(var e=0;e<this.others.length;e++)this.session.removeMarker(this.others[e].markerId)},this.onUpdate=function(e){var t=e.data,n=t.range;if(n.start.row!==n.end.row)return;if(n.start.row!==this.pos.row)return;if(this.$updating)return;this.$updating=!0;var i=t.action==="insertText"?n.end.column-n.start.column:n.start.column-n.end.column;if(n.start.column>=this.pos.column&&n.start.column<=this.pos.column+this.length+1){var s=n.start.column-this.pos.column;this.length+=i;if(!this.session.$fromUndo){if(t.action==="insertText")for(var o=this.others.length-1;o>=0;o--){var u=this.others[o],a={row:u.row,column:u.column+s};u.row===n.start.row&&n.start.column<u.column&&(a.column+=i),this.doc.insert(a,t.text)}else if(t.action==="removeText")for(var o=this.others.length-1;o>=0;o--){var u=this.others[o],a={row:u.row,column:u.column+s};u.row===n.start.row&&n.start.column<u.column&&(a.column+=i),this.doc.remove(new r(a.row,a.column,a.row,a.column-i))}n.start.column===this.pos.column&&t.action==="insertText"?setTimeout(function(){this.pos.setPosition(this.pos.row,this.pos.column-i);for(var e=0;e<this.others.length;e++){var t=this.others[e],r={row:t.row,column:t.column-i};t.row===n.start.row&&n.start.column<t.column&&(r.column+=i),t.setPosition(r.row,r.column)}}.bind(this),0):n.start.column===this.pos.column&&t.action==="removeText"&&setTimeout(function(){for(var e=0;e<this.others.length;e++){var t=this.others[e];t.row===n.start.row&&n.start.column<t.column&&t.setPosition(t.row,t.column-i)}}.bind(this),0)}this.pos._emit("change",{value:this.pos});for(var o=0;o<this.others.length;o++)this.others[o]._emit("change",{value:this.others[o]})}this.$updating=!1},this.onCursorChange=function(e){if(this.$updating)return;var t=this.session.selection.getCursor();t.row===this.pos.row&&t.column>=this.pos.column&&t.column<=this.pos.column+this.length?(this.showOtherMarkers(),this._emit("cursorEnter",e)):(this.hideOtherMarkers(),this._emit("cursorLeave",e))},this.detach=function(){this.session.removeMarker(this.markerId),this.hideOtherMarkers(),this.doc.removeEventListener("change",this.$onUpdate),this.session.selection.removeEventListener("changeCursor",this.$onCursorChange),this.pos.detach();for(var e=0;e<this.others.length;e++)this.others[e].detach();this.session.setUndoSelect(!0)},this.cancel=function(){if(this.$undoStackDepth===-1)throw Error("Canceling placeholders only supported with undo manager attached to session.");var e=this.session.getUndoManager(),t=(e.$undoStack||e.$undostack).length-this.$undoStackDepth;for(var n=0;n<t;n++)e.undo(!0)}}).call(o.prototype),t.PlaceHolder=o}),define("ace/lib/event",["require","exports","module","ace/lib/keys","ace/lib/useragent"],function(e,t,n){function r(e,t,n){var r=o(t);if(!s.isMac&&u){if(u[91]||u[92])r|=8;if(u.altGr){if((3&r)==3)return;u.altGr=0}if(n===18||n===17){var f=t.location||t.keyLocation;if(n===17&&f===1)a=t.timeStamp;else if(n===18&&r===3&&f===2){var l=-a;a=t.timeStamp,l+=a,l<3&&(u.altGr=!0)}}}if(n in i.MODIFIER_KEYS){switch(i.MODIFIER_KEYS[n]){case"Alt":r=2;break;case"Shift":r=4;break;case"Ctrl":r=1;break;default:r=8}n=-1}r&8&&(n===91||n===93)&&(n=-1);if(!r&&n===13)if(t.location||t.keyLocation===3){e(t,r,-n);if(t.defaultPrevented)return}return!!r||n in i.FUNCTION_KEYS||n in i.PRINTABLE_KEYS?e(t,r,n):!1}var i=e("./keys"),s=e("./useragent");t.addListener=function(e,t,n){if(e.addEventListener)return e.addEventListener(t,n,!1);if(e.attachEvent){var r=function(){n.call(e,window.event)};n._wrapper=r,e.attachEvent("on"+t,r)}},t.removeListener=function(e,t,n){if(e.removeEventListener)return e.removeEventListener(t,n,!1);e.detachEvent&&e.detachEvent("on"+t,n._wrapper||n)},t.stopEvent=function(e){return t.stopPropagation(e),t.preventDefault(e),!1},t.stopPropagation=function(e){e.stopPropagation?e.stopPropagation():e.cancelBubble=!0},t.preventDefault=function(e){e.preventDefault?e.preventDefault():e.returnValue=!1},t.getButton=function(e){return e.type=="dblclick"?0:e.type=="contextmenu"||e.ctrlKey&&s.isMac?2:e.preventDefault?e.button:{1:0,2:2,4:1}[e.button]},t.capture=function(e,n,r){function i(e){n&&n(e),r&&r(e),t.removeListener(document,"mousemove",n,!0),t.removeListener(document,"mouseup",i,!0),t.removeListener(document,"dragstart",i,!0)}return t.addListener(document,"mousemove",n,!0),t.addListener(document,"mouseup",i,!0),t.addListener(document,"dragstart",i,!0),i},t.addMouseWheelListener=function(e,n){"onmousewheel"in e?t.addListener(e,"mousewheel",function(e){var t=8;e.wheelDeltaX!==undefined?(e.wheelX=-e.wheelDeltaX/t,e.wheelY=-e.wheelDeltaY/t):(e.wheelX=0,e.wheelY=-e.wheelDelta/t),n(e)}):"onwheel"in e?t.addListener(e,"wheel",function(e){var t=.35;switch(e.deltaMode){case e.DOM_DELTA_PIXEL:e.wheelX=e.deltaX*t||0,e.wheelY=e.deltaY*t||0;break;case e.DOM_DELTA_LINE:case e.DOM_DELTA_PAGE:e.wheelX=(e.deltaX||0)*5,e.wheelY=(e.deltaY||0)*5}n(e)}):t.addListener(e,"DOMMouseScroll",function(e){e.axis&&e.axis==e.HORIZONTAL_AXIS?(e.wheelX=(e.detail||0)*5,e.wheelY=0):(e.wheelX=0,e.wheelY=(e.detail||0)*5),n(e)})},t.addMultiMouseDownListener=function(e,n,r,i){var o=0,u,a,f,l={2:"dblclick",3:"tripleclick",4:"quadclick"};t.addListener(e,"mousedown",function(e){t.getButton(e)!==0?o=0:e.detail>1?(o++,o>4&&(o=1)):o=1;if(s.isIE){var n=Math.abs(e.clientX-u)>5||Math.abs(e.clientY-a)>5;n&&(o=1),o==1&&(u=e.clientX,a=e.clientY)}r[i]("mousedown",e);if(o>4)o=0;else if(o>1)return r[i](l[o],e)}),s.isOldIE&&t.addListener(e,"dblclick",function(e){o=2,f&&clearTimeout(f),f=setTimeout(function(){f=null},n[o-1]||600),r[i]("mousedown",e),r[i](l[o],e)})};var o=!s.isMac||!s.isOpera||"KeyboardEvent"in window?function(e){return 0|(e.ctrlKey?1:0)|(e.altKey?2:0)|(e.shiftKey?4:0)|(e.metaKey?8:0)}:function(e){return 0|(e.metaKey?1:0)|(e.altKey?2:0)|(e.shiftKey?4:0)|(e.ctrlKey?8:0)};t.getModifierString=function(e){return i.KEY_MODS[o(e)]};var u=null,a=0;t.addCommandKeyListener=function(e,n){var i=t.addListener;if(s.isOldGecko||s.isOpera&&!("KeyboardEvent"in window)){var o=null;i(e,"keydown",function(e){o=e.keyCode}),i(e,"keypress",function(e){return r(n,e,o)})}else{var a=null;i(e,"keydown",function(e){u[e.keyCode]=!0;var t=r(n,e,e.keyCode);return a=e.defaultPrevented,t}),i(e,"keypress",function(e){a&&(e.ctrlKey||e.altKey||e.shiftKey||e.metaKey)&&(t.stopEvent(e),a=null)}),i(e,"keyup",function(e){u[e.keyCode]=null}),u||(u=Object.create(null),i(window,"focus",function(e){u=Object.create(null)}))}};if(window.postMessage&&!s.isOldIE){var f=1;t.nextTick=function(e,n){n=n||window;var r="zero-timeout-message-"+f;t.addListener(n,"message",function i(s){s.data==r&&(t.stopPropagation(s),t.removeListener(n,"message",i),e())}),n.postMessage(r,"*")}}t.nextFrame=window.requestAnimationFrame||window.mozRequestAnimationFrame||window.webkitRequestAnimationFrame||window.msRequestAnimationFrame||window.oRequestAnimationFrame,t.nextFrame?t.nextFrame=t.nextFrame.bind(window):t.nextFrame=function(e){setTimeout(e,17)}}),define("ace/mode/folding/fold_mode",["require","exports","module","ace/range"],function(e,t,n){var r=e("../../range").Range,i=t.FoldMode=function(){};(function(){this.foldingStartMarker=null,this.foldingStopMarker=null,this.getFoldWidget=function(e,t,n){var r=e.getLine(n);return this.foldingStartMarker.test(r)?"start":t=="markbeginend"&&this.foldingStopMarker&&this.foldingStopMarker.test(r)?"end":""},this.getFoldWidgetRange=function(e,t,n){return null},this.indentationBlock=function(e,t,n){var i=/\S/,s=e.getLine(t),o=s.search(i);if(o==-1)return;var u=n||s.length,a=e.getLength(),f=t,l=t;while(++t<a){var c=e.getLine(t).search(i);if(c==-1)continue;if(c<=o)break;l=t}if(l>f){var h=e.getLine(l).length;return new r(f,u,l,h)}},this.openingBracketBlock=function(e,t,n,i,s){var o={row:n,column:i+1},u=e.$findClosingBracket(t,o,s);if(!u)return;var a=e.foldWidgets[u.row];return a==null&&(a=e.getFoldWidget(u.row)),a=="start"&&u.row>o.row&&(u.row--,u.column=e.getLine(u.row).length),r.fromPoints(o,u)},this.closingBracketBlock=function(e,t,n,i,s){var o={row:n,column:i},u=e.$findOpeningBracket(t,o);if(!u)return;return u.column++,o.column--,r.fromPoints(u,o)}}).call(i.prototype)}),define("ace/lib/dom",["require","exports","module"],function(e,t,n){if(typeof document=="undefined")return;var r="http://www.w3.org/1999/xhtml";t.getDocumentHead=function(e){return e||(e=document),e.head||e.getElementsByTagName("head")[0]||e.documentElement},t.createElement=function(e,t){return document.createElementNS?document.createElementNS(t||r,e):document.createElement(e)},t.hasCssClass=function(e,t){var n=e.className.split(/\s+/g);return n.indexOf(t)!==-1},t.addCssClass=function(e,n){t.hasCssClass(e,n)||(e.className+=" "+n)},t.removeCssClass=function(e,t){var n=e.className.split(/\s+/g);for(;;){var r=n.indexOf(t);if(r==-1)break;n.splice(r,1)}e.className=n.join(" ")},t.toggleCssClass=function(e,t){var n=e.className.split(/\s+/g),r=!0;for(;;){var i=n.indexOf(t);if(i==-1)break;r=!1,n.splice(i,1)}return r&&n.push(t),e.className=n.join(" "),r},t.setCssClass=function(e,n,r){r?t.addCssClass(e,n):t.removeCssClass(e,n)},t.hasCssString=function(e,t){var n=0,r;t=t||document;if(t.createStyleSheet&&(r=t.styleSheets)){while(n<r.length)if(r[n++].owningElement.id===e)return!0}else if(r=t.getElementsByTagName("style"))while(n<r.length)if(r[n++].id===e)return!0;return!1},t.importCssString=function(e,n,i){i=i||document;if(n&&t.hasCssString(n,i))return null;var s;i.createStyleSheet?(s=i.createStyleSheet(),s.cssText=e,n&&(s.owningElement.id=n)):(s=i.createElementNS?i.createElementNS(r,"style"):i.createElement("style"),s.appendChild(i.createTextNode(e)),n&&(s.id=n),t.getDocumentHead(i).appendChild(s))},t.importCssStylsheet=function(e,n){if(n.createStyleSheet)n.createStyleSheet(e);else{var r=t.createElement("link");r.rel="stylesheet",r.href=e,t.getDocumentHead(n).appendChild(r)}},t.getInnerWidth=function(e){return parseInt(t.computedStyle(e,"paddingLeft"),10)+parseInt(t.computedStyle(e,"paddingRight"),10)+e.clientWidth},t.getInnerHeight=function(e){return parseInt(t.computedStyle(e,"paddingTop"),10)+parseInt(t.computedStyle(e,"paddingBottom"),10)+e.clientHeight},window.pageYOffset!==undefined?(t.getPageScrollTop=function(){return window.pageYOffset},t.getPageScrollLeft=function(){return window.pageXOffset}):(t.getPageScrollTop=function(){return document.body.scrollTop},t.getPageScrollLeft=function(){return document.body.scrollLeft}),window.getComputedStyle?t.computedStyle=function(e,t){return t?(window.getComputedStyle(e,"")||{})[t]||"":window.getComputedStyle(e,"")||{}}:t.computedStyle=function(e,t){return t?e.currentStyle[t]:e.currentStyle},t.scrollbarWidth=function(e){var n=t.createElement("ace_inner");n.style.width="100%",n.style.minWidth="0px",n.style.height="200px",n.style.display="block";var r=t.createElement("ace_outer"),i=r.style;i.position="absolute",i.left="-10000px",i.overflow="hidden",i.width="200px",i.minWidth="0px",i.height="150px",i.display="block",r.appendChild(n);var s=e.documentElement;s.appendChild(r);var o=n.offsetWidth;i.overflow="scroll";var u=n.offsetWidth;return o==u&&(u=r.clientWidth),s.removeChild(r),o-u},t.setInnerHtml=function(e,t){var n=e.cloneNode(!1);return n.innerHTML=t,e.parentNode.replaceChild(n,e),n},"textContent"in document.documentElement?(t.setInnerText=function(e,t){e.textContent=t},t.getInnerText=function(e){return e.textContent}):(t.setInnerText=function(e,t){e.innerText=t},t.getInnerText=function(e){return e.innerText}),t.getParentWindow=function(e){return e.defaultView||e.parentWindow}}),define("ace/theme/textmate",["require","exports","module","ace/lib/dom"],function(e,t,n){t.isDark=!1,t.cssClass="ace-tm",t.cssText='.ace-tm .ace_gutter {background: #f0f0f0;color: #333;}.ace-tm .ace_print-margin {width: 1px;background: #e8e8e8;}.ace-tm .ace_fold {background-color: #6B72E6;}.ace-tm {background-color: #FFFFFF;color: black;}.ace-tm .ace_cursor {color: black;}.ace-tm .ace_invisible {color: rgb(191, 191, 191);}.ace-tm .ace_storage,.ace-tm .ace_keyword {color: blue;}.ace-tm .ace_constant {color: rgb(197, 6, 11);}.ace-tm .ace_constant.ace_buildin {color: rgb(88, 72, 246);}.ace-tm .ace_constant.ace_language {color: rgb(88, 92, 246);}.ace-tm .ace_constant.ace_library {color: rgb(6, 150, 14);}.ace-tm .ace_invalid {background-color: rgba(255, 0, 0, 0.1);color: red;}.ace-tm .ace_support.ace_function {color: rgb(60, 76, 114);}.ace-tm .ace_support.ace_constant {color: rgb(6, 150, 14);}.ace-tm .ace_support.ace_type,.ace-tm .ace_support.ace_class {color: rgb(109, 121, 222);}.ace-tm .ace_keyword.ace_operator {color: rgb(104, 118, 135);}.ace-tm .ace_string {color: rgb(3, 106, 7);}.ace-tm .ace_comment {color: rgb(76, 136, 107);}.ace-tm .ace_comment.ace_doc {color: rgb(0, 102, 255);}.ace-tm .ace_comment.ace_doc.ace_tag {color: rgb(128, 159, 191);}.ace-tm .ace_constant.ace_numeric {color: rgb(0, 0, 205);}.ace-tm .ace_variable {color: rgb(49, 132, 149);}.ace-tm .ace_xml-pe {color: rgb(104, 104, 91);}.ace-tm .ace_entity.ace_name.ace_function {color: #0000A2;}.ace-tm .ace_heading {color: rgb(12, 7, 255);}.ace-tm .ace_list {color:rgb(185, 6, 144);}.ace-tm .ace_meta.ace_tag {color:rgb(0, 22, 142);}.ace-tm .ace_string.ace_regex {color: rgb(255, 0, 0)}.ace-tm .ace_marker-layer .ace_selection {background: rgb(181, 213, 255);}.ace-tm.ace_multiselect .ace_selection.ace_start {box-shadow: 0 0 3px 0px white;border-radius: 2px;}.ace-tm .ace_marker-layer .ace_step {background: rgb(252, 255, 0);}.ace-tm .ace_marker-layer .ace_stack {background: rgb(164, 229, 101);}.ace-tm .ace_marker-layer .ace_bracket {margin: -1px 0 0 -1px;border: 1px solid rgb(192, 192, 192);}.ace-tm .ace_marker-layer .ace_active-line {background: rgba(0, 0, 0, 0.07);}.ace-tm .ace_gutter-active-line {background-color : #dcdcdc;}.ace-tm .ace_marker-layer .ace_selected-word {background: rgb(250, 250, 255);border: 1px solid rgb(200, 200, 250);}.ace-tm .ace_indent-guide {background: url("data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAACCAYAAACZgbYnAAAAE0lEQVQImWP4////f4bLly//BwAmVgd1/w11/gAAAABJRU5ErkJggg==") right repeat-y;}';var r=e("../lib/dom");r.importCssString(t.cssText,t.cssClass)}),define("ace/lib/es5-shim",["require","exports","module"],function(e,t,n){function r(){}function i(e){try{return Object.defineProperty(e,"sentinel",{}),"sentinel"in e}catch(t){}}function s(e){return e=+e,e!==e?e=0:e!==0&&e!==1/0&&e!==-1/0&&(e=(e>0||-1)*Math.floor(Math.abs(e))),e}function o(e){var t=typeof e;return e===null||t==="undefined"||t==="boolean"||t==="number"||t==="string"}function u(e){var t,n,r;if(o(e))return e;n=e.valueOf;if(typeof n=="function"){t=n.call(e);if(o(t))return t}r=e.toString;if(typeof r=="function"){t=r.call(e);if(o(t))return t}throw new TypeError}Function.prototype.bind||(Function.prototype.bind=function(e){var t=this;if(typeof t!="function")throw new TypeError("Function.prototype.bind called on incompatible "+t);var n=c.call(arguments,1),i=function(){if(this instanceof i){var r=t.apply(this,n.concat(c.call(arguments)));return Object(r)===r?r:this}return t.apply(e,n.concat(c.call(arguments)))};return t.prototype&&(r.prototype=t.prototype,i.prototype=new r,r.prototype=null),i});var a=Function.prototype.call,f=Array.prototype,l=Object.prototype,c=f.slice,h=a.bind(l.toString),p=a.bind(l.hasOwnProperty),d,v,m,g,y;if(y=p(l,"__defineGetter__"))d=a.bind(l.__defineGetter__),v=a.bind(l.__defineSetter__),m=a.bind(l.__lookupGetter__),g=a.bind(l.__lookupSetter__);if([1,2].splice(0).length!=2)if(!function(){function e(e){var t=new Array(e+2);return t[0]=t[1]=0,t}var t=[],n;t.splice.apply(t,e(20)),t.splice.apply(t,e(26)),n=t.length,t.splice(5,0,"XXX"),n+1==t.length;if(n+1==t.length)return!0}())Array.prototype.splice=function(e,t){var n=this.length;e>0?e>n&&(e=n):e==void 0?e=0:e<0&&(e=Math.max(n+e,0)),e+t<n||(t=n-e);var r=this.slice(e,e+t),i=c.call(arguments,2),s=i.length;if(e===n)s&&this.push.apply(this,i);else{var o=Math.min(t,n-e),u=e+o,a=u+s-o,f=n-u,l=n-o;if(a<u)for(var h=0;h<f;++h)this[a+h]=this[u+h];else if(a>u)for(h=f;h--;)this[a+h]=this[u+h];if(s&&e===l)this.length=l,this.push.apply(this,i);else{this.length=l+s;for(h=0;h<s;++h)this[e+h]=i[h]}}return r};else{var b=Array.prototype.splice;Array.prototype.splice=function(e,t){return arguments.length?b.apply(this,[e===void 0?0:e,t===void 0?this.length-e:t].concat(c.call(arguments,2))):[]}}Array.isArray||(Array.isArray=function(e){return h(e)=="[object Array]"});var w=Object("a"),E=w[0]!="a"||!(0 in w);Array.prototype.forEach||(Array.prototype.forEach=function(e){var t=F(this),n=E&&h(this)=="[object String]"?this.split(""):t,r=arguments[1],i=-1,s=n.length>>>0;if(h(e)!="[object Function]")throw new TypeError;while(++i<s)i in n&&e.call(r,n[i],i,t)}),Array.prototype.map||(Array.prototype.map=function(e){var t=F(this),n=E&&h(this)=="[object String]"?this.split(""):t,r=n.length>>>0,i=Array(r),s=arguments[1];if(h(e)!="[object Function]")throw new TypeError(e+" is not a function");for(var o=0;o<r;o++)o in n&&(i[o]=e.call(s,n[o],o,t));return i}),Array.prototype.filter||(Array.prototype.filter=function(e){var t=F(this),n=E&&h(this)=="[object String]"?this.split(""):t,r=n.length>>>0,i=[],s,o=arguments[1];if(h(e)!="[object Function]")throw new TypeError(e+" is not a function");for(var u=0;u<r;u++)u in n&&(s=n[u],e.call(o,s,u,t)&&i.push(s));return i}),Array.prototype.every||(Array.prototype.every=function(e){var t=F(this),n=E&&h(this)=="[object String]"?this.split(""):t,r=n.length>>>0,i=arguments[1];if(h(e)!="[object Function]")throw new TypeError(e+" is not a function");for(var s=0;s<r;s++)if(s in n&&!e.call(i,n[s],s,t))return!1;return!0}),Array.prototype.some||(Array.prototype.some=function(e){var t=F(this),n=E&&h(this)=="[object String]"?this.split(""):t,r=n.length>>>0,i=arguments[1];if(h(e)!="[object Function]")throw new TypeError(e+" is not a function");for(var s=0;s<r;s++)if(s in n&&e.call(i,n[s],s,t))return!0;return!1}),Array.prototype.reduce||(Array.prototype.reduce=function(e){var t=F(this),n=E&&h(this)=="[object String]"?this.split(""):t,r=n.length>>>0;if(h(e)!="[object Function]")throw new TypeError(e+" is not a function");if(!r&&arguments.length==1)throw new TypeError("reduce of empty array with no initial value");var i=0,s;if(arguments.length>=2)s=arguments[1];else do{if(i in n){s=n[i++];break}if(++i>=r)throw new TypeError("reduce of empty array with no initial value")}while(!0);for(;i<r;i++)i in n&&(s=e.call(void 0,s,n[i],i,t));return s}),Array.prototype.reduceRight||(Array.prototype.reduceRight=function(e){var t=F(this),n=E&&h(this)=="[object String]"?this.split(""):t,r=n.length>>>0;if(h(e)!="[object Function]")throw new TypeError(e+" is not a function");if(!r&&arguments.length==1)throw new TypeError("reduceRight of empty array with no initial value");var i,s=r-1;if(arguments.length>=2)i=arguments[1];else do{if(s in n){i=n[s--];break}if(--s<0)throw new TypeError("reduceRight of empty array with no initial value")}while(!0);do s in this&&(i=e.call(void 0,i,n[s],s,t));while(s--);return i});if(!Array.prototype.indexOf||[0,1].indexOf(1,2)!=-1)Array.prototype.indexOf=function(e){var t=E&&h(this)=="[object String]"?this.split(""):F(this),n=t.length>>>0;if(!n)return-1;var r=0;arguments.length>1&&(r=s(arguments[1])),r=r>=0?r:Math.max(0,n+r);for(;r<n;r++)if(r in t&&t[r]===e)return r;return-1};if(!Array.prototype.lastIndexOf||[0,1].lastIndexOf(0,-3)!=-1)Array.prototype.lastIndexOf=function(e){var t=E&&h(this)=="[object String]"?this.split(""):F(this),n=t.length>>>0;if(!n)return-1;var r=n-1;arguments.length>1&&(r=Math.min(r,s(arguments[1]))),r=r>=0?r:n-Math.abs(r);for(;r>=0;r--)if(r in t&&e===t[r])return r;return-1};Object.getPrototypeOf||(Object.getPrototypeOf=function(e){return e.__proto__||(e.constructor?e.constructor.prototype:l)});if(!Object.getOwnPropertyDescriptor){var S="Object.getOwnPropertyDescriptor called on a non-object: ";Object.getOwnPropertyDescriptor=function(e,t){if(typeof e!="object"&&typeof e!="function"||e===null)throw new TypeError(S+e);if(!p(e,t))return;var n,r,i;n={enumerable:!0,configurable:!0};if(y){var s=e.__proto__;e.__proto__=l;var r=m(e,t),i=g(e,t);e.__proto__=s;if(r||i)return r&&(n.get=r),i&&(n.set=i),n}return n.value=e[t],n}}Object.getOwnPropertyNames||(Object.getOwnPropertyNames=function(e){return Object.keys(e)});if(!Object.create){var x;Object.prototype.__proto__===null?x=function(){return{__proto__:null}}:x=function(){var e={};for(var t in e)e[t]=null;return e.constructor=e.hasOwnProperty=e.propertyIsEnumerable=e.isPrototypeOf=e.toLocaleString=e.toString=e.valueOf=e.__proto__=null,e},Object.create=function(e,t){var n;if(e===null)n=x();else{if(typeof e!="object")throw new TypeError("typeof prototype["+typeof e+"] != 'object'");var r=function(){};r.prototype=e,n=new r,n.__proto__=e}return t!==void 0&&Object.defineProperties(n,t),n}}if(Object.defineProperty){var T=i({}),N=typeof document=="undefined"||i(document.createElement("div"));if(!T||!N)var C=Object.defineProperty}if(!Object.defineProperty||C){var k="Property description must be an object: ",L="Object.defineProperty called on non-object: ",A="getters & setters can not be defined on this javascript engine";Object.defineProperty=function(e,t,n){if(typeof e!="object"&&typeof e!="function"||e===null)throw new TypeError(L+e);if(typeof n!="object"&&typeof n!="function"||n===null)throw new TypeError(k+n);if(C)try{return C.call(Object,e,t,n)}catch(r){}if(p(n,"value"))if(y&&(m(e,t)||g(e,t))){var i=e.__proto__;e.__proto__=l,delete e[t],e[t]=n.value,e.__proto__=i}else e[t]=n.value;else{if(!y)throw new TypeError(A);p(n,"get")&&d(e,t,n.get),p(n,"set")&&v(e,t,n.set)}return e}}Object.defineProperties||(Object.defineProperties=function(e,t){for(var n in t)p(t,n)&&Object.defineProperty(e,n,t[n]);return e}),Object.seal||(Object.seal=function(e){return e}),Object.freeze||(Object.freeze=function(e){return e});try{Object.freeze(function(){})}catch(O){Object.freeze=function(e){return function(t){return typeof t=="function"?t:e(t)}}(Object.freeze)}Object.preventExtensions||(Object.preventExtensions=function(e){return e}),Object.isSealed||(Object.isSealed=function(e){return!1}),Object.isFrozen||(Object.isFrozen=function(e){return!1}),Object.isExtensible||(Object.isExtensible=function(e){if(Object(e)===e)throw new TypeError;var t="";while(p(e,t))t+="?";e[t]=!0;var n=p(e,t);return delete e[t],n});if(!Object.keys){var M=!0,_=["toString","toLocaleString","valueOf","hasOwnProperty","isPrototypeOf","propertyIsEnumerable","constructor"],D=_.length;for(var P in{toString:null})M=!1;Object.keys=function I(e){if(typeof e!="object"&&typeof e!="function"||e===null)throw new TypeError("Object.keys called on a non-object");var I=[];for(var t in e)p(e,t)&&I.push(t);if(M)for(var n=0,r=D;n<r;n++){var i=_[n];p(e,i)&&I.push(i)}return I}}Date.now||(Date.now=function(){return(new Date).getTime()});var H=" \n\v\f\r \u2028\u2029";if(!String.prototype.trim||H.trim()){H="["+H+"]";var B=new RegExp("^"+H+H+"*"),j=new RegExp(H+H+"*$");String.prototype.trim=function(){return String(this).replace(B,"").replace(j,"")}}var F=function(e){if(e==null)throw new TypeError("can't convert "+e+" to object");return Object(e)}}),define("ace/lib/regexp",["require","exports","module"],function(e,t,n){function r(e){return(e.global?"g":"")+(e.ignoreCase?"i":"")+(e.multiline?"m":"")+(e.extended?"x":"")+(e.sticky?"y":"")}function i(e,t,n){if(Array.prototype.indexOf)return e.indexOf(t,n);for(var r=n||0;r<e.length;r++)if(e[r]===t)return r;return-1}var s={exec:RegExp.prototype.exec,test:RegExp.prototype.test,match:String.prototype.match,replace:String.prototype.replace,split:String.prototype.split},o=s.exec.call(/()??/,"")[1]===undefined,u=function(){var e=/^/g;return s.test.call(e,""),!e.lastIndex}();if(u&&o)return;RegExp.prototype.exec=function(e){var t=s.exec.apply(this,arguments),n,a;if(typeof e=="string"&&t){!o&&t.length>1&&i(t,"")>-1&&(a=RegExp(this.source,s.replace.call(r(this),"g","")),s.replace.call(e.slice(t.index),a,function(){for(var e=1;e<arguments.length-2;e++)arguments[e]===undefined&&(t[e]=undefined)}));if(this._xregexp&&this._xregexp.captureNames)for(var f=1;f<t.length;f++)n=this._xregexp.captureNames[f-1],n&&(t[n]=t[f]);!u&&this.global&&!t[0].length&&this.lastIndex>t.index&&this.lastIndex--}return t},u||(RegExp.prototype.test=function(e){var t=s.exec.call(this,e);return t&&this.global&&!t[0].length&&this.lastIndex>t.index&&this.lastIndex--,!!t})}),define("ace/ext/error_marker",["require","exports","module","ace/line_widgets","ace/lib/dom","ace/range"],function(e,t,n){function r(e,t,n){var r=0,i=e.length-1;while(r<=i){var s=r+i>>1,o=n(t,e[s]);if(o>0)r=s+1;else{if(!(o<0))return s;i=s-1}}return-(r+1)}function i(e,t,n){var i=e.getAnnotations().sort(u.comparePoints);if(!i.length)return;var s=r(i,{row:t,column:-1},u.comparePoints);s<0&&(s=-s-1),s>=i.length-1?s=n>0?0:i.length-1:s===0&&n<0&&(s=i.length-1);var o=i[s];if(!o||!n)return;if(o.row===t){do o=i[s+=n];while(o&&o.row===t);if(!o)return i.slice()}var a=[];t=o.row;do a[n<0?"unshift":"push"](o),o=i[s+=n];while(o&&o.row==t);return a.length&&a}var s=e("ace/line_widgets").LineWidgets,o=e("ace/lib/dom"),u=e("ace/range").Range;t.showErrorMarker=function(e,t){var n=e.session;n.widgetManager||(n.widgetManager=new s(n),n.widgetManager.attach(e));var r=e.getCursorPosition(),u=r.row,a=n.lineWidgets&&n.lineWidgets[u];a?a.destroy():u-=t;var f=i(n,u,t),l;if(f){var c=f[0];r.column=(c.pos&&typeof c.column!="number"?c.pos.sc:c.column)||0,r.row=c.row,l=e.renderer.$gutterLayer.$annotations[r.row]}else{if(a)return;l={text:["Looks good!"],className:"ace_ok"}}e.session.unfold(r.row),e.selection.moveToPosition(r);var h={row:r.row,fixedWidth:!0,coverGutter:!0,el:o.createElement("div")},p=h.el.appendChild(o.createElement("div")),d=h.el.appendChild(o.createElement("div"));d.className="error_widget_arrow "+l.className;var v=e.renderer.$cursorLayer.getPixelPosition(r).left;d.style.left=v+e.renderer.gutterWidth-5+"px",h.el.className="error_widget_wrapper",p.className="error_widget "+l.className,p.innerHTML=l.text.join("<br>"),p.appendChild(o.createElement("div"));var m=function(e,t,n){if(t===0&&(n==="esc"||n==="return"))return h.destroy(),{command:"null"}};h.destroy=function(){if(e.$mouseHandler.isMousePressed)return;e.keyBinding.removeKeyboardHandler(m),n.widgetManager.removeLineWidget(h),e.off("changeSelection",h.destroy),e.off("changeSession",h.destroy),e.off("mouseup",h.destroy),e.off("change",h.destroy)},e.keyBinding.addKeyboardHandler(m),e.on("changeSelection",h.destroy),e.on("changeSession",h.destroy),e.on("mouseup",h.destroy),e.on("change",h.destroy),e.session.widgetManager.addLineWidget(h),h.el.onmousedown=e.focus.bind(e),e.renderer.scrollCursorIntoView(null,.5,{bottom:h.el.offsetHeight})},o.importCssString(" .error_widget_wrapper { background: inherit; color: inherit; border:none } .error_widget { border-top: solid 2px; border-bottom: solid 2px; margin: 5px 0; padding: 10px 40px; white-space: pre-wrap; } .error_widget.ace_error, .error_widget_arrow.ace_error{ border-color: #ff5a5a } .error_widget.ace_warning, .error_widget_arrow.ace_warning{ border-color: #F1D817 } .error_widget.ace_info, .error_widget_arrow.ace_info{ border-color: #5a5a5a } .error_widget.ace_ok, .error_widget_arrow.ace_ok{ border-color: #5aaa5a } .error_widget_arrow { position: absolute; border: solid 5px; border-top-color: transparent!important; border-right-color: transparent!important; border-left-color: transparent!important; top: -5px; }","")}),define("ace/lib/fixoldbrowsers",["require","exports","module","ace/lib/regexp","ace/lib/es5-shim"],function(e,t,n){e("./regexp"),e("./es5-shim")}),define("ace/line_widgets",["require","exports","module","ace/lib/oop","ace/lib/dom","ace/range"],function(e,t,n){function r(e){this.session=e,this.session.widgetManager=this,this.session.getRowLength=this.getRowLength,this.session.$getWidgetScreenLength=this.$getWidgetScreenLength,this.updateOnChange=this.updateOnChange.bind(this),this.renderWidgets=this.renderWidgets.bind(this),this.measureWidgets=this.measureWidgets.bind(this),this.session._changedWidgets=[],this.detach=this.detach.bind(this),this.session.on("change",this.updateOnChange)}var i=e("./lib/oop"),s=e("./lib/dom"),o=e("./range").Range;(function(){this.getRowLength=function(e){var t;return this.lineWidgets?t=this.lineWidgets[e]&&this.lineWidgets[e].rowCount||0:t=0,!this.$useWrapMode||!this.$wrapData[e]?1+t:this.$wrapData[e].length+1+t},this.$getWidgetScreenLength=function(){var e=0;return this.lineWidgets.forEach(function(t){t&&t.rowCount&&(e+=t.rowCount)}),e},this.attach=function(e){e.widgetManager&&e.widgetManager!=this&&e.widgetManager.detach();if(this.editor==e)return;this.detach(),this.editor=e,this.editor.on("changeSession",this.detach),e.widgetManager=this,e.setOption("enableLineWidgets",!0),e.renderer.on("beforeRender",this.measureWidgets),e.renderer.on("afterRender",this.renderWidgets)},this.detach=function(e){if(e&&e.session==this.session)return;var t=this.editor;if(!t)return;t.off("changeSession",this.detach),this.editor=null,t.widgetManager=null,t.renderer.off("beforeRender",this.measureWidgets),t.renderer.off("afterRender",this.renderWidgets);var n=this.session.lineWidgets;n&&n.forEach(function(e){e&&e.el&&e.el.parentNode&&(e._inDocument=!1,e.el.parentNode.removeChild(e.el))})},this.updateOnChange=function(e){var t=this.session.lineWidgets;if(!t)return;var n=e.data,r=n.range,i=r.start.row,s=r.end.row-i;if(s!==0)if(n.action=="removeText"||n.action=="removeLines"){var o=t.splice(i+1,s);o.forEach(function(e){e&&this.removeLineWidget(e)},this),this.$updateRows()}else{var u=new Array(s);u.unshift(i,0),t.splice.apply(t,u),this.$updateRows()}},this.$updateRows=function(){var e=this.session.lineWidgets;if(!e)return;var t=!0;e.forEach(function(e,n){e&&(t=!1,e.row=n)}),t&&(this.session.lineWidgets=null)},this.addLineWidget=function(e){this.session.lineWidgets||(this.session.lineWidgets=new Array(this.session.getLength())),this.session.lineWidgets[e.row]=e;var t=this.editor.renderer;return e.html&&!e.el&&(e.el=s.createElement("div"),e.el.innerHTML=e.html),e.el&&(s.addCssClass(e.el,"ace_lineWidgetContainer"),e.el.style.position="absolute",e.el.style.zIndex=5,t.container.appendChild(e.el),e._inDocument=!0),e.coverGutter||(e.el.style.zIndex=3),e.pixelHeight||(e.pixelHeight=e.el.offsetHeight),e.rowCount==null&&(e.rowCount=e.pixelHeight/t.layerConfig.lineHeight),this.session._emit("changeFold",{data:{start:{row:e.row}}}),this.$updateRows(),this.renderWidgets(null,t),e},this.removeLineWidget=function(e){e._inDocument=!1,e.el&&e.el.parentNode&&e.el.parentNode.removeChild(e.el);if(e.editor&&e.editor.destroy)try{e.editor.destroy()}catch(t){}this.session.lineWidgets&&(this.session.lineWidgets[e.row]=undefined),this.session._emit("changeFold",{data:{start:{row:e.row}}}),this.$updateRows()},this.onWidgetChanged=function(e){this.session._changedWidgets.push(e),this.editor&&this.editor.renderer.updateFull()},this.measureWidgets=function(e,t){var n=this.session._changedWidgets,r=t.layerConfig;if(!n||!n.length)return;var i=Infinity;for(var s=0;s<n.length;s++){var o=n[s];o._inDocument||(o._inDocument=!0,t.container.appendChild(o.el)),o.h=o.el.offsetHeight,o.fixedWidth||(o.w=o.el.offsetWidth,o.screenWidth=Math.ceil(o.w/r.characterWidth));var u=o.h/r.lineHeight;o.coverLine&&(u-=this.session.getRowLineCount(o.row),u<0&&(u=0)),o.rowCount!=u&&(o.rowCount=u,o.row<i&&(i=o.row))}i!=Infinity&&(this.session._emit("changeFold",{data:{start:{row:i}}}),this.session.lineWidgetWidth=null),this.session._changedWidgets=[]},this.renderWidgets=function(e,t){var n=t.layerConfig,r=this.session.lineWidgets;if(!r)return;var i=Math.min(this.firstRow,n.firstRow),s=Math.max(this.lastRow,n.lastRow,r.length);while(i>0&&!r[i])i--;this.firstRow=n.firstRow,this.lastRow=n.lastRow,t.$cursorLayer.config=n;for(var o=i;o<=s;o++){var u=r[o];if(!u||!u.el)continue;u._inDocument||(u._inDocument=!0,t.container.appendChild(u.el));var a=t.$cursorLayer.getPixelPosition({row:o,column:0},!0).top;u.coverLine||(a+=n.lineHeight*this.session.getRowLineCount(u.row)),u.el.style.top=a-n.offset+"px";var f=u.coverGutter?0:t.gutterWidth;u.fixedWidth||(f-=t.scrollLeft),u.el.style.left=f+"px",u.fixedWidth?u.el.style.right=t.scrollBar.getWidth()+"px":u.el.style.right=""}}}).call(r.prototype),t.LineWidgets=r}),define("ace/document",["require","exports","module","ace/lib/oop","ace/lib/event_emitter","ace/range","ace/anchor"],function(e,t,n){var r=e("./lib/oop"),i=e("./lib/event_emitter").EventEmitter,s=e("./range").Range,o=e("./anchor").Anchor,u=function(e){this.$lines=[],e.length===0?this.$lines=[""]:Array.isArray(e)?this._insertLines(0,e):this.insert({row:0,column:0},e)};(function(){r.implement(this,i),this.setValue=function(e){var t=this.getLength();this.remove(new s(0,0,t,this.getLine(t-1).length)),this.insert({row:0,column:0},e)},this.getValue=function(){return this.getAllLines().join(this.getNewLineCharacter())},this.createAnchor=function(e,t){return new o(this,e,t)},"aaa".split(/a/).length===0?this.$split=function(e){return e.replace(/\r\n|\r/g,"\n").split("\n")}:this.$split=function(e){return e.split(/\r\n|\r|\n/)},this.$detectNewLine=function(e){var t=e.match(/^.*?(\r\n|\r|\n)/m);this.$autoNewLine=t?t[1]:"\n",this._signal("changeNewLineMode")},this.getNewLineCharacter=function(){switch(this.$newLineMode){case"windows":return"\r\n";case"unix":return"\n";default:return this.$autoNewLine||"\n"}},this.$autoNewLine="",this.$newLineMode="auto",this.setNewLineMode=function(e){if(this.$newLineMode===e)return;this.$newLineMode=e,this._signal("changeNewLineMode")},this.getNewLineMode=function(){return this.$newLineMode},this.isNewLine=function(e){return e=="\r\n"||e=="\r"||e=="\n"},this.getLine=function(e){return this.$lines[e]||""},this.getLines=function(e,t){return this.$lines.slice(e,t+1)},this.getAllLines=function(){return this.getLines(0,this.getLength())},this.getLength=function(){return this.$lines.length},this.getTextRange=function(e){if(e.start.row==e.end.row)return this.getLine(e.start.row).substring(e.start.column,e.end.column);var t=this.getLines(e.start.row,e.end.row);t[0]=(t[0]||"").substring(e.start.column);var n=t.length-1;return e.end.row-e.start.row==n&&(t[n]=t[n].substring(0,e.end.column)),t.join(this.getNewLineCharacter())},this.$clipPosition=function(e){var t=this.getLength();return e.row>=t?(e.row=Math.max(0,t-1),e.column=this.getLine(t-1).length):e.row<0&&(e.row=0),e},this.insert=function(e,t){if(!t||t.length===0)return e;e=this.$clipPosition(e),this.getLength()<=1&&this.$detectNewLine(t);var n=this.$split(t),r=n.splice(0,1)[0],i=n.length==0?null:n.splice(n.length-1,1)[0];return e=this.insertInLine(e,r),i!==null&&(e=this.insertNewLine(e),e=this._insertLines(e.row,n),e=this.insertInLine(e,i||"")),e},this.insertLines=function(e,t){return e>=this.getLength()?this.insert({row:e,column:0},"\n"+t.join("\n")):this._insertLines(Math.max(e,0),t)},this._insertLines=function(e,t){if(t.length==0)return{row:e,column:0};while(t.length>61440){var n=this._insertLines(e,t.slice(0,61440));t=t.slice(61440),e=n.row}var r=[e,0];r.push.apply(r,t),this.$lines.splice.apply(this.$lines,r);var i=new s(e,0,e+t.length,0),o={action:"insertLines",range:i,lines:t};return this._signal("change",{data:o}),i.end},this.insertNewLine=function(e){e=this.$clipPosition(e);var t=this.$lines[e.row]||"";this.$lines[e.row]=t.substring(0,e.column),this.$lines.splice(e.row+1,0,t.substring(e.column,t.length));var n={row:e.row+1,column:0},r={action:"insertText",range:s.fromPoints(e,n),text:this.getNewLineCharacter()};return this._signal("change",{data:r}),n},this.insertInLine=function(e,t){if(t.length==0)return e;var n=this.$lines[e.row]||"";this.$lines[e.row]=n.substring(0,e.column)+t+n.substring(e.column);var r={row:e.row,column:e.column+t.length},i={action:"insertText",range:s.fromPoints(e,r),text:t};return this._signal("change",{data:i}),r},this.remove=function(e){e instanceof s||(e=s.fromPoints(e.start,e.end)),e.start=this.$clipPosition(e.start),e.end=this.$clipPosition(e.end);if(e.isEmpty())return e.start;var t=e.start.row,n=e.end.row;if(e.isMultiLine()){var r=e.start.column==0?t:t+1,i=n-1;e.end.column>0&&this.removeInLine(n,0,e.end.column),i>=r&&this._removeLines(r,i),r!=t&&(this.removeInLine(t,e.start.column,this.getLine(t).length),this.removeNewLine(e.start.row))}else this.removeInLine(t,e.start.column,e.end.column);return e.start},this.removeInLine=function(e,t,n){if(t==n)return;var r=new s(e,t,e,n),i=this.getLine(e),o=i.substring(t,n),u=i.substring(0,t)+i.substring(n,i.length);this.$lines.splice(e,1,u);var a={action:"removeText",range:r,text:o};return this._signal("change",{data:a}),r.start},this.removeLines=function(e,t){return e<0||t>=this.getLength()?this.remove(new s(e,0,t+1,0)):this._removeLines(e,t)},this._removeLines=function(e,t){var n=new s(e,0,t+1,0),r=this.$lines.splice(e,t-e+1),i={action:"removeLines",range:n,nl:this.getNewLineCharacter(),lines:r};return this._signal("change",{data:i}),r},this.removeNewLine=function(e){var t=this.getLine(e),n=this.getLine(e+1),r=new s(e,t.length,e+1,0),i=t+n;this.$lines.splice(e,2,i);var o={action:"removeText",range:r,text:this.getNewLineCharacter()};this._signal("change",{data:o})},this.replace=function(e,t){e instanceof s||(e=s.fromPoints(e.start,e.end));if(t.length==0&&e.isEmpty())return e.start;if(t==this.getTextRange(e))return e.end;this.remove(e);if(t)var n=this.insert(e.start,t);else n=e.start;return n},this.applyDeltas=function(e){for(var t=0;t<e.length;t++){var n=e[t],r=s.fromPoints(n.range.start,n.range.end);n.action=="insertLines"?this.insertLines(r.start.row,n.lines):n.action=="insertText"?this.insert(r.start,n.text):n.action=="removeLines"?this._removeLines(r.start.row,r.end.row-1):n.action=="removeText"&&this.remove(r)}},this.revertDeltas=function(e){for(var t=e.length-1;t>=0;t--){var n=e[t],r=s.fromPoints(n.range.start,n.range.end);n.action=="insertLines"?this._removeLines(r.start.row,r.end.row-1):n.action=="insertText"?this.remove(r):n.action=="removeLines"?this._insertLines(r.start.row,n.lines):n.action=="removeText"&&this.insert(r.start,n.text)}},this.indexToPosition=function(e,t){var n=this.$lines||this.getAllLines(),r=this.getNewLineCharacter().length;for(var i=t||0,s=n.length;i<s;i++){e-=n[i].length+r;if(e<0)return{row:i,column:e+n[i].length+r}}return{row:s-1,column:n[s-1].length}},this.positionToIndex=function(e,t){var n=this.$lines||this.getAllLines(),r=this.getNewLineCharacter().length,i=0,s=Math.min(e.row,n.length);for(var o=t||0;o<s;++o)i+=n[o].length+r;return i+e.column}}).call(u.prototype),t.Document=u}),function(){window.require(["ace/ace"],function(e){e&&e.config.init(!0),window.ace||(window.ace=e);for(var t in e)e.hasOwnProperty(t)&&(ace[t]=e[t])})}();
\ No newline at end of file
--- /dev/null
+define("ace/mode/css",["require","exports","module","ace/lib/oop","ace/mode/text","ace/tokenizer","ace/mode/css_highlight_rules","ace/mode/matching_brace_outdent","ace/worker/worker_client","ace/mode/behaviour/css","ace/mode/folding/cstyle"],function(e,t,n){var r=e("../lib/oop"),i=e("./text").Mode,s=e("../tokenizer").Tokenizer,o=e("./css_highlight_rules").CssHighlightRules,u=e("./matching_brace_outdent").MatchingBraceOutdent,a=e("../worker/worker_client").WorkerClient,f=e("./behaviour/css").CssBehaviour,l=e("./folding/cstyle").FoldMode,c=function(){this.HighlightRules=o,this.$outdent=new u,this.$behaviour=new f,this.foldingRules=new l};r.inherits(c,i),function(){this.foldingRules="cStyle",this.blockComment={start:"/*",end:"*/"},this.getNextLineIndent=function(e,t,n){var r=this.$getIndent(t),i=this.getTokenizer().getLineTokens(t,e).tokens;if(i.length&&i[i.length-1].type=="comment")return r;var s=t.match(/^.*\{\s*$/);return s&&(r+=n),r},this.checkOutdent=function(e,t,n){return this.$outdent.checkOutdent(t,n)},this.autoOutdent=function(e,t,n){this.$outdent.autoOutdent(t,n)},this.createWorker=function(e){var t=new a(["ace"],"ace/mode/css_worker","Worker");return t.attachToDocument(e.getDocument()),t.on("csslint",function(t){e.setAnnotations(t.data)}),t.on("terminate",function(){e.clearAnnotations()}),t},this.$id="ace/mode/css"}.call(c.prototype),t.Mode=c}),define("ace/mode/css_highlight_rules",["require","exports","module","ace/lib/oop","ace/lib/lang","ace/mode/text_highlight_rules"],function(e,t,n){var r=e("../lib/oop"),i=e("../lib/lang"),s=e("./text_highlight_rules").TextHighlightRules,o=t.supportType="animation-fill-mode|alignment-adjust|alignment-baseline|animation-delay|animation-direction|animation-duration|animation-iteration-count|animation-name|animation-play-state|animation-timing-function|animation|appearance|azimuth|backface-visibility|background-attachment|background-break|background-clip|background-color|background-image|background-origin|background-position|background-repeat|background-size|background|baseline-shift|binding|bleed|bookmark-label|bookmark-level|bookmark-state|bookmark-target|border-bottom|border-bottom-color|border-bottom-left-radius|border-bottom-right-radius|border-bottom-style|border-bottom-width|border-collapse|border-color|border-image|border-image-outset|border-image-repeat|border-image-slice|border-image-source|border-image-width|border-left|border-left-color|border-left-style|border-left-width|border-radius|border-right|border-right-color|border-right-style|border-right-width|border-spacing|border-style|border-top|border-top-color|border-top-left-radius|border-top-right-radius|border-top-style|border-top-width|border-width|border|bottom|box-align|box-decoration-break|box-direction|box-flex-group|box-flex|box-lines|box-ordinal-group|box-orient|box-pack|box-shadow|box-sizing|break-after|break-before|break-inside|caption-side|clear|clip|color-profile|color|column-count|column-fill|column-gap|column-rule|column-rule-color|column-rule-style|column-rule-width|column-span|column-width|columns|content|counter-increment|counter-reset|crop|cue-after|cue-before|cue|cursor|direction|display|dominant-baseline|drop-initial-after-adjust|drop-initial-after-align|drop-initial-before-adjust|drop-initial-before-align|drop-initial-size|drop-initial-value|elevation|empty-cells|fit|fit-position|float-offset|float|font-family|font-size|font-size-adjust|font-stretch|font-style|font-variant|font-weight|font|grid-columns|grid-rows|hanging-punctuation|height|hyphenate-after|hyphenate-before|hyphenate-character|hyphenate-lines|hyphenate-resource|hyphens|icon|image-orientation|image-rendering|image-resolution|inline-box-align|left|letter-spacing|line-height|line-stacking-ruby|line-stacking-shift|line-stacking-strategy|line-stacking|list-style-image|list-style-position|list-style-type|list-style|margin-bottom|margin-left|margin-right|margin-top|margin|mark-after|mark-before|mark|marks|marquee-direction|marquee-play-count|marquee-speed|marquee-style|max-height|max-width|min-height|min-width|move-to|nav-down|nav-index|nav-left|nav-right|nav-up|opacity|orphans|outline-color|outline-offset|outline-style|outline-width|outline|overflow-style|overflow-x|overflow-y|overflow|padding-bottom|padding-left|padding-right|padding-top|padding|page-break-after|page-break-before|page-break-inside|page-policy|page|pause-after|pause-before|pause|perspective-origin|perspective|phonemes|pitch-range|pitch|play-during|pointer-events|position|presentation-level|punctuation-trim|quotes|rendering-intent|resize|rest-after|rest-before|rest|richness|right|rotation-point|rotation|ruby-align|ruby-overhang|ruby-position|ruby-span|size|speak-header|speak-numeral|speak-punctuation|speak|speech-rate|stress|string-set|table-layout|target-name|target-new|target-position|target|text-align-last|text-align|text-decoration|text-emphasis|text-height|text-indent|text-justify|text-outline|text-shadow|text-transform|text-wrap|top|transform-origin|transform-style|transform|transition-delay|transition-duration|transition-property|transition-timing-function|transition|unicode-bidi|vertical-align|visibility|voice-balance|voice-duration|voice-family|voice-pitch-range|voice-pitch|voice-rate|voice-stress|voice-volume|volume|white-space-collapse|white-space|widows|width|word-break|word-spacing|word-wrap|z-index",u=t.supportFunction="rgb|rgba|url|attr|counter|counters",a=t.supportConstant="absolute|after-edge|after|all-scroll|all|alphabetic|always|antialiased|armenian|auto|avoid-column|avoid-page|avoid|balance|baseline|before-edge|before|below|bidi-override|block-line-height|block|bold|bolder|border-box|both|bottom|box|break-all|break-word|capitalize|caps-height|caption|center|central|char|circle|cjk-ideographic|clone|close-quote|col-resize|collapse|column|consider-shifts|contain|content-box|cover|crosshair|cubic-bezier|dashed|decimal-leading-zero|decimal|default|disabled|disc|disregard-shifts|distribute-all-lines|distribute-letter|distribute-space|distribute|dotted|double|e-resize|ease-in|ease-in-out|ease-out|ease|ellipsis|end|exclude-ruby|fill|fixed|georgian|glyphs|grid-height|groove|hand|hanging|hebrew|help|hidden|hiragana-iroha|hiragana|horizontal|icon|ideograph-alpha|ideograph-numeric|ideograph-parenthesis|ideograph-space|ideographic|inactive|include-ruby|inherit|initial|inline-block|inline-box|inline-line-height|inline-table|inline|inset|inside|inter-ideograph|inter-word|invert|italic|justify|katakana-iroha|katakana|keep-all|last|left|lighter|line-edge|line-through|line|linear|list-item|local|loose|lower-alpha|lower-greek|lower-latin|lower-roman|lowercase|lr-tb|ltr|mathematical|max-height|max-size|medium|menu|message-box|middle|move|n-resize|ne-resize|newspaper|no-change|no-close-quote|no-drop|no-open-quote|no-repeat|none|normal|not-allowed|nowrap|nw-resize|oblique|open-quote|outset|outside|overline|padding-box|page|pointer|pre-line|pre-wrap|pre|preserve-3d|progress|relative|repeat-x|repeat-y|repeat|replaced|reset-size|ridge|right|round|row-resize|rtl|s-resize|scroll|se-resize|separate|slice|small-caps|small-caption|solid|space|square|start|static|status-bar|step-end|step-start|steps|stretch|strict|sub|super|sw-resize|table-caption|table-cell|table-column-group|table-column|table-footer-group|table-header-group|table-row-group|table-row|table|tb-rl|text-after-edge|text-before-edge|text-bottom|text-size|text-top|text|thick|thin|transparent|underline|upper-alpha|upper-latin|upper-roman|uppercase|use-script|vertical-ideographic|vertical-text|visible|w-resize|wait|whitespace|z-index|zero",f=t.supportConstantColor="aqua|black|blue|fuchsia|gray|green|lime|maroon|navy|olive|orange|purple|red|silver|teal|white|yellow",l=t.supportConstantFonts="arial|century|comic|courier|garamond|georgia|helvetica|impact|lucida|symbol|system|tahoma|times|trebuchet|utopia|verdana|webdings|sans-serif|serif|monospace",c=t.numRe="\\-?(?:(?:[0-9]+)|(?:[0-9]*\\.[0-9]+))",h=t.pseudoElements="(\\:+)\\b(after|before|first-letter|first-line|moz-selection|selection)\\b",p=t.pseudoClasses="(:)\\b(active|checked|disabled|empty|enabled|first-child|first-of-type|focus|hover|indeterminate|invalid|last-child|last-of-type|link|not|nth-child|nth-last-child|nth-last-of-type|nth-of-type|only-child|only-of-type|required|root|target|valid|visited)\\b",d=function(){var e=this.createKeywordMapper({"support.function":u,"support.constant":a,"support.type":o,"support.constant.color":f,"support.constant.fonts":l},"text",!0);this.$rules={start:[{token:"comment",regex:"\\/\\*",push:"comment"},{token:"paren.lparen",regex:"\\{",push:"ruleset"},{token:"string",regex:"@.*?{",push:"media"},{token:"keyword",regex:"#[a-z0-9-_]+"},{token:"variable",regex:"\\.[a-z0-9-_]+"},{token:"string",regex:":[a-z0-9-_]+"},{token:"constant",regex:"[a-z0-9-_]+"},{caseInsensitive:!0}],media:[{token:"comment",regex:"\\/\\*",push:"comment"},{token:"paren.lparen",regex:"\\{",push:"ruleset"},{token:"string",regex:"\\}",next:"pop"},{token:"keyword",regex:"#[a-z0-9-_]+"},{token:"variable",regex:"\\.[a-z0-9-_]+"},{token:"string",regex:":[a-z0-9-_]+"},{token:"constant",regex:"[a-z0-9-_]+"},{caseInsensitive:!0}],comment:[{token:"comment",regex:"\\*\\/",next:"pop"},{defaultToken:"comment"}],ruleset:[{token:"paren.rparen",regex:"\\}",next:"pop"},{token:"comment",regex:"\\/\\*",push:"comment"},{token:"string",regex:'["](?:(?:\\\\.)|(?:[^"\\\\]))*?["]'},{token:"string",regex:"['](?:(?:\\\\.)|(?:[^'\\\\]))*?[']"},{token:["constant.numeric","keyword"],regex:"("+c+")(ch|cm|deg|em|ex|fr|gd|grad|Hz|in|kHz|mm|ms|pc|pt|px|rad|rem|s|turn|vh|vm|vw|%)"},{token:"constant.numeric",regex:c},{token:"constant.numeric",regex:"#[a-f0-9]{6}"},{token:"constant.numeric",regex:"#[a-f0-9]{3}"},{token:["punctuation","entity.other.attribute-name.pseudo-element.css"],regex:h},{token:["punctuation","entity.other.attribute-name.pseudo-class.css"],regex:p},{token:["support.function","string","support.function"],regex:"(url\\()(.*)(\\))"},{token:e,regex:"\\-?[a-zA-Z_][a-zA-Z0-9_\\-]*"},{caseInsensitive:!0}]},this.normalizeRules()};r.inherits(d,s),t.CssHighlightRules=d}),define("ace/mode/matching_brace_outdent",["require","exports","module","ace/range"],function(e,t,n){var r=e("../range").Range,i=function(){};(function(){this.checkOutdent=function(e,t){return/^\s+$/.test(e)?/^\s*\}/.test(t):!1},this.autoOutdent=function(e,t){var n=e.getLine(t),i=n.match(/^(\s*\})/);if(!i)return 0;var s=i[1].length,o=e.findMatchingBracket({row:t,column:s});if(!o||o.row==t)return 0;var u=this.$getIndent(e.getLine(o.row));e.replace(new r(t,0,t,s-1),u)},this.$getIndent=function(e){return e.match(/^\s*/)[0]}}).call(i.prototype),t.MatchingBraceOutdent=i}),define("ace/mode/behaviour/css",["require","exports","module","ace/lib/oop","ace/mode/behaviour","ace/mode/behaviour/cstyle","ace/token_iterator"],function(e,t,n){var r=e("../../lib/oop"),i=e("../behaviour").Behaviour,s=e("./cstyle").CstyleBehaviour,o=e("../../token_iterator").TokenIterator,u=function(){this.inherit(s),this.add("colon","insertion",function(e,t,n,r,i){if(i===":"){var s=n.getCursorPosition(),u=new o(r,s.row,s.column),a=u.getCurrentToken();a&&a.value.match(/\s+/)&&(a=u.stepBackward());if(a&&a.type==="support.type"){var f=r.doc.getLine(s.row),l=f.substring(s.column,s.column+1);if(l===":")return{text:"",selection:[1,1]};if(!f.substring(s.column).match(/^\s*;/))return{text:":;",selection:[1,1]}}}}),this.add("colon","deletion",function(e,t,n,r,i){var s=r.doc.getTextRange(i);if(!i.isMultiLine()&&s===":"){var u=n.getCursorPosition(),a=new o(r,u.row,u.column),f=a.getCurrentToken();f&&f.value.match(/\s+/)&&(f=a.stepBackward());if(f&&f.type==="support.type"){var l=r.doc.getLine(i.start.row),c=l.substring(i.end.column,i.end.column+1);if(c===";")return i.end.column++,i}}}),this.add("semicolon","insertion",function(e,t,n,r,i){if(i===";"){var s=n.getCursorPosition(),o=r.doc.getLine(s.row),u=o.substring(s.column,s.column+1);if(u===";")return{text:"",selection:[1,1]}}})};r.inherits(u,s),t.CssBehaviour=u}),define("ace/mode/behaviour/cstyle",["require","exports","module","ace/lib/oop","ace/mode/behaviour","ace/token_iterator","ace/lib/lang"],function(e,t,n){var r=e("../../lib/oop"),i=e("../behaviour").Behaviour,s=e("../../token_iterator").TokenIterator,o=e("../../lib/lang"),u=["text","paren.rparen","punctuation.operator"],a=["text","paren.rparen","punctuation.operator","comment"],f,l={},c=function(e){var t=-1;e.multiSelect&&(t=e.selection.id,l.rangeCount!=e.multiSelect.rangeCount&&(l={rangeCount:e.multiSelect.rangeCount}));if(l[t])return f=l[t];f=l[t]={autoInsertedBrackets:0,autoInsertedRow:-1,autoInsertedLineEnd:"",maybeInsertedBrackets:0,maybeInsertedRow:-1,maybeInsertedLineStart:"",maybeInsertedLineEnd:""}},h=function(){this.add("braces","insertion",function(e,t,n,r,i){var s=n.getCursorPosition(),u=r.doc.getLine(s.row);if(i=="{"){c(n);var a=n.getSelectionRange(),l=r.doc.getTextRange(a);if(l!==""&&l!=="{"&&n.getWrapBehavioursEnabled())return{text:"{"+l+"}",selection:!1};if(h.isSaneInsertion(n,r))return/[\]\}\)]/.test(u[s.column])||n.inMultiSelectMode?(h.recordAutoInsert(n,r,"}"),{text:"{}",selection:[1,1]}):(h.recordMaybeInsert(n,r,"{"),{text:"{",selection:[1,1]})}else if(i=="}"){c(n);var p=u.substring(s.column,s.column+1);if(p=="}"){var d=r.$findOpeningBracket("}",{column:s.column+1,row:s.row});if(d!==null&&h.isAutoInsertedClosing(s,u,i))return h.popAutoInsertedClosing(),{text:"",selection:[1,1]}}}else{if(i=="\n"||i=="\r\n"){c(n);var v="";h.isMaybeInsertedClosing(s,u)&&(v=o.stringRepeat("}",f.maybeInsertedBrackets),h.clearMaybeInsertedClosing());var p=u.substring(s.column,s.column+1);if(p==="}"){var m=r.findMatchingBracket({row:s.row,column:s.column+1},"}");if(!m)return null;var g=this.$getIndent(r.getLine(m.row))}else{if(!v){h.clearMaybeInsertedClosing();return}var g=this.$getIndent(u)}var y=g+r.getTabString();return{text:"\n"+y+"\n"+g+v,selection:[1,y.length,1,y.length]}}h.clearMaybeInsertedClosing()}}),this.add("braces","deletion",function(e,t,n,r,i){var s=r.doc.getTextRange(i);if(!i.isMultiLine()&&s=="{"){c(n);var o=r.doc.getLine(i.start.row),u=o.substring(i.end.column,i.end.column+1);if(u=="}")return i.end.column++,i;f.maybeInsertedBrackets--}}),this.add("parens","insertion",function(e,t,n,r,i){if(i=="("){c(n);var s=n.getSelectionRange(),o=r.doc.getTextRange(s);if(o!==""&&n.getWrapBehavioursEnabled())return{text:"("+o+")",selection:!1};if(h.isSaneInsertion(n,r))return h.recordAutoInsert(n,r,")"),{text:"()",selection:[1,1]}}else if(i==")"){c(n);var u=n.getCursorPosition(),a=r.doc.getLine(u.row),f=a.substring(u.column,u.column+1);if(f==")"){var l=r.$findOpeningBracket(")",{column:u.column+1,row:u.row});if(l!==null&&h.isAutoInsertedClosing(u,a,i))return h.popAutoInsertedClosing(),{text:"",selection:[1,1]}}}}),this.add("parens","deletion",function(e,t,n,r,i){var s=r.doc.getTextRange(i);if(!i.isMultiLine()&&s=="("){c(n);var o=r.doc.getLine(i.start.row),u=o.substring(i.start.column+1,i.start.column+2);if(u==")")return i.end.column++,i}}),this.add("brackets","insertion",function(e,t,n,r,i){if(i=="["){c(n);var s=n.getSelectionRange(),o=r.doc.getTextRange(s);if(o!==""&&n.getWrapBehavioursEnabled())return{text:"["+o+"]",selection:!1};if(h.isSaneInsertion(n,r))return h.recordAutoInsert(n,r,"]"),{text:"[]",selection:[1,1]}}else if(i=="]"){c(n);var u=n.getCursorPosition(),a=r.doc.getLine(u.row),f=a.substring(u.column,u.column+1);if(f=="]"){var l=r.$findOpeningBracket("]",{column:u.column+1,row:u.row});if(l!==null&&h.isAutoInsertedClosing(u,a,i))return h.popAutoInsertedClosing(),{text:"",selection:[1,1]}}}}),this.add("brackets","deletion",function(e,t,n,r,i){var s=r.doc.getTextRange(i);if(!i.isMultiLine()&&s=="["){c(n);var o=r.doc.getLine(i.start.row),u=o.substring(i.start.column+1,i.start.column+2);if(u=="]")return i.end.column++,i}}),this.add("string_dquotes","insertion",function(e,t,n,r,i){if(i=='"'||i=="'"){c(n);var s=i,o=n.getSelectionRange(),u=r.doc.getTextRange(o);if(u!==""&&u!=="'"&&u!='"'&&n.getWrapBehavioursEnabled())return{text:s+u+s,selection:!1};var a=n.getCursorPosition(),f=r.doc.getLine(a.row),l=f.substring(a.column-1,a.column);if(l=="\\")return null;var p=r.getTokens(o.start.row),d=0,v,m=-1;for(var g=0;g<p.length;g++){v=p[g],v.type=="string"?m=-1:m<0&&(m=v.value.indexOf(s));if(v.value.length+d>o.start.column)break;d+=p[g].value.length}if(!v||m<0&&v.type!=="comment"&&(v.type!=="string"||o.start.column!==v.value.length+d-1&&v.value.lastIndexOf(s)===v.value.length-1)){if(!h.isSaneInsertion(n,r))return;return{text:s+s,selection:[1,1]}}if(v&&v.type==="string"){var y=f.substring(a.column,a.column+1);if(y==s)return{text:"",selection:[1,1]}}}}),this.add("string_dquotes","deletion",function(e,t,n,r,i){var s=r.doc.getTextRange(i);if(!i.isMultiLine()&&(s=='"'||s=="'")){c(n);var o=r.doc.getLine(i.start.row),u=o.substring(i.start.column+1,i.start.column+2);if(u==s)return i.end.column++,i}})};h.isSaneInsertion=function(e,t){var n=e.getCursorPosition(),r=new s(t,n.row,n.column);if(!this.$matchTokenType(r.getCurrentToken()||"text",u)){var i=new s(t,n.row,n.column+1);if(!this.$matchTokenType(i.getCurrentToken()||"text",u))return!1}return r.stepForward(),r.getCurrentTokenRow()!==n.row||this.$matchTokenType(r.getCurrentToken()||"text",a)},h.$matchTokenType=function(e,t){return t.indexOf(e.type||e)>-1},h.recordAutoInsert=function(e,t,n){var r=e.getCursorPosition(),i=t.doc.getLine(r.row);this.isAutoInsertedClosing(r,i,f.autoInsertedLineEnd[0])||(f.autoInsertedBrackets=0),f.autoInsertedRow=r.row,f.autoInsertedLineEnd=n+i.substr(r.column),f.autoInsertedBrackets++},h.recordMaybeInsert=function(e,t,n){var r=e.getCursorPosition(),i=t.doc.getLine(r.row);this.isMaybeInsertedClosing(r,i)||(f.maybeInsertedBrackets=0),f.maybeInsertedRow=r.row,f.maybeInsertedLineStart=i.substr(0,r.column)+n,f.maybeInsertedLineEnd=i.substr(r.column),f.maybeInsertedBrackets++},h.isAutoInsertedClosing=function(e,t,n){return f.autoInsertedBrackets>0&&e.row===f.autoInsertedRow&&n===f.autoInsertedLineEnd[0]&&t.substr(e.column)===f.autoInsertedLineEnd},h.isMaybeInsertedClosing=function(e,t){return f.maybeInsertedBrackets>0&&e.row===f.maybeInsertedRow&&t.substr(e.column)===f.maybeInsertedLineEnd&&t.substr(0,e.column)==f.maybeInsertedLineStart},h.popAutoInsertedClosing=function(){f.autoInsertedLineEnd=f.autoInsertedLineEnd.substr(1),f.autoInsertedBrackets--},h.clearMaybeInsertedClosing=function(){f&&(f.maybeInsertedBrackets=0,f.maybeInsertedRow=-1)},r.inherits(h,i),t.CstyleBehaviour=h}),define("ace/mode/folding/cstyle",["require","exports","module","ace/lib/oop","ace/range","ace/mode/folding/fold_mode"],function(e,t,n){var r=e("../../lib/oop"),i=e("../../range").Range,s=e("./fold_mode").FoldMode,o=t.FoldMode=function(e){e&&(this.foldingStartMarker=new RegExp(this.foldingStartMarker.source.replace(/\|[^|]*?$/,"|"+e.start)),this.foldingStopMarker=new RegExp(this.foldingStopMarker.source.replace(/\|[^|]*?$/,"|"+e.end)))};r.inherits(o,s),function(){this.foldingStartMarker=/(\{|\[)[^\}\]]*$|^\s*(\/\*)/,this.foldingStopMarker=/^[^\[\{]*(\}|\])|^[\s\*]*(\*\/)/,this.getFoldWidgetRange=function(e,t,n,r){var i=e.getLine(n),s=i.match(this.foldingStartMarker);if(s){var o=s.index;if(s[1])return this.openingBracketBlock(e,s[1],n,o);var u=e.getCommentFoldRange(n,o+s[0].length,1);return u&&!u.isMultiLine()&&(r?u=this.getSectionRange(e,n):t!="all"&&(u=null)),u}if(t==="markbegin")return;var s=i.match(this.foldingStopMarker);if(s){var o=s.index+s[0].length;return s[1]?this.closingBracketBlock(e,s[1],n,o):e.getCommentFoldRange(n,o,-1)}},this.getSectionRange=function(e,t){var n=e.getLine(t),r=n.search(/\S/),s=t,o=n.length;t+=1;var u=t,a=e.getLength();while(++t<a){n=e.getLine(t);var f=n.search(/\S/);if(f===-1)continue;if(r>f)break;var l=this.getFoldWidgetRange(e,"all",t);if(l){if(l.start.row<=s)break;if(l.isMultiLine())t=l.end.row;else if(r==f)break}u=t}return new i(s,o,u,e.getLine(u).length)}}.call(o.prototype)});
\ No newline at end of file
--- /dev/null
+define("ace/theme/textmate",["require","exports","module","ace/lib/dom"],function(e,t,n){t.isDark=!1,t.cssClass="ace-tm",t.cssText='.ace-tm .ace_gutter {background: #f0f0f0;color: #333;}.ace-tm .ace_print-margin {width: 1px;background: #e8e8e8;}.ace-tm .ace_fold {background-color: #6B72E6;}.ace-tm {background-color: #FFFFFF;color: black;}.ace-tm .ace_cursor {color: black;}.ace-tm .ace_invisible {color: rgb(191, 191, 191);}.ace-tm .ace_storage,.ace-tm .ace_keyword {color: blue;}.ace-tm .ace_constant {color: rgb(197, 6, 11);}.ace-tm .ace_constant.ace_buildin {color: rgb(88, 72, 246);}.ace-tm .ace_constant.ace_language {color: rgb(88, 92, 246);}.ace-tm .ace_constant.ace_library {color: rgb(6, 150, 14);}.ace-tm .ace_invalid {background-color: rgba(255, 0, 0, 0.1);color: red;}.ace-tm .ace_support.ace_function {color: rgb(60, 76, 114);}.ace-tm .ace_support.ace_constant {color: rgb(6, 150, 14);}.ace-tm .ace_support.ace_type,.ace-tm .ace_support.ace_class {color: rgb(109, 121, 222);}.ace-tm .ace_keyword.ace_operator {color: rgb(104, 118, 135);}.ace-tm .ace_string {color: rgb(3, 106, 7);}.ace-tm .ace_comment {color: rgb(76, 136, 107);}.ace-tm .ace_comment.ace_doc {color: rgb(0, 102, 255);}.ace-tm .ace_comment.ace_doc.ace_tag {color: rgb(128, 159, 191);}.ace-tm .ace_constant.ace_numeric {color: rgb(0, 0, 205);}.ace-tm .ace_variable {color: rgb(49, 132, 149);}.ace-tm .ace_xml-pe {color: rgb(104, 104, 91);}.ace-tm .ace_entity.ace_name.ace_function {color: #0000A2;}.ace-tm .ace_heading {color: rgb(12, 7, 255);}.ace-tm .ace_list {color:rgb(185, 6, 144);}.ace-tm .ace_meta.ace_tag {color:rgb(0, 22, 142);}.ace-tm .ace_string.ace_regex {color: rgb(255, 0, 0)}.ace-tm .ace_marker-layer .ace_selection {background: rgb(181, 213, 255);}.ace-tm.ace_multiselect .ace_selection.ace_start {box-shadow: 0 0 3px 0px white;border-radius: 2px;}.ace-tm .ace_marker-layer .ace_step {background: rgb(252, 255, 0);}.ace-tm .ace_marker-layer .ace_stack {background: rgb(164, 229, 101);}.ace-tm .ace_marker-layer .ace_bracket {margin: -1px 0 0 -1px;border: 1px solid rgb(192, 192, 192);}.ace-tm .ace_marker-layer .ace_active-line {background: rgba(0, 0, 0, 0.07);}.ace-tm .ace_gutter-active-line {background-color : #dcdcdc;}.ace-tm .ace_marker-layer .ace_selected-word {background: rgb(250, 250, 255);border: 1px solid rgb(200, 200, 250);}.ace-tm .ace_indent-guide {background: url("data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAACCAYAAACZgbYnAAAAE0lEQVQImWP4////f4bLly//BwAmVgd1/w11/gAAAABJRU5ErkJggg==") right repeat-y;}';var r=e("../lib/dom");console.log(t),r.importCssString(t.cssText,t.cssClass)});
\ No newline at end of file
--- /dev/null
+"no use strict";(function(e){if(typeof e.window!="undefined"&&e.document)return;e.console=function(){var e=Array.prototype.slice.call(arguments,0);postMessage({type:"log",data:e})},e.console.error=e.console.warn=e.console.log=e.console.trace=e.console,e.window=e,e.ace=e,e.onerror=function(e,t,n,r,i){console.error("Worker "+(i?i.stack:e))},e.normalizeModule=function(t,n){if(n.indexOf("!")!==-1){var r=n.split("!");return e.normalizeModule(t,r[0])+"!"+e.normalizeModule(t,r[1])}if(n.charAt(0)=="."){var i=t.split("/").slice(0,-1).join("/");n=(i?i+"/":"")+n;while(n.indexOf(".")!==-1&&s!=n){var s=n;n=n.replace(/^\.\//,"").replace(/\/\.\//,"/").replace(/[^\/]+\/\.\.\//,"")}}return n},e.require=function(t,n){n||(n=t,t=null);if(!n.charAt)throw new Error("worker.js require() accepts only (parentId, id) as arguments");n=e.normalizeModule(t,n);var r=e.require.modules[n];if(r)return r.initialized||(r.initialized=!0,r.exports=r.factory().exports),r.exports;var i=n.split("/");if(!e.require.tlns)return console.log("unable to load "+n);i[0]=e.require.tlns[i[0]]||i[0];var s=i.join("/")+".js";return e.require.id=n,importScripts(s),e.require(t,n)},e.require.modules={},e.require.tlns={},e.define=function(t,n,r){arguments.length==2?(r=n,typeof t!="string"&&(n=t,t=e.require.id)):arguments.length==1&&(r=t,n=[],t=e.require.id),n.length||(n=["require","exports","module"]);if(t.indexOf("text!")===0)return;var i=function(n){return e.require(t,n)};e.require.modules[t]={exports:{},factory:function(){var e=this,t=r.apply(this,n.map(function(t){switch(t){case"require":return i;case"exports":return e.exports;case"module":return e;default:return i(t)}}));return t&&(e.exports=t),e}}},e.define.amd={},e.initBaseUrls=function(t){require.tlns=t},e.initSender=function(){var n=e.require("ace/lib/event_emitter").EventEmitter,r=e.require("ace/lib/oop"),i=function(){};return function(){r.implement(this,n),this.callback=function(e,t){postMessage({type:"call",id:t,data:e})},this.emit=function(e,t){postMessage({type:"event",name:e,data:t})}}.call(i.prototype),new i};var t=e.main=null,n=e.sender=null;e.onmessage=function(r){var i=r.data;if(i.command){if(!t[i.command])throw new Error("Unknown command:"+i.command);t[i.command].apply(t,i.args)}else if(i.init){initBaseUrls(i.tlns),require("ace/lib/es5-shim"),n=e.sender=initSender();var s=require(i.module)[i.classname];t=e.main=new s(n)}else i.event&&n&&n._signal(i.event,i.data)}})(this),define("ace/mode/css_worker",["require","exports","module","ace/lib/oop","ace/lib/lang","ace/worker/mirror","ace/mode/css/csslint"],function(e,t,n){var r=e("../lib/oop"),i=e("../lib/lang"),s=e("../worker/mirror").Mirror,o=e("./css/csslint").CSSLint,u=t.Worker=function(e){s.call(this,e),this.setTimeout(400),this.ruleset=null,this.setDisabledRules("ids"),this.setInfoRules("adjoining-classes|qualified-headings|zero-units|gradients|import|outline-none")};r.inherits(u,s),function(){this.setInfoRules=function(e){typeof e=="string"&&(e=e.split("|")),this.infoRules=i.arrayToMap(e),this.doc.getValue()&&this.deferredUpdate.schedule(100)},this.setDisabledRules=function(e){if(!e)this.ruleset=null;else{typeof e=="string"&&(e=e.split("|"));var t={};o.getRules().forEach(function(e){t[e.id]=!0}),e.forEach(function(e){delete t[e]}),this.ruleset=t}this.doc.getValue()&&this.deferredUpdate.schedule(100)},this.onUpdate=function(){var e=this.doc.getValue(),t=this.infoRules,n=o.verify(e,this.ruleset);this.sender.emit("csslint",n.messages.map(function(e){return{row:e.line-1,column:e.col-1,text:e.message,type:t[e.rule.id]?"info":e.type,rule:e.rule.name}}))}}.call(u.prototype)}),define("ace/lib/oop",["require","exports","module"],function(e,t,n){t.inherits=function(e,t){e.super_=t,e.prototype=Object.create(t.prototype,{constructor:{value:e,enumerable:!1,writable:!0,configurable:!0}})},t.mixin=function(e,t){for(var n in t)e[n]=t[n];return e},t.implement=function(e,n){t.mixin(e,n)}}),define("ace/lib/lang",["require","exports","module"],function(e,t,n){t.last=function(e){return e[e.length-1]},t.stringReverse=function(e){return e.split("").reverse().join("")},t.stringRepeat=function(e,t){var n="";while(t>0){t&1&&(n+=e);if(t>>=1)e+=e}return n};var r=/^\s\s*/,i=/\s\s*$/;t.stringTrimLeft=function(e){return e.replace(r,"")},t.stringTrimRight=function(e){return e.replace(i,"")},t.copyObject=function(e){var t={};for(var n in e)t[n]=e[n];return t},t.copyArray=function(e){var t=[];for(var n=0,r=e.length;n<r;n++)e[n]&&typeof e[n]=="object"?t[n]=this.copyObject(e[n]):t[n]=e[n];return t},t.deepCopy=function(e){if(typeof e!="object"||!e)return e;var n=e.constructor;if(n===RegExp)return e;var r=n();for(var i in e)typeof e[i]=="object"?r[i]=t.deepCopy(e[i]):r[i]=e[i];return r},t.arrayToMap=function(e){var t={};for(var n=0;n<e.length;n++)t[e[n]]=1;return t},t.createMap=function(e){var t=Object.create(null);for(var n in e)t[n]=e[n];return t},t.arrayRemove=function(e,t){for(var n=0;n<=e.length;n++)t===e[n]&&e.splice(n,1)},t.escapeRegExp=function(e){return e.replace(/([.*+?^${}()|[\]\/\\])/g,"\\$1")},t.escapeHTML=function(e){return e.replace(/&/g,"&").replace(/"/g,""").replace(/'/g,"'").replace(/</g,"<")},t.getMatchOffsets=function(e,t){var n=[];return e.replace(t,function(e){n.push({offset:arguments[arguments.length-2],length:e.length})}),n},t.deferredCall=function(e){var t=null,n=function(){t=null,e()},r=function(e){return r.cancel(),t=setTimeout(n,e||0),r};return r.schedule=r,r.call=function(){return this.cancel(),e(),r},r.cancel=function(){return clearTimeout(t),t=null,r},r.isPending=function(){return t},r},t.delayedCall=function(e,t){var n=null,r=function(){n=null,e()},i=function(e){n==null&&(n=setTimeout(r,e||t))};return i.delay=function(e){n&&clearTimeout(n),n=setTimeout(r,e||t)},i.schedule=i,i.call=function(){this.cancel(),e()},i.cancel=function(){n&&clearTimeout(n),n=null},i.isPending=function(){return n},i}}),define("ace/lib/es5-shim",["require","exports","module"],function(e,t,n){function r(){}function w(e){try{return Object.defineProperty(e,"sentinel",{}),"sentinel"in e}catch(t){}}function H(e){return e=+e,e!==e?e=0:e!==0&&e!==1/0&&e!==-1/0&&(e=(e>0||-1)*Math.floor(Math.abs(e))),e}function B(e){var t=typeof e;return e===null||t==="undefined"||t==="boolean"||t==="number"||t==="string"}function j(e){var t,n,r;if(B(e))return e;n=e.valueOf;if(typeof n=="function"){t=n.call(e);if(B(t))return t}r=e.toString;if(typeof r=="function"){t=r.call(e);if(B(t))return t}throw new TypeError}Function.prototype.bind||(Function.prototype.bind=function(t){var n=this;if(typeof n!="function")throw new TypeError("Function.prototype.bind called on incompatible "+n);var i=u.call(arguments,1),s=function(){if(this instanceof s){var e=n.apply(this,i.concat(u.call(arguments)));return Object(e)===e?e:this}return n.apply(t,i.concat(u.call(arguments)))};return n.prototype&&(r.prototype=n.prototype,s.prototype=new r,r.prototype=null),s});var i=Function.prototype.call,s=Array.prototype,o=Object.prototype,u=s.slice,a=i.bind(o.toString),f=i.bind(o.hasOwnProperty),l,c,h,p,d;if(d=f(o,"__defineGetter__"))l=i.bind(o.__defineGetter__),c=i.bind(o.__defineSetter__),h=i.bind(o.__lookupGetter__),p=i.bind(o.__lookupSetter__);if([1,2].splice(0).length!=2)if(!function(){function e(e){var t=new Array(e+2);return t[0]=t[1]=0,t}var t=[],n;t.splice.apply(t,e(20)),t.splice.apply(t,e(26)),n=t.length,t.splice(5,0,"XXX"),n+1==t.length;if(n+1==t.length)return!0}())Array.prototype.splice=function(e,t){var n=this.length;e>0?e>n&&(e=n):e==void 0?e=0:e<0&&(e=Math.max(n+e,0)),e+t<n||(t=n-e);var r=this.slice(e,e+t),i=u.call(arguments,2),s=i.length;if(e===n)s&&this.push.apply(this,i);else{var o=Math.min(t,n-e),a=e+o,f=a+s-o,l=n-a,c=n-o;if(f<a)for(var h=0;h<l;++h)this[f+h]=this[a+h];else if(f>a)for(h=l;h--;)this[f+h]=this[a+h];if(s&&e===c)this.length=c,this.push.apply(this,i);else{this.length=c+s;for(h=0;h<s;++h)this[e+h]=i[h]}}return r};else{var v=Array.prototype.splice;Array.prototype.splice=function(e,t){return arguments.length?v.apply(this,[e===void 0?0:e,t===void 0?this.length-e:t].concat(u.call(arguments,2))):[]}}Array.isArray||(Array.isArray=function(t){return a(t)=="[object Array]"});var m=Object("a"),g=m[0]!="a"||!(0 in m);Array.prototype.forEach||(Array.prototype.forEach=function(t){var n=F(this),r=g&&a(this)=="[object String]"?this.split(""):n,i=arguments[1],s=-1,o=r.length>>>0;if(a(t)!="[object Function]")throw new TypeError;while(++s<o)s in r&&t.call(i,r[s],s,n)}),Array.prototype.map||(Array.prototype.map=function(t){var n=F(this),r=g&&a(this)=="[object String]"?this.split(""):n,i=r.length>>>0,s=Array(i),o=arguments[1];if(a(t)!="[object Function]")throw new TypeError(t+" is not a function");for(var u=0;u<i;u++)u in r&&(s[u]=t.call(o,r[u],u,n));return s}),Array.prototype.filter||(Array.prototype.filter=function(t){var n=F(this),r=g&&a(this)=="[object String]"?this.split(""):n,i=r.length>>>0,s=[],o,u=arguments[1];if(a(t)!="[object Function]")throw new TypeError(t+" is not a function");for(var f=0;f<i;f++)f in r&&(o=r[f],t.call(u,o,f,n)&&s.push(o));return s}),Array.prototype.every||(Array.prototype.every=function(t){var n=F(this),r=g&&a(this)=="[object String]"?this.split(""):n,i=r.length>>>0,s=arguments[1];if(a(t)!="[object Function]")throw new TypeError(t+" is not a function");for(var o=0;o<i;o++)if(o in r&&!t.call(s,r[o],o,n))return!1;return!0}),Array.prototype.some||(Array.prototype.some=function(t){var n=F(this),r=g&&a(this)=="[object String]"?this.split(""):n,i=r.length>>>0,s=arguments[1];if(a(t)!="[object Function]")throw new TypeError(t+" is not a function");for(var o=0;o<i;o++)if(o in r&&t.call(s,r[o],o,n))return!0;return!1}),Array.prototype.reduce||(Array.prototype.reduce=function(t){var n=F(this),r=g&&a(this)=="[object String]"?this.split(""):n,i=r.length>>>0;if(a(t)!="[object Function]")throw new TypeError(t+" is not a function");if(!i&&arguments.length==1)throw new TypeError("reduce of empty array with no initial value");var s=0,o;if(arguments.length>=2)o=arguments[1];else do{if(s in r){o=r[s++];break}if(++s>=i)throw new TypeError("reduce of empty array with no initial value")}while(!0);for(;s<i;s++)s in r&&(o=t.call(void 0,o,r[s],s,n));return o}),Array.prototype.reduceRight||(Array.prototype.reduceRight=function(t){var n=F(this),r=g&&a(this)=="[object String]"?this.split(""):n,i=r.length>>>0;if(a(t)!="[object Function]")throw new TypeError(t+" is not a function");if(!i&&arguments.length==1)throw new TypeError("reduceRight of empty array with no initial value");var s,o=i-1;if(arguments.length>=2)s=arguments[1];else do{if(o in r){s=r[o--];break}if(--o<0)throw new TypeError("reduceRight of empty array with no initial value")}while(!0);do o in this&&(s=t.call(void 0,s,r[o],o,n));while(o--);return s});if(!Array.prototype.indexOf||[0,1].indexOf(1,2)!=-1)Array.prototype.indexOf=function(t){var n=g&&a(this)=="[object String]"?this.split(""):F(this),r=n.length>>>0;if(!r)return-1;var i=0;arguments.length>1&&(i=H(arguments[1])),i=i>=0?i:Math.max(0,r+i);for(;i<r;i++)if(i in n&&n[i]===t)return i;return-1};if(!Array.prototype.lastIndexOf||[0,1].lastIndexOf(0,-3)!=-1)Array.prototype.lastIndexOf=function(t){var n=g&&a(this)=="[object String]"?this.split(""):F(this),r=n.length>>>0;if(!r)return-1;var i=r-1;arguments.length>1&&(i=Math.min(i,H(arguments[1]))),i=i>=0?i:r-Math.abs(i);for(;i>=0;i--)if(i in n&&t===n[i])return i;return-1};Object.getPrototypeOf||(Object.getPrototypeOf=function(t){return t.__proto__||(t.constructor?t.constructor.prototype:o)});if(!Object.getOwnPropertyDescriptor){var y="Object.getOwnPropertyDescriptor called on a non-object: ";Object.getOwnPropertyDescriptor=function(t,n){if(typeof t!="object"&&typeof t!="function"||t===null)throw new TypeError(y+t);if(!f(t,n))return;var r,i,s;r={enumerable:!0,configurable:!0};if(d){var u=t.__proto__;t.__proto__=o;var i=h(t,n),s=p(t,n);t.__proto__=u;if(i||s)return i&&(r.get=i),s&&(r.set=s),r}return r.value=t[n],r}}Object.getOwnPropertyNames||(Object.getOwnPropertyNames=function(t){return Object.keys(t)});if(!Object.create){var b;Object.prototype.__proto__===null?b=function(){return{__proto__:null}}:b=function(){var e={};for(var t in e)e[t]=null;return e.constructor=e.hasOwnProperty=e.propertyIsEnumerable=e.isPrototypeOf=e.toLocaleString=e.toString=e.valueOf=e.__proto__=null,e},Object.create=function(t,n){var r;if(t===null)r=b();else{if(typeof t!="object")throw new TypeError("typeof prototype["+typeof t+"] != 'object'");var i=function(){};i.prototype=t,r=new i,r.__proto__=t}return n!==void 0&&Object.defineProperties(r,n),r}}if(Object.defineProperty){var E=w({}),S=typeof document=="undefined"||w(document.createElement("div"));if(!E||!S)var x=Object.defineProperty}if(!Object.defineProperty||x){var T="Property description must be an object: ",N="Object.defineProperty called on non-object: ",C="getters & setters can not be defined on this javascript engine";Object.defineProperty=function(t,n,r){if(typeof t!="object"&&typeof t!="function"||t===null)throw new TypeError(N+t);if(typeof r!="object"&&typeof r!="function"||r===null)throw new TypeError(T+r);if(x)try{return x.call(Object,t,n,r)}catch(i){}if(f(r,"value"))if(d&&(h(t,n)||p(t,n))){var s=t.__proto__;t.__proto__=o,delete t[n],t[n]=r.value,t.__proto__=s}else t[n]=r.value;else{if(!d)throw new TypeError(C);f(r,"get")&&l(t,n,r.get),f(r,"set")&&c(t,n,r.set)}return t}}Object.defineProperties||(Object.defineProperties=function(t,n){for(var r in n)f(n,r)&&Object.defineProperty(t,r,n[r]);return t}),Object.seal||(Object.seal=function(t){return t}),Object.freeze||(Object.freeze=function(t){return t});try{Object.freeze(function(){})}catch(k){Object.freeze=function(t){return function(n){return typeof n=="function"?n:t(n)}}(Object.freeze)}Object.preventExtensions||(Object.preventExtensions=function(t){return t}),Object.isSealed||(Object.isSealed=function(t){return!1}),Object.isFrozen||(Object.isFrozen=function(t){return!1}),Object.isExtensible||(Object.isExtensible=function(t){if(Object(t)===t)throw new TypeError;var n="";while(f(t,n))n+="?";t[n]=!0;var r=f(t,n);return delete t[n],r});if(!Object.keys){var L=!0,A=["toString","toLocaleString","valueOf","hasOwnProperty","isPrototypeOf","propertyIsEnumerable","constructor"],O=A.length;for(var M in{toString:null})L=!1;Object.keys=function I(e){if(typeof e!="object"&&typeof e!="function"||e===null)throw new TypeError("Object.keys called on a non-object");var I=[];for(var t in e)f(e,t)&&I.push(t);if(L)for(var n=0,r=O;n<r;n++){var i=A[n];f(e,i)&&I.push(i)}return I}}Date.now||(Date.now=function(){return(new Date).getTime()});var _=" \n\v\f\r \u2028\u2029";if(!String.prototype.trim||_.trim()){_="["+_+"]";var D=new RegExp("^"+_+_+"*"),P=new RegExp(_+_+"*$");String.prototype.trim=function(){return String(this).replace(D,"").replace(P,"")}}var F=function(e){if(e==null)throw new TypeError("can't convert "+e+" to object");return Object(e)}}),define("ace/document",["require","exports","module","ace/lib/oop","ace/lib/event_emitter","ace/range","ace/anchor"],function(e,t,n){var r=e("./lib/oop"),i=e("./lib/event_emitter").EventEmitter,s=e("./range").Range,o=e("./anchor").Anchor,u=function(e){this.$lines=[],e.length===0?this.$lines=[""]:Array.isArray(e)?this._insertLines(0,e):this.insert({row:0,column:0},e)};(function(){r.implement(this,i),this.setValue=function(e){var t=this.getLength();this.remove(new s(0,0,t,this.getLine(t-1).length)),this.insert({row:0,column:0},e)},this.getValue=function(){return this.getAllLines().join(this.getNewLineCharacter())},this.createAnchor=function(e,t){return new o(this,e,t)},"aaa".split(/a/).length===0?this.$split=function(e){return e.replace(/\r\n|\r/g,"\n").split("\n")}:this.$split=function(e){return e.split(/\r\n|\r|\n/)},this.$detectNewLine=function(e){var t=e.match(/^.*?(\r\n|\r|\n)/m);this.$autoNewLine=t?t[1]:"\n",this._signal("changeNewLineMode")},this.getNewLineCharacter=function(){switch(this.$newLineMode){case"windows":return"\r\n";case"unix":return"\n";default:return this.$autoNewLine||"\n"}},this.$autoNewLine="",this.$newLineMode="auto",this.setNewLineMode=function(e){if(this.$newLineMode===e)return;this.$newLineMode=e,this._signal("changeNewLineMode")},this.getNewLineMode=function(){return this.$newLineMode},this.isNewLine=function(e){return e=="\r\n"||e=="\r"||e=="\n"},this.getLine=function(e){return this.$lines[e]||""},this.getLines=function(e,t){return this.$lines.slice(e,t+1)},this.getAllLines=function(){return this.getLines(0,this.getLength())},this.getLength=function(){return this.$lines.length},this.getTextRange=function(e){if(e.start.row==e.end.row)return this.getLine(e.start.row).substring(e.start.column,e.end.column);var t=this.getLines(e.start.row,e.end.row);t[0]=(t[0]||"").substring(e.start.column);var n=t.length-1;return e.end.row-e.start.row==n&&(t[n]=t[n].substring(0,e.end.column)),t.join(this.getNewLineCharacter())},this.$clipPosition=function(e){var t=this.getLength();return e.row>=t?(e.row=Math.max(0,t-1),e.column=this.getLine(t-1).length):e.row<0&&(e.row=0),e},this.insert=function(e,t){if(!t||t.length===0)return e;e=this.$clipPosition(e),this.getLength()<=1&&this.$detectNewLine(t);var n=this.$split(t),r=n.splice(0,1)[0],i=n.length==0?null:n.splice(n.length-1,1)[0];return e=this.insertInLine(e,r),i!==null&&(e=this.insertNewLine(e),e=this._insertLines(e.row,n),e=this.insertInLine(e,i||"")),e},this.insertLines=function(e,t){return e>=this.getLength()?this.insert({row:e,column:0},"\n"+t.join("\n")):this._insertLines(Math.max(e,0),t)},this._insertLines=function(e,t){if(t.length==0)return{row:e,column:0};while(t.length>61440){var n=this._insertLines(e,t.slice(0,61440));t=t.slice(61440),e=n.row}var r=[e,0];r.push.apply(r,t),this.$lines.splice.apply(this.$lines,r);var i=new s(e,0,e+t.length,0),o={action:"insertLines",range:i,lines:t};return this._signal("change",{data:o}),i.end},this.insertNewLine=function(e){e=this.$clipPosition(e);var t=this.$lines[e.row]||"";this.$lines[e.row]=t.substring(0,e.column),this.$lines.splice(e.row+1,0,t.substring(e.column,t.length));var n={row:e.row+1,column:0},r={action:"insertText",range:s.fromPoints(e,n),text:this.getNewLineCharacter()};return this._signal("change",{data:r}),n},this.insertInLine=function(e,t){if(t.length==0)return e;var n=this.$lines[e.row]||"";this.$lines[e.row]=n.substring(0,e.column)+t+n.substring(e.column);var r={row:e.row,column:e.column+t.length},i={action:"insertText",range:s.fromPoints(e,r),text:t};return this._signal("change",{data:i}),r},this.remove=function(e){e instanceof s||(e=s.fromPoints(e.start,e.end)),e.start=this.$clipPosition(e.start),e.end=this.$clipPosition(e.end);if(e.isEmpty())return e.start;var t=e.start.row,n=e.end.row;if(e.isMultiLine()){var r=e.start.column==0?t:t+1,i=n-1;e.end.column>0&&this.removeInLine(n,0,e.end.column),i>=r&&this._removeLines(r,i),r!=t&&(this.removeInLine(t,e.start.column,this.getLine(t).length),this.removeNewLine(e.start.row))}else this.removeInLine(t,e.start.column,e.end.column);return e.start},this.removeInLine=function(e,t,n){if(t==n)return;var r=new s(e,t,e,n),i=this.getLine(e),o=i.substring(t,n),u=i.substring(0,t)+i.substring(n,i.length);this.$lines.splice(e,1,u);var a={action:"removeText",range:r,text:o};return this._signal("change",{data:a}),r.start},this.removeLines=function(e,t){return e<0||t>=this.getLength()?this.remove(new s(e,0,t+1,0)):this._removeLines(e,t)},this._removeLines=function(e,t){var n=new s(e,0,t+1,0),r=this.$lines.splice(e,t-e+1),i={action:"removeLines",range:n,nl:this.getNewLineCharacter(),lines:r};return this._signal("change",{data:i}),r},this.removeNewLine=function(e){var t=this.getLine(e),n=this.getLine(e+1),r=new s(e,t.length,e+1,0),i=t+n;this.$lines.splice(e,2,i);var o={action:"removeText",range:r,text:this.getNewLineCharacter()};this._signal("change",{data:o})},this.replace=function(e,t){e instanceof s||(e=s.fromPoints(e.start,e.end));if(t.length==0&&e.isEmpty())return e.start;if(t==this.getTextRange(e))return e.end;this.remove(e);if(t)var n=this.insert(e.start,t);else n=e.start;return n},this.applyDeltas=function(e){for(var t=0;t<e.length;t++){var n=e[t],r=s.fromPoints(n.range.start,n.range.end);n.action=="insertLines"?this.insertLines(r.start.row,n.lines):n.action=="insertText"?this.insert(r.start,n.text):n.action=="removeLines"?this._removeLines(r.start.row,r.end.row-1):n.action=="removeText"&&this.remove(r)}},this.revertDeltas=function(e){for(var t=e.length-1;t>=0;t--){var n=e[t],r=s.fromPoints(n.range.start,n.range.end);n.action=="insertLines"?this._removeLines(r.start.row,r.end.row-1):n.action=="insertText"?this.remove(r):n.action=="removeLines"?this._insertLines(r.start.row,n.lines):n.action=="removeText"&&this.insert(r.start,n.text)}},this.indexToPosition=function(e,t){var n=this.$lines||this.getAllLines(),r=this.getNewLineCharacter().length;for(var i=t||0,s=n.length;i<s;i++){e-=n[i].length+r;if(e<0)return{row:i,column:e+n[i].length+r}}return{row:s-1,column:n[s-1].length}},this.positionToIndex=function(e,t){var n=this.$lines||this.getAllLines(),r=this.getNewLineCharacter().length,i=0,s=Math.min(e.row,n.length);for(var o=t||0;o<s;++o)i+=n[o].length+r;return i+e.column}}).call(u.prototype),t.Document=u}),define("ace/lib/event_emitter",["require","exports","module"],function(e,t,n){var r={},i=function(){this.propagationStopped=!0},s=function(){this.defaultPrevented=!0};r._emit=r._dispatchEvent=function(e,t){this._eventRegistry||(this._eventRegistry={}),this._defaultHandlers||(this._defaultHandlers={});var n=this._eventRegistry[e]||[],r=this._defaultHandlers[e];if(!n.length&&!r)return;if(typeof t!="object"||!t)t={};t.type||(t.type=e),t.stopPropagation||(t.stopPropagation=i),t.preventDefault||(t.preventDefault=s),n=n.slice();for(var o=0;o<n.length;o++){n[o](t,this);if(t.propagationStopped)break}if(r&&!t.defaultPrevented)return r(t,this)},r._signal=function(e,t){var n=(this._eventRegistry||{})[e];if(!n)return;n=n.slice();for(var r=0;r<n.length;r++)n[r](t,this)},r.once=function(e,t){var n=this;t&&this.addEventListener(e,function r(){n.removeEventListener(e,r),t.apply(null,arguments)})},r.setDefaultHandler=function(e,t){var n=this._defaultHandlers;n||(n=this._defaultHandlers={_disabled_:{}});if(n[e]){var r=n[e],i=n._disabled_[e];i||(n._disabled_[e]=i=[]),i.push(r);var s=i.indexOf(t);s!=-1&&i.splice(s,1)}n[e]=t},r.removeDefaultHandler=function(e,t){var n=this._defaultHandlers;if(!n)return;var r=n._disabled_[e];if(n[e]==t){var i=n[e];r&&this.setDefaultHandler(e,r.pop())}else if(r){var s=r.indexOf(t);s!=-1&&r.splice(s,1)}},r.on=r.addEventListener=function(e,t,n){this._eventRegistry=this._eventRegistry||{};var r=this._eventRegistry[e];return r||(r=this._eventRegistry[e]=[]),r.indexOf(t)==-1&&r[n?"unshift":"push"](t),t},r.off=r.removeListener=r.removeEventListener=function(e,t){this._eventRegistry=this._eventRegistry||{};var n=this._eventRegistry[e];if(!n)return;var r=n.indexOf(t);r!==-1&&n.splice(r,1)},r.removeAllListeners=function(e){this._eventRegistry&&(this._eventRegistry[e]=[])},t.EventEmitter=r}),define("ace/range",["require","exports","module"],function(e,t,n){var r=function(e,t){return e.row-t.row||e.column-t.column},i=function(e,t,n,r){this.start={row:e,column:t},this.end={row:n,column:r}};(function(){this.isEqual=function(e){return this.start.row===e.start.row&&this.end.row===e.end.row&&this.start.column===e.start.column&&this.end.column===e.end.column},this.toString=function(){return"Range: ["+this.start.row+"/"+this.start.column+"] -> ["+this.end.row+"/"+this.end.column+"]"},this.contains=function(e,t){return this.compare(e,t)==0},this.compareRange=function(e){var t,n=e.end,r=e.start;return t=this.compare(n.row,n.column),t==1?(t=this.compare(r.row,r.column),t==1?2:t==0?1:0):t==-1?-2:(t=this.compare(r.row,r.column),t==-1?-1:t==1?42:0)},this.comparePoint=function(e){return this.compare(e.row,e.column)},this.containsRange=function(e){return this.comparePoint(e.start)==0&&this.comparePoint(e.end)==0},this.intersects=function(e){var t=this.compareRange(e);return t==-1||t==0||t==1},this.isEnd=function(e,t){return this.end.row==e&&this.end.column==t},this.isStart=function(e,t){return this.start.row==e&&this.start.column==t},this.setStart=function(e,t){typeof e=="object"?(this.start.column=e.column,this.start.row=e.row):(this.start.row=e,this.start.column=t)},this.setEnd=function(e,t){typeof e=="object"?(this.end.column=e.column,this.end.row=e.row):(this.end.row=e,this.end.column=t)},this.inside=function(e,t){return this.compare(e,t)==0?this.isEnd(e,t)||this.isStart(e,t)?!1:!0:!1},this.insideStart=function(e,t){return this.compare(e,t)==0?this.isEnd(e,t)?!1:!0:!1},this.insideEnd=function(e,t){return this.compare(e,t)==0?this.isStart(e,t)?!1:!0:!1},this.compare=function(e,t){return!this.isMultiLine()&&e===this.start.row?t<this.start.column?-1:t>this.end.column?1:0:e<this.start.row?-1:e>this.end.row?1:this.start.row===e?t>=this.start.column?0:-1:this.end.row===e?t<=this.end.column?0:1:0},this.compareStart=function(e,t){return this.start.row==e&&this.start.column==t?-1:this.compare(e,t)},this.compareEnd=function(e,t){return this.end.row==e&&this.end.column==t?1:this.compare(e,t)},this.compareInside=function(e,t){return this.end.row==e&&this.end.column==t?1:this.start.row==e&&this.start.column==t?-1:this.compare(e,t)},this.clipRows=function(e,t){if(this.end.row>t)var n={row:t+1,column:0};else if(this.end.row<e)var n={row:e,column:0};if(this.start.row>t)var r={row:t+1,column:0};else if(this.start.row<e)var r={row:e,column:0};return i.fromPoints(r||this.start,n||this.end)},this.extend=function(e,t){var n=this.compare(e,t);if(n==0)return this;if(n==-1)var r={row:e,column:t};else var s={row:e,column:t};return i.fromPoints(r||this.start,s||this.end)},this.isEmpty=function(){return this.start.row===this.end.row&&this.start.column===this.end.column},this.isMultiLine=function(){return this.start.row!==this.end.row},this.clone=function(){return i.fromPoints(this.start,this.end)},this.collapseRows=function(){return this.end.column==0?new i(this.start.row,0,Math.max(this.start.row,this.end.row-1),0):new i(this.start.row,0,this.end.row,0)},this.toScreenRange=function(e){var t=e.documentToScreenPosition(this.start),n=e.documentToScreenPosition(this.end);return new i(t.row,t.column,n.row,n.column)},this.moveBy=function(e,t){this.start.row+=e,this.start.column+=t,this.end.row+=e,this.end.column+=t}}).call(i.prototype),i.fromPoints=function(e,t){return new i(e.row,e.column,t.row,t.column)},i.comparePoints=r,i.comparePoints=function(e,t){return e.row-t.row||e.column-t.column},t.Range=i}),define("ace/anchor",["require","exports","module","ace/lib/oop","ace/lib/event_emitter"],function(e,t,n){var r=e("./lib/oop"),i=e("./lib/event_emitter").EventEmitter,s=t.Anchor=function(e,t,n){this.$onChange=this.onChange.bind(this),this.attach(e),typeof n=="undefined"?this.setPosition(t.row,t.column):this.setPosition(t,n)};(function(){r.implement(this,i),this.getPosition=function(){return this.$clipPositionToDocument(this.row,this.column)},this.getDocument=function(){return this.document},this.$insertRight=!1,this.onChange=function(e){var t=e.data,n=t.range;if(n.start.row==n.end.row&&n.start.row!=this.row)return;if(n.start.row>this.row)return;if(n.start.row==this.row&&n.start.column>this.column)return;var r=this.row,i=this.column,s=n.start,o=n.end;if(t.action==="insertText")if(s.row===r&&s.column<=i){if(s.column!==i||!this.$insertRight)s.row===o.row?i+=o.column-s.column:(i-=s.column,r+=o.row-s.row)}else s.row!==o.row&&s.row<r&&(r+=o.row-s.row);else t.action==="insertLines"?s.row<=r&&(r+=o.row-s.row):t.action==="removeText"?s.row===r&&s.column<i?o.column>=i?i=s.column:i=Math.max(0,i-(o.column-s.column)):s.row!==o.row&&s.row<r?(o.row===r&&(i=Math.max(0,i-o.column)+s.column),r-=o.row-s.row):o.row===r&&(r-=o.row-s.row,i=Math.max(0,i-o.column)+s.column):t.action=="removeLines"&&s.row<=r&&(o.row<=r?r-=o.row-s.row:(r=s.row,i=0));this.setPosition(r,i,!0)},this.setPosition=function(e,t,n){var r;n?r={row:e,column:t}:r=this.$clipPositionToDocument(e,t);if(this.row==r.row&&this.column==r.column)return;var i={row:this.row,column:this.column};this.row=r.row,this.column=r.column,this._signal("change",{old:i,value:r})},this.detach=function(){this.document.removeEventListener("change",this.$onChange)},this.attach=function(e){this.document=e||this.document,this.document.on("change",this.$onChange)},this.$clipPositionToDocument=function(e,t){var n={};return e>=this.document.getLength()?(n.row=Math.max(0,this.document.getLength()-1),n.column=this.document.getLine(n.row).length):e<0?(n.row=0,n.column=0):(n.row=e,n.column=Math.min(this.document.getLine(n.row).length,Math.max(0,t))),t<0&&(n.column=0),n}}).call(s.prototype)}),define("ace/mode/css/csslint",["require","exports","module"],function(require,exports,module){function Reporter(e,t){this.messages=[],this.stats=[],this.lines=e,this.ruleset=t}var parserlib={};(function(){function e(){this._listeners={}}function t(e){this._input=e.replace(/\n\r?/g,"\n"),this._line=1,this._col=1,this._cursor=0}function n(e,t,n){this.col=n,this.line=t,this.message=e}function r(e,t,n,r){this.col=n,this.line=t,this.text=e,this.type=r}function i(e,n){this._reader=e?new t(e.toString()):null,this._token=null,this._tokenData=n,this._lt=[],this._ltIndex=0,this._ltIndexCache=[]}e.prototype={constructor:e,addListener:function(e,t){this._listeners[e]||(this._listeners[e]=[]),this._listeners[e].push(t)},fire:function(e){typeof e=="string"&&(e={type:e}),typeof e.target!="undefined"&&(e.target=this);if(typeof e.type=="undefined")throw new Error("Event object missing 'type' property.");if(this._listeners[e.type]){var t=this._listeners[e.type].concat();for(var n=0,r=t.length;n<r;n++)t[n].call(this,e)}},removeListener:function(e,t){if(this._listeners[e]){var n=this._listeners[e];for(var r=0,i=n.length;r<i;r++)if(n[r]===t){n.splice(r,1);break}}}},t.prototype={constructor:t,getCol:function(){return this._col},getLine:function(){return this._line},eof:function(){return this._cursor==this._input.length},peek:function(e){var t=null;return e=typeof e=="undefined"?1:e,this._cursor<this._input.length&&(t=this._input.charAt(this._cursor+e-1)),t},read:function(){var e=null;return this._cursor<this._input.length&&(this._input.charAt(this._cursor)=="\n"?(this._line++,this._col=1):this._col++,e=this._input.charAt(this._cursor++)),e},mark:function(){this._bookmark={cursor:this._cursor,line:this._line,col:this._col}},reset:function(){this._bookmark&&(this._cursor=this._bookmark.cursor,this._line=this._bookmark.line,this._col=this._bookmark.col,delete this._bookmark)},readTo:function(e){var t="",n;while(t.length<e.length||t.lastIndexOf(e)!=t.length-e.length){n=this.read();if(!n)throw new Error('Expected "'+e+'" at line '+this._line+", col "+this._col+".");t+=n}return t},readWhile:function(e){var t="",n=this.read();while(n!==null&&e(n))t+=n,n=this.read();return t},readMatch:function(e){var t=this._input.substring(this._cursor),n=null;return typeof e=="string"?t.indexOf(e)===0&&(n=this.readCount(e.length)):e instanceof RegExp&&e.test(t)&&(n=this.readCount(RegExp.lastMatch.length)),n},readCount:function(e){var t="";while(e--)t+=this.read();return t}},n.prototype=new Error,r.fromToken=function(e){return new r(e.value,e.startLine,e.startCol)},r.prototype={constructor:r,valueOf:function(){return this.toString()},toString:function(){return this.text}},i.createTokenData=function(e){var t=[],n={},r=e.concat([]),i=0,s=r.length+1;r.UNKNOWN=-1,r.unshift({name:"EOF"});for(;i<s;i++)t.push(r[i].name),r[r[i].name]=i,r[i].text&&(n[r[i].text]=i);return r.name=function(e){return t[e]},r.type=function(e){return n[e]},r},i.prototype={constructor:i,match:function(e,t){e instanceof Array||(e=[e]);var n=this.get(t),r=0,i=e.length;while(r<i)if(n==e[r++])return!0;return this.unget(),!1},mustMatch:function(e,t){var r;e instanceof Array||(e=[e]);if(!this.match.apply(this,arguments))throw r=this.LT(1),new n("Expected "+this._tokenData[e[0]].name+" at line "+r.startLine+", col "+r.startCol+".",r.startLine,r.startCol)},advance:function(e,t){while(this.LA(0)!==0&&!this.match(e,t))this.get();return this.LA(0)},get:function(e){var t=this._tokenData,n=this._reader,r,i=0,s=t.length,o=!1,u,a;if(this._lt.length&&this._ltIndex>=0&&this._ltIndex<this._lt.length){i++,this._token=this._lt[this._ltIndex++],a=t[this._token.type];while(a.channel!==undefined&&e!==a.channel&&this._ltIndex<this._lt.length)this._token=this._lt[this._ltIndex++],a=t[this._token.type],i++;if((a.channel===undefined||e===a.channel)&&this._ltIndex<=this._lt.length)return this._ltIndexCache.push(i),this._token.type}return u=this._getToken(),u.type>-1&&!t[u.type].hide&&(u.channel=t[u.type].channel,this._token=u,this._lt.push(u),this._ltIndexCache.push(this._lt.length-this._ltIndex+i),this._lt.length>5&&this._lt.shift(),this._ltIndexCache.length>5&&this._ltIndexCache.shift(),this._ltIndex=this._lt.length),a=t[u.type],a&&(a.hide||a.channel!==undefined&&e!==a.channel)?this.get(e):u.type},LA:function(e){var t=e,n;if(e>0){if(e>5)throw new Error("Too much lookahead.");while(t)n=this.get(),t--;while(t<e)this.unget(),t++}else if(e<0){if(!this._lt[this._ltIndex+e])throw new Error("Too much lookbehind.");n=this._lt[this._ltIndex+e].type}else n=this._token.type;return n},LT:function(e){return this.LA(e),this._lt[this._ltIndex+e-1]},peek:function(){return this.LA(1)},token:function(){return this._token},tokenName:function(e){return e<0||e>this._tokenData.length?"UNKNOWN_TOKEN":this._tokenData[e].name},tokenType:function(e){return this._tokenData[e]||-1},unget:function(){if(!this._ltIndexCache.length)throw new Error("Too much lookahead.");this._ltIndex-=this._ltIndexCache.pop(),this._token=this._lt[this._ltIndex-1]}},parserlib.util={StringReader:t,SyntaxError:n,SyntaxUnit:r,EventTarget:e,TokenStreamBase:i}})(),function(){function Combinator(e,t,n){SyntaxUnit.call(this,e,t,n,Parser.COMBINATOR_TYPE),this.type="unknown",/^\s+$/.test(e)?this.type="descendant":e==">"?this.type="child":e=="+"?this.type="adjacent-sibling":e=="~"&&(this.type="sibling")}function MediaFeature(e,t){SyntaxUnit.call(this,"("+e+(t!==null?":"+t:"")+")",e.startLine,e.startCol,Parser.MEDIA_FEATURE_TYPE),this.name=e,this.value=t}function MediaQuery(e,t,n,r,i){SyntaxUnit.call(this,(e?e+" ":"")+(t?t:"")+(t&&n.length>0?" and ":"")+n.join(" and "),r,i,Parser.MEDIA_QUERY_TYPE),this.modifier=e,this.mediaType=t,this.features=n}function Parser(e){EventTarget.call(this),this.options=e||{},this._tokenStream=null}function PropertyName(e,t,n,r){SyntaxUnit.call(this,e,n,r,Parser.PROPERTY_NAME_TYPE),this.hack=t}function PropertyValue(e,t,n){SyntaxUnit.call(this,e.join(" "),t,n,Parser.PROPERTY_VALUE_TYPE),this.parts=e}function PropertyValueIterator(e){this._i=0,this._parts=e.parts,this._marks=[],this.value=e}function PropertyValuePart(text,line,col){SyntaxUnit.call(this,text,line,col,Parser.PROPERTY_VALUE_PART_TYPE),this.type="unknown";var temp;if(/^([+\-]?[\d\.]+)([a-z]+)$/i.test(text)){this.type="dimension",this.value=+RegExp.$1,this.units=RegExp.$2;switch(this.units.toLowerCase()){case"em":case"rem":case"ex":case"px":case"cm":case"mm":case"in":case"pt":case"pc":case"ch":case"vh":case"vw":case"vm":this.type="length";break;case"deg":case"rad":case"grad":this.type="angle";break;case"ms":case"s":this.type="time";break;case"hz":case"khz":this.type="frequency";break;case"dpi":case"dpcm":this.type="resolution"}}else/^([+\-]?[\d\.]+)%$/i.test(text)?(this.type="percentage",this.value=+RegExp.$1):/^([+\-]?[\d\.]+)%$/i.test(text)?(this.type="percentage",this.value=+RegExp.$1):/^([+\-]?\d+)$/i.test(text)?(this.type="integer",this.value=+RegExp.$1):/^([+\-]?[\d\.]+)$/i.test(text)?(this.type="number",this.value=+RegExp.$1):/^#([a-f0-9]{3,6})/i.test(text)?(this.type="color",temp=RegExp.$1,temp.length==3?(this.red=parseInt(temp.charAt(0)+temp.charAt(0),16),this.green=parseInt(temp.charAt(1)+temp.charAt(1),16),this.blue=parseInt(temp.charAt(2)+temp.charAt(2),16)):(this.red=parseInt(temp.substring(0,2),16),this.green=parseInt(temp.substring(2,4),16),this.blue=parseInt(temp.substring(4,6),16))):/^rgb\(\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)\s*\)/i.test(text)?(this.type="color",this.red=+RegExp.$1,this.green=+RegExp.$2,this.blue=+RegExp.$3):/^rgb\(\s*(\d+)%\s*,\s*(\d+)%\s*,\s*(\d+)%\s*\)/i.test(text)?(this.type="color",this.red=+RegExp.$1*255/100,this.green=+RegExp.$2*255/100,this.blue=+RegExp.$3*255/100):/^rgba\(\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)\s*,\s*([\d\.]+)\s*\)/i.test(text)?(this.type="color",this.red=+RegExp.$1,this.green=+RegExp.$2,this.blue=+RegExp.$3,this.alpha=+RegExp.$4):/^rgba\(\s*(\d+)%\s*,\s*(\d+)%\s*,\s*(\d+)%\s*,\s*([\d\.]+)\s*\)/i.test(text)?(this.type="color",this.red=+RegExp.$1*255/100,this.green=+RegExp.$2*255/100,this.blue=+RegExp.$3*255/100,this.alpha=+RegExp.$4):/^hsl\(\s*(\d+)\s*,\s*(\d+)%\s*,\s*(\d+)%\s*\)/i.test(text)?(this.type="color",this.hue=+RegExp.$1,this.saturation=+RegExp.$2/100,this.lightness=+RegExp.$3/100):/^hsla\(\s*(\d+)\s*,\s*(\d+)%\s*,\s*(\d+)%\s*,\s*([\d\.]+)\s*\)/i.test(text)?(this.type="color",this.hue=+RegExp.$1,this.saturation=+RegExp.$2/100,this.lightness=+RegExp.$3/100,this.alpha=+RegExp.$4):/^url\(["']?([^\)"']+)["']?\)/i.test(text)?(this.type="uri",this.uri=RegExp.$1):/^([^\(]+)\(/i.test(text)?(this.type="function",this.name=RegExp.$1,this.value=text):/^["'][^"']*["']/.test(text)?(this.type="string",this.value=eval(text)):Colors[text.toLowerCase()]?(this.type="color",temp=Colors[text.toLowerCase()].substring(1),this.red=parseInt(temp.substring(0,2),16),this.green=parseInt(temp.substring(2,4),16),this.blue=parseInt(temp.substring(4,6),16)):/^[\,\/]$/.test(text)?(this.type="operator",this.value=text):/^[a-z\-\u0080-\uFFFF][a-z0-9\-\u0080-\uFFFF]*$/i.test(text)&&(this.type="identifier",this.value=text)}function Selector(e,t,n){SyntaxUnit.call(this,e.join(" "),t,n,Parser.SELECTOR_TYPE),this.parts=e,this.specificity=Specificity.calculate(this)}function SelectorPart(e,t,n,r,i){SyntaxUnit.call(this,n,r,i,Parser.SELECTOR_PART_TYPE),this.elementName=e,this.modifiers=t}function SelectorSubPart(e,t,n,r){SyntaxUnit.call(this,e,n,r,Parser.SELECTOR_SUB_PART_TYPE),this.type=t,this.args=[]}function Specificity(e,t,n,r){this.a=e,this.b=t,this.c=n,this.d=r}function isHexDigit(e){return e!==null&&h.test(e)}function isDigit(e){return e!==null&&/\d/.test(e)}function isWhitespace(e){return e!==null&&/\s/.test(e)}function isNewLine(e){return e!==null&&nl.test(e)}function isNameStart(e){return e!==null&&/[a-z_\u0080-\uFFFF\\]/i.test(e)}function isNameChar(e){return e!==null&&(isNameStart(e)||/[0-9\-\\]/.test(e))}function isIdentStart(e){return e!==null&&(isNameStart(e)||/\-\\/.test(e))}function mix(e,t){for(var n in t)t.hasOwnProperty(n)&&(e[n]=t[n]);return e}function TokenStream(e){TokenStreamBase.call(this,e,Tokens)}function ValidationError(e,t,n){this.col=n,this.line=t,this.message=e}var EventTarget=parserlib.util.EventTarget,TokenStreamBase=parserlib.util.TokenStreamBase,StringReader=parserlib.util.StringReader,SyntaxError=parserlib.util.SyntaxError,SyntaxUnit=parserlib.util.SyntaxUnit,Colors={aliceblue:"#f0f8ff",antiquewhite:"#faebd7",aqua:"#00ffff",aquamarine:"#7fffd4",azure:"#f0ffff",beige:"#f5f5dc",bisque:"#ffe4c4",black:"#000000",blanchedalmond:"#ffebcd",blue:"#0000ff",blueviolet:"#8a2be2",brown:"#a52a2a",burlywood:"#deb887",cadetblue:"#5f9ea0",chartreuse:"#7fff00",chocolate:"#d2691e",coral:"#ff7f50",cornflowerblue:"#6495ed",cornsilk:"#fff8dc",crimson:"#dc143c",cyan:"#00ffff",darkblue:"#00008b",darkcyan:"#008b8b",darkgoldenrod:"#b8860b",darkgray:"#a9a9a9",darkgreen:"#006400",darkkhaki:"#bdb76b",darkmagenta:"#8b008b",darkolivegreen:"#556b2f",darkorange:"#ff8c00",darkorchid:"#9932cc",darkred:"#8b0000",darksalmon:"#e9967a",darkseagreen:"#8fbc8f",darkslateblue:"#483d8b",darkslategray:"#2f4f4f",darkturquoise:"#00ced1",darkviolet:"#9400d3",deeppink:"#ff1493",deepskyblue:"#00bfff",dimgray:"#696969",dodgerblue:"#1e90ff",firebrick:"#b22222",floralwhite:"#fffaf0",forestgreen:"#228b22",fuchsia:"#ff00ff",gainsboro:"#dcdcdc",ghostwhite:"#f8f8ff",gold:"#ffd700",goldenrod:"#daa520",gray:"#808080",green:"#008000",greenyellow:"#adff2f",honeydew:"#f0fff0",hotpink:"#ff69b4",indianred:"#cd5c5c",indigo:"#4b0082",ivory:"#fffff0",khaki:"#f0e68c",lavender:"#e6e6fa",lavenderblush:"#fff0f5",lawngreen:"#7cfc00",lemonchiffon:"#fffacd",lightblue:"#add8e6",lightcoral:"#f08080",lightcyan:"#e0ffff",lightgoldenrodyellow:"#fafad2",lightgray:"#d3d3d3",lightgreen:"#90ee90",lightpink:"#ffb6c1",lightsalmon:"#ffa07a",lightseagreen:"#20b2aa",lightskyblue:"#87cefa",lightslategray:"#778899",lightsteelblue:"#b0c4de",lightyellow:"#ffffe0",lime:"#00ff00",limegreen:"#32cd32",linen:"#faf0e6",magenta:"#ff00ff",maroon:"#800000",mediumaquamarine:"#66cdaa",mediumblue:"#0000cd",mediumorchid:"#ba55d3",mediumpurple:"#9370d8",mediumseagreen:"#3cb371",mediumslateblue:"#7b68ee",mediumspringgreen:"#00fa9a",mediumturquoise:"#48d1cc",mediumvioletred:"#c71585",midnightblue:"#191970",mintcream:"#f5fffa",mistyrose:"#ffe4e1",moccasin:"#ffe4b5",navajowhite:"#ffdead",navy:"#000080",oldlace:"#fdf5e6",olive:"#808000",olivedrab:"#6b8e23",orange:"#ffa500",orangered:"#ff4500",orchid:"#da70d6",palegoldenrod:"#eee8aa",palegreen:"#98fb98",paleturquoise:"#afeeee",palevioletred:"#d87093",papayawhip:"#ffefd5",peachpuff:"#ffdab9",peru:"#cd853f",pink:"#ffc0cb",plum:"#dda0dd",powderblue:"#b0e0e6",purple:"#800080",red:"#ff0000",rosybrown:"#bc8f8f",royalblue:"#4169e1",saddlebrown:"#8b4513",salmon:"#fa8072",sandybrown:"#f4a460",seagreen:"#2e8b57",seashell:"#fff5ee",sienna:"#a0522d",silver:"#c0c0c0",skyblue:"#87ceeb",slateblue:"#6a5acd",slategray:"#708090",snow:"#fffafa",springgreen:"#00ff7f",steelblue:"#4682b4",tan:"#d2b48c",teal:"#008080",thistle:"#d8bfd8",tomato:"#ff6347",turquoise:"#40e0d0",violet:"#ee82ee",wheat:"#f5deb3",white:"#ffffff",whitesmoke:"#f5f5f5",yellow:"#ffff00",yellowgreen:"#9acd32",activeBorder:"Active window border.",activecaption:"Active window caption.",appworkspace:"Background color of multiple document interface.",background:"Desktop background.",buttonface:"The face background color for 3-D elements that appear 3-D due to one layer of surrounding border.",buttonhighlight:"The color of the border facing the light source for 3-D elements that appear 3-D due to one layer of surrounding border.",buttonshadow:"The color of the border away from the light source for 3-D elements that appear 3-D due to one layer of surrounding border.",buttontext:"Text on push buttons.",captiontext:"Text in caption, size box, and scrollbar arrow box.",graytext:"Grayed (disabled) text. This color is set to #000 if the current display driver does not support a solid gray color.",highlight:"Item(s) selected in a control.",highlighttext:"Text of item(s) selected in a control.",inactiveborder:"Inactive window border.",inactivecaption:"Inactive window caption.",inactivecaptiontext:"Color of text in an inactive caption.",infobackground:"Background color for tooltip controls.",infotext:"Text color for tooltip controls.",menu:"Menu background.",menutext:"Text in menus.",scrollbar:"Scroll bar gray area.",threeddarkshadow:"The color of the darker (generally outer) of the two borders away from the light source for 3-D elements that appear 3-D due to two concentric layers of surrounding border.",threedface:"The face background color for 3-D elements that appear 3-D due to two concentric layers of surrounding border.",threedhighlight:"The color of the lighter (generally outer) of the two borders facing the light source for 3-D elements that appear 3-D due to two concentric layers of surrounding border.",threedlightshadow:"The color of the darker (generally inner) of the two borders facing the light source for 3-D elements that appear 3-D due to two concentric layers of surrounding border.",threedshadow:"The color of the lighter (generally inner) of the two borders away from the light source for 3-D elements that appear 3-D due to two concentric layers of surrounding border.",window:"Window background.",windowframe:"Window frame.",windowtext:"Text in windows."};Combinator.prototype=new SyntaxUnit,Combinator.prototype.constructor=Combinator,MediaFeature.prototype=new SyntaxUnit,MediaFeature.prototype.constructor=MediaFeature,MediaQuery.prototype=new SyntaxUnit,MediaQuery.prototype.constructor=MediaQuery,Parser.DEFAULT_TYPE=0,Parser.COMBINATOR_TYPE=1,Parser.MEDIA_FEATURE_TYPE=2,Parser.MEDIA_QUERY_TYPE=3,Parser.PROPERTY_NAME_TYPE=4,Parser.PROPERTY_VALUE_TYPE=5,Parser.PROPERTY_VALUE_PART_TYPE=6,Parser.SELECTOR_TYPE=7,Parser.SELECTOR_PART_TYPE=8,Parser.SELECTOR_SUB_PART_TYPE=9,Parser.prototype=function(){var e=new EventTarget,t,n={constructor:Parser,DEFAULT_TYPE:0,COMBINATOR_TYPE:1,MEDIA_FEATURE_TYPE:2,MEDIA_QUERY_TYPE:3,PROPERTY_NAME_TYPE:4,PROPERTY_VALUE_TYPE:5,PROPERTY_VALUE_PART_TYPE:6,SELECTOR_TYPE:7,SELECTOR_PART_TYPE:8,SELECTOR_SUB_PART_TYPE:9,_stylesheet:function(){var e=this._tokenStream,t=null,n,r,i;this.fire("startstylesheet"),this._charset(),this._skipCruft();while(e.peek()==Tokens.IMPORT_SYM)this._import(),this._skipCruft();while(e.peek()==Tokens.NAMESPACE_SYM)this._namespace(),this._skipCruft();i=e.peek();while(i>Tokens.EOF){try{switch(i){case Tokens.MEDIA_SYM:this._media(),this._skipCruft();break;case Tokens.PAGE_SYM:this._page(),this._skipCruft();break;case Tokens.FONT_FACE_SYM:this._font_face(),this._skipCruft();break;case Tokens.KEYFRAMES_SYM:this._keyframes(),this._skipCruft();break;case Tokens.VIEWPORT_SYM:this._viewport(),this._skipCruft();break;case Tokens.UNKNOWN_SYM:e.get();if(!!this.options.strict)throw new SyntaxError("Unknown @ rule.",e.LT(0).startLine,e.LT(0).startCol);this.fire({type:"error",error:null,message:"Unknown @ rule: "+e.LT(0).value+".",line:e.LT(0).startLine,col:e.LT(0).startCol}),n=0;while(e.advance([Tokens.LBRACE,Tokens.RBRACE])==Tokens.LBRACE)n++;while(n)e.advance([Tokens.RBRACE]),n--;break;case Tokens.S:this._readWhitespace();break;default:if(!this._ruleset())switch(i){case Tokens.CHARSET_SYM:throw r=e.LT(1),this._charset(!1),new SyntaxError("@charset not allowed here.",r.startLine,r.startCol);case Tokens.IMPORT_SYM:throw r=e.LT(1),this._import(!1),new SyntaxError("@import not allowed here.",r.startLine,r.startCol);case Tokens.NAMESPACE_SYM:throw r=e.LT(1),this._namespace(!1),new SyntaxError("@namespace not allowed here.",r.startLine,r.startCol);default:e.get(),this._unexpectedToken(e.token())}}}catch(s){if(!(s instanceof SyntaxError&&!this.options.strict))throw s;this.fire({type:"error",error:s,message:s.message,line:s.line,col:s.col})}i=e.peek()}i!=Tokens.EOF&&this._unexpectedToken(e.token()),this.fire("endstylesheet")},_charset:function(e){var t=this._tokenStream,n,r,i,s;t.match(Tokens.CHARSET_SYM)&&(i=t.token().startLine,s=t.token().startCol,this._readWhitespace(),t.mustMatch(Tokens.STRING),r=t.token(),n=r.value,this._readWhitespace(),t.mustMatch(Tokens.SEMICOLON),e!==!1&&this.fire({type:"charset",charset:n,line:i,col:s}))},_import:function(e){var t=this._tokenStream,n,r,i,s=[];t.mustMatch(Tokens.IMPORT_SYM),i=t.token(),this._readWhitespace(),t.mustMatch([Tokens.STRING,Tokens.URI]),r=t.token().value.replace(/(?:url\()?["']([^"']+)["']\)?/,"$1"),this._readWhitespace(),s=this._media_query_list(),t.mustMatch(Tokens.SEMICOLON),this._readWhitespace(),e!==!1&&this.fire({type:"import",uri:r,media:s,line:i.startLine,col:i.startCol})},_namespace:function(e){var t=this._tokenStream,n,r,i,s;t.mustMatch(Tokens.NAMESPACE_SYM),n=t.token().startLine,r=t.token().startCol,this._readWhitespace(),t.match(Tokens.IDENT)&&(i=t.token().value,this._readWhitespace()),t.mustMatch([Tokens.STRING,Tokens.URI]),s=t.token().value.replace(/(?:url\()?["']([^"']+)["']\)?/,"$1"),this._readWhitespace(),t.mustMatch(Tokens.SEMICOLON),this._readWhitespace(),e!==!1&&this.fire({type:"namespace",prefix:i,uri:s,line:n,col:r})},_media:function(){var e=this._tokenStream,t,n,r;e.mustMatch(Tokens.MEDIA_SYM),t=e.token().startLine,n=e.token().startCol,this._readWhitespace(),r=this._media_query_list(),e.mustMatch(Tokens.LBRACE),this._readWhitespace(),this.fire({type:"startmedia",media:r,line:t,col:n});for(;;)if(e.peek()==Tokens.PAGE_SYM)this._page();else if(e.peek()==Tokens.FONT_FACE_SYM)this._font_face();else if(!this._ruleset())break;e.mustMatch(Tokens.RBRACE),this._readWhitespace(),this.fire({type:"endmedia",media:r,line:t,col:n})},_media_query_list:function(){var e=this._tokenStream,t=[];this._readWhitespace(),(e.peek()==Tokens.IDENT||e.peek()==Tokens.LPAREN)&&t.push(this._media_query());while(e.match(Tokens.COMMA))this._readWhitespace(),t.push(this._media_query());return t},_media_query:function(){var e=this._tokenStream,t=null,n=null,r=null,i=[];e.match(Tokens.IDENT)&&(n=e.token().value.toLowerCase(),n!="only"&&n!="not"?(e.unget(),n=null):r=e.token()),this._readWhitespace(),e.peek()==Tokens.IDENT?(t=this._media_type(),r===null&&(r=e.token())):e.peek()==Tokens.LPAREN&&(r===null&&(r=e.LT(1)),i.push(this._media_expression()));if(t===null&&i.length===0)return null;this._readWhitespace();while(e.match(Tokens.IDENT))e.token().value.toLowerCase()!="and"&&this._unexpectedToken(e.token()),this._readWhitespace(),i.push(this._media_expression());return new MediaQuery(n,t,i,r.startLine,r.startCol)},_media_type:function(){return this._media_feature()},_media_expression:function(){var e=this._tokenStream,t=null,n,r=null;return e.mustMatch(Tokens.LPAREN),t=this._media_feature(),this._readWhitespace(),e.match(Tokens.COLON)&&(this._readWhitespace(),n=e.LT(1),r=this._expression()),e.mustMatch(Tokens.RPAREN),this._readWhitespace(),new MediaFeature(t,r?new SyntaxUnit(r,n.startLine,n.startCol):null)},_media_feature:function(){var e=this._tokenStream;return e.mustMatch(Tokens.IDENT),SyntaxUnit.fromToken(e.token())},_page:function(){var e=this._tokenStream,t,n,r=null,i=null;e.mustMatch(Tokens.PAGE_SYM),t=e.token().startLine,n=e.token().startCol,this._readWhitespace(),e.match(Tokens.IDENT)&&(r=e.token().value,r.toLowerCase()==="auto"&&this._unexpectedToken(e.token())),e.peek()==Tokens.COLON&&(i=this._pseudo_page()),this._readWhitespace(),this.fire({type:"startpage",id:r,pseudo:i,line:t,col:n}),this._readDeclarations(!0,!0),this.fire({type:"endpage",id:r,pseudo:i,line:t,col:n})},_margin:function(){var e=this._tokenStream,t,n,r=this._margin_sym();return r?(t=e.token().startLine,n=e.token().startCol,this.fire({type:"startpagemargin",margin:r,line:t,col:n}),this._readDeclarations(!0),this.fire({type:"endpagemargin",margin:r,line:t,col:n}),!0):!1},_margin_sym:function(){var e=this._tokenStream;return e.match([Tokens.TOPLEFTCORNER_SYM,Tokens.TOPLEFT_SYM,Tokens.TOPCENTER_SYM,Tokens.TOPRIGHT_SYM,Tokens.TOPRIGHTCORNER_SYM,Tokens.BOTTOMLEFTCORNER_SYM,Tokens.BOTTOMLEFT_SYM,Tokens.BOTTOMCENTER_SYM,Tokens.BOTTOMRIGHT_SYM,Tokens.BOTTOMRIGHTCORNER_SYM,Tokens.LEFTTOP_SYM,Tokens.LEFTMIDDLE_SYM,Tokens.LEFTBOTTOM_SYM,Tokens.RIGHTTOP_SYM,Tokens.RIGHTMIDDLE_SYM,Tokens.RIGHTBOTTOM_SYM])?SyntaxUnit.fromToken(e.token()):null},_pseudo_page:function(){var e=this._tokenStream;return e.mustMatch(Tokens.COLON),e.mustMatch(Tokens.IDENT),e.token().value},_font_face:function(){var e=this._tokenStream,t,n;e.mustMatch(Tokens.FONT_FACE_SYM),t=e.token().startLine,n=e.token().startCol,this._readWhitespace(),this.fire({type:"startfontface",line:t,col:n}),this._readDeclarations(!0),this.fire({type:"endfontface",line:t,col:n})},_viewport:function(){var e=this._tokenStream,t,n;e.mustMatch(Tokens.VIEWPORT_SYM),t=e.token().startLine,n=e.token().startCol,this._readWhitespace(),this.fire({type:"startviewport",line:t,col:n}),this._readDeclarations(!0),this.fire({type:"endviewport",line:t,col:n})},_operator:function(e){var t=this._tokenStream,n=null;if(t.match([Tokens.SLASH,Tokens.COMMA])||e&&t.match([Tokens.PLUS,Tokens.STAR,Tokens.MINUS]))n=t.token(),this._readWhitespace();return n?PropertyValuePart.fromToken(n):null},_combinator:function(){var e=this._tokenStream,t=null,n;return e.match([Tokens.PLUS,Tokens.GREATER,Tokens.TILDE])&&(n=e.token(),t=new Combinator(n.value,n.startLine,n.startCol),this._readWhitespace()),t},_unary_operator:function(){var e=this._tokenStream;return e.match([Tokens.MINUS,Tokens.PLUS])?e.token().value:null},_property:function(){var e=this._tokenStream,t=null,n=null,r,i,s,o;return e.peek()==Tokens.STAR&&this.options.starHack&&(e.get(),i=e.token(),n=i.value,s=i.startLine,o=i.startCol),e.match(Tokens.IDENT)&&(i=e.token(),r=i.value,r.charAt(0)=="_"&&this.options.underscoreHack&&(n="_",r=r.substring(1)),t=new PropertyName(r,n,s||i.startLine,o||i.startCol),this._readWhitespace()),t},_ruleset:function(){var e=this._tokenStream,t,n;try{n=this._selectors_group()}catch(r){if(r instanceof SyntaxError&&!this.options.strict){this.fire({type:"error",error:r,message:r.message,line:r.line,col:r.col}),t=e.advance([Tokens.RBRACE]);if(t!=Tokens.RBRACE)throw r;return!0}throw r}return n&&(this.fire({type:"startrule",selectors:n,line:n[0].line,col:n[0].col}),this._readDeclarations(!0),this.fire({type:"endrule",selectors:n,line:n[0].line,col:n[0].col})),n},_selectors_group:function(){var e=this._tokenStream,t=[],n;n=this._selector();if(n!==null){t.push(n);while(e.match(Tokens.COMMA))this._readWhitespace(),n=this._selector(),n!==null?t.push(n):this._unexpectedToken(e.LT(1))}return t.length?t:null},_selector:function(){var e=this._tokenStream,t=[],n=null,r=null,i=null;n=this._simple_selector_sequence();if(n===null)return null;t.push(n);do{r=this._combinator();if(r!==null)t.push(r),n=this._simple_selector_sequence(),n===null?this._unexpectedToken(e.LT(1)):t.push(n);else{if(!this._readWhitespace())break;i=new Combinator(e.token().value,e.token().startLine,e.token().startCol),r=this._combinator(),n=this._simple_selector_sequence(),n===null?r!==null&&this._unexpectedToken(e.LT(1)):(r!==null?t.push(r):t.push(i),t.push(n))}}while(!0);return new Selector(t,t[0].line,t[0].col)},_simple_selector_sequence:function(){var e=this._tokenStream,t=null,n=[],r="",i=[function(){return e.match(Tokens.HASH)?new SelectorSubPart(e.token().value,"id",e.token().startLine,e.token().startCol):null},this._class,this._attrib,this._pseudo,this._negation],s=0,o=i.length,u=null,a=!1,f,l;f=e.LT(1).startLine,l=e.LT(1).startCol,t=this._type_selector(),t||(t=this._universal()),t!==null&&(r+=t);for(;;){if(e.peek()===Tokens.S)break;while(s<o&&u===null)u=i[s++].call(this);if(u===null){if(r==="")return null;break}s=0,n.push(u),r+=u.toString(),u=null}return r!==""?new SelectorPart(t,n,r,f,l):null},_type_selector:function(){var e=this._tokenStream,t=this._namespace_prefix(),n=this._element_name();return n?(t&&(n.text=t+n.text,n.col-=t.length),n):(t&&(e.unget(),t.length>1&&e.unget()),null)},_class:function(){var e=this._tokenStream,t;return e.match(Tokens.DOT)?(e.mustMatch(Tokens.IDENT),t=e.token(),new SelectorSubPart("."+t.value,"class",t.startLine,t.startCol-1)):null},_element_name:function(){var e=this._tokenStream,t;return e.match(Tokens.IDENT)?(t=e.token(),new SelectorSubPart(t.value,"elementName",t.startLine,t.startCol)):null},_namespace_prefix:function(){var e=this._tokenStream,t="";if(e.LA(1)===Tokens.PIPE||e.LA(2)===Tokens.PIPE)e.match([Tokens.IDENT,Tokens.STAR])&&(t+=e.token().value),e.mustMatch(Tokens.PIPE),t+="|";return t.length?t:null},_universal:function(){var e=this._tokenStream,t="",n;return n=this._namespace_prefix(),n&&(t+=n),e.match(Tokens.STAR)&&(t+="*"),t.length?t:null},_attrib:function(){var e=this._tokenStream,t=null,n,r;return e.match(Tokens.LBRACKET)?(r=e.token(),t=r.value,t+=this._readWhitespace(),n=this._namespace_prefix(),n&&(t+=n),e.mustMatch(Tokens.IDENT),t+=e.token().value,t+=this._readWhitespace(),e.match([Tokens.PREFIXMATCH,Tokens.SUFFIXMATCH,Tokens.SUBSTRINGMATCH,Tokens.EQUALS,Tokens.INCLUDES,Tokens.DASHMATCH])&&(t+=e.token().value,t+=this._readWhitespace(),e.mustMatch([Tokens.IDENT,Tokens.STRING]),t+=e.token().value,t+=this._readWhitespace()),e.mustMatch(Tokens.RBRACKET),new SelectorSubPart(t+"]","attribute",r.startLine,r.startCol)):null},_pseudo:function(){var e=this._tokenStream,t=null,n=":",r,i;return e.match(Tokens.COLON)&&(e.match(Tokens.COLON)&&(n+=":"),e.match(Tokens.IDENT)?(t=e.token().value,r=e.token().startLine,i=e.token().startCol-n.length):e.peek()==Tokens.FUNCTION&&(r=e.LT(1).startLine,i=e.LT(1).startCol-n.length,t=this._functional_pseudo()),t&&(t=new SelectorSubPart(n+t,"pseudo",r,i))),t},_functional_pseudo:function(){var e=this._tokenStream,t=null;return e.match(Tokens.FUNCTION)&&(t=e.token().value,t+=this._readWhitespace(),t+=this._expression(),e.mustMatch(Tokens.RPAREN),t+=")"),t},_expression:function(){var e=this._tokenStream,t="";while(e.match([Tokens.PLUS,Tokens.MINUS,Tokens.DIMENSION,Tokens.NUMBER,Tokens.STRING,Tokens.IDENT,Tokens.LENGTH,Tokens.FREQ,Tokens.ANGLE,Tokens.TIME,Tokens.RESOLUTION,Tokens.SLASH]))t+=e.token().value,t+=this._readWhitespace();return t.length?t:null},_negation:function(){var e=this._tokenStream,t,n,r="",i,s=null;return e.match(Tokens.NOT)&&(r=e.token().value,t=e.token().startLine,n=e.token().startCol,r+=this._readWhitespace(),i=this._negation_arg(),r+=i,r+=this._readWhitespace(),e.match(Tokens.RPAREN),r+=e.token().value,s=new SelectorSubPart(r,"not",t,n),s.args.push(i)),s},_negation_arg:function(){var e=this._tokenStream,t=[this._type_selector,this._universal,function(){return e.match(Tokens.HASH)?new SelectorSubPart(e.token().value,"id",e.token().startLine,e.token().startCol):null},this._class,this._attrib,this._pseudo],n=null,r=0,i=t.length,s,o,u,a;o=e.LT(1).startLine,u=e.LT(1).startCol;while(r<i&&n===null)n=t[r].call(this),r++;return n===null&&this._unexpectedToken(e.LT(1)),n.type=="elementName"?a=new SelectorPart(n,[],n.toString(),o,u):a=new SelectorPart(null,[n],n.toString(),o,u),a},_declaration:function(){var e=this._tokenStream,t=null,n=null,r=null,i=null,s=null,o="";t=this._property();if(t!==null){e.mustMatch(Tokens.COLON),this._readWhitespace(),n=this._expr(),(!n||n.length===0)&&this._unexpectedToken(e.LT(1)),r=this._prio(),o=t.toString();if(this.options.starHack&&t.hack=="*"||this.options.underscoreHack&&t.hack=="_")o=t.text;try{this._validateProperty(o,n)}catch(u){s=u}return this.fire({type:"property",property:t,value:n,important:r,line:t.line,col:t.col,invalid:s}),!0}return!1},_prio:function(){var e=this._tokenStream,t=e.match(Tokens.IMPORTANT_SYM);return this._readWhitespace(),t},_expr:function(e){var t=this._tokenStream,n=[],r=null,i=null;r=this._term();if(r!==null){n.push(r);do{i=this._operator(e),i&&n.push(i),r=this._term();if(r===null)break;n.push(r)}while(!0)}return n.length>0?new PropertyValue(n,n[0].line,n[0].col):null},_term:function(){var e=this._tokenStream,t=null,n=null,r,i,s;return t=this._unary_operator(),t!==null&&(i=e.token().startLine,s=e.token().startCol),e.peek()==Tokens.IE_FUNCTION&&this.options.ieFilters?(n=this._ie_function(),t===null&&(i=e.token().startLine,s=e.token().startCol)):e.match([Tokens.NUMBER,Tokens.PERCENTAGE,Tokens.LENGTH,Tokens.ANGLE,Tokens.TIME,Tokens.FREQ,Tokens.STRING,Tokens.IDENT,Tokens.URI,Tokens.UNICODE_RANGE])?(n=e.token().value,t===null&&(i=e.token().startLine,s=e.token().startCol),this._readWhitespace()):(r=this._hexcolor(),r===null?(t===null&&(i=e.LT(1).startLine,s=e.LT(1).startCol),n===null&&(e.LA(3)==Tokens.EQUALS&&this.options.ieFilters?n=this._ie_function():n=this._function())):(n=r.value,t===null&&(i=r.startLine,s=r.startCol))),n!==null?new PropertyValuePart(t!==null?t+n:n,i,s):null},_function:function(){var e=this._tokenStream,t=null,n=null,r;if(e.match(Tokens.FUNCTION)){t=e.token().value,this._readWhitespace(),n=this._expr(!0),t+=n;if(this.options.ieFilters&&e.peek()==Tokens.EQUALS)do{this._readWhitespace()&&(t+=e.token().value),e.LA(0)==Tokens.COMMA&&(t+=e.token().value),e.match(Tokens.IDENT),t+=e.token().value,e.match(Tokens.EQUALS),t+=e.token().value,r=e.peek();while(r!=Tokens.COMMA&&r!=Tokens.S&&r!=Tokens.RPAREN)e.get(),t+=e.token().value,r=e.peek()}while(e.match([Tokens.COMMA,Tokens.S]));e.match(Tokens.RPAREN),t+=")",this._readWhitespace()}return t},_ie_function:function(){var e=this._tokenStream,t=null,n=null,r;if(e.match([Tokens.IE_FUNCTION,Tokens.FUNCTION])){t=e.token().value;do{this._readWhitespace()&&(t+=e.token().value),e.LA(0)==Tokens.COMMA&&(t+=e.token().value),e.match(Tokens.IDENT),t+=e.token().value,e.match(Tokens.EQUALS),t+=e.token().value,r=e.peek();while(r!=Tokens.COMMA&&r!=Tokens.S&&r!=Tokens.RPAREN)e.get(),t+=e.token().value,r=e.peek()}while(e.match([Tokens.COMMA,Tokens.S]));e.match(Tokens.RPAREN),t+=")",this._readWhitespace()}return t},_hexcolor:function(){var e=this._tokenStream,t=null,n;if(e.match(Tokens.HASH)){t=e.token(),n=t.value;if(!/#[a-f0-9]{3,6}/i.test(n))throw new SyntaxError("Expected a hex color but found '"+n+"' at line "+t.startLine+", col "+t.startCol+".",t.startLine,t.startCol);this._readWhitespace()}return t},_keyframes:function(){var e=this._tokenStream,t,n,r,i="";e.mustMatch(Tokens.KEYFRAMES_SYM),t=e.token(),/^@\-([^\-]+)\-/.test(t.value)&&(i=RegExp.$1),this._readWhitespace(),r=this._keyframe_name(),this._readWhitespace(),e.mustMatch(Tokens.LBRACE),this.fire({type:"startkeyframes",name:r,prefix:i,line:t.startLine,col:t.startCol}),this._readWhitespace(),n=e.peek();while(n==Tokens.IDENT||n==Tokens.PERCENTAGE)this._keyframe_rule(),this._readWhitespace(),n=e.peek();this.fire({type:"endkeyframes",name:r,prefix:i,line:t.startLine,col:t.startCol}),this._readWhitespace(),e.mustMatch(Tokens.RBRACE)},_keyframe_name:function(){var e=this._tokenStream,t;return e.mustMatch([Tokens.IDENT,Tokens.STRING]),SyntaxUnit.fromToken(e.token())},_keyframe_rule:function(){var e=this._tokenStream,t,n=this._key_list();this.fire({type:"startkeyframerule",keys:n,line:n[0].line,col:n[0].col}),this._readDeclarations(!0),this.fire({type:"endkeyframerule",keys:n,line:n[0].line,col:n[0].col})},_key_list:function(){var e=this._tokenStream,t,n,r=[];r.push(this._key()),this._readWhitespace();while(e.match(Tokens.COMMA))this._readWhitespace(),r.push(this._key()),this._readWhitespace();return r},_key:function(){var e=this._tokenStream,t;if(e.match(Tokens.PERCENTAGE))return SyntaxUnit.fromToken(e.token());if(e.match(Tokens.IDENT)){t=e.token();if(/from|to/i.test(t.value))return SyntaxUnit.fromToken(t);e.unget()}this._unexpectedToken(e.LT(1))},_skipCruft:function(){while(this._tokenStream.match([Tokens.S,Tokens.CDO,Tokens.CDC]));},_readDeclarations:function(e,t){var n=this._tokenStream,r;this._readWhitespace(),e&&n.mustMatch(Tokens.LBRACE),this._readWhitespace();try{for(;;){if(!(n.match(Tokens.SEMICOLON)||t&&this._margin())){if(!this._declaration())break;if(!n.match(Tokens.SEMICOLON))break}this._readWhitespace()}n.mustMatch(Tokens.RBRACE),this._readWhitespace()}catch(i){if(!(i instanceof SyntaxError&&!this.options.strict))throw i;this.fire({type:"error",error:i,message:i.message,line:i.line,col:i.col}),r=n.advance([Tokens.SEMICOLON,Tokens.RBRACE]);if(r==Tokens.SEMICOLON)this._readDeclarations(!1,t);else if(r!=Tokens.RBRACE)throw i}},_readWhitespace:function(){var e=this._tokenStream,t="";while(e.match(Tokens.S))t+=e.token().value;return t},_unexpectedToken:function(e){throw new SyntaxError("Unexpected token '"+e.value+"' at line "+e.startLine+", col "+e.startCol+".",e.startLine,e.startCol)},_verifyEnd:function(){this._tokenStream.LA(1)!=Tokens.EOF&&this._unexpectedToken(this._tokenStream.LT(1))},_validateProperty:function(e,t){Validation.validate(e,t)},parse:function(e){this._tokenStream=new TokenStream(e,Tokens),this._stylesheet()},parseStyleSheet:function(e){return this.parse(e)},parseMediaQuery:function(e){this._tokenStream=new TokenStream(e,Tokens);var t=this._media_query();return this._verifyEnd(),t},parsePropertyValue:function(e){this._tokenStream=new TokenStream(e,Tokens),this._readWhitespace();var t=this._expr();return this._readWhitespace(),this._verifyEnd(),t},parseRule:function(e){this._tokenStream=new TokenStream(e,Tokens),this._readWhitespace();var t=this._ruleset();return this._readWhitespace(),this._verifyEnd(),t},parseSelector:function(e){this._tokenStream=new TokenStream(e,Tokens),this._readWhitespace();var t=this._selector();return this._readWhitespace(),this._verifyEnd(),t},parseStyleAttribute:function(e){e+="}",this._tokenStream=new TokenStream(e,Tokens),this._readDeclarations()}};for(t in n)n.hasOwnProperty(t)&&(e[t]=n[t]);return e}();var Properties={"alignment-adjust":"auto | baseline | before-edge | text-before-edge | middle | central | after-edge | text-after-edge | ideographic | alphabetic | hanging | mathematical | <percentage> | <length>","alignment-baseline":"baseline | use-script | before-edge | text-before-edge | after-edge | text-after-edge | central | middle | ideographic | alphabetic | hanging | mathematical",animation:1,"animation-delay":{multi:"<time>",comma:!0},"animation-direction":{multi:"normal | alternate",comma:!0},"animation-duration":{multi:"<time>",comma:!0},"animation-iteration-count":{multi:"<number> | infinite",comma:!0},"animation-name":{multi:"none | <ident>",comma:!0},"animation-play-state":{multi:"running | paused",comma:!0},"animation-timing-function":1,"-moz-animation-delay":{multi:"<time>",comma:!0},"-moz-animation-direction":{multi:"normal | alternate",comma:!0},"-moz-animation-duration":{multi:"<time>",comma:!0},"-moz-animation-iteration-count":{multi:"<number> | infinite",comma:!0},"-moz-animation-name":{multi:"none | <ident>",comma:!0},"-moz-animation-play-state":{multi:"running | paused",comma:!0},"-ms-animation-delay":{multi:"<time>",comma:!0},"-ms-animation-direction":{multi:"normal | alternate",comma:!0},"-ms-animation-duration":{multi:"<time>",comma:!0},"-ms-animation-iteration-count":{multi:"<number> | infinite",comma:!0},"-ms-animation-name":{multi:"none | <ident>",comma:!0},"-ms-animation-play-state":{multi:"running | paused",comma:!0},"-webkit-animation-delay":{multi:"<time>",comma:!0},"-webkit-animation-direction":{multi:"normal | alternate",comma:!0},"-webkit-animation-duration":{multi:"<time>",comma:!0},"-webkit-animation-iteration-count":{multi:"<number> | infinite",comma:!0},"-webkit-animation-name":{multi:"none | <ident>",comma:!0},"-webkit-animation-play-state":{multi:"running | paused",comma:!0},"-o-animation-delay":{multi:"<time>",comma:!0},"-o-animation-direction":{multi:"normal | alternate",comma:!0},"-o-animation-duration":{multi:"<time>",comma:!0},"-o-animation-iteration-count":{multi:"<number> | infinite",comma:!0},"-o-animation-name":{multi:"none | <ident>",comma:!0},"-o-animation-play-state":{multi:"running | paused",comma:!0},appearance:"icon | window | desktop | workspace | document | tooltip | dialog | button | push-button | hyperlink | radio-button | checkbox | menu-item | tab | menu | menubar | pull-down-menu | pop-up-menu | list-menu | radio-group | checkbox-group | outline-tree | range | field | combo-box | signature | password | normal | none | inherit",azimuth:function(e){var t="<angle> | leftwards | rightwards | inherit",n="left-side | far-left | left | center-left | center | center-right | right | far-right | right-side",r=!1,i=!1,s;ValidationTypes.isAny(e,t)||(ValidationTypes.isAny(e,"behind")&&(r=!0,i=!0),ValidationTypes.isAny(e,n)&&(i=!0,r||ValidationTypes.isAny(e,"behind")));if(e.hasNext())throw s=e.next(),i?new ValidationError("Expected end of value but found '"+s+"'.",s.line,s.col):new ValidationError("Expected (<'azimuth'>) but found '"+s+"'.",s.line,s.col)},"backface-visibility":"visible | hidden",background:1,"background-attachment":{multi:"<attachment>",comma:!0},"background-clip":{multi:"<box>",comma:!0},"background-color":"<color> | inherit","background-image":{multi:"<bg-image>",comma:!0},"background-origin":{multi:"<box>",comma:!0},"background-position":{multi:"<bg-position>",comma:!0},"background-repeat":{multi:"<repeat-style>"},"background-size":{multi:"<bg-size>",comma:!0},"baseline-shift":"baseline | sub | super | <percentage> | <length>",behavior:1,binding:1,bleed:"<length>","bookmark-label":"<content> | <attr> | <string>","bookmark-level":"none | <integer>","bookmark-state":"open | closed","bookmark-target":"none | <uri> | <attr>",border:"<border-width> || <border-style> || <color>","border-bottom":"<border-width> || <border-style> || <color>","border-bottom-color":"<color> | inherit","border-bottom-left-radius":"<x-one-radius>","border-bottom-right-radius":"<x-one-radius>","border-bottom-style":"<border-style>","border-bottom-width":"<border-width>","border-collapse":"collapse | separate | inherit","border-color":{multi:"<color> | inherit",max:4},"border-image":1,"border-image-outset":{multi:"<length> | <number>",max:4},"border-image-repeat":{multi:"stretch | repeat | round",max:2},"border-image-slice":function(e){var t=!1,n="<number> | <percentage>",r=!1,i=0,s=4,o;ValidationTypes.isAny(e,"fill")&&(r=!0,t=!0);while(e.hasNext()&&i<s){t=ValidationTypes.isAny(e,n);if(!t)break;i++}r?t=!0:ValidationTypes.isAny(e,"fill");if(e.hasNext())throw o=e.next(),t?new ValidationError("Expected end of value but found '"+o+"'.",o.line,o.col):new ValidationError("Expected ([<number> | <percentage>]{1,4} && fill?) but found '"+o+"'.",o.line,o.col)},"border-image-source":"<image> | none","border-image-width":{multi:"<length> | <percentage> | <number> | auto",max:4},"border-left":"<border-width> || <border-style> || <color>","border-left-color":"<color> | inherit","border-left-style":"<border-style>","border-left-width":"<border-width>","border-radius":function(e){var t=!1,n="<length> | <percentage> | inherit",r=!1,i=!1,s=0,o=8,u;while(e.hasNext()&&s<o){t=ValidationTypes.isAny(e,n);if(!t){if(!(e.peek()=="/"&&s>0&&!r))break;r=!0,o=s+5,e.next()}s++}if(e.hasNext())throw u=e.next(),t?new ValidationError("Expected end of value but found '"+u+"'.",u.line,u.col):new ValidationError("Expected (<'border-radius'>) but found '"+u+"'.",u.line,u.col)},"border-right":"<border-width> || <border-style> || <color>","border-right-color":"<color> | inherit","border-right-style":"<border-style>","border-right-width":"<border-width>","border-spacing":{multi:"<length> | inherit",max:2},"border-style":{multi:"<border-style>",max:4},"border-top":"<border-width> || <border-style> || <color>","border-top-color":"<color> | inherit","border-top-left-radius":"<x-one-radius>","border-top-right-radius":"<x-one-radius>","border-top-style":"<border-style>","border-top-width":"<border-width>","border-width":{multi:"<border-width>",max:4},bottom:"<margin-width> | inherit","box-align":"start | end | center | baseline | stretch","box-decoration-break":"slice |clone","box-direction":"normal | reverse | inherit","box-flex":"<number>","box-flex-group":"<integer>","box-lines":"single | multiple","box-ordinal-group":"<integer>","box-orient":"horizontal | vertical | inline-axis | block-axis | inherit","box-pack":"start | end | center | justify","box-shadow":function(e){var t=!1,n;if(!ValidationTypes.isAny(e,"none"))Validation.multiProperty("<shadow>",e,!0,Infinity);else if(e.hasNext())throw n=e.next(),new ValidationError("Expected end of value but found '"+n+"'.",n.line,n.col)},"box-sizing":"content-box | border-box | inherit","break-after":"auto | always | avoid | left | right | page | column | avoid-page | avoid-column","break-before":"auto | always | avoid | left | right | page | column | avoid-page | avoid-column","break-inside":"auto | avoid | avoid-page | avoid-column","caption-side":"top | bottom | inherit",clear:"none | right | left | both | inherit",clip:1,color:"<color> | inherit","color-profile":1,"column-count":"<integer> | auto","column-fill":"auto | balance","column-gap":"<length> | normal","column-rule":"<border-width> || <border-style> || <color>","column-rule-color":"<color>","column-rule-style":"<border-style>","column-rule-width":"<border-width>","column-span":"none | all","column-width":"<length> | auto",columns:1,content:1,"counter-increment":1,"counter-reset":1,crop:"<shape> | auto",cue:"cue-after | cue-before | inherit","cue-after":1,"cue-before":1,cursor:1,direction:"ltr | rtl | inherit",display:"inline | block | list-item | inline-block | table | inline-table | table-row-group | table-header-group | table-footer-group | table-row | table-column-group | table-column | table-cell | table-caption | box | inline-box | grid | inline-grid | none | inherit | -moz-box | -moz-inline-block | -moz-inline-box | -moz-inline-grid | -moz-inline-stack | -moz-inline-table | -moz-grid | -moz-grid-group | -moz-grid-line | -moz-groupbox | -moz-deck | -moz-popup | -moz-stack | -moz-marker | -webkit-box | -webkit-inline-box","dominant-baseline":1,"drop-initial-after-adjust":"central | middle | after-edge | text-after-edge | ideographic | alphabetic | mathematical | <percentage> | <length>","drop-initial-after-align":"baseline | use-script | before-edge | text-before-edge | after-edge | text-after-edge | central | middle | ideographic | alphabetic | hanging | mathematical","drop-initial-before-adjust":"before-edge | text-before-edge | central | middle | hanging | mathematical | <percentage> | <length>","drop-initial-before-align":"caps-height | baseline | use-script | before-edge | text-before-edge | after-edge | text-after-edge | central | middle | ideographic | alphabetic | hanging | mathematical","drop-initial-size":"auto | line | <length> | <percentage>","drop-initial-value":"initial | <integer>",elevation:"<angle> | below | level | above | higher | lower | inherit","empty-cells":"show | hide | inherit",filter:1,fit:"fill | hidden | meet | slice","fit-position":1,"float":"left | right | none | inherit","float-offset":1,font:1,"font-family":1,"font-size":"<absolute-size> | <relative-size> | <length> | <percentage> | inherit","font-size-adjust":"<number> | none | inherit","font-stretch":"normal | ultra-condensed | extra-condensed | condensed | semi-condensed | semi-expanded | expanded | extra-expanded | ultra-expanded | inherit","font-style":"normal | italic | oblique | inherit","font-variant":"normal | small-caps | inherit","font-weight":"normal | bold | bolder | lighter | 100 | 200 | 300 | 400 | 500 | 600 | 700 | 800 | 900 | inherit","grid-cell-stacking":"columns | rows | layer","grid-column":1,"grid-columns":1,"grid-column-align":"start | end | center | stretch","grid-column-sizing":1,"grid-column-span":"<integer>","grid-flow":"none | rows | columns","grid-layer":"<integer>","grid-row":1,"grid-rows":1,"grid-row-align":"start | end | center | stretch","grid-row-span":"<integer>","grid-row-sizing":1,"hanging-punctuation":1,height:"<margin-width> | inherit","hyphenate-after":"<integer> | auto","hyphenate-before":"<integer> | auto","hyphenate-character":"<string> | auto","hyphenate-lines":"no-limit | <integer>","hyphenate-resource":1,hyphens:"none | manual | auto",icon:1,"image-orientation":"angle | auto","image-rendering":1,"image-resolution":1,"inline-box-align":"initial | last | <integer>",left:"<margin-width> | inherit","letter-spacing":"<length> | normal | inherit","line-height":"<number> | <length> | <percentage> | normal | inherit","line-break":"auto | loose | normal | strict","line-stacking":1,"line-stacking-ruby":"exclude-ruby | include-ruby","line-stacking-shift":"consider-shifts | disregard-shifts","line-stacking-strategy":"inline-line-height | block-line-height | max-height | grid-height","list-style":1,"list-style-image":"<uri> | none | inherit","list-style-position":"inside | outside | inherit","list-style-type":"disc | circle | square | decimal | decimal-leading-zero | lower-roman | upper-roman | lower-greek | lower-latin | upper-latin | armenian | georgian | lower-alpha | upper-alpha | none | inherit",margin:{multi:"<margin-width> | inherit",max:4},"margin-bottom":"<margin-width> | inherit","margin-left":"<margin-width> | inherit","margin-right":"<margin-width> | inherit","margin-top":"<margin-width> | inherit",mark:1,"mark-after":1,"mark-before":1,marks:1,"marquee-direction":1,"marquee-play-count":1,"marquee-speed":1,"marquee-style":1,"max-height":"<length> | <percentage> | none | inherit","max-width":"<length> | <percentage> | none | inherit","min-height":"<length> | <percentage> | inherit","min-width":"<length> | <percentage> | inherit","move-to":1,"nav-down":1,"nav-index":1,"nav-left":1,"nav-right":1,"nav-up":1,opacity:"<number> | inherit",orphans:"<integer> | inherit",outline:1,"outline-color":"<color> | invert | inherit","outline-offset":1,"outline-style":"<border-style> | inherit","outline-width":"<border-width> | inherit",overflow:"visible | hidden | scroll | auto | inherit","overflow-style":1,"overflow-x":1,"overflow-y":1,padding:{multi:"<padding-width> | inherit",max:4},"padding-bottom":"<padding-width> | inherit","padding-left":"<padding-width> | inherit","padding-right":"<padding-width> | inherit","padding-top":"<padding-width> | inherit",page:1,"page-break-after":"auto | always | avoid | left | right | inherit","page-break-before":"auto | always | avoid | left | right | inherit","page-break-inside":"auto | avoid | inherit","page-policy":1,pause:1,"pause-after":1,"pause-before":1,perspective:1,"perspective-origin":1,phonemes:1,pitch:1,"pitch-range":1,"play-during":1,"pointer-events":"auto | none | visiblePainted | visibleFill | visibleStroke | visible | painted | fill | stroke | all | inherit",position:"static | relative | absolute | fixed | inherit","presentation-level":1,"punctuation-trim":1,quotes:1,"rendering-intent":1,resize:1,rest:1,"rest-after":1,"rest-before":1,richness:1,right:"<margin-width> | inherit",rotation:1,"rotation-point":1,"ruby-align":1,"ruby-overhang":1,"ruby-position":1,"ruby-span":1,size:1,speak:"normal | none | spell-out | inherit","speak-header":"once | always | inherit","speak-numeral":"digits | continuous | inherit","speak-punctuation":"code | none | inherit","speech-rate":1,src:1,stress:1,"string-set":1,"table-layout":"auto | fixed | inherit","tab-size":"<integer> | <length>",target:1,"target-name":1,"target-new":1,"target-position":1,"text-align":"left | right | center | justify | inherit","text-align-last":1,"text-decoration":1,"text-emphasis":1,"text-height":1,"text-indent":"<length> | <percentage> | inherit","text-justify":"auto | none | inter-word | inter-ideograph | inter-cluster | distribute | kashida","text-outline":1,"text-overflow":1,"text-rendering":"auto | optimizeSpeed | optimizeLegibility | geometricPrecision | inherit","text-shadow":1,"text-transform":"capitalize | uppercase | lowercase | none | inherit","text-wrap":"normal | none | avoid",top:"<margin-width> | inherit",transform:1,"transform-origin":1,"transform-style":1,transition:1,"transition-delay":1,"transition-duration":1,"transition-property":1,"transition-timing-function":1,"unicode-bidi":"normal | embed | bidi-override | inherit","user-modify":"read-only | read-write | write-only | inherit","user-select":"none | text | toggle | element | elements | all | inherit","vertical-align":"auto | use-script | baseline | sub | super | top | text-top | central | middle | bottom | text-bottom | <percentage> | <length>",visibility:"visible | hidden | collapse | inherit","voice-balance":1,"voice-duration":1,"voice-family":1,"voice-pitch":1,"voice-pitch-range":1,"voice-rate":1,"voice-stress":1,"voice-volume":1,volume:1,"white-space":"normal | pre | nowrap | pre-wrap | pre-line | inherit | -pre-wrap | -o-pre-wrap | -moz-pre-wrap | -hp-pre-wrap","white-space-collapse":1,widows:"<integer> | inherit",width:"<length> | <percentage> | auto | inherit","word-break":"normal | keep-all | break-all","word-spacing":"<length> | normal | inherit","word-wrap":1,"z-index":"<integer> | auto | inherit",zoom:"<number> | <percentage> | normal"};PropertyName.prototype=new SyntaxUnit,PropertyName.prototype.constructor=PropertyName,PropertyName.prototype.toString=function(){return(this.hack?this.hack:"")+this.text},PropertyValue.prototype=new SyntaxUnit,PropertyValue.prototype.constructor=PropertyValue,PropertyValueIterator.prototype.count=function(){return this._parts.length},PropertyValueIterator.prototype.isFirst=function(){return this._i===0},PropertyValueIterator.prototype.hasNext=function(){return this._i<this._parts.length},PropertyValueIterator.prototype.mark=function(){this._marks.push(this._i)},PropertyValueIterator.prototype.peek=function(e){return this.hasNext()?this._parts[this._i+(e||0)]:null},PropertyValueIterator.prototype.next=function(){return this.hasNext()?this._parts[this._i++]:null},PropertyValueIterator.prototype.previous=function(){return this._i>0?this._parts[--this._i]:null},PropertyValueIterator.prototype.restore=function(){this._marks.length&&(this._i=this._marks.pop())},PropertyValuePart.prototype=new SyntaxUnit,PropertyValuePart.prototype.constructor=PropertyValuePart,PropertyValuePart.fromToken=function(e){return new PropertyValuePart(e.value,e.startLine,e.startCol)};var Pseudos={":first-letter":1,":first-line":1,":before":1,":after":1};Pseudos.ELEMENT=1,Pseudos.CLASS=2,Pseudos.isElement=function(e){return e.indexOf("::")===0||Pseudos[e.toLowerCase()]==Pseudos.ELEMENT},Selector.prototype=new SyntaxUnit,Selector.prototype.constructor=Selector,SelectorPart.prototype=new SyntaxUnit,SelectorPart.prototype.constructor=SelectorPart,SelectorSubPart.prototype=new SyntaxUnit,SelectorSubPart.prototype.constructor=SelectorSubPart,Specificity.prototype={constructor:Specificity,compare:function(e){var t=["a","b","c","d"],n,r;for(n=0,r=t.length;n<r;n++){if(this[t[n]]<e[t[n]])return-1;if(this[t[n]]>e[t[n]])return 1}return 0},valueOf:function(){return this.a*1e3+this.b*100+this.c*10+this.d},toString:function(){return this.a+","+this.b+","+this.c+","+this.d}},Specificity.calculate=function(e){function u(e){var t,n,r,a,f=e.elementName?e.elementName.text:"",l;f&&f.charAt(f.length-1)!="*"&&o++;for(t=0,r=e.modifiers.length;t<r;t++){l=e.modifiers[t];switch(l.type){case"class":case"attribute":s++;break;case"id":i++;break;case"pseudo":Pseudos.isElement(l.text)?o++:s++;break;case"not":for(n=0,a=l.args.length;n<a;n++)u(l.args[n])}}}var t,n,r,i=0,s=0,o=0;for(t=0,n=e.parts.length;t<n;t++)r=e.parts[t],r instanceof SelectorPart&&u(r);return new Specificity(0,i,s,o)};var h=/^[0-9a-fA-F]$/,nonascii=/^[\u0080-\uFFFF]$/,nl=/\n|\r\n|\r|\f/;TokenStream.prototype=mix(new TokenStreamBase,{_getToken:function(e){var t,n=this._reader,r=null,i=n.getLine(),s=n.getCol();t=n.read();while(t){switch(t){case"/":n.peek()=="*"?r=this.commentToken(t,i,s):r=this.charToken(t,i,s);break;case"|":case"~":case"^":case"$":case"*":n.peek()=="="?r=this.comparisonToken(t,i,s):r=this.charToken(t,i,s);break;case'"':case"'":r=this.stringToken(t,i,s);break;case"#":isNameChar(n.peek())?r=this.hashToken(t,i,s):r=this.charToken(t,i,s);break;case".":isDigit(n.peek())?r=this.numberToken(t,i,s):r=this.charToken(t,i,s);break;case"-":n.peek()=="-"?r=this.htmlCommentEndToken(t,i,s):isNameStart(n.peek())?r=this.identOrFunctionToken(t,i,s):r=this.charToken(t,i,s);break;case"!":r=this.importantToken(t,i,s);break;case"@":r=this.atRuleToken(t,i,s);break;case":":r=this.notToken(t,i,s);break;case"<":r=this.htmlCommentStartToken(t,i,s);break;case"U":case"u":if(n.peek()=="+"){r=this.unicodeRangeToken(t,i,s);break};default:isDigit(t)?r=this.numberToken(t,i,s):isWhitespace(t)?r=this.whitespaceToken(t,i,s):isIdentStart(t)?r=this.identOrFunctionToken(t,i,s):r=this.charToken(t,i,s)}break}return!r&&t===null&&(r=this.createToken(Tokens.EOF,null,i,s)),r},createToken:function(e,t,n,r,i){var s=this._reader;return i=i||{},{value:t,type:e,channel:i.channel,hide:i.hide||!1,startLine:n,startCol:r,endLine:s.getLine(),endCol:s.getCol()}},atRuleToken:function(e,t,n){var r=e,i=this._reader,s=Tokens.CHAR,o=!1,u,a;i.mark(),u=this.readName(),r=e+u,s=Tokens.type(r.toLowerCase());if(s==Tokens.CHAR||s==Tokens.UNKNOWN)r.length>1?s=Tokens.UNKNOWN_SYM:(s=Tokens.CHAR,r=e,i.reset());return this.createToken(s,r,t,n)},charToken:function(e,t,n){var r=Tokens.type(e);return r==-1&&(r=Tokens.CHAR),this.createToken(r,e,t,n)},commentToken:function(e,t,n){var r=this._reader,i=this.readComment(e);return this.createToken(Tokens.COMMENT,i,t,n)},comparisonToken:function(e,t,n){var r=this._reader,i=e+r.read(),s=Tokens.type(i)||Tokens.CHAR;return this.createToken(s,i,t,n)},hashToken:function(e,t,n){var r=this._reader,i=this.readName(e);return this.createToken(Tokens.HASH,i,t,n)},htmlCommentStartToken:function(e,t,n){var r=this._reader,i=e;return r.mark(),i+=r.readCount(3),i=="<!--"?this.createToken(Tokens.CDO,i,t,n):(r.reset(),this.charToken(e,t,n))},htmlCommentEndToken:function(e,t,n){var r=this._reader,i=e;return r.mark(),i+=r.readCount(2),i=="-->"?this.createToken(Tokens.CDC,i,t,n):(r.reset(),this.charToken(e,t,n))},identOrFunctionToken:function(e,t,n){var r=this._reader,i=this.readName(e),s=Tokens.IDENT;return r.peek()=="("?(i+=r.read(),i.toLowerCase()=="url("?(s=Tokens.URI,i=this.readURI(i),i.toLowerCase()=="url("&&(s=Tokens.FUNCTION)):s=Tokens.FUNCTION):r.peek()==":"&&i.toLowerCase()=="progid"&&(i+=r.readTo("("),s=Tokens.IE_FUNCTION),this.createToken(s,i,t,n)},importantToken:function(e,t,n){var r=this._reader,i=e,s=Tokens.CHAR,o,u;r.mark(),u=r.read();while(u){if(u=="/"){if(r.peek()!="*")break;o=this.readComment(u);if(o==="")break}else{if(!isWhitespace(u)){if(/i/i.test(u)){o=r.readCount(8),/mportant/i.test(o)&&(i+=u+o,s=Tokens.IMPORTANT_SYM);break}break}i+=u+this.readWhitespace()}u=r.read()}return s==Tokens.CHAR?(r.reset(),this.charToken(e,t,n)):this.createToken(s,i,t,n)},notToken:function(e,t,n){var r=this._reader,i=e;return r.mark(),i+=r.readCount(4),i.toLowerCase()==":not("?this.createToken(Tokens.NOT,i,t,n):(r.reset(),this.charToken(e,t,n))},numberToken:function(e,t,n){var r=this._reader,i=this.readNumber(e),s,o=Tokens.NUMBER,u=r.peek();return isIdentStart(u)?(s=this.readName(r.read()),i+=s,/^em$|^ex$|^px$|^gd$|^rem$|^vw$|^vh$|^vm$|^ch$|^cm$|^mm$|^in$|^pt$|^pc$/i.test(s)?o=Tokens.LENGTH:/^deg|^rad$|^grad$/i.test(s)?o=Tokens.ANGLE:/^ms$|^s$/i.test(s)?o=Tokens.TIME:/^hz$|^khz$/i.test(s)?o=Tokens.FREQ:/^dpi$|^dpcm$/i.test(s)?o=Tokens.RESOLUTION:o=Tokens.DIMENSION):u=="%"&&(i+=r.read(),o=Tokens.PERCENTAGE),this.createToken(o,i,t,n)},stringToken:function(e,t,n){var r=e,i=e,s=this._reader,o=e,u=Tokens.STRING,a=s.read();while(a){i+=a;if(a==r&&o!="\\")break;if(isNewLine(s.peek())&&a!="\\"){u=Tokens.INVALID;break}o=a,a=s.read()}return a===null&&(u=Tokens.INVALID),this.createToken(u,i,t,n)},unicodeRangeToken:function(e,t,n){var r=this._reader,i=e,s,o=Tokens.CHAR;return r.peek()=="+"&&(r.mark(),i+=r.read(),i+=this.readUnicodeRangePart(!0),i.length==2?r.reset():(o=Tokens.UNICODE_RANGE,i.indexOf("?")==-1&&r.peek()=="-"&&(r.mark(),s=r.read(),s+=this.readUnicodeRangePart(!1),s.length==1?r.reset():i+=s))),this.createToken(o,i,t,n)},whitespaceToken:function(e,t,n){var r=this._reader,i=e+this.readWhitespace();return this.createToken(Tokens.S,i,t,n)},readUnicodeRangePart:function(e){var t=this._reader,n="",r=t.peek();while(isHexDigit(r)&&n.length<6)t.read(),n+=r,r=t.peek();if(e)while(r=="?"&&n.length<6)t.read(),n+=r,r=t.peek();return n},readWhitespace:function(){var e=this._reader,t="",n=e.peek();while(isWhitespace(n))e.read(),t+=n,n=e.peek();return t},readNumber:function(e){var t=this._reader,n=e,r=e==".",i=t.peek();while(i){if(isDigit(i))n+=t.read();else{if(i!=".")break;if(r)break;r=!0,n+=t.read()}i=t.peek()}return n},readString:function(){var e=this._reader,t=e.read(),n=t,r=t,i=e.peek();while(i){i=e.read(),n+=i;if(i==t&&r!="\\")break;if(isNewLine(e.peek())&&i!="\\"){n="";break}r=i,i=e.peek()}return i===null&&(n=""),n},readURI:function(e){var t=this._reader,n=e,r="",i=t.peek();t.mark();while(i&&isWhitespace(i))t.read(),i=t.peek();i=="'"||i=='"'?r=this.readString():r=this.readURL(),i=t.peek();while(i&&isWhitespace(i))t.read(),i=t.peek();return r===""||i!=")"?(n=e,t.reset()):n+=r+t.read(),n},readURL:function(){var e=this._reader,t="",n=e.peek();while(/^[!#$%&\\*-~]$/.test(n))t+=e.read(),n=e.peek();return t},readName:function(e){var t=this._reader,n=e||"",r=t.peek();for(;;)if(r=="\\")n+=this.readEscape(t.read()),r=t.peek();else{if(!r||!isNameChar(r))break;n+=t.read(),r=t.peek()}return n},readEscape:function(e){var t=this._reader,n=e||"",r=0,i=t.peek();if(isHexDigit(i))do n+=t.read(),i=t.peek();while(i&&isHexDigit(i)&&++r<6);return n.length==3&&/\s/.test(i)||n.length==7||n.length==1?t.read():i="",n+i},readComment:function(e){var t=this._reader,n=e||"",r=t.read();if(r=="*"){while(r){n+=r;if(n.length>2&&r=="*"&&t.peek()=="/"){n+=t.read();break}r=t.read()}return n}return""}});var Tokens=[{name:"CDO"},{name:"CDC"},{name:"S",whitespace:!0},{name:"COMMENT",comment:!0,hide:!0,channel:"comment"},{name:"INCLUDES",text:"~="},{name:"DASHMATCH",text:"|="},{name:"PREFIXMATCH",text:"^="},{name:"SUFFIXMATCH",text:"$="},{name:"SUBSTRINGMATCH",text:"*="},{name:"STRING"},{name:"IDENT"},{name:"HASH"},{name:"IMPORT_SYM",text:"@import"},{name:"PAGE_SYM",text:"@page"},{name:"MEDIA_SYM",text:"@media"},{name:"FONT_FACE_SYM",text:"@font-face"},{name:"CHARSET_SYM",text:"@charset"},{name:"NAMESPACE_SYM",text:"@namespace"},{name:"VIEWPORT_SYM",text:"@viewport"},{name:"UNKNOWN_SYM"},{name:"KEYFRAMES_SYM",text:["@keyframes","@-webkit-keyframes","@-moz-keyframes","@-o-keyframes"]},{name:"IMPORTANT_SYM"},{name:"LENGTH"},{name:"ANGLE"},{name:"TIME"},{name:"FREQ"},{name:"DIMENSION"},{name:"PERCENTAGE"},{name:"NUMBER"},{name:"URI"},{name:"FUNCTION"},{name:"UNICODE_RANGE"},{name:"INVALID"},{name:"PLUS",text:"+"},{name:"GREATER",text:">"},{name:"COMMA",text:","},{name:"TILDE",text:"~"},{name:"NOT"},{name:"TOPLEFTCORNER_SYM",text:"@top-left-corner"},{name:"TOPLEFT_SYM",text:"@top-left"},{name:"TOPCENTER_SYM",text:"@top-center"},{name:"TOPRIGHT_SYM",text:"@top-right"},{name:"TOPRIGHTCORNER_SYM",text:"@top-right-corner"},{name:"BOTTOMLEFTCORNER_SYM",text:"@bottom-left-corner"},{name:"BOTTOMLEFT_SYM",text:"@bottom-left"},{name:"BOTTOMCENTER_SYM",text:"@bottom-center"},{name:"BOTTOMRIGHT_SYM",text:"@bottom-right"},{name:"BOTTOMRIGHTCORNER_SYM",text:"@bottom-right-corner"},{name:"LEFTTOP_SYM",text:"@left-top"},{name:"LEFTMIDDLE_SYM",text:"@left-middle"},{name:"LEFTBOTTOM_SYM",text:"@left-bottom"},{name:"RIGHTTOP_SYM",text:"@right-top"},{name:"RIGHTMIDDLE_SYM",text:"@right-middle"},{name:"RIGHTBOTTOM_SYM",text:"@right-bottom"},{name:"RESOLUTION",state:"media"},{name:"IE_FUNCTION"},{name:"CHAR"},{name:"PIPE",text:"|"},{name:"SLASH",text:"/"},{name:"MINUS",text:"-"},{name:"STAR",text:"*"},{name:"LBRACE",text:"{"},{name:"RBRACE",text:"}"},{name:"LBRACKET",text:"["},{name:"RBRACKET",text:"]"},{name:"EQUALS",text:"="},{name:"COLON",text:":"},{name:"SEMICOLON",text:";"},{name:"LPAREN",text:"("},{name:"RPAREN",text:")"},{name:"DOT",text:"."}];(function(){var e=[],t={};Tokens.UNKNOWN=-1,Tokens.unshift({name:"EOF"});for(var n=0,r=Tokens.length;n<r;n++){e.push(Tokens[n].name),Tokens[Tokens[n].name]=n;if(Tokens[n].text)if(Tokens[n].text instanceof Array)for(var i=0;i<Tokens[n].text.length;i++)t[Tokens[n].text[i]]=n;else t[Tokens[n].text]=n}Tokens.name=function(t){return e[t]},Tokens.type=function(e){return t[e]||-1}})();var Validation={validate:function(e,t){var n=e.toString().toLowerCase(),r=t.parts,i=new PropertyValueIterator(t),s=Properties[n],o,u,a,f,l,c,h,p,d,v,m;if(!s){if(n.indexOf("-")!==0)throw new ValidationError("Unknown property '"+e+"'.",e.line,e.col)}else typeof s!="number"&&(typeof s=="string"?s.indexOf("||")>-1?this.groupProperty(s,i):this.singleProperty(s,i,1):s.multi?this.multiProperty(s.multi,i,s.comma,s.max||Infinity):typeof s=="function"&&s(i))},singleProperty:function(e,t,n,r){var i=!1,s=t.value,o=0,u;while(t.hasNext()&&o<n){i=ValidationTypes.isAny(t,e);if(!i)break;o++}if(!i)throw t.hasNext()&&!t.isFirst()?(u=t.peek(),new ValidationError("Expected end of value but found '"+u+"'.",u.line,u.col)):new ValidationError("Expected ("+e+") but found '"+s+"'.",s.line,s.col);if(t.hasNext())throw u=t.next(),new ValidationError("Expected end of value but found '"+u+"'.",u.line,u.col)},multiProperty:function(e,t,n,r){var i=!1,s=t.value,o=0,u=!1,a;while(t.hasNext()&&!i&&o<r){if(!ValidationTypes.isAny(t,e))break;o++;if(!t.hasNext())i=!0;else if(n){if(t.peek()!=",")break;a=t.next()}}if(!i)throw t.hasNext()&&!t.isFirst()?(a=t.peek(),new ValidationError("Expected end of value but found '"+a+"'.",a.line,a.col)):(a=t.previous(),n&&a==","?new ValidationError("Expected end of value but found '"+a+"'.",a.line,a.col):new ValidationError("Expected ("+e+") but found '"+s+"'.",s.line,s.col));if(t.hasNext())throw a=t.next(),new ValidationError("Expected end of value but found '"+a+"'.",a.line,a.col)},groupProperty:function(e,t,n){var r=!1,i=t.value,s=e.split("||").length,o={count:0},u=!1,a,f;while(t.hasNext()&&!r){a=ValidationTypes.isAnyOfGroup(t,e);if(!a)break;if(o[a])break;o[a]=1,o.count++,u=!0;if(o.count==s||!t.hasNext())r=!0}if(!r)throw u&&t.hasNext()?(f=t.peek(),new ValidationError("Expected end of value but found '"+f+"'.",f.line,f.col)):new ValidationError("Expected ("+e+") but found '"+i+"'.",i.line,i.col);if(t.hasNext())throw f=t.next(),new ValidationError("Expected end of value but found '"+f+"'.",f.line,f.col)}};ValidationError.prototype=new Error;var ValidationTypes={isLiteral:function(e,t){var n=e.text.toString().toLowerCase(),r=t.split(" | "),i,s,o=!1;for(i=0,s=r.length;i<s&&!o;i++)n==r[i].toLowerCase()&&(o=!0);return o},isSimple:function(e){return!!this.simple[e]},isComplex:function(e){return!!this.complex[e]},isAny:function(e,t){var n=t.split(" | "),r,i,s=!1;for(r=0,i=n.length;r<i&&!s&&e.hasNext();r++)s=this.isType(e,n[r]);return s},isAnyOfGroup:function(e,t){var n=t.split(" || "),r,i,s=!1;for(r=0,i=n.length;r<i&&!s;r++)s=this.isType(e,n[r]);return s?n[r-1]:!1},isType:function(e,t){var n=e.peek(),r=!1;return t.charAt(0)!="<"?(r=this.isLiteral(n,t),r&&e.next()):this.simple[t]?(r=this.simple[t](n),r&&e.next()):r=this.complex[t](e),r},simple:{"<absolute-size>":function(e){return ValidationTypes.isLiteral(e,"xx-small | x-small | small | medium | large | x-large | xx-large")},"<attachment>":function(e){return ValidationTypes.isLiteral(e,"scroll | fixed | local")},"<attr>":function(e){return e.type=="function"&&e.name=="attr"},"<bg-image>":function(e){return this["<image>"](e)||this["<gradient>"](e)||e=="none"},"<gradient>":function(e){return e.type=="function"&&/^(?:\-(?:ms|moz|o|webkit)\-)?(?:repeating\-)?(?:radial\-|linear\-)?gradient/i.test(e)},"<box>":function(e){return ValidationTypes.isLiteral(e,"padding-box | border-box | content-box")},"<content>":function(e){return e.type=="function"&&e.name=="content"},"<relative-size>":function(e){return ValidationTypes.isLiteral(e,"smaller | larger")},"<ident>":function(e){return e.type=="identifier"},"<length>":function(e){return e.type=="function"&&/^(?:\-(?:ms|moz|o|webkit)\-)?calc/i.test(e)?!0:e.type=="length"||e.type=="number"||e.type=="integer"||e=="0"},"<color>":function(e){return e.type=="color"||e=="transparent"},"<number>":function(e){return e.type=="number"||this["<integer>"](e)},"<integer>":function(e){return e.type=="integer"},"<line>":function(e){return e.type=="integer"},"<angle>":function(e){return e.type=="angle"},"<uri>":function(e){return e.type=="uri"},"<image>":function(e){return this["<uri>"](e)},"<percentage>":function(e){return e.type=="percentage"||e=="0"},"<border-width>":function(e){return this["<length>"](e)||ValidationTypes.isLiteral(e,"thin | medium | thick")},"<border-style>":function(e){return ValidationTypes.isLiteral(e,"none | hidden | dotted | dashed | solid | double | groove | ridge | inset | outset")},"<margin-width>":function(e){return this["<length>"](e)||this["<percentage>"](e)||ValidationTypes.isLiteral(e,"auto")},"<padding-width>":function(e){return this["<length>"](e)||this["<percentage>"](e)},"<shape>":function(e){return e.type=="function"&&(e.name=="rect"||e.name=="inset-rect")},"<time>":function(e){return e.type=="time"}},complex:{"<bg-position>":function(e){var t=this,n=!1,r="<percentage> | <length>",i="left | right",s="top | bottom",o=0,u=function(){return e.hasNext()&&e.peek()!=","};while(e.peek(o)&&e.peek(o)!=",")o++;return o<3?ValidationTypes.isAny(e,i+" | center | "+r)?(n=!0,ValidationTypes.isAny(e,s+" | center | "+r)):ValidationTypes.isAny(e,s)&&(n=!0,ValidationTypes.isAny(e,i+" | center")):ValidationTypes.isAny(e,i)?ValidationTypes.isAny(e,s)?(n=!0,ValidationTypes.isAny(e,r)):ValidationTypes.isAny(e,r)&&(ValidationTypes.isAny(e,s)?(n=!0,ValidationTypes.isAny(e,r)):ValidationTypes.isAny(e,"center")&&(n=!0)):ValidationTypes.isAny(e,s)?ValidationTypes.isAny(e,i)?(n=!0,ValidationTypes.isAny(e,r)):ValidationTypes.isAny(e,r)&&(ValidationTypes.isAny(e,i)?(n=!0,ValidationTypes.isAny(e,r)):ValidationTypes.isAny(e,"center")&&(n=!0)):ValidationTypes.isAny(e,"center")&&ValidationTypes.isAny(e,i+" | "+s)&&(n=!0,ValidationTypes.isAny(e,r)),n},"<bg-size>":function(e){var t=this,n=!1,r="<percentage> | <length> | auto",i,s,o;return ValidationTypes.isAny(e,"cover | contain")?n=!0:ValidationTypes.isAny(e,r)&&(n=!0,ValidationTypes.isAny(e,r)),n},"<repeat-style>":function(e){var t=!1,n="repeat | space | round | no-repeat",r;return e.hasNext()&&(r=e.next(),ValidationTypes.isLiteral(r,"repeat-x | repeat-y")?t=!0:ValidationTypes.isLiteral(r,n)&&(t=!0,e.hasNext()&&ValidationTypes.isLiteral(e.peek(),n)&&e.next())),t},"<shadow>":function(e){var t=!1,n=0,r=!1,i=!1,s;if(e.hasNext()){ValidationTypes.isAny(e,"inset")&&(r=!0),ValidationTypes.isAny(e,"<color>")&&(i=!0);while(ValidationTypes.isAny(e,"<length>")&&n<4)n++;e.hasNext()&&(i||ValidationTypes.isAny(e,"<color>"),r||ValidationTypes.isAny(e,"inset")),t=n>=2&&n<=4}return t},"<x-one-radius>":function(e){var t=!1,n="<length> | <percentage> | inherit";return ValidationTypes.isAny(e,n)&&(t=!0,ValidationTypes.isAny(e,n)),t}}};parserlib.css={Colors:Colors,Combinator:Combinator,Parser:Parser,PropertyName:PropertyName,PropertyValue:PropertyValue,PropertyValuePart:PropertyValuePart,MediaFeature:MediaFeature,MediaQuery:MediaQuery,Selector:Selector,SelectorPart:SelectorPart,SelectorSubPart:SelectorSubPart,Specificity:Specificity,TokenStream:TokenStream,Tokens:Tokens,ValidationError:ValidationError}}(),function(){for(var e in parserlib)exports[e]=parserlib[e]}();var CSSLint=function(){function i(e,t){var r,i=e&&e.match(n),s=i&&i[1];return s&&(r={"true":2,"":1,"false":0,2:2,1:1,0:0},s.toLowerCase().split(",").forEach(function(e){var n=e.split(":"),i=n[0]||"",s=n[1]||"";t[i.trim()]=r[s.trim()]})),t}var e=[],t=[],n=/\/\*csslint([^\*]*)\*\//,r=new parserlib.util.EventTarget;return r.version="0.10.0",r.addRule=function(t){e.push(t),e[t.id]=t},r.clearRules=function(){e=[]},r.getRules=function(){return[].concat(e).sort(function(e,t){return e.id>t.id?1:0})},r.getRuleset=function(){var t={},n=0,r=e.length;while(n<r)t[e[n++].id]=1;return t},r.addFormatter=function(e){t[e.id]=e},r.getFormatter=function(e){return t[e]},r.format=function(e,t,n,r){var i=this.getFormatter(n),s=null;return i&&(s=i.startFormat(),s+=i.formatResults(e,t,r||{}),s+=i.endFormat()),s},r.hasFormat=function(e){return t.hasOwnProperty(e)},r.verify=function(t,r){var s=0,o=e.length,u,a,f,l=new parserlib.css.Parser({starHack:!0,ieFilters:!0,underscoreHack:!0,strict:!1});a=t.replace(/\n\r?/g,"$split$").split("$split$"),r||(r=this.getRuleset()),n.test(t)&&(r=i(t,r)),u=new Reporter(a,r),r.errors=2;for(s in r)r.hasOwnProperty(s)&&r[s]&&e[s]&&e[s].init(l,u);try{l.parse(t)}catch(c){u.error("Fatal error, cannot continue: "+c.message,c.line,c.col,{})}return f={messages:u.messages,stats:u.stats,ruleset:u.ruleset},f.messages.sort(function(e,t){return e.rollup&&!t.rollup?1:!e.rollup&&t.rollup?-1:e.line-t.line}),f},r}();Reporter.prototype={constructor:Reporter,error:function(e,t,n,r){this.messages.push({type:"error",line:t,col:n,message:e,evidence:this.lines[t-1],rule:r||{}})},warn:function(e,t,n,r){this.report(e,t,n,r)},report:function(e,t,n,r){this.messages.push({type:this.ruleset[r.id]==2?"error":"warning",line:t,col:n,message:e,evidence:this.lines[t-1],rule:r})},info:function(e,t,n,r){this.messages.push({type:"info",line:t,col:n,message:e,evidence:this.lines[t-1],rule:r})},rollupError:function(e,t){this.messages.push({type:"error",rollup:!0,message:e,rule:t})},rollupWarn:function(e,t){this.messages.push({type:"warning",rollup:!0,message:e,rule:t})},stat:function(e,t){this.stats[e]=t}},CSSLint._Reporter=Reporter,CSSLint.Util={mix:function(e,t){var n;for(n in t)t.hasOwnProperty(n)&&(e[n]=t[n]);return n},indexOf:function(e,t){if(e.indexOf)return e.indexOf(t);for(var n=0,r=e.length;n<r;n++)if(e[n]===t)return n;return-1},forEach:function(e,t){if(e.forEach)return e.forEach(t);for(var n=0,r=e.length;n<r;n++)t(e[n],n,e)}},CSSLint.addRule({id:"adjoining-classes",name:"Disallow adjoining classes",desc:"Don't use adjoining classes.",browsers:"IE6",init:function(e,t){var n=this;e.addListener("startrule",function(r){var i=r.selectors,s,o,u,a,f,l,c;for(f=0;f<i.length;f++){s=i[f];for(l=0;l<s.parts.length;l++){o=s.parts[l];if(o.type==e.SELECTOR_PART_TYPE){a=0;for(c=0;c<o.modifiers.length;c++)u=o.modifiers[c],u.type=="class"&&a++,a>1&&t.report("Don't use adjoining classes.",o.line,o.col,n)}}}})}}),CSSLint.addRule({id:"box-model",name:"Beware of broken box size",desc:"Don't use width or height when using padding or border.",browsers:"All",init:function(e,t){function u(){s={},o=!1}function a(){var e,u;if(!o){if(s.height)for(e in i)i.hasOwnProperty(e)&&s[e]&&(u=s[e].value,(e!="padding"||u.parts.length!==2||u.parts[0].value!==0)&&t.report("Using height with "+e+" can sometimes make elements larger than you expect.",s[e].line,s[e].col,n));if(s.width)for(e in r)r.hasOwnProperty(e)&&s[e]&&(u=s[e].value,(e!="padding"||u.parts.length!==2||u.parts[1].value!==0)&&t.report("Using width with "+e+" can sometimes make elements larger than you expect.",s[e].line,s[e].col,n))}}var n=this,r={border:1,"border-left":1,"border-right":1,padding:1,"padding-left":1,"padding-right":1},i={border:1,"border-bottom":1,"border-top":1,padding:1,"padding-bottom":1,"padding-top":1},s,o=!1;e.addListener("startrule",u),e.addListener("startfontface",u),e.addListener("startpage",u),e.addListener("startpagemargin",u),e.addListener("startkeyframerule",u),e.addListener("property",function(e){var t=e.property.text.toLowerCase();i[t]||r[t]?!/^0\S*$/.test(e.value)&&(t!="border"||e.value!="none")&&(s[t]={line:e.property.line,col:e.property.col,value:e.value}):/^(width|height)/i.test(t)&&/^(length|percentage)/.test(e.value.parts[0].type)?s[t]=1:t=="box-sizing"&&(o=!0)}),e.addListener("endrule",a),e.addListener("endfontface",a),e.addListener("endpage",a),e.addListener("endpagemargin",a),e.addListener("endkeyframerule",a)}}),CSSLint.addRule({id:"box-sizing",name:"Disallow use of box-sizing",desc:"The box-sizing properties isn't supported in IE6 and IE7.",browsers:"IE6, IE7",tags:["Compatibility"],init:function(e,t){var n=this;e.addListener("property",function(e){var r=e.property.text.toLowerCase();r=="box-sizing"&&t.report("The box-sizing property isn't supported in IE6 and IE7.",e.line,e.col,n)})}}),CSSLint.addRule({id:"bulletproof-font-face",name:"Use the bulletproof @font-face syntax",desc:"Use the bulletproof @font-face syntax to avoid 404's in old IE (http://www.fontspring.com/blog/the-new-bulletproof-font-face-syntax).",browsers:"All",init:function(e,t){var n=this,r=0,i=!1,s=!0,o=!1,u,a;e.addListener("startfontface",function(e){i=!0}),e.addListener("property",function(e){if(!i)return;var t=e.property.toString().toLowerCase(),n=e.value.toString();u=e.line,a=e.col;if(t==="src"){var r=/^\s?url\(['"].+\.eot\?.*['"]\)\s*format\(['"]embedded-opentype['"]\).*$/i;!n.match(r)&&s?(o=!0,s=!1):n.match(r)&&!s&&(o=!1)}}),e.addListener("endfontface",function(e){i=!1,o&&t.report("@font-face declaration doesn't follow the fontspring bulletproof syntax.",u,a,n)})}}),CSSLint.addRule({id:"compatible-vendor-prefixes",name:"Require compatible vendor prefixes",desc:"Include all compatible vendor prefixes to reach a wider range of users.",browsers:"All",init:function(e,t){var n=this,r,i,s,o,u,a,f,l=!1,c=Array.prototype.push,h=[];r={animation:"webkit moz","animation-delay":"webkit moz","animation-direction":"webkit moz","animation-duration":"webkit moz","animation-fill-mode":"webkit moz","animation-iteration-count":"webkit moz","animation-name":"webkit moz","animation-play-state":"webkit moz","animation-timing-function":"webkit moz",appearance:"webkit moz","border-end":"webkit moz","border-end-color":"webkit moz","border-end-style":"webkit moz","border-end-width":"webkit moz","border-image":"webkit moz o","border-radius":"webkit","border-start":"webkit moz","border-start-color":"webkit moz","border-start-style":"webkit moz","border-start-width":"webkit moz","box-align":"webkit moz ms","box-direction":"webkit moz ms","box-flex":"webkit moz ms","box-lines":"webkit ms","box-ordinal-group":"webkit moz ms","box-orient":"webkit moz ms","box-pack":"webkit moz ms","box-sizing":"webkit moz","box-shadow":"webkit moz","column-count":"webkit moz ms","column-gap":"webkit moz ms","column-rule":"webkit moz ms","column-rule-color":"webkit moz ms","column-rule-style":"webkit moz ms","column-rule-width":"webkit moz ms","column-width":"webkit moz ms",hyphens:"epub moz","line-break":"webkit ms","margin-end":"webkit moz","margin-start":"webkit moz","marquee-speed":"webkit wap","marquee-style":"webkit wap","padding-end":"webkit moz","padding-start":"webkit moz","tab-size":"moz o","text-size-adjust":"webkit ms",transform:"webkit moz ms o","transform-origin":"webkit moz ms o",transition:"webkit moz o","transition-delay":"webkit moz o","transition-duration":"webkit moz o","transition-property":"webkit moz o","transition-timing-function":"webkit moz o","user-modify":"webkit moz","user-select":"webkit moz ms","word-break":"epub ms","writing-mode":"epub ms"};for(s in r)if(r.hasOwnProperty(s)){o=[],u=r[s].split(" ");for(a=0,f=u.length;a<f;a++)o.push("-"+u[a]+"-"+s);r[s]=o,c.apply(h,o)}e.addListener("startrule",function(){i=[]}),e.addListener("startkeyframes",function(e){l=e.prefix||!0}),e.addListener("endkeyframes",function(e){l=!1}),e.addListener("property",function(e){var t=e.property;CSSLint.Util.indexOf(h,t.text)>-1&&(!l||typeof l!="string"||t.text.indexOf("-"+l+"-")!==0)&&i.push(t)}),e.addListener("endrule",function(e){if(!i.length)return;var s={},o,u,a,f,l,c,h,p,d,v;for(o=0,u=i.length;o<u;o++){a=i[o];for(f in r)r.hasOwnProperty(f)&&(l=r[f],CSSLint.Util.indexOf(l,a.text)>-1&&(s[f]||(s[f]={full:l.slice(0),actual:[],actualNodes:[]}),CSSLint.Util.indexOf(s[f].actual,a.text)===-1&&(s[f].actual.push(a.text),s[f].actualNodes.push(a))))}for(f in s)if(s.hasOwnProperty(f)){c=s[f],h=c.full,p=c.actual;if(h.length>p.length)for(o=0,u=h.length;o<u;o++)d=h[o],CSSLint.Util.indexOf(p,d)===-1&&(v=p.length===1?p[0]:p.length==2?p.join(" and "):p.join(", "),t.report("The property "+d+" is compatible with "+v+" and should be included as well.",c.actualNodes[0].line,c.actualNodes[0].col,n))}})}}),CSSLint.addRule({id:"display-property-grouping",name:"Require properties appropriate for display",desc:"Certain properties shouldn't be used with certain display property values.",browsers:"All",init:function(e,t){function s(e,s,o){i[e]&&(typeof r[e]!="string"||i[e].value.toLowerCase()!=r[e])&&t.report(o||e+" can't be used with display: "+s+".",i[e].line,i[e].col,n)}function o(){i={}}function u(){var e=i.display?i.display.value:null;if(e)switch(e){case"inline":s("height",e),s("width",e),s("margin",e),s("margin-top",e),s("margin-bottom",e),s("float",e,"display:inline has no effect on floated elements (but may be used to fix the IE6 double-margin bug).");break;case"block":s("vertical-align",e);break;case"inline-block":s("float",e);break;default:e.indexOf("table-")===0&&(s("margin",e),s("margin-left",e),s("margin-right",e),s("margin-top",e),s("margin-bottom",e),s("float",e))}}var n=this,r={display:1,"float":"none",height:1,width:1,margin:1,"margin-left":1,"margin-right":1,"margin-bottom":1,"margin-top":1,padding:1,"padding-left":1,"padding-right":1,"padding-bottom":1,"padding-top":1,"vertical-align":1},i;e.addListener("startrule",o),e.addListener("startfontface",o),e.addListener("startkeyframerule",o),e.addListener("startpagemargin",o),e.addListener("startpage",o),e.addListener("property",function(e){var t=e.property.text.toLowerCase();r[t]&&(i[t]={value:e.value.text,line:e.property.line,col:e.property.col})}),e.addListener("endrule",u),e.addListener("endfontface",u),e.addListener("endkeyframerule",u),e.addListener("endpagemargin",u),e.addListener("endpage",u)}}),CSSLint.addRule({id:"duplicate-background-images",name:"Disallow duplicate background images",desc:"Every background-image should be unique. Use a common class for e.g. sprites.",browsers:"All",init:function(e,t){var n=this,r={};e.addListener("property",function(e){var i=e.property.text,s=e.value,o,u;if(i.match(/background/i))for(o=0,u=s.parts.length;o<u;o++)s.parts[o].type=="uri"&&(typeof r[s.parts[o].uri]=="undefined"?r[s.parts[o].uri]=e:t.report("Background image '"+s.parts[o].uri+"' was used multiple times, first declared at line "+r[s.parts[o].uri].line+", col "+r[s.parts[o].uri].col+".",e.line,e.col,n))})}}),CSSLint.addRule({id:"duplicate-properties",name:"Disallow duplicate properties",desc:"Duplicate properties must appear one after the other.",browsers:"All",init:function(e,t){function s(e){r={}}var n=this,r,i;e.addListener("startrule",s),e.addListener("startfontface",s),e.addListener("startpage",s),e.addListener("startpagemargin",s),e.addListener("startkeyframerule",s),e.addListener("property",function(e){var s=e.property,o=s.text.toLowerCase();r[o]&&(i!=o||r[o]==e.value.text)&&t.report("Duplicate property '"+e.property+"' found.",e.line,e.col,n),r[o]=e.value.text,i=o})}}),CSSLint.addRule({id:"empty-rules",name:"Disallow empty rules",desc:"Rules without any properties specified should be removed.",browsers:"All",init:function(e,t){var n=this,r=0;e.addListener("startrule",function(){r=0}),e.addListener("property",function(){r++}),e.addListener("endrule",function(e){var i=e.selectors;r===0&&t.report("Rule is empty.",i[0].line,i[0].col,n)})}}),CSSLint.addRule({id:"errors",name:"Parsing Errors",desc:"This rule looks for recoverable syntax errors.",browsers:"All",init:function(e,t){var n=this;e.addListener("error",function(e){t.error(e.message,e.line,e.col,n)})}}),CSSLint.addRule({id:"fallback-colors",name:"Require fallback colors",desc:"For older browsers that don't support RGBA, HSL, or HSLA, provide a fallback color.",browsers:"IE6,IE7,IE8",init:function(e,t){function o(e){s={},r=null}var n=this,r,i={color:1,background:1,"border-color":1,"border-top-color":1,"border-right-color":1,"border-bottom-color":1,"border-left-color":1,border:1,"border-top":1,"border-right":1,"border-bottom":1,"border-left":1,"background-color":1},s;e.addListener("startrule",o),e.addListener("startfontface",o),e.addListener("startpage",o),e.addListener("startpagemargin",o),e.addListener("startkeyframerule",o),e.addListener("property",function(e){var s=e.property,o=s.text.toLowerCase(),u=e.value.parts,a=0,f="",l=u.length;if(i[o])while(a<l)u[a].type=="color"&&("alpha"in u[a]||"hue"in u[a]?(/([^\)]+)\(/.test(u[a])&&(f=RegExp.$1.toUpperCase()),(!r||r.property.text.toLowerCase()!=o||r.colorType!="compat")&&t.report("Fallback "+o+" (hex or RGB) should precede "+f+" "+o+".",e.line,e.col,n)):e.colorType="compat"),a++;r=e})}}),CSSLint.addRule({id:"floats",name:"Disallow too many floats",desc:"This rule tests if the float property is used too many times",browsers:"All",init:function(e,t){var n=this,r=0;e.addListener("property",function(e){e.property.text.toLowerCase()=="float"&&e.value.text.toLowerCase()!="none"&&r++}),e.addListener("endstylesheet",function(){t.stat("floats",r),r>=10&&t.rollupWarn("Too many floats ("+r+"), you're probably using them for layout. Consider using a grid system instead.",n)})}}),CSSLint.addRule({id:"font-faces",name:"Don't use too many web fonts",desc:"Too many different web fonts in the same stylesheet.",browsers:"All",init:function(e,t){var n=this,r=0;e.addListener("startfontface",function(){r++}),e.addListener("endstylesheet",function(){r>5&&t.rollupWarn("Too many @font-face declarations ("+r+").",n)})}}),CSSLint.addRule({id:"font-sizes",name:"Disallow too many font sizes",desc:"Checks the number of font-size declarations.",browsers:"All",init:function(e,t){var n=this,r=0;e.addListener("property",function(e){e.property=="font-size"&&r++}),e.addListener("endstylesheet",function(){t.stat("font-sizes",r),r>=10&&t.rollupWarn("Too many font-size declarations ("+r+"), abstraction needed.",n)})}}),CSSLint.addRule({id:"gradients",name:"Require all gradient definitions",desc:"When using a vendor-prefixed gradient, make sure to use them all.",browsers:"All",init:function(e,t){var n=this,r;e.addListener("startrule",function(){r={moz:0,webkit:0,oldWebkit:0,o:0}}),e.addListener("property",function(e){/\-(moz|o|webkit)(?:\-(?:linear|radial))\-gradient/i.test(e.value)?r[RegExp.$1]=1:/\-webkit\-gradient/i.test(e.value)&&(r.oldWebkit=1)}),e.addListener("endrule",function(e){var i=[];r.moz||i.push("Firefox 3.6+"),r.webkit||i.push("Webkit (Safari 5+, Chrome)"),r.oldWebkit||i.push("Old Webkit (Safari 4+, Chrome)"),r.o||i.push("Opera 11.1+"),i.length&&i.length<4&&t.report("Missing vendor-prefixed CSS gradients for "+i.join(", ")+".",e.selectors[0].line,e.selectors[0].col,n)})}}),CSSLint.addRule({id:"ids",name:"Disallow IDs in selectors",desc:"Selectors should not contain IDs.",browsers:"All",init:function(e,t){var n=this;e.addListener("startrule",function(r){var i=r.selectors,s,o,u,a,f,l,c;for(f=0;f<i.length;f++){s=i[f],a=0;for(l=0;l<s.parts.length;l++){o=s.parts[l];if(o.type==e.SELECTOR_PART_TYPE)for(c=0;c<o.modifiers.length;c++)u=o.modifiers[c],u.type=="id"&&a++}a==1?t.report("Don't use IDs in selectors.",s.line,s.col,n):a>1&&t.report(a+" IDs in the selector, really?",s.line,s.col,n)}})}}),CSSLint.addRule({id:"import",name:"Disallow @import",desc:"Don't use @import, use <link> instead.",browsers:"All",init:function(e,t){var n=this;e.addListener("import",function(e){t.report("@import prevents parallel downloads, use <link> instead.",e.line,e.col,n)})}}),CSSLint.addRule({id:"important",name:"Disallow !important",desc:"Be careful when using !important declaration",browsers:"All",init:function(e,t){var n=this,r=0;e.addListener("property",function(e){e.important===!0&&(r++,t.report("Use of !important",e.line,e.col,n))}),e.addListener("endstylesheet",function(){t.stat("important",r),r>=10&&t.rollupWarn("Too many !important declarations ("+r+"), try to use less than 10 to avoid specificity issues.",n)})}}),CSSLint.addRule({id:"known-properties",name:"Require use of known properties",desc:"Properties should be known (listed in CSS3 specification) or be a vendor-prefixed property.",browsers:"All",init:function(e,t){var n=this;e.addListener("property",function(e){var r=e.property.text.toLowerCase();e.invalid&&t.report(e.invalid.message,e.line,e.col,n)})}}),CSSLint.addRule({id:"outline-none",name:"Disallow outline: none",desc:"Use of outline: none or outline: 0 should be limited to :focus rules.",browsers:"All",tags:["Accessibility"],init:function(e,t){function i(e){e.selectors?r={line:e.line,col:e.col,selectors:e.selectors,propCount:0,outline:!1}:r=null}function s(e){r&&r.outline&&(r.selectors.toString().toLowerCase().indexOf(":focus")==-1?t.report("Outlines should only be modified using :focus.",r.line,r.col,n):r.propCount==1&&t.report("Outlines shouldn't be hidden unless other visual changes are made.",r.line,r.col,n))}var n=this,r;e.addListener("startrule",i),e.addListener("startfontface",i),e.addListener("startpage",i),e.addListener("startpagemargin",i),e.addListener("startkeyframerule",i),e.addListener("property",function(e){var t=e.property.text.toLowerCase(),n=e.value;r&&(r.propCount++,t=="outline"&&(n=="none"||n=="0")&&(r.outline=!0))}),e.addListener("endrule",s),e.addListener("endfontface",s),e.addListener("endpage",s),e.addListener("endpagemargin",s),e.addListener("endkeyframerule",s)}}),CSSLint.addRule({id:"overqualified-elements",name:"Disallow overqualified elements",desc:"Don't use classes or IDs with elements (a.foo or a#foo).",browsers:"All",init:function(e,t){var n=this,r={};e.addListener("startrule",function(i){var s=i.selectors,o,u,a,f,l,c;for(f=0;f<s.length;f++){o=s[f];for(l=0;l<o.parts.length;l++){u=o.parts[l];if(u.type==e.SELECTOR_PART_TYPE)for(c=0;c<u.modifiers.length;c++)a=u.modifiers[c],u.elementName&&a.type=="id"?t.report("Element ("+u+") is overqualified, just use "+a+" without element name.",u.line,u.col,n):a.type=="class"&&(r[a]||(r[a]=[]),r[a].push({modifier:a,part:u}))}}}),e.addListener("endstylesheet",function(){var e;for(e in r)r.hasOwnProperty(e)&&r[e].length==1&&r[e][0].part.elementName&&t.report("Element ("+r[e][0].part+") is overqualified, just use "+r[e][0].modifier+" without element name.",r[e][0].part.line,r[e][0].part.col,n)})}}),CSSLint.addRule({id:"qualified-headings",name:"Disallow qualified headings",desc:"Headings should not be qualified (namespaced).",browsers:"All",init:function(e,t){var n=this;e.addListener("startrule",function(r){var i=r.selectors,s,o,u,a;for(u=0;u<i.length;u++){s=i[u];for(a=0;a<s.parts.length;a++)o=s.parts[a],o.type==e.SELECTOR_PART_TYPE&&o.elementName&&/h[1-6]/.test(o.elementName.toString())&&a>0&&t.report("Heading ("+o.elementName+") should not be qualified.",o.line,o.col,n)}})}}),CSSLint.addRule({id:"regex-selectors",name:"Disallow selectors that look like regexs",desc:"Selectors that look like regular expressions are slow and should be avoided.",browsers:"All",init:function(e,t){var n=this;e.addListener("startrule",function(r){var i=r.selectors,s,o,u,a,f,l;for(a=0;a<i.length;a++){s=i[a];for(f=0;f<s.parts.length;f++){o=s.parts[f];if(o.type==e.SELECTOR_PART_TYPE)for(l=0;l<o.modifiers.length;l++)u=o.modifiers[l],u.type=="attribute"&&/([\~\|\^\$\*]=)/.test(u)&&t.report("Attribute selectors with "+RegExp.$1+" are slow!",u.line,u.col,n)}}})}}),CSSLint.addRule({id:"rules-count",name:"Rules Count",desc:"Track how many rules there are.",browsers:"All",init:function(e,t){var n=this,r=0;e.addListener("startrule",function(){r++}),e.addListener("endstylesheet",function(){t.stat("rule-count",r)})}}),CSSLint.addRule({id:"selector-max-approaching",name:"Warn when approaching the 4095 selector limit for IE",desc:"Will warn when selector count is >= 3800 selectors.",browsers:"IE",init:function(e,t){var n=this,r=0;e.addListener("startrule",function(e){r+=e.selectors.length}),e.addListener("endstylesheet",function(){r>=3800&&t.report("You have "+r+" selectors. Internet Explorer supports a maximum of 4095 selectors per stylesheet. Consider refactoring.",0,0,n)})}}),CSSLint.addRule({id:"selector-max",name:"Error when past the 4095 selector limit for IE",desc:"Will error when selector count is > 4095.",browsers:"IE",init:function(e,t){var n=this,r=0;e.addListener("startrule",function(e){r+=e.selectors.length}),e.addListener("endstylesheet",function(){r>4095&&t.report("You have "+r+" selectors. Internet Explorer supports a maximum of 4095 selectors per stylesheet. Consider refactoring.",0,0,n)})}}),CSSLint.addRule({id:"shorthand",name:"Require shorthand properties",desc:"Use shorthand properties where possible.",browsers:"All",init:function(e,t){function f(e){u={}}function l(e){var r,i,s,o;for(r in a)if(a.hasOwnProperty(r)){o=0;for(i=0,s=a[r].length;i<s;i++)o+=u[a[r][i]]?1:0;o==a[r].length&&t.report("The properties "+a[r].join(", ")+" can be replaced by "+r+".",e.line,e.col,n)}}var n=this,r,i,s,o={},u,a={margin:["margin-top","margin-bottom","margin-left","margin-right"],padding:["padding-top","padding-bottom","padding-left","padding-right"]};for(r in a)if(a.hasOwnProperty(r))for(i=0,s=a[r].length;i<s;i++)o[a[r][i]]=r;e.addListener("startrule",f),e.addListener("startfontface",f),e.addListener("property",function(e){var t=e.property.toString().toLowerCase(),n=e.value.parts[0].value;o[t]&&(u[t]=1)}),e.addListener("endrule",l),e.addListener("endfontface",l)}}),CSSLint.addRule({id:"star-property-hack",name:"Disallow properties with a star prefix",desc:"Checks for the star property hack (targets IE6/7)",browsers:"All",init:function(e,t){var n=this;e.addListener("property",function(e){var r=e.property;r.hack=="*"&&t.report("Property with star prefix found.",e.property.line,e.property.col,n)})}}),CSSLint.addRule({id:"text-indent",name:"Disallow negative text-indent",desc:"Checks for text indent less than -99px",browsers:"All",init:function(e,t){function s(e){r=!1,i="inherit"}function o(e){r&&i!="ltr"&&t.report("Negative text-indent doesn't work well with RTL. If you use text-indent for image replacement explicitly set direction for that item to ltr.",r.line,r.col,n)}var n=this,r,i;e.addListener("startrule",s),e.addListener("startfontface",s),e.addListener("property",function(e){var t=e.property.toString().toLowerCase(),n=e.value;t=="text-indent"&&n.parts[0].value<-99?r=e.property:t=="direction"&&n=="ltr"&&(i="ltr")}),e.addListener("endrule",o),e.addListener("endfontface",o)}}),CSSLint.addRule({id:"underscore-property-hack",name:"Disallow properties with an underscore prefix",desc:"Checks for the underscore property hack (targets IE6)",browsers:"All",init:function(e,t){var n=this;e.addListener("property",function(e){var r=e.property;r.hack=="_"&&t.report("Property with underscore prefix found.",e.property.line,e.property.col,n)})}}),CSSLint.addRule({id:"unique-headings",name:"Headings should only be defined once",desc:"Headings should be defined only once.",browsers:"All",init:function(e,t){var n=this,r={h1:0,h2:0,h3:0,h4:0,h5:0,h6:0};e.addListener("startrule",function(e){var i=e.selectors,s,o,u,a,f;for(a=0;a<i.length;a++){s=i[a],o=s.parts[s.parts.length-1];if(o.elementName&&/(h[1-6])/i.test(o.elementName.toString())){for(f=0;f<o.modifiers.length;f++)if(o.modifiers[f].type=="pseudo"){u=!0;break}u||(r[RegExp.$1]++,r[RegExp.$1]>1&&t.report("Heading ("+o.elementName+") has already been defined.",o.line,o.col,n))}}}),e.addListener("endstylesheet",function(e){var i,s=[];for(i in r)r.hasOwnProperty(i)&&r[i]>1&&s.push(r[i]+" "+i+"s");s.length&&t.rollupWarn("You have "+s.join(", ")+" defined in this stylesheet.",n)})}}),CSSLint.addRule({id:"universal-selector",name:"Disallow universal selector",desc:"The universal selector (*) is known to be slow.",browsers:"All",init:function(e,t){var n=this;e.addListener("startrule",function(e){var r=e.selectors,i,s,o,u,a,f;for(u=0;u<r.length;u++)i=r[u],s=i.parts[i.parts.length-1],s.elementName=="*"&&t.report(n.desc,s.line,s.col,n)})}}),CSSLint.addRule({id:"unqualified-attributes",name:"Disallow unqualified attribute selectors",desc:"Unqualified attribute selectors are known to be slow.",browsers:"All",init:function(e,t){var n=this;e.addListener("startrule",function(r){var i=r.selectors,s,o,u,a,f,l;for(a=0;a<i.length;a++){s=i[a],o=s.parts[s.parts.length-1];if(o.type==e.SELECTOR_PART_TYPE)for(l=0;l<o.modifiers.length;l++)u=o.modifiers[l],u.type=="attribute"&&(!o.elementName||o.elementName=="*")&&t.report(n.desc,o.line,o.col,n)}})}}),CSSLint.addRule({id:"vendor-prefix",name:"Require standard property with vendor prefix",desc:"When using a vendor-prefixed property, make sure to include the standard one.",browsers:"All",init:function(e,t){function o(){r={},i=1}function u(e){var i,o,u,a,f,l,c=[];for(i in r)s[i]&&c.push({actual:i,needed:s[i]});for(o=0,u=c.length;o<u;o++)f=c[o].needed,l=c[o].actual,r[f]?r[f][0].pos<r[l][0].pos&&t.report("Standard property '"+f+"' should come after vendor-prefixed property '"+l+"'.",r[l][0].name.line,r[l][0].name.col,n):t.report("Missing standard property '"+f+"' to go along with '"+l+"'.",r[l][0].name.line,r[l][0].name.col,n)}var n=this,r,i,s={"-webkit-border-radius":"border-radius","-webkit-border-top-left-radius":"border-top-left-radius","-webkit-border-top-right-radius":"border-top-right-radius","-webkit-border-bottom-left-radius":"border-bottom-left-radius","-webkit-border-bottom-right-radius":"border-bottom-right-radius","-o-border-radius":"border-radius","-o-border-top-left-radius":"border-top-left-radius","-o-border-top-right-radius":"border-top-right-radius","-o-border-bottom-left-radius":"border-bottom-left-radius","-o-border-bottom-right-radius":"border-bottom-right-radius","-moz-border-radius":"border-radius","-moz-border-radius-topleft":"border-top-left-radius","-moz-border-radius-topright":"border-top-right-radius","-moz-border-radius-bottomleft":"border-bottom-left-radius","-moz-border-radius-bottomright":"border-bottom-right-radius","-moz-column-count":"column-count","-webkit-column-count":"column-count","-moz-column-gap":"column-gap","-webkit-column-gap":"column-gap","-moz-column-rule":"column-rule","-webkit-column-rule":"column-rule","-moz-column-rule-style":"column-rule-style","-webkit-column-rule-style":"column-rule-style","-moz-column-rule-color":"column-rule-color","-webkit-column-rule-color":"column-rule-color","-moz-column-rule-width":"column-rule-width","-webkit-column-rule-width":"column-rule-width","-moz-column-width":"column-width","-webkit-column-width":"column-width","-webkit-column-span":"column-span","-webkit-columns":"columns","-moz-box-shadow":"box-shadow","-webkit-box-shadow":"box-shadow","-moz-transform":"transform","-webkit-transform":"transform","-o-transform":"transform","-ms-transform":"transform","-moz-transform-origin":"transform-origin","-webkit-transform-origin":"transform-origin","-o-transform-origin":"transform-origin","-ms-transform-origin":"transform-origin","-moz-box-sizing":"box-sizing","-webkit-box-sizing":"box-sizing","-moz-user-select":"user-select","-khtml-user-select":"user-select","-webkit-user-select":"user-select"};e.addListener("startrule",o),e.addListener("startfontface",o),e.addListener("startpage",o),e.addListener("startpagemargin",o),e.addListener("startkeyframerule",o),e.addListener("property",function(e){var t=e.property.text.toLowerCase();r[t]||(r[t]=[]),r[t].push({name:e.property,value:e.value,pos:i++})}),e.addListener("endrule",u),e.addListener("endfontface",u),e.addListener("endpage",u),e.addListener("endpagemargin",u),e.addListener("endkeyframerule",u)}}),CSSLint.addRule({id:"zero-units",name:"Disallow units for 0 values",desc:"You don't need to specify units when a value is 0.",browsers:"All",init:function(e,t){var n=this;e.addListener("property",function(e){var r=e.value.parts,i=0,s=r.length;while(i<s)(r[i].units||r[i].type=="percentage")&&r[i].value===0&&r[i].type!="time"&&t.report("Values of 0 shouldn't have units specified.",r[i].line,r[i].col,n),i++})}}),function(){var e=function(e){return!e||e.constructor!==String?"":e.replace(/[\"&><]/g,function(e){switch(e){case'"':return""";case"&":return"&";case"<":return"<";case">":return">"}})};CSSLint.addFormatter({id:"checkstyle-xml",name:"Checkstyle XML format",startFormat:function(){return'<?xml version="1.0" encoding="utf-8"?><checkstyle>'},endFormat:function(){return"</checkstyle>"},readError:function(t,n){return'<file name="'+e(t)+'"><error line="0" column="0" severty="error" message="'+e(n)+'"></error></file>'},formatResults:function(t,n,r){var i=t.messages,s=[],o=function(e){return!!e&&"name"in e?"net.csslint."+e.name.replace(/\s/g,""):""};return i.length>0&&(s.push('<file name="'+n+'">'),CSSLint.Util.forEach(i,function(t,n){t.rollup||s.push('<error line="'+t.line+'" column="'+t.col+'" severity="'+t.type+'"'+' message="'+e(t.message)+'" source="'+o(t.rule)+'"/>')}),s.push("</file>")),s.join("")}})}(),CSSLint.addFormatter({id:"compact",name:"Compact, 'porcelain' format",startFormat:function(){return""},endFormat:function(){return""},formatResults:function(e,t,n){var r=e.messages,i="";n=n||{};var s=function(e){return e.charAt(0).toUpperCase()+e.slice(1)};return r.length===0?n.quiet?"":t+": Lint Free!":(CSSLint.Util.forEach(r,function(e,n){e.rollup?i+=t+": "+s(e.type)+" - "+e.message+"\n":i+=t+": "+"line "+e.line+", col "+e.col+", "+s(e.type)+" - "+e.message+"\n"}),i)}}),CSSLint.addFormatter({id:"csslint-xml",name:"CSSLint XML format",startFormat:function(){return'<?xml version="1.0" encoding="utf-8"?><csslint>'},endFormat:function(){return"</csslint>"},formatResults:function(e,t,n){var r=e.messages,i=[],s=function(e){return!e||e.constructor!==String?"":e.replace(/\"/g,"'").replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">")};return r.length>0&&(i.push('<file name="'+t+'">'),CSSLint.Util.forEach(r,function(e,t){e.rollup?i.push('<issue severity="'+e.type+'" reason="'+s(e.message)+'" evidence="'+s(e.evidence)+'"/>'):i.push('<issue line="'+e.line+'" char="'+e.col+'" severity="'+e.type+'"'+' reason="'+s(e.message)+'" evidence="'+s(e.evidence)+'"/>')}),i.push("</file>")),i.join("")}}),CSSLint.addFormatter({id:"junit-xml",name:"JUNIT XML format",startFormat:function(){return'<?xml version="1.0" encoding="utf-8"?><testsuites>'},endFormat:function(){return"</testsuites>"},formatResults:function(e,t,n){var r=e.messages,i=[],s={error:0,failure:0},o=function(e){return!!e&&"name"in e?"net.csslint."+e.name.replace(/\s/g,""):""},u=function(e){return!e||e.constructor!==String?"":e.replace(/\"/g,"'").replace(/</g,"<").replace(/>/g,">")};return r.length>0&&(r.forEach(function(e,t){var n=e.type==="warning"?"error":e.type;e.rollup||(i.push('<testcase time="0" name="'+o(e.rule)+'">'),i.push("<"+n+' message="'+u(e.message)+'"><![CDATA['+e.line+":"+e.col+":"+u(e.evidence)+"]]></"+n+">"),i.push("</testcase>"),s[n]+=1)}),i.unshift('<testsuite time="0" tests="'+r.length+'" skipped="0" errors="'+s.error+'" failures="'+s.failure+'" package="net.csslint" name="'+t+'">'),i.push("</testsuite>")),i.join("")}}),CSSLint.addFormatter({id:"lint-xml",name:"Lint XML format",startFormat:function(){return'<?xml version="1.0" encoding="utf-8"?><lint>'},endFormat:function(){return"</lint>"},formatResults:function(e,t,n){var r=e.messages,i=[],s=function(e){return!e||e.constructor!==String?"":e.replace(/\"/g,"'").replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">")};return r.length>0&&(i.push('<file name="'+t+'">'),CSSLint.Util.forEach(r,function(e,t){e.rollup?i.push('<issue severity="'+e.type+'" reason="'+s(e.message)+'" evidence="'+s(e.evidence)+'"/>'):i.push('<issue line="'+e.line+'" char="'+e.col+'" severity="'+e.type+'"'+' reason="'+s(e.message)+'" evidence="'+s(e.evidence)+'"/>')}),i.push("</file>")),i.join("")}}),CSSLint.addFormatter({id:"text",name:"Plain Text",startFormat:function(){return""},endFormat:function(){return""},formatResults:function(e,t,n){var r=e.messages,i="";n=n||{};if(r.length===0)return n.quiet?"":"\n\ncsslint: No errors in "+t+".";i="\n\ncsslint: There are "+r.length+" problems in "+t+".";var s=t.lastIndexOf("/"),o=t;return s===-1&&(s=t.lastIndexOf("\\")),s>-1&&(o=t.substring(s+1)),CSSLint.Util.forEach(r,function(e,t){i=i+"\n\n"+o,e.rollup?(i+="\n"+(t+1)+": "+e.type,i+="\n"+e.message):(i+="\n"+(t+1)+": "+e.type+" at line "+e.line+", col "+e.col,i+="\n"+e.message,i+="\n"+e.evidence)}),i}}),exports.CSSLint=CSSLint}),define("ace/worker/mirror",["require","exports","module","ace/document","ace/lib/lang"],function(e,t,n){var r=e("../document").Document,i=e("../lib/lang"),s=t.Mirror=function(e){this.sender=e;var t=this.doc=new r(""),n=this.deferredUpdate=i.delayedCall(this.onUpdate.bind(this)),s=this;e.on("change",function(e){t.applyDeltas(e.data);if(s.$timeout)return n.schedule(s.$timeout);s.onUpdate()})};(function(){this.$timeout=500,this.setTimeout=function(e){this.$timeout=e},this.setValue=function(e){this.doc.setValue(e),this.deferredUpdate.schedule(this.$timeout)},this.getValue=function(e){this.sender.callback(this.doc.getValue(),e)},this.onUpdate=function(){},this.isPending=function(){return this.deferredUpdate.isPending()}}).call(s.prototype)});
\ No newline at end of file
--- /dev/null
+(function(e){function n(e){return typeof e=="object"?e:{top:e,left:e}}var t=e.scrollTo=function(t,n,r){e(window).scrollTo(t,n,r)};t.defaults={axis:"xy",duration:parseFloat(e.fn.jquery)>=1.3?0:1},t.window=function(t){return e(window)._scrollable()},e.fn._scrollable=function(){return this.map(function(){var t=this,n=!t.nodeName||e.inArray(t.nodeName.toLowerCase(),["iframe","#document","html","body"])!=-1;if(!n)return t;var r=(t.contentWindow||t).document||t.ownerDocument||t;return e.browser.safari||r.compatMode=="BackCompat"?r.body:r.documentElement})},e.fn.scrollTo=function(r,i,s){return typeof i=="object"&&(s=i,i=0),typeof s=="function"&&(s={onAfter:s}),r=="max"&&(r=9e9),s=e.extend({},t.defaults,s),i=i||s.speed||s.duration,s.queue=s.queue&&s.axis.length>1,s.queue&&(i/=2),s.offset=n(s.offset),s.over=n(s.over),this._scrollable().each(function(){function h(e){u.animate(l,i,s.easing,e&&function(){e.call(this,r,s)})}var o=this,u=e(o),a=r,f,l={},c=u.is("html,body");switch(typeof a){case"number":case"string":if(/^([+-]=)?\d+(\.\d+)?(px|%)?$/.test(a)){a=n(a);break}a=e(a,this);case"object":if(a.is||a.style)f=(a=e(a)).offset()}e.each(s.axis.split(""),function(e,n){var r=n=="x"?"Left":"Top",i=r.toLowerCase(),p="scroll"+r,d=o[p],v=t.max(o,n);if(f)l[p]=f[i]+(c?0:d-u.offset()[i]),s.margin&&(l[p]-=parseInt(a.css("margin"+r))||0,l[p]-=parseInt(a.css("border"+r+"Width"))||0),l[p]+=s.offset[i]||0,s.over[i]&&(l[p]+=a[n=="x"?"width":"height"]()*s.over[i]);else{var m=a[i];l[p]=m.slice&&m.slice(-1)=="%"?parseFloat(m)/100*v:m}/^\d+$/.test(l[p])&&(l[p]=l[p]<=0?0:Math.min(l[p],v)),!e&&s.queue&&(d!=l[p]&&h(s.onAfterFirst),delete l[p])}),h(s.onAfter)}).end()},t.max=function(t,n){var r=n=="x"?"Width":"Height",i="scroll"+r;if(!e(t).is("html,body"))return t[i]-e(t)[r.toLowerCase()]();var s="client"+r,o=t.ownerDocument.documentElement,u=t.ownerDocument.body;return Math.max(o[i],u[i])-Math.min(o[s],u[s])}})(jQuery);
\ No newline at end of file
--- /dev/null
+(function(e){function t(e){window.console&&window.console.log&&window.console.log("textarea count: "+e.size())}function n(e,t,n){var s=e.scrollTop;e.setSelectionRange?r(e,t,n):document.selection&&i(e,t,n),e.scrollTop=s}function r(e,t,n){var r=e.selectionStart,i=e.selectionEnd;if(r==i)t?r-n.tabString==e.value.substring(r-n.tabString.length,r)?(e.value=e.value.substring(0,r-n.tabString.length)+e.value.substring(r),e.focus(),e.setSelectionRange(r-n.tabString.length,r-n.tabString.length)):r-n.tabString==e.value.substring(r,r+n.tabString.length)&&(e.value=e.value.substring(0,r)+e.value.substring(r+n.tabString.length),e.focus(),e.setSelectionRange(r,r)):(e.value=e.value.substring(0,r)+n.tabString+e.value.substring(r),e.focus(),e.setSelectionRange(r+n.tabString.length,r+n.tabString.length));else{while(r<e.value.length&&e.value.charAt(r).match(/[ \t]/))r++;var s=e.value.split("\n"),o=new Array,u=0,a=0,f=!1;for(var l in s)a=u+s[l].length,o.push({start:u,end:a,selected:u<=r&&a>r||a>=i&&u<i||u>r&&a<i}),u=a+1;var c=0;for(var l in o)if(o[l].selected){var h=o[l].start+c;t&&n.tabString==e.value.substring(h,h+n.tabString.length)?(e.value=e.value.substring(0,h)+e.value.substring(h+n.tabString.length),c-=n.tabString.length):t||(e.value=e.value.substring(0,h)+n.tabString+e.value.substring(h),c+=n.tabString.length)}e.focus();var p=r+(c>0?n.tabString.length:c<0?-n.tabString.length:0),d=i+c;e.setSelectionRange(p,d)}}function i(t,n,r){var i=document.selection.createRange();if(t==i.parentElement())if(""==i.text)if(n){var s=i.getBookmark();i.moveStart("character",-r.tabString.length),r.tabString==i.text?i.text="":(i.moveToBookmark(s),i.moveEnd("character",r.tabString.length),r.tabString==i.text&&(i.text="")),i.collapse(!0),i.select()}else i.text=r.tabString,i.collapse(!1),i.select();else{var o=i.text,u=o.length,a=o.split("\r\n"),f=document.body.createTextRange();f.moveToElementText(t),f.setEndPoint("EndToStart",i);var l=f.text,c=l.split("\r\n"),h=l.length,p=document.body.createTextRange();p.moveToElementText(t),p.setEndPoint("StartToEnd",i);var v=p.text,m=document.body.createTextRange();m.moveToElementText(t),m.setEndPoint("StartToEnd",f);var g=m.text,y=e(t).html();e("#r3").text(h+" + "+u+" + "+v.length+" = "+y.length),h+g.length<y.length?(c.push(""),h+=2,n&&r.tabString==a[0].substring(0,r.tabString.length)?a[0]=a[0].substring(r.tabString.length):n||(a[0]=r.tabString+a[0])):n&&r.tabString==c[c.length-1].substring(0,r.tabString.length)?c[c.length-1]=c[c.length-1].substring(r.tabString.length):n||(c[c.length-1]=r.tabString+c[c.length-1]);for(var b=1;b<a.length;b++)n&&r.tabString==a[b].substring(0,r.tabString.length)?a[b]=a[b].substring(r.tabString.length):n||(a[b]=r.tabString+a[b]);1==c.length&&0==h&&(n&&r.tabString==a[0].substring(0,r.tabString.length)?a[0]=a[0].substring(r.tabString.length):n||(a[0]=r.tabString+a[0])),h+u+v.length<y.length&&(a.push(""),u+=2),f.text=c.join("\r\n"),i.text=a.join("\r\n");var w=document.body.createTextRange();w.moveToElementText(t),0<h?w.setEndPoint("StartToEnd",f):w.setEndPoint("StartToStart",f),w.setEndPoint("EndToEnd",i),w.select()}}e.fn.tabby=function(t){var r=e.extend({},e.fn.tabby.defaults,t),i=e.fn.tabby.pressed;return this.each(function(){$this=e(this);var t=e.meta?e.extend({},r,$this.data()):r;$this.bind("keydown",function(r){var s=e.fn.tabby.catch_kc(r);16==s&&(i.shft=!0),17==s&&(i.ctrl=!0,setTimeout("$.fn.tabby.pressed.ctrl = false;",1e3)),18==s&&(i.alt=!0,setTimeout("$.fn.tabby.pressed.alt = false;",1e3));if(9==s&&!i.ctrl&&!i.alt)return r.preventDefault,i.last=s,setTimeout("$.fn.tabby.pressed.last = null;",0),n(e(r.target).get(0),i.shft,t),!1}).bind("keyup",function(t){16==e.fn.tabby.catch_kc(t)&&(i.shft=!1)}).bind("blur",function(t){9==i.last&&e(t.target).one("focus",function(e){i.last=null}).get(0).focus()})})},e.fn.tabby.catch_kc=function(e){return e.keyCode?e.keyCode:e.charCode?e.charCode:e.which},e.fn.tabby.pressed={shft:!1,ctrl:!1,alt:!1,last:null},e.fn.tabby.defaults={tabString:String.fromCharCode(9)}})(jQuery);
\ No newline at end of file
--- /dev/null
+var requirejs,require,define;(function(global){function isFunction(e){return ostring.call(e)==="[object Function]"}function isArray(e){return ostring.call(e)==="[object Array]"}function each(e,t){if(e){var n;for(n=0;n<e.length;n+=1)if(e[n]&&t(e[n],n,e))break}}function eachReverse(e,t){if(e){var n;for(n=e.length-1;n>-1;n-=1)if(e[n]&&t(e[n],n,e))break}}function hasProp(e,t){return hasOwn.call(e,t)}function getOwn(e,t){return hasProp(e,t)&&e[t]}function eachProp(e,t){var n;for(n in e)if(hasProp(e,n)&&t(e[n],n))break}function mixin(e,t,n,r){return t&&eachProp(t,function(t,i){if(n||!hasProp(e,i))r&&typeof t=="object"&&t&&!isArray(t)&&!isFunction(t)&&!(t instanceof RegExp)?(e[i]||(e[i]={}),mixin(e[i],t,n,r)):e[i]=t}),e}function bind(e,t){return function(){return t.apply(e,arguments)}}function scripts(){return document.getElementsByTagName("script")}function defaultOnError(e){throw e}function getGlobal(e){if(!e)return e;var t=global;return each(e.split("."),function(e){t=t[e]}),t}function makeError(e,t,n,r){var i=new Error(t+"\nhttp://requirejs.org/docs/errors.html#"+e);return i.requireType=e,i.requireModules=r,n&&(i.originalError=n),i}function newContext(e){function m(e){var t,n,r=e.length;for(t=0;t<r;t++){n=e[t];if(n===".")e.splice(t,1),t-=1;else if(n===".."){if(t===1&&(e[2]===".."||e[0]===".."))break;t>0&&(e.splice(t-1,2),t-=2)}}}function g(e,t,n){var r,i,s,u,a,f,l,c,h,p,d,v=t&&t.split("/"),g=v,y=o.map,b=y&&y["*"];e&&e.charAt(0)==="."&&(t?(g=v.slice(0,v.length-1),e=e.split("/"),l=e.length-1,o.nodeIdCompat&&jsSuffixRegExp.test(e[l])&&(e[l]=e[l].replace(jsSuffixRegExp,"")),e=g.concat(e),m(e),e=e.join("/")):e.indexOf("./")===0&&(e=e.substring(2)));if(n&&y&&(v||b)){s=e.split("/");e:for(u=s.length;u>0;u-=1){f=s.slice(0,u).join("/");if(v)for(a=v.length;a>0;a-=1){i=getOwn(y,v.slice(0,a).join("/"));if(i){i=getOwn(i,f);if(i){c=i,h=u;break e}}}!p&&b&&getOwn(b,f)&&(p=getOwn(b,f),d=u)}!c&&p&&(c=p,h=d),c&&(s.splice(0,h,c),e=s.join("/"))}return r=getOwn(o.pkgs,e),r?r:e}function y(e){isBrowser&&each(scripts(),function(t){if(t.getAttribute("data-requiremodule")===e&&t.getAttribute("data-requirecontext")===r.contextName)return t.parentNode.removeChild(t),!0})}function b(e){var t=getOwn(o.paths,e);if(t&&isArray(t)&&t.length>1)return t.shift(),r.require.undef(e),r.require([e]),!0}function w(e){var t,n=e?e.indexOf("!"):-1;return n>-1&&(t=e.substring(0,n),e=e.substring(n+1,e.length)),[t,e]}function E(e,t,n,i){var s,o,u,a,f=null,l=t?t.name:null,h=e,p=!0,m="";return e||(p=!1,e="_@r"+(d+=1)),a=w(e),f=a[0],e=a[1],f&&(f=g(f,l,i),o=getOwn(c,f)),e&&(f?o&&o.normalize?m=o.normalize(e,function(e){return g(e,l,i)}):m=g(e,l,i):(m=g(e,l,i),a=w(m),f=a[0],m=a[1],n=!0,s=r.nameToUrl(m))),u=f&&!o&&!n?"_unnormalized"+(v+=1):"",{prefix:f,name:m,parentMap:t,unnormalized:!!u,url:s,originalName:h,isDefine:p,id:(f?f+"!"+m:m)+u}}function S(e){var t=e.id,n=getOwn(u,t);return n||(n=u[t]=new r.Module(e)),n}function x(e,t,n){var r=e.id,i=getOwn(u,r);hasProp(c,r)&&(!i||i.defineEmitComplete)?t==="defined"&&n(c[r]):(i=S(e),i.error&&t==="error"?n(i.error):i.on(t,n))}function T(e,t){var n=e.requireModules,r=!1;t?t(e):(each(n,function(t){var n=getOwn(u,t);n&&(n.error=e,n.events.error&&(r=!0,n.emit("error",e)))}),r||req.onError(e))}function N(){globalDefQueue.length&&(apsp.apply(l,[l.length,0].concat(globalDefQueue)),globalDefQueue=[])}function C(e){delete u[e],delete a[e]}function k(e,t,n){var r=e.map.id;e.error?e.emit("error",e.error):(t[r]=!0,each(e.depMaps,function(r,i){var s=r.id,o=getOwn(u,s);o&&!e.depMatched[i]&&!n[s]&&(getOwn(t,s)?(e.defineDep(i,c[s]),e.check()):k(o,t,n))}),n[r]=!0)}function L(){var e,n,i=o.waitSeconds*1e3,u=i&&r.startTime+i<(new Date).getTime(),f=[],l=[],c=!1,h=!0;if(t)return;t=!0,eachProp(a,function(e){var t=e.map,r=t.id;if(!e.enabled)return;t.isDefine||l.push(e);if(!e.error)if(!e.inited&&u)b(r)?(n=!0,c=!0):(f.push(r),y(r));else if(!e.inited&&e.fetched&&t.isDefine){c=!0;if(!t.prefix)return h=!1}});if(u&&f.length)return e=makeError("timeout","Load timeout for modules: "+f,null,f),e.contextName=r.contextName,T(e);h&&each(l,function(e){k(e,{},{})}),(!u||n)&&c&&(isBrowser||isWebWorker)&&!s&&(s=setTimeout(function(){s=0,L()},50)),t=!1}function A(e){hasProp(c,e[0])||S(E(e[0],null,!0)).init(e[1],e[2])}function O(e,t,n,r){e.detachEvent&&!isOpera?r&&e.detachEvent(r,t):e.removeEventListener(n,t,!1)}function M(e){var t=e.currentTarget||e.srcElement;return O(t,r.onScriptLoad,"load","onreadystatechange"),O(t,r.onScriptError,"error"),{node:t,id:t&&t.getAttribute("data-requiremodule")}}function _(){var e;N();while(l.length){e=l.shift();if(e[0]===null)return T(makeError("mismatch","Mismatched anonymous define() module: "+e[e.length-1]));A(e)}}var t,n,r,i,s,o={waitSeconds:7,baseUrl:"./",paths:{},bundles:{},pkgs:{},shim:{},config:{}},u={},a={},f={},l=[],c={},h={},p={},d=1,v=1;return i={require:function(e){return e.require?e.require:e.require=r.makeRequire(e.map)},exports:function(e){e.usingExports=!0;if(e.map.isDefine)return e.exports?c[e.map.id]=e.exports:e.exports=c[e.map.id]={}},module:function(e){return e.module?e.module:e.module={id:e.map.id,uri:e.map.url,config:function(){return getOwn(o.config,e.map.id)||{}},exports:e.exports||(e.exports={})}}},n=function(e){this.events=getOwn(f,e.id)||{},this.map=e,this.shim=getOwn(o.shim,e.id),this.depExports=[],this.depMaps=[],this.depMatched=[],this.pluginMaps={},this.depCount=0},n.prototype={init:function(e,t,n,r){r=r||{};if(this.inited)return;this.factory=t,n?this.on("error",n):this.events.error&&(n=bind(this,function(e){this.emit("error",e)})),this.depMaps=e&&e.slice(0),this.errback=n,this.inited=!0,this.ignore=r.ignore,r.enabled||this.enabled?this.enable():this.check()},defineDep:function(e,t){this.depMatched[e]||(this.depMatched[e]=!0,this.depCount-=1,this.depExports[e]=t)},fetch:function(){if(this.fetched)return;this.fetched=!0,r.startTime=(new Date).getTime();var e=this.map;if(!this.shim)return e.prefix?this.callPlugin():this.load();r.makeRequire(this.map,{enableBuildCallback:!0})(this.shim.deps||[],bind(this,function(){return e.prefix?this.callPlugin():this.load()}))},load:function(){var e=this.map.url;h[e]||(h[e]=!0,r.load(this.map.id,e))},check:function(){if(!this.enabled||this.enabling)return;var e,t,n=this.map.id,i=this.depExports,s=this.exports,o=this.factory;if(!this.inited)this.fetch();else if(this.error)this.emit("error",this.error);else if(!this.defining){this.defining=!0;if(this.depCount<1&&!this.defined){if(isFunction(o)){if(this.events.error&&this.map.isDefine||req.onError!==defaultOnError)try{s=r.execCb(n,o,i,s)}catch(u){e=u}else s=r.execCb(n,o,i,s);this.map.isDefine&&s===undefined&&(t=this.module,t?s=t.exports:this.usingExports&&(s=this.exports));if(e)return e.requireMap=this.map,e.requireModules=this.map.isDefine?[this.map.id]:null,e.requireType=this.map.isDefine?"define":"require",T(this.error=e)}else s=o;this.exports=s,this.map.isDefine&&!this.ignore&&(c[n]=s,req.onResourceLoad&&req.onResourceLoad(r,this.map,this.depMaps)),C(n),this.defined=!0}this.defining=!1,this.defined&&!this.defineEmitted&&(this.defineEmitted=!0,this.emit("defined",this.exports),this.defineEmitComplete=!0)}},callPlugin:function(){var e=this.map,t=e.id,n=E(e.prefix);this.depMaps.push(n),x(n,"defined",bind(this,function(n){var i,s,a,f=getOwn(p,this.map.id),l=this.map.name,c=this.map.parentMap?this.map.parentMap.name:null,h=r.makeRequire(e.parentMap,{enableBuildCallback:!0});if(this.map.unnormalized){n.normalize&&(l=n.normalize(l,function(e){return g(e,c,!0)})||""),s=E(e.prefix+"!"+l,this.map.parentMap),x(s,"defined",bind(this,function(e){this.init([],function(){return e},null,{enabled:!0,ignore:!0})})),a=getOwn(u,s.id),a&&(this.depMaps.push(s),this.events.error&&a.on("error",bind(this,function(e){this.emit("error",e)})),a.enable());return}if(f){this.map.url=r.nameToUrl(f),this.load();return}i=bind(this,function(e){this.init([],function(){return e},null,{enabled:!0})}),i.error=bind(this,function(e){this.inited=!0,this.error=e,e.requireModules=[t],eachProp(u,function(e){e.map.id.indexOf(t+"_unnormalized")===0&&C(e.map.id)}),T(e)}),i.fromText=bind(this,function(n,s){var u=e.name,a=E(u),f=useInteractive;s&&(n=s),f&&(useInteractive=!1),S(a),hasProp(o.config,t)&&(o.config[u]=o.config[t]);try{req.exec(n)}catch(l){return T(makeError("fromtexteval","fromText eval for "+t+" failed: "+l,l,[t]))}f&&(useInteractive=!0),this.depMaps.push(a),r.completeLoad(u),h([u],i)}),n.load(e.name,h,i,o)})),r.enable(n,this),this.pluginMaps[n.id]=n},enable:function(){a[this.map.id]=this,this.enabled=!0,this.enabling=!0,each(this.depMaps,bind(this,function(e,t){var n,s,o;if(typeof e=="string"){e=E(e,this.map.isDefine?this.map:this.map.parentMap,!1,!this.skipMap),this.depMaps[t]=e,o=getOwn(i,e.id);if(o){this.depExports[t]=o(this);return}this.depCount+=1,x(e,"defined",bind(this,function(e){this.defineDep(t,e),this.check()})),this.errback&&x(e,"error",bind(this,this.errback))}n=e.id,s=u[n],!hasProp(i,n)&&s&&!s.enabled&&r.enable(e,this)})),eachProp(this.pluginMaps,bind(this,function(e){var t=getOwn(u,e.id);t&&!t.enabled&&r.enable(e,this)})),this.enabling=!1,this.check()},on:function(e,t){var n=this.events[e];n||(n=this.events[e]=[]),n.push(t)},emit:function(e,t){each(this.events[e],function(e){e(t)}),e==="error"&&delete this.events[e]}},r={config:o,contextName:e,registry:u,defined:c,urlFetched:h,defQueue:l,Module:n,makeModuleMap:E,nextTick:req.nextTick,onError:T,configure:function(e){e.baseUrl&&e.baseUrl.charAt(e.baseUrl.length-1)!=="/"&&(e.baseUrl+="/");var t=o.shim,n={paths:!0,bundles:!0,config:!0,map:!0};eachProp(e,function(e,t){n[t]?(o[t]||(o[t]={}),mixin(o[t],e,!0,!0)):o[t]=e}),e.bundles&&eachProp(e.bundles,function(e,t){each(e,function(e){e!==t&&(p[e]=t)})}),e.shim&&(eachProp(e.shim,function(e,n){isArray(e)&&(e={deps:e}),(e.exports||e.init)&&!e.exportsFn&&(e.exportsFn=r.makeShimExports(e)),t[n]=e}),o.shim=t),e.packages&&each(e.packages,function(e){var t,n;e=typeof e=="string"?{name:e}:e,n=e.name,t=e.location,t&&(o.paths[n]=e.location),o.pkgs[n]=e.name+"/"+(e.main||"main").replace(currDirRegExp,"").replace(jsSuffixRegExp,"")}),eachProp(u,function(e,t){!e.inited&&!e.map.unnormalized&&(e.map=E(t))}),(e.deps||e.callback)&&r.require(e.deps||[],e.callback)},makeShimExports:function(e){function t(){var t;return e.init&&(t=e.init.apply(global,arguments)),t||e.exports&&getGlobal(e.exports)}return t},makeRequire:function(t,n){function s(o,a,f){var l,h,p;return n.enableBuildCallback&&a&&isFunction(a)&&(a.__requireJsBuild=!0),typeof o=="string"?isFunction(a)?T(makeError("requireargs","Invalid require call"),f):t&&hasProp(i,o)?i[o](u[t.id]):req.get?req.get(r,o,t,s):(h=E(o,t,!1,!0),l=h.id,hasProp(c,l)?c[l]:T(makeError("notloaded",'Module name "'+l+'" has not been loaded yet for context: '+e+(t?"":". Use require([])")))):(_(),r.nextTick(function(){_(),p=S(E(null,t)),p.skipMap=n.skipMap,p.init(o,a,f,{enabled:!0}),L()}),s)}return n=n||{},mixin(s,{isBrowser:isBrowser,toUrl:function(e){var n,i=e.lastIndexOf("."),s=e.split("/")[0],o=s==="."||s==="..";return i!==-1&&(!o||i>1)&&(n=e.substring(i,e.length),e=e.substring(0,i)),r.nameToUrl(g(e,t&&t.id,!0),n,!0)},defined:function(e){return hasProp(c,E(e,t,!1,!0).id)},specified:function(e){return e=E(e,t,!1,!0).id,hasProp(c,e)||hasProp(u,e)}}),t||(s.undef=function(e){N();var n=E(e,t,!0),r=getOwn(u,e);y(e),delete c[e],delete h[n.url],delete f[e],eachReverse(l,function(t,n){t[0]===e&&l.splice(n,1)}),r&&(r.events.defined&&(f[e]=r.events),C(e))}),s},enable:function(e){var t=getOwn(u,e.id);t&&S(e).enable()},completeLoad:function(e){var t,n,r,i=getOwn(o.shim,e)||{},s=i.exports;N();while(l.length){n=l.shift();if(n[0]===null){n[0]=e;if(t)break;t=!0}else n[0]===e&&(t=!0);A(n)}r=getOwn(u,e);if(!t&&!hasProp(c,e)&&r&&!r.inited){if(o.enforceDefine&&(!s||!getGlobal(s))){if(b(e))return;return T(makeError("nodefine","No define call for "+e,null,[e]))}A([e,i.deps||[],i.exportsFn])}L()},nameToUrl:function(e,t,n){var i,s,u,a,f,l,c,h=getOwn(o.pkgs,e);h&&(e=h),c=getOwn(p,e);if(c)return r.nameToUrl(c,t,n);if(req.jsExtRegExp.test(e))f=e+(t||"");else{i=o.paths,s=e.split("/");for(u=s.length;u>0;u-=1){a=s.slice(0,u).join("/"),l=getOwn(i,a);if(l){isArray(l)&&(l=l[0]),s.splice(0,u,l);break}}f=s.join("/"),f+=t||(/^data\:|\?/.test(f)||n?"":".js"),f=(f.charAt(0)==="/"||f.match(/^[\w\+\.\-]+:/)?"":o.baseUrl)+f}return o.urlArgs?f+((f.indexOf("?")===-1?"?":"&")+o.urlArgs):f},load:function(e,t){req.load(r,e,t)},execCb:function(e,t,n,r){return t.apply(r,n)},onScriptLoad:function(e){if(e.type==="load"||readyRegExp.test((e.currentTarget||e.srcElement).readyState)){interactiveScript=null;var t=M(e);r.completeLoad(t.id)}},onScriptError:function(e){var t=M(e);if(!b(t.id))return T(makeError("scripterror","Script error for: "+t.id,e,[t.id]))}},r.require=r.makeRequire(),r}function getInteractiveScript(){return interactiveScript&&interactiveScript.readyState==="interactive"?interactiveScript:(eachReverse(scripts(),function(e){if(e.readyState==="interactive")return interactiveScript=e}),interactiveScript)}var req,s,head,baseElement,dataMain,src,interactiveScript,currentlyAddingScript,mainScript,subPath,version="2.1.11",commentRegExp=/(\/\*([\s\S]*?)\*\/|([^:]|^)\/\/(.*)$)/mg,cjsRequireRegExp=/[^.]\s*require\s*\(\s*["']([^'"\s]+)["']\s*\)/g,jsSuffixRegExp=/\.js$/,currDirRegExp=/^\.\//,op=Object.prototype,ostring=op.toString,hasOwn=op.hasOwnProperty,ap=Array.prototype,apsp=ap.splice,isBrowser=typeof window!="undefined"&&typeof navigator!="undefined"&&!!window.document,isWebWorker=!isBrowser&&typeof importScripts!="undefined",readyRegExp=isBrowser&&navigator.platform==="PLAYSTATION 3"?/^complete$/:/^(complete|loaded)$/,defContextName="_",isOpera=typeof opera!="undefined"&&opera.toString()==="[object Opera]",contexts={},cfg={},globalDefQueue=[],useInteractive=!1;if(typeof define!="undefined")return;if(typeof requirejs!="undefined"){if(isFunction(requirejs))return;cfg=requirejs,requirejs=undefined}typeof require!="undefined"&&!isFunction(require)&&(cfg=require,require=undefined),req=requirejs=function(e,t,n,r){var i,s,o=defContextName;return!isArray(e)&&typeof e!="string"&&(s=e,isArray(t)?(e=t,t=n,n=r):e=[]),s&&s.context&&(o=s.context),i=getOwn(contexts,o),i||(i=contexts[o]=req.s.newContext(o)),s&&i.configure(s),i.require(e,t,n)},req.config=function(e){return req(e)},req.nextTick=typeof setTimeout!="undefined"?function(e){setTimeout(e,4)}:function(e){e()},require||(require=req),req.version=version,req.jsExtRegExp=/^\/|:|\?|\.js$/,req.isBrowser=isBrowser,s=req.s={contexts:contexts,newContext:newContext},req({}),each(["toUrl","undef","defined","specified"],function(e){req[e]=function(){var t=contexts[defContextName];return t.require[e].apply(t,arguments)}}),isBrowser&&(head=s.head=document.getElementsByTagName("head")[0],baseElement=document.getElementsByTagName("base")[0],baseElement&&(head=s.head=baseElement.parentNode)),req.onError=defaultOnError,req.createNode=function(e,t,n){var r=e.xhtml?document.createElementNS("http://www.w3.org/1999/xhtml","html:script"):document.createElement("script");return r.type=e.scriptType||"text/javascript",r.charset="utf-8",r.async=!0,r},req.load=function(e,t,n){var r=e&&e.config||{},i;if(isBrowser)return i=req.createNode(r,t,n),i.setAttribute("data-requirecontext",e.contextName),i.setAttribute("data-requiremodule",t),i.attachEvent&&!(i.attachEvent.toString&&i.attachEvent.toString().indexOf("[native code")<0)&&!isOpera?(useInteractive=!0,i.attachEvent("onreadystatechange",e.onScriptLoad)):(i.addEventListener("load",e.onScriptLoad,!1),i.addEventListener("error",e.onScriptError,!1)),i.src=n,currentlyAddingScript=i,baseElement?head.insertBefore(i,baseElement):head.appendChild(i),currentlyAddingScript=null,i;if(isWebWorker)try{importScripts(n),e.completeLoad(t)}catch(s){e.onError(makeError("importscripts","importScripts failed for "+t+" at "+n,s,[t]))}},isBrowser&&!cfg.skipDataMain&&eachReverse(scripts(),function(e){head||(head=e.parentNode),dataMain=e.getAttribute("data-main");if(dataMain)return mainScript=dataMain,cfg.baseUrl||(src=mainScript.split("/"),mainScript=src.pop(),subPath=src.length?src.join("/")+"/":"./",cfg.baseUrl=subPath),mainScript=mainScript.replace(jsSuffixRegExp,""),req.jsExtRegExp.test(mainScript)&&(mainScript=dataMain),cfg.deps=cfg.deps?cfg.deps.concat(mainScript):[mainScript],!0}),define=function(e,t,n){var r,i;typeof e!="string"&&(n=t,t=e,e=null),isArray(t)||(n=t,t=null),!t&&isFunction(n)&&(t=[],n.length&&(n.toString().replace(commentRegExp,"").replace(cjsRequireRegExp,function(e,n){t.push(n)}),t=(n.length===1?["require"]:["require","exports","module"]).concat(t))),useInteractive&&(r=currentlyAddingScript||getInteractiveScript(),r&&(e||(e=r.getAttribute("data-requiremodule")),i=contexts[r.getAttribute("data-requirecontext")])),(i?i.defQueue:globalDefQueue).push([e,t,n])},define.amd={jQuery:!0},req.exec=function(text){return eval(text)},req(cfg)})(this),function(e,t){typeof module=="object"&&typeof module.exports=="object"?module.exports=e.document?t(e,!0):function(e){if(!e.document)throw new Error("jQuery requires a window with a document");return t(e)}:t(e)}(typeof window!="undefined"?window:this,function(window,noGlobal){function isArraylike(e){var t=e.length,n=jQuery.type(e);return n==="function"||jQuery.isWindow(e)?!1:e.nodeType===1&&t?!0:n==="array"||t===0||typeof t=="number"&&t>0&&t-1 in e}function winnow(e,t,n){if(jQuery.isFunction(t))return jQuery.grep(e,function(e,r){return!!t.call(e,r,e)!==n});if(t.nodeType)return jQuery.grep(e,function(e){return e===t!==n});if(typeof t=="string"){if(risSimple.test(t))return jQuery.filter(t,e,n);t=jQuery.filter(t,e)}return jQuery.grep(e,function(e){return indexOf.call(t,e)>=0!==n})}function sibling(e,t){while((e=e[t])&&e.nodeType!==1);return e}function createOptions(e){var t=optionsCache[e]={};return jQuery.each(e.match(rnotwhite)||[],function(e,n){t[n]=!0}),t}function completed(){document.removeEventListener("DOMContentLoaded",completed,!1),window.removeEventListener("load",completed,!1),jQuery.ready()}function Data(){Object.defineProperty(this.cache={},0,{get:function(){return{}}}),this.expando=jQuery.expando+Math.random()}function dataAttr(e,t,n){var r;if(n===undefined&&e.nodeType===1){r="data-"+t.replace(rmultiDash,"-$1").toLowerCase(),n=e.getAttribute(r);if(typeof n=="string"){try{n=n==="true"?!0:n==="false"?!1:n==="null"?null:+n+""===n?+n:rbrace.test(n)?jQuery.parseJSON(n):n}catch(i){}data_user.set(e,t,n)}else n=undefined}return n}function returnTrue(){return!0}function returnFalse(){return!1}function safeActiveElement(){try{return document.activeElement}catch(e){}}function manipulationTarget(e,t){return jQuery.nodeName(e,"table")&&jQuery.nodeName(t.nodeType!==11?t:t.firstChild,"tr")?e.getElementsByTagName("tbody")[0]||e.appendChild(e.ownerDocument.createElement("tbody")):e}function disableScript(e){return e.type=(e.getAttribute("type")!==null)+"/"+e.type,e}function restoreScript(e){var t=rscriptTypeMasked.exec(e.type);return t?e.type=t[1]:e.removeAttribute("type"),e}function setGlobalEval(e,t){var n=0,r=e.length;for(;n<r;n++)data_priv.set(e[n],"globalEval",!t||data_priv.get(t[n],"globalEval"))}function cloneCopyEvent(e,t){var n,r,i,s,o,u,a,f;if(t.nodeType!==1)return;if(data_priv.hasData(e)){s=data_priv.access(e),o=data_priv.set(t,s),f=s.events;if(f){delete o.handle,o.events={};for(i in f)for(n=0,r=f[i].length;n<r;n++)jQuery.event.add(t,i,f[i][n])}}data_user.hasData(e)&&(u=data_user.access(e),a=jQuery.extend({},u),data_user.set(t,a))}function getAll(e,t){var n=e.getElementsByTagName?e.getElementsByTagName(t||"*"):e.querySelectorAll?e.querySelectorAll(t||"*"):[];return t===undefined||t&&jQuery.nodeName(e,t)?jQuery.merge([e],n):n}function fixInput(e,t){var n=t.nodeName.toLowerCase();if(n==="input"&&rcheckableType.test(e.type))t.checked=e.checked;else if(n==="input"||n==="textarea")t.defaultValue=e.defaultValue}function actualDisplay(e,t){var n=jQuery(t.createElement(e)).appendTo(t.body),r=window.getDefaultComputedStyle?window.getDefaultComputedStyle(n[0]).display:jQuery.css(n[0],"display");return n.detach(),r}function defaultDisplay(e){var t=document,n=elemdisplay[e];if(!n){n=actualDisplay(e,t);if(n==="none"||!n)iframe=(iframe||jQuery("<iframe frameborder='0' width='0' height='0'/>")).appendTo(t.documentElement),t=iframe[0].contentDocument,t.write(),t.close(),n=actualDisplay(e,t),iframe.detach();elemdisplay[e]=n}return n}function curCSS(e,t,n){var r,i,s,o,u=e.style;return n=n||getStyles(e),n&&(o=n.getPropertyValue(t)||n[t]),n&&(o===""&&!jQuery.contains(e.ownerDocument,e)&&(o=jQuery.style(e,t)),rnumnonpx.test(o)&&rmargin.test(t)&&(r=u.width,i=u.minWidth,s=u.maxWidth,u.minWidth=u.maxWidth=u.width=o,o=n.width,u.width=r,u.minWidth=i,u.maxWidth=s)),o!==undefined?o+"":o}function addGetHookIf(e,t){return{get:function(){if(e()){delete this.get;return}return(this.get=t).apply(this,arguments)}}}function vendorPropName(e,t){if(t in e)return t;var n=t[0].toUpperCase()+t.slice(1),r=t,i=cssPrefixes.length;while(i--){t=cssPrefixes[i]+n;if(t in e)return t}return r}function setPositiveNumber(e,t,n){var r=rnumsplit.exec(t);return r?Math.max(0,r[1]-(n||0))+(r[2]||"px"):t}function augmentWidthOrHeight(e,t,n,r,i){var s=n===(r?"border":"content")?4:t==="width"?1:0,o=0;for(;s<4;s+=2)n==="margin"&&(o+=jQuery.css(e,n+cssExpand[s],!0,i)),r?(n==="content"&&(o-=jQuery.css(e,"padding"+cssExpand[s],!0,i)),n!=="margin"&&(o-=jQuery.css(e,"border"+cssExpand[s]+"Width",!0,i))):(o+=jQuery.css(e,"padding"+cssExpand[s],!0,i),n!=="padding"&&(o+=jQuery.css(e,"border"+cssExpand[s]+"Width",!0,i)));return o}function getWidthOrHeight(e,t,n){var r=!0,i=t==="width"?e.offsetWidth:e.offsetHeight,s=getStyles(e),o=jQuery.css(e,"boxSizing",!1,s)==="border-box";if(i<=0||i==null){i=curCSS(e,t,s);if(i<0||i==null)i=e.style[t];if(rnumnonpx.test(i))return i;r=o&&(support.boxSizingReliable()||i===e.style[t]),i=parseFloat(i)||0}return i+augmentWidthOrHeight(e,t,n||(o?"border":"content"),r,s)+"px"}function showHide(e,t){var n,r,i,s=[],o=0,u=e.length;for(;o<u;o++){r=e[o];if(!r.style)continue;s[o]=data_priv.get(r,"olddisplay"),n=r.style.display,t?(!s[o]&&n==="none"&&(r.style.display=""),r.style.display===""&&isHidden(r)&&(s[o]=data_priv.access(r,"olddisplay",defaultDisplay(r.nodeName)))):s[o]||(i=isHidden(r),(n&&n!=="none"||!i)&&data_priv.set(r,"olddisplay",i?n:jQuery.css(r,"display")))}for(o=0;o<u;o++){r=e[o];if(!r.style)continue;if(!t||r.style.display==="none"||r.style.display==="")r.style.display=t?s[o]||"":"none"}return e}function Tween(e,t,n,r,i){return new Tween.prototype.init(e,t,n,r,i)}function createFxNow(){return setTimeout(function(){fxNow=undefined}),fxNow=jQuery.now()}function genFx(e,t){var n,r=0,i={height:e};t=t?1:0;for(;r<4;r+=2-t)n=cssExpand[r],i["margin"+n]=i["padding"+n]=e;return t&&(i.opacity=i.width=e),i}function createTween(e,t,n){var r,i=(tweeners[t]||[]).concat(tweeners["*"]),s=0,o=i.length;for(;s<o;s++)if(r=i[s].call(n,t,e))return r}function defaultPrefilter(e,t,n){var r,i,s,o,u,a,f,l=this,c={},h=e.style,p=e.nodeType&&isHidden(e),d=data_priv.get(e,"fxshow");n.queue||(u=jQuery._queueHooks(e,"fx"),u.unqueued==null&&(u.unqueued=0,a=u.empty.fire,u.empty.fire=function(){u.unqueued||a()}),u.unqueued++,l.always(function(){l.always(function(){u.unqueued--,jQuery.queue(e,"fx").length||u.empty.fire()})})),e.nodeType===1&&("height"in t||"width"in t)&&(n.overflow=[h.overflow,h.overflowX,h.overflowY],f=jQuery.css(e,"display"),f==="none"&&(f=defaultDisplay(e.nodeName)),f==="inline"&&jQuery.css(e,"float")==="none"&&(h.display="inline-block")),n.overflow&&(h.overflow="hidden",l.always(function(){h.overflow=n.overflow[0],h.overflowX=n.overflow[1],h.overflowY=n.overflow[2]}));for(r in t){i=t[r];if(rfxtypes.exec(i)){delete t[r],s=s||i==="toggle";if(i===(p?"hide":"show")){if(i!=="show"||!d||d[r]===undefined)continue;p=!0}c[r]=d&&d[r]||jQuery.style(e,r)}}if(!jQuery.isEmptyObject(c)){d?"hidden"in d&&(p=d.hidden):d=data_priv.access(e,"fxshow",{}),s&&(d.hidden=!p),p?jQuery(e).show():l.done(function(){jQuery(e).hide()}),l.done(function(){var t;data_priv.remove(e,"fxshow");for(t in c)jQuery.style(e,t,c[t])});for(r in c)o=createTween(p?d[r]:0,r,l),r in d||(d[r]=o.start,p&&(o.end=o.start,o.start=r==="width"||r==="height"?1:0))}}function propFilter(e,t){var n,r,i,s,o;for(n in e){r=jQuery.camelCase(n),i=t[r],s=e[n],jQuery.isArray(s)&&(i=s[1],s=e[n]=s[0]),n!==r&&(e[r]=s,delete e[n]),o=jQuery.cssHooks[r];if(o&&"expand"in o){s=o.expand(s),delete e[r];for(n in s)n in e||(e[n]=s[n],t[n]=i)}else t[r]=i}}function Animation(e,t,n){var r,i,s=0,o=animationPrefilters.length,u=jQuery.Deferred().always(function(){delete a.elem}),a=function(){if(i)return!1;var t=fxNow||createFxNow(),n=Math.max(0,f.startTime+f.duration-t),r=n/f.duration||0,s=1-r,o=0,a=f.tweens.length;for(;o<a;o++)f.tweens[o].run(s);return u.notifyWith(e,[f,s,n]),s<1&&a?n:(u.resolveWith(e,[f]),!1)},f=u.promise({elem:e,props:jQuery.extend({},t),opts:jQuery.extend(!0,{specialEasing:{}},n),originalProperties:t,originalOptions:n,startTime:fxNow||createFxNow(),duration:n.duration,tweens:[],createTween:function(t,n){var r=jQuery.Tween(e,f.opts,t,n,f.opts.specialEasing[t]||f.opts.easing);return f.tweens.push(r),r},stop:function(t){var n=0,r=t?f.tweens.length:0;if(i)return this;i=!0;for(;n<r;n++)f.tweens[n].run(1);return t?u.resolveWith(e,[f,t]):u.rejectWith(e,[f,t]),this}}),l=f.props;propFilter(l,f.opts.specialEasing);for(;s<o;s++){r=animationPrefilters[s].call(f,e,l,f.opts);if(r)return r}return jQuery.map(l,createTween,f),jQuery.isFunction(f.opts.start)&&f.opts.start.call(e,f),jQuery.fx.timer(jQuery.extend(a,{elem:e,anim:f,queue:f.opts.queue})),f.progress(f.opts.progress).done(f.opts.done,f.opts.complete).fail(f.opts.fail).always(f.opts.always)}function addToPrefiltersOrTransports(e){return function(t,n){typeof t!="string"&&(n=t,t="*");var r,i=0,s=t.toLowerCase().match(rnotwhite)||[];if(jQuery.isFunction(n))while(r=s[i++])r[0]==="+"?(r=r.slice(1)||"*",(e[r]=e[r]||[]).unshift(n)):(e[r]=e[r]||[]).push(n)}}function inspectPrefiltersOrTransports(e,t,n,r){function o(u){var a;return i[u]=!0,jQuery.each(e[u]||[],function(e,u){var f=u(t,n,r);if(typeof f=="string"&&!s&&!i[f])return t.dataTypes.unshift(f),o(f),!1;if(s)return!(a=f)}),a}var i={},s=e===transports;return o(t.dataTypes[0])||!i["*"]&&o("*")}function ajaxExtend(e,t){var n,r,i=jQuery.ajaxSettings.flatOptions||{};for(n in t)t[n]!==undefined&&((i[n]?e:r||(r={}))[n]=t[n]);return r&&jQuery.extend(!0,e,r),e}function ajaxHandleResponses(e,t,n){var r,i,s,o,u=e.contents,a=e.dataTypes;while(a[0]==="*")a.shift(),r===undefined&&(r=e.mimeType||t.getResponseHeader("Content-Type"));if(r)for(i in u)if(u[i]&&u[i].test(r)){a.unshift(i);break}if(a[0]in n)s=a[0];else{for(i in n){if(!a[0]||e.converters[i+" "+a[0]]){s=i;break}o||(o=i)}s=s||o}if(s)return s!==a[0]&&a.unshift(s),n[s]}function ajaxConvert(e,t,n,r){var i,s,o,u,a,f={},l=e.dataTypes.slice();if(l[1])for(o in e.converters)f[o.toLowerCase()]=e.converters[o];s=l.shift();while(s){e.responseFields[s]&&(n[e.responseFields[s]]=t),!a&&r&&e.dataFilter&&(t=e.dataFilter(t,e.dataType)),a=s,s=l.shift();if(s)if(s==="*")s=a;else if(a!=="*"&&a!==s){o=f[a+" "+s]||f["* "+s];if(!o)for(i in f){u=i.split(" ");if(u[1]===s){o=f[a+" "+u[0]]||f["* "+u[0]];if(o){o===!0?o=f[i]:f[i]!==!0&&(s=u[0],l.unshift(u[1]));break}}}if(o!==!0)if(o&&e["throws"])t=o(t);else try{t=o(t)}catch(c){return{state:"parsererror",error:o?c:"No conversion from "+a+" to "+s}}}}return{state:"success",data:t}}function buildParams(e,t,n,r){var i;if(jQuery.isArray(t))jQuery.each(t,function(t,i){n||rbracket.test(e)?r(e,i):buildParams(e+"["+(typeof i=="object"?t:"")+"]",i,n,r)});else if(!n&&jQuery.type(t)==="object")for(i in t)buildParams(e+"["+i+"]",t[i],n,r);else r(e,t)}function getWindow(e){return jQuery.isWindow(e)?e:e.nodeType===9&&e.defaultView}var arr=[],slice=arr.slice,concat=arr.concat,push=arr.push,indexOf=arr.indexOf,class2type={},toString=class2type.toString,hasOwn=class2type.hasOwnProperty,trim="".trim,support={},document=window.document,version="2.1.0",jQuery=function(e,t){return new jQuery.fn.init(e,t)},rmsPrefix=/^-ms-/,rdashAlpha=/-([\da-z])/gi,fcamelCase=function(e,t){return t.toUpperCase()};jQuery.fn=jQuery.prototype={jquery:version,constructor:jQuery,selector:"",length:0,toArray:function(){return slice.call(this)},get:function(e){return e!=null?e<0?this[e+this.length]:this[e]:slice.call(this)},pushStack:function(e){var t=jQuery.merge(this.constructor(),e);return t.prevObject=this,t.context=this.context,t},each:function(e,t){return jQuery.each(this,e,t)},map:function(e){return this.pushStack(jQuery.map(this,function(t,n){return e.call(t,n,t)}))},slice:function(){return this.pushStack(slice.apply(this,arguments))},first:function(){return this.eq(0)},last:function(){return this.eq(-1)},eq:function(e){var t=this.length,n=+e+(e<0?t:0);return this.pushStack(n>=0&&n<t?[this[n]]:[])},end:function(){return this.prevObject||this.constructor(null)},push:push,sort:arr.sort,splice:arr.splice},jQuery.extend=jQuery.fn.extend=function(){var e,t,n,r,i,s,o=arguments[0]||{},u=1,a=arguments.length,f=!1;typeof o=="boolean"&&(f=o,o=arguments[u]||{},u++),typeof o!="object"&&!jQuery.isFunction(o)&&(o={}),u===a&&(o=this,u--);for(;u<a;u++)if((e=arguments[u])!=null)for(t in e){n=o[t],r=e[t];if(o===r)continue;f&&r&&(jQuery.isPlainObject(r)||(i=jQuery.isArray(r)))?(i?(i=!1,s=n&&jQuery.isArray(n)?n:[]):s=n&&jQuery.isPlainObject(n)?n:{},o[t]=jQuery.extend(f,s,r)):r!==undefined&&(o[t]=r)}return o},jQuery.extend({expando:"jQuery"+(version+Math.random()).replace(/\D/g,""),isReady:!0,error:function(e){throw new Error(e)},noop:function(){},isFunction:function(e){return jQuery.type(e)==="function"},isArray:Array.isArray,isWindow:function(e){return e!=null&&e===e.window},isNumeric:function(e){return e-parseFloat(e)>=0},isPlainObject:function(e){if(jQuery.type(e)!=="object"||e.nodeType||jQuery.isWindow(e))return!1;try{if(e.constructor&&!hasOwn.call(e.constructor.prototype,"isPrototypeOf"))return!1}catch(t){return!1}return!0},isEmptyObject:function(e){var t;for(t in e)return!1;return!0},type:function(e){return e==null?e+"":typeof e=="object"||typeof e=="function"?class2type[toString.call(e)]||"object":typeof e},globalEval:function(code){var script,indirect=eval;code=jQuery.trim(code),code&&(code.indexOf("use strict")===1?(script=document.createElement("script"),script.text=code,document.head.appendChild(script).parentNode.removeChild(script)):indirect(code))},camelCase:function(e){return e.replace(rmsPrefix,"ms-").replace(rdashAlpha,fcamelCase)},nodeName:function(e,t){return e.nodeName&&e.nodeName.toLowerCase()===t.toLowerCase()},each:function(e,t,n){var r,i=0,s=e.length,o=isArraylike(e);if(n)if(o)for(;i<s;i++){r=t.apply(e[i],n);if(r===!1)break}else for(i in e){r=t.apply(e[i],n);if(r===!1)break}else if(o)for(;i<s;i++){r=t.call(e[i],i,e[i]);if(r===!1)break}else for(i in e){r=t.call(e[i],i,e[i]);if(r===!1)break}return e},trim:function(e){return e==null?"":trim.call(e)},makeArray:function(e,t){var n=t||[];return e!=null&&(isArraylike(Object(e))?jQuery.merge(n,typeof e=="string"?[e]:e):push.call(n,e)),n},inArray:function(e,t,n){return t==null?-1:indexOf.call(t,e,n)},merge:function(e,t){var n=+t.length,r=0,i=e.length;for(;r<n;r++)e[i++]=t[r];return e.length=i,e},grep:function(e,t,n){var r,i=[],s=0,o=e.length,u=!n;for(;s<o;s++)r=!t(e[s],s),r!==u&&i.push(e[s]);return i},map:function(e,t,n){var r,i=0,s=e.length,o=isArraylike(e),u=[];if(o)for(;i<s;i++)r=t(e[i],i,n),r!=null&&u.push(r);else for(i in e)r=t(e[i],i,n),r!=null&&u.push(r);return concat.apply([],u)},guid:1,proxy:function(e,t){var n,r,i;return typeof t=="string"&&(n=e[t],t=e,e=n),jQuery.isFunction(e)?(r=slice.call(arguments,2),i=function(){return e.apply(t||this,r.concat(slice.call(arguments)))},i.guid=e.guid=e.guid||jQuery.guid++,i):undefined},now:Date.now,support:support}),jQuery.each("Boolean Number String Function Array Date RegExp Object Error".split(" "),function(e,t){class2type["[object "+t+"]"]=t.toLowerCase()});var Sizzle=function(e){function rt(e,t,r,i){var s,o,u,a,f,h,v,m,w,E;(t?t.ownerDocument||t:b)!==c&&l(t),t=t||c,r=r||[];if(!e||typeof e!="string")return r;if((a=t.nodeType)!==1&&a!==9)return[];if(p&&!i){if(s=G.exec(e))if(u=s[1]){if(a===9){o=t.getElementById(u);if(!o||!o.parentNode)return r;if(o.id===u)return r.push(o),r}else if(t.ownerDocument&&(o=t.ownerDocument.getElementById(u))&&g(t,o)&&o.id===u)return r.push(o),r}else{if(s[2])return _.apply(r,t.getElementsByTagName(e)),r;if((u=s[3])&&n.getElementsByClassName&&t.getElementsByClassName)return _.apply(r,t.getElementsByClassName(u)),r}if(n.qsa&&(!d||!d.test(e))){m=v=y,w=t,E=a===9&&e;if(a===1&&t.nodeName.toLowerCase()!=="object"){h=dt(e),(v=t.getAttribute("id"))?m=v.replace(Z,"\\$&"):t.setAttribute("id",m),m="[id='"+m+"'] ",f=h.length;while(f--)h[f]=m+vt(h[f]);w=Y.test(e)&&ht(t.parentNode)||t,E=h.join(",")}if(E)try{return _.apply(r,w.querySelectorAll(E)),r}catch(S){}finally{v||t.removeAttribute("id")}}}return xt(e.replace(R,"$1"),t,r,i)}function it(){function t(n,i){return e.push(n+" ")>r.cacheLength&&delete t[e.shift()],t[n+" "]=i}var e=[];return t}function st(e){return e[y]=!0,e}function ot(e){var t=c.createElement("div");try{return!!e(t)}catch(n){return!1}finally{t.parentNode&&t.parentNode.removeChild(t),t=null}}function ut(e,t){var n=e.split("|"),i=e.length;while(i--)r.attrHandle[n[i]]=t}function at(e,t){var n=t&&e,r=n&&e.nodeType===1&&t.nodeType===1&&(~t.sourceIndex||k)-(~e.sourceIndex||k);if(r)return r;if(n)while(n=n.nextSibling)if(n===t)return-1;return e?1:-1}function ft(e){return function(t){var n=t.nodeName.toLowerCase();return n==="input"&&t.type===e}}function lt(e){return function(t){var n=t.nodeName.toLowerCase();return(n==="input"||n==="button")&&t.type===e}}function ct(e){return st(function(t){return t=+t,st(function(n,r){var i,s=e([],n.length,t),o=s.length;while(o--)n[i=s[o]]&&(n[i]=!(r[i]=n[i]))})})}function ht(e){return e&&typeof e.getElementsByTagName!==C&&e}function pt(){}function dt(e,t){var n,i,s,o,u,a,f,l=x[e+" "];if(l)return t?0:l.slice(0);u=e,a=[],f=r.preFilter;while(u){if(!n||(i=U.exec(u)))i&&(u=u.slice(i[0].length)||u),a.push(s=[]);n=!1;if(i=z.exec(u))n=i.shift(),s.push({value:n,type:i[0].replace(R," ")}),u=u.slice(n.length);for(o in r.filter)(i=$[o].exec(u))&&(!f[o]||(i=f[o](i)))&&(n=i.shift(),s.push({value:n,type:o,matches:i}),u=u.slice(n.length));if(!n)break}return t?u.length:u?rt.error(e):x(e,a).slice(0)}function vt(e){var t=0,n=e.length,r="";for(;t<n;t++)r+=e[t].value;return r}function mt(e,t,n){var r=t.dir,i=n&&r==="parentNode",s=E++;return t.first?function(t,n,s){while(t=t[r])if(t.nodeType===1||i)return e(t,n,s)}:function(t,n,o){var u,a,f=[w,s];if(o){while(t=t[r])if(t.nodeType===1||i)if(e(t,n,o))return!0}else while(t=t[r])if(t.nodeType===1||i){a=t[y]||(t[y]={});if((u=a[r])&&u[0]===w&&u[1]===s)return f[2]=u[2];a[r]=f;if(f[2]=e(t,n,o))return!0}}}function gt(e){return e.length>1?function(t,n,r){var i=e.length;while(i--)if(!e[i](t,n,r))return!1;return!0}:e[0]}function yt(e,t,n,r,i){var s,o=[],u=0,a=e.length,f=t!=null;for(;u<a;u++)if(s=e[u])if(!n||n(s,r,i))o.push(s),f&&t.push(u);return o}function bt(e,t,n,r,i,s){return r&&!r[y]&&(r=bt(r)),i&&!i[y]&&(i=bt(i,s)),st(function(s,o,u,a){var f,l,c,h=[],p=[],d=o.length,v=s||St(t||"*",u.nodeType?[u]:u,[]),m=e&&(s||!t)?yt(v,h,e,u,a):v,g=n?i||(s?e:d||r)?[]:o:m;n&&n(m,g,u,a);if(r){f=yt(g,p),r(f,[],u,a),l=f.length;while(l--)if(c=f[l])g[p[l]]=!(m[p[l]]=c)}if(s){if(i||e){if(i){f=[],l=g.length;while(l--)(c=g[l])&&f.push(m[l]=c);i(null,g=[],f,a)}l=g.length;while(l--)(c=g[l])&&(f=i?P.call(s,c):h[l])>-1&&(s[f]=!(o[f]=c))}}else g=yt(g===o?g.splice(d,g.length):g),i?i(null,o,g,a):_.apply(o,g)})}function wt(e){var t,n,i,s=e.length,o=r.relative[e[0].type],a=o||r.relative[" "],f=o?1:0,l=mt(function(e){return e===t},a,!0),c=mt(function(e){return P.call(t,e)>-1},a,!0),h=[function(e,n,r){return!o&&(r||n!==u)||((t=n).nodeType?l(e,n,r):c(e,n,r))}];for(;f<s;f++)if(n=r.relative[e[f].type])h=[mt(gt(h),n)];else{n=r.filter[e[f].type].apply(null,e[f].matches);if(n[y]){i=++f;for(;i<s;i++)if(r.relative[e[i].type])break;return bt(f>1&>(h),f>1&&vt(e.slice(0,f-1).concat({value:e[f-2].type===" "?"*":""})).replace(R,"$1"),n,f<i&&wt(e.slice(f,i)),i<s&&wt(e=e.slice(i)),i<s&&vt(e))}h.push(n)}return gt(h)}function Et(e,t){var n=t.length>0,i=e.length>0,s=function(s,o,a,f,l){var h,p,d,v=0,m="0",g=s&&[],y=[],b=u,E=s||i&&r.find.TAG("*",l),S=w+=b==null?1:Math.random()||.1,x=E.length;l&&(u=o!==c&&o);for(;m!==x&&(h=E[m])!=null;m++){if(i&&h){p=0;while(d=e[p++])if(d(h,o,a)){f.push(h);break}l&&(w=S)}n&&((h=!d&&h)&&v--,s&&g.push(h))}v+=m;if(n&&m!==v){p=0;while(d=t[p++])d(g,y,o,a);if(s){if(v>0)while(m--)!g[m]&&!y[m]&&(y[m]=O.call(f));y=yt(y)}_.apply(f,y),l&&!s&&y.length>0&&v+t.length>1&&rt.uniqueSort(f)}return l&&(w=S,u=b),g};return n?st(s):s}function St(e,t,n){var r=0,i=t.length;for(;r<i;r++)rt(e,t[r],n);return n}function xt(e,t,i,s){var u,a,f,l,c,h=dt(e);if(!s&&h.length===1){a=h[0]=h[0].slice(0);if(a.length>2&&(f=a[0]).type==="ID"&&n.getById&&t.nodeType===9&&p&&r.relative[a[1].type]){t=(r.find.ID(f.matches[0].replace(et,tt),t)||[])[0];if(!t)return i;e=e.slice(a.shift().value.length)}u=$.needsContext.test(e)?0:a.length;while(u--){f=a[u];if(r.relative[l=f.type])break;if(c=r.find[l])if(s=c(f.matches[0].replace(et,tt),Y.test(a[0].type)&&ht(t.parentNode)||t)){a.splice(u,1),e=s.length&&vt(a);if(!e)return _.apply(i,s),i;break}}}return o(e,h)(s,t,!p,i,Y.test(e)&&ht(t.parentNode)||t),i}var t,n,r,i,s,o,u,a,f,l,c,h,p,d,v,m,g,y="sizzle"+ -(new Date),b=e.document,w=0,E=0,S=it(),x=it(),T=it(),N=function(e,t){return e===t&&(f=!0),0},C=typeof undefined,k=1<<31,L={}.hasOwnProperty,A=[],O=A.pop,M=A.push,_=A.push,D=A.slice,P=A.indexOf||function(e){var t=0,n=this.length;for(;t<n;t++)if(this[t]===e)return t;return-1},H="checked|selected|async|autofocus|autoplay|controls|defer|disabled|hidden|ismap|loop|multiple|open|readonly|required|scoped",B="[\\x20\\t\\r\\n\\f]",j="(?:\\\\.|[\\w-]|[^\\x00-\\xa0])+",F=j.replace("w","w#"),I="\\["+B+"*("+j+")"+B+"*(?:([*^$|!~]?=)"+B+"*(?:(['\"])((?:\\\\.|[^\\\\])*?)\\3|("+F+")|)|)"+B+"*\\]",q=":("+j+")(?:\\(((['\"])((?:\\\\.|[^\\\\])*?)\\3|((?:\\\\.|[^\\\\()[\\]]|"+I.replace(3,8)+")*)|.*)\\)|)",R=new RegExp("^"+B+"+|((?:^|[^\\\\])(?:\\\\.)*)"+B+"+$","g"),U=new RegExp("^"+B+"*,"+B+"*"),z=new RegExp("^"+B+"*([>+~]|"+B+")"+B+"*"),W=new RegExp("="+B+"*([^\\]'\"]*?)"+B+"*\\]","g"),X=new RegExp(q),V=new RegExp("^"+F+"$"),$={ID:new RegExp("^#("+j+")"),CLASS:new RegExp("^\\.("+j+")"),TAG:new RegExp("^("+j.replace("w","w*")+")"),ATTR:new RegExp("^"+I),PSEUDO:new RegExp("^"+q),CHILD:new RegExp("^:(only|first|last|nth|nth-last)-(child|of-type)(?:\\("+B+"*(even|odd|(([+-]|)(\\d*)n|)"+B+"*(?:([+-]|)"+B+"*(\\d+)|))"+B+"*\\)|)","i"),bool:new RegExp("^(?:"+H+")$","i"),needsContext:new RegExp("^"+B+"*[>+~]|:(even|odd|eq|gt|lt|nth|first|last)(?:\\("+B+"*((?:-\\d)?\\d*)"+B+"*\\)|)(?=[^-]|$)","i")},J=/^(?:input|select|textarea|button)$/i,K=/^h\d$/i,Q=/^[^{]+\{\s*\[native \w/,G=/^(?:#([\w-]+)|(\w+)|\.([\w-]+))$/,Y=/[+~]/,Z=/'|\\/g,et=new RegExp("\\\\([\\da-f]{1,6}"+B+"?|("+B+")|.)","ig"),tt=function(e,t,n){var r="0x"+t-65536;return r!==r||n?t:r<0?String.fromCharCode(r+65536):String.fromCharCode(r>>10|55296,r&1023|56320)};try{_.apply(A=D.call(b.childNodes),b.childNodes),A[b.childNodes.length].nodeType}catch(nt){_={apply:A.length?function(e,t){M.apply(e,D.call(t))}:function(e,t){var n=e.length,r=0;while(e[n++]=t[r++]);e.length=n-1}}}n=rt.support={},s=rt.isXML=function(e){var t=e&&(e.ownerDocument||e).documentElement;return t?t.nodeName!=="HTML":!1},l=rt.setDocument=function(e){var t,i=e?e.ownerDocument||e:b,o=i.defaultView;if(i===c||i.nodeType!==9||!i.documentElement)return c;c=i,h=i.documentElement,p=!s(i),o&&o!==o.top&&(o.addEventListener?o.addEventListener("unload",function(){l()},!1):o.attachEvent&&o.attachEvent("onunload",function(){l()})),n.attributes=ot(function(e){return e.className="i",!e.getAttribute("className")}),n.getElementsByTagName=ot(function(e){return e.appendChild(i.createComment("")),!e.getElementsByTagName("*").length}),n.getElementsByClassName=Q.test(i.getElementsByClassName)&&ot(function(e){return e.innerHTML="<div class='a'></div><div class='a i'></div>",e.firstChild.className="i",e.getElementsByClassName("i").length===2}),n.getById=ot(function(e){return h.appendChild(e).id=y,!i.getElementsByName||!i.getElementsByName(y).length}),n.getById?(r.find.ID=function(e,t){if(typeof t.getElementById!==C&&p){var n=t.getElementById(e);return n&&n.parentNode?[n]:[]}},r.filter.ID=function(e){var t=e.replace(et,tt);return function(e){return e.getAttribute("id")===t}}):(delete r.find.ID,r.filter.ID=function(e){var t=e.replace(et,tt);return function(e){var n=typeof e.getAttributeNode!==C&&e.getAttributeNode("id");return n&&n.value===t}}),r.find.TAG=n.getElementsByTagName?function(e,t){if(typeof t.getElementsByTagName!==C)return t.getElementsByTagName(e)}:function(e,t){var n,r=[],i=0,s=t.getElementsByTagName(e);if(e==="*"){while(n=s[i++])n.nodeType===1&&r.push(n);return r}return s},r.find.CLASS=n.getElementsByClassName&&function(e,t){if(typeof t.getElementsByClassName!==C&&p)return t.getElementsByClassName(e)},v=[],d=[];if(n.qsa=Q.test(i.querySelectorAll))ot(function(e){e.innerHTML="<select t=''><option selected=''></option></select>",e.querySelectorAll("[t^='']").length&&d.push("[*^$]="+B+"*(?:''|\"\")"),e.querySelectorAll("[selected]").length||d.push("\\["+B+"*(?:value|"+H+")"),e.querySelectorAll(":checked").length||d.push(":checked")}),ot(function(e){var t=i.createElement("input");t.setAttribute("type","hidden"),e.appendChild(t).setAttribute("name","D"),e.querySelectorAll("[name=d]").length&&d.push("name"+B+"*[*^$|!~]?="),e.querySelectorAll(":enabled").length||d.push(":enabled",":disabled"),e.querySelectorAll("*,:x"),d.push(",.*:")});return(n.matchesSelector=Q.test(m=h.webkitMatchesSelector||h.mozMatchesSelector||h.oMatchesSelector||h.msMatchesSelector))&&ot(function(e){n.disconnectedMatch=m.call(e,"div"),m.call(e,"[s!='']:x"),v.push("!=",q)}),d=d.length&&new RegExp(d.join("|")),v=v.length&&new RegExp(v.join("|")),t=Q.test(h.compareDocumentPosition),g=t||Q.test(h.contains)?function(e,t){var n=e.nodeType===9?e.documentElement:e,r=t&&t.parentNode;return e===r||!!r&&r.nodeType===1&&!!(n.contains?n.contains(r):e.compareDocumentPosition&&e.compareDocumentPosition(r)&16)}:function(e,t){if(t)while(t=t.parentNode)if(t===e)return!0;return!1},N=t?function(e,t){if(e===t)return f=!0,0;var r=!e.compareDocumentPosition-!t.compareDocumentPosition;return r?r:(r=(e.ownerDocument||e)===(t.ownerDocument||t)?e.compareDocumentPosition(t):1,r&1||!n.sortDetached&&t.compareDocumentPosition(e)===r?e===i||e.ownerDocument===b&&g(b,e)?-1:t===i||t.ownerDocument===b&&g(b,t)?1:a?P.call(a,e)-P.call(a,t):0:r&4?-1:1)}:function(e,t){if(e===t)return f=!0,0;var n,r=0,s=e.parentNode,o=t.parentNode,u=[e],l=[t];if(!s||!o)return e===i?-1:t===i?1:s?-1:o?1:a?P.call(a,e)-P.call(a,t):0;if(s===o)return at(e,t);n=e;while(n=n.parentNode)u.unshift(n);n=t;while(n=n.parentNode)l.unshift(n);while(u[r]===l[r])r++;return r?at(u[r],l[r]):u[r]===b?-1:l[r]===b?1:0},i},rt.matches=function(e,t){return rt(e,null,null,t)},rt.matchesSelector=function(e,t){(e.ownerDocument||e)!==c&&l(e),t=t.replace(W,"='$1']");if(n.matchesSelector&&p&&(!v||!v.test(t))&&(!d||!d.test(t)))try{var r=m.call(e,t);if(r||n.disconnectedMatch||e.document&&e.document.nodeType!==11)return r}catch(i){}return rt(t,c,null,[e]).length>0},rt.contains=function(e,t){return(e.ownerDocument||e)!==c&&l(e),g(e,t)},rt.attr=function(e,t){(e.ownerDocument||e)!==c&&l(e);var i=r.attrHandle[t.toLowerCase()],s=i&&L.call(r.attrHandle,t.toLowerCase())?i(e,t,!p):undefined;return s!==undefined?s:n.attributes||!p?e.getAttribute(t):(s=e.getAttributeNode(t))&&s.specified?s.value:null},rt.error=function(e){throw new Error("Syntax error, unrecognized expression: "+e)},rt.uniqueSort=function(e){var t,r=[],i=0,s=0;f=!n.detectDuplicates,a=!n.sortStable&&e.slice(0),e.sort(N);if(f){while(t=e[s++])t===e[s]&&(i=r.push(s));while(i--)e.splice(r[i],1)}return a=null,e},i=rt.getText=function(e){var t,n="",r=0,s=e.nodeType;if(!s)while(t=e[r++])n+=i(t);else if(s===1||s===9||s===11){if(typeof e.textContent=="string")return e.textContent;for(e=e.firstChild;e;e=e.nextSibling)n+=i(e)}else if(s===3||s===4)return e.nodeValue;return n},r=rt.selectors={cacheLength:50,createPseudo:st,match:$,attrHandle:{},find:{},relative:{">":{dir:"parentNode",first:!0}," ":{dir:"parentNode"},"+":{dir:"previousSibling",first:!0},"~":{dir:"previousSibling"}},preFilter:{ATTR:function(e){return e[1]=e[1].replace(et,tt),e[3]=(e[4]||e[5]||"").replace(et,tt),e[2]==="~="&&(e[3]=" "+e[3]+" "),e.slice(0,4)},CHILD:function(e){return e[1]=e[1].toLowerCase(),e[1].slice(0,3)==="nth"?(e[3]||rt.error(e[0]),e[4]=+(e[4]?e[5]+(e[6]||1):2*(e[3]==="even"||e[3]==="odd")),e[5]=+(e[7]+e[8]||e[3]==="odd")):e[3]&&rt.error(e[0]),e},PSEUDO:function(e){var t,n=!e[5]&&e[2];return $.CHILD.test(e[0])?null:(e[3]&&e[4]!==undefined?e[2]=e[4]:n&&X.test(n)&&(t=dt(n,!0))&&(t=n.indexOf(")",n.length-t)-n.length)&&(e[0]=e[0].slice(0,t),e[2]=n.slice(0,t)),e.slice(0,3))}},filter:{TAG:function(e){var t=e.replace(et,tt).toLowerCase();return e==="*"?function(){return!0}:function(e){return e.nodeName&&e.nodeName.toLowerCase()===t}},CLASS:function(e){var t=S[e+" "];return t||(t=new RegExp("(^|"+B+")"+e+"("+B+"|$)"))&&S(e,function(e){return t.test(typeof e.className=="string"&&e.className||typeof e.getAttribute!==C&&e.getAttribute("class")||"")})},ATTR:function(e,t,n){return function(r){var i=rt.attr(r,e);return i==null?t==="!=":t?(i+="",t==="="?i===n:t==="!="?i!==n:t==="^="?n&&i.indexOf(n)===0:t==="*="?n&&i.indexOf(n)>-1:t==="$="?n&&i.slice(-n.length)===n:t==="~="?(" "+i+" ").indexOf(n)>-1:t==="|="?i===n||i.slice(0,n.length+1)===n+"-":!1):!0}},CHILD:function(e,t,n,r,i){var s=e.slice(0,3)!=="nth",o=e.slice(-4)!=="last",u=t==="of-type";return r===1&&i===0?function(e){return!!e.parentNode}:function(t,n,a){var f,l,c,h,p,d,v=s!==o?"nextSibling":"previousSibling",m=t.parentNode,g=u&&t.nodeName.toLowerCase(),b=!a&&!u;if(m){if(s){while(v){c=t;while(c=c[v])if(u?c.nodeName.toLowerCase()===g:c.nodeType===1)return!1;d=v=e==="only"&&!d&&"nextSibling"}return!0}d=[o?m.firstChild:m.lastChild];if(o&&b){l=m[y]||(m[y]={}),f=l[e]||[],p=f[0]===w&&f[1],h=f[0]===w&&f[2],c=p&&m.childNodes[p];while(c=++p&&c&&c[v]||(h=p=0)||d.pop())if(c.nodeType===1&&++h&&c===t){l[e]=[w,p,h];break}}else if(b&&(f=(t[y]||(t[y]={}))[e])&&f[0]===w)h=f[1];else while(c=++p&&c&&c[v]||(h=p=0)||d.pop())if((u?c.nodeName.toLowerCase()===g:c.nodeType===1)&&++h){b&&((c[y]||(c[y]={}))[e]=[w,h]);if(c===t)break}return h-=i,h===r||h%r===0&&h/r>=0}}},PSEUDO:function(e,t){var n,i=r.pseudos[e]||r.setFilters[e.toLowerCase()]||rt.error("unsupported pseudo: "+e);return i[y]?i(t):i.length>1?(n=[e,e,"",t],r.setFilters.hasOwnProperty(e.toLowerCase())?st(function(e,n){var r,s=i(e,t),o=s.length;while(o--)r=P.call(e,s[o]),e[r]=!(n[r]=s[o])}):function(e){return i(e,0,n)}):i}},pseudos:{not:st(function(e){var t=[],n=[],r=o(e.replace(R,"$1"));return r[y]?st(function(e,t,n,i){var s,o=r(e,null,i,[]),u=e.length;while(u--)if(s=o[u])e[u]=!(t[u]=s)}):function(e,i,s){return t[0]=e,r(t,null,s,n),!n.pop()}}),has:st(function(e){return function(t){return rt(e,t).length>0}}),contains:st(function(e){return function(t){return(t.textContent||t.innerText||i(t)).indexOf(e)>-1}}),lang:st(function(e){return V.test(e||"")||rt.error("unsupported lang: "+e),e=e.replace(et,tt).toLowerCase(),function(t){var n;do if(n=p?t.lang:t.getAttribute("xml:lang")||t.getAttribute("lang"))return n=n.toLowerCase(),n===e||n.indexOf(e+"-")===0;while((t=t.parentNode)&&t.nodeType===1);return!1}}),target:function(t){var n=e.location&&e.location.hash;return n&&n.slice(1)===t.id},root:function(e){return e===h},focus:function(e){return e===c.activeElement&&(!c.hasFocus||c.hasFocus())&&!!(e.type||e.href||~e.tabIndex)},enabled:function(e){return e.disabled===!1},disabled:function(e){return e.disabled===!0},checked:function(e){var t=e.nodeName.toLowerCase();return t==="input"&&!!e.checked||t==="option"&&!!e.selected},selected:function(e){return e.parentNode&&e.parentNode.selectedIndex,e.selected===!0},empty:function(e){for(e=e.firstChild;e;e=e.nextSibling)if(e.nodeType<6)return!1;return!0},parent:function(e){return!r.pseudos.empty(e)},header:function(e){return K.test(e.nodeName)},input:function(e){return J.test(e.nodeName)},button:function(e){var t=e.nodeName.toLowerCase();return t==="input"&&e.type==="button"||t==="button"},text:function(e){var t;return e.nodeName.toLowerCase()==="input"&&e.type==="text"&&((t=e.getAttribute("type"))==null||t.toLowerCase()==="text")},first:ct(function(){return[0]}),last:ct(function(e,t){return[t-1]}),eq:ct(function(e,t,n){return[n<0?n+t:n]}),even:ct(function(e,t){var n=0;for(;n<t;n+=2)e.push(n);return e}),odd:ct(function(e,t){var n=1;for(;n<t;n+=2)e.push(n);return e}),lt:ct(function(e,t,n){var r=n<0?n+t:n;for(;--r>=0;)e.push(r);return e}),gt:ct(function(e,t,n){var r=n<0?n+t:n;for(;++r<t;)e.push(r);return e})}},r.pseudos.nth=r.pseudos.eq;for(t in{radio:!0,checkbox:!0,file:!0,password:!0,image:!0})r.pseudos[t]=ft(t);for(t in{submit:!0,reset:!0})r.pseudos[t]=lt(t);return pt.prototype=r.filters=r.pseudos,r.setFilters=new pt,o=rt.compile=function(e,t){var n,r=[],i=[],s=T[e+" "];if(!s){t||(t=dt(e)),n=t.length;while(n--)s=wt(t[n]),s[y]?r.push(s):i.push(s);s=T(e,Et(i,r))}return s},n.sortStable=y.split("").sort(N).join("")===y,n.detectDuplicates=!!f,l(),n.sortDetached=ot(function(e){return e.compareDocumentPosition(c.createElement("div"))&1}),ot(function(e){return e.innerHTML="<a href='#'></a>",e.firstChild.getAttribute("href")==="#"})||ut("type|href|height|width",function(e,t,n){if(!n)return e.getAttribute(t,t.toLowerCase()==="type"?1:2)}),(!n.attributes||!ot(function(e){return e.innerHTML="<input/>",e.firstChild.setAttribute("value",""),e.firstChild.getAttribute("value")===""}))&&ut("value",function(e,t,n){if(!n&&e.nodeName.toLowerCase()==="input")return e.defaultValue}),ot(function(e){return e.getAttribute("disabled")==null})||ut(H,function(e,t,n){var r;if(!n)return e[t]===!0?t.toLowerCase():(r=e.getAttributeNode(t))&&r.specified?r.value:null}),rt}(window);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;var rneedsContext=jQuery.expr.match.needsContext,rsingleTag=/^<(\w+)\s*\/?>(?:<\/\1>|)$/,risSimple=/^.[^:#\[\.,]*$/;jQuery.filter=function(e,t,n){var r=t[0];return n&&(e=":not("+e+")"),t.length===1&&r.nodeType===1?jQuery.find.matchesSelector(r,e)?[r]:[]:jQuery.find.matches(e,jQuery.grep(t,function(e){return e.nodeType===1}))},jQuery.fn.extend({find:function(e){var t,n=this.length,r=[],i=this;if(typeof e!="string")return this.pushStack(jQuery(e).filter(function(){for(t=0;t<n;t++)if(jQuery.contains(i[t],this))return!0}));for(t=0;t<n;t++)jQuery.find(e,i[t],r);return r=this.pushStack(n>1?jQuery.unique(r):r),r.selector=this.selector?this.selector+" "+e:e,r},filter:function(e){return this.pushStack(winnow(this,e||[],!1))},not:function(e){return this.pushStack(winnow(this,e||[],!0))},is:function(e){return!!winnow(this,typeof e=="string"&&rneedsContext.test(e)?jQuery(e):e||[],!1).length}});var rootjQuery,rquickExpr=/^(?:\s*(<[\w\W]+>)[^>]*|#([\w-]*))$/,init=jQuery.fn.init=function(e,t){var n,r;if(!e)return this;if(typeof e=="string"){e[0]==="<"&&e[e.length-1]===">"&&e.length>=3?n=[null,e,null]:n=rquickExpr.exec(e);if(n&&(n[1]||!t)){if(n[1]){t=t instanceof jQuery?t[0]:t,jQuery.merge(this,jQuery.parseHTML(n[1],t&&t.nodeType?t.ownerDocument||t:document,!0));if(rsingleTag.test(n[1])&&jQuery.isPlainObject(t))for(n in t)jQuery.isFunction(this[n])?this[n](t[n]):this.attr(n,t[n]);return this}return r=document.getElementById(n[2]),r&&r.parentNode&&(this.length=1,this[0]=r),this.context=document,this.selector=e,this}return!t||t.jquery?(t||rootjQuery).find(e):this.constructor(t).find(e)}return e.nodeType?(this.context=this[0]=e,this.length=1,this):jQuery.isFunction(e)?typeof rootjQuery.ready!="undefined"?rootjQuery.ready(e):e(jQuery):(e.selector!==undefined&&(this.selector=e.selector,this.context=e.context),jQuery.makeArray(e,this))};init.prototype=jQuery.fn,rootjQuery=jQuery(document);var rparentsprev=/^(?:parents|prev(?:Until|All))/,guaranteedUnique={children:!0,contents:!0,next:!0,prev:!0};jQuery.extend({dir:function(e,t,n){var r=[],i=n!==undefined;while((e=e[t])&&e.nodeType!==9)if(e.nodeType===1){if(i&&jQuery(e).is(n))break;r.push(e)}return r},sibling:function(e,t){var n=[];for(;e;e=e.nextSibling)e.nodeType===1&&e!==t&&n.push(e);return n}}),jQuery.fn.extend({has:function(e){var t=jQuery(e,this),n=t.length;return this.filter(function(){var e=0;for(;e<n;e++)if(jQuery.contains(this,t[e]))return!0})},closest:function(e,t){var n,r=0,i=this.length,s=[],o=rneedsContext.test(e)||typeof e!="string"?jQuery(e,t||this.context):0;for(;r<i;r++)for(n=this[r];n&&n!==t;n=n.parentNode)if(n.nodeType<11&&(o?o.index(n)>-1:n.nodeType===1&&jQuery.find.matchesSelector(n,e))){s.push(n);break}return this.pushStack(s.length>1?jQuery.unique(s):s)},index:function(e){return e?typeof e=="string"?indexOf.call(jQuery(e),this[0]):indexOf.call(this,e.jquery?e[0]:e):this[0]&&this[0].parentNode?this.first().prevAll().length:-1},add:function(e,t){return this.pushStack(jQuery.unique(jQuery.merge(this.get(),jQuery(e,t))))},addBack:function(e){return this.add(e==null?this.prevObject:this.prevObject.filter(e))}}),jQuery.each({parent:function(e){var t=e.parentNode;return t&&t.nodeType!==11?t:null},parents:function(e){return jQuery.dir(e,"parentNode")},parentsUntil:function(e,t,n){return jQuery.dir(e,"parentNode",n)},next:function(e){return sibling(e,"nextSibling")},prev:function(e){return sibling(e,"previousSibling")},nextAll:function(e){return jQuery.dir(e,"nextSibling")},prevAll:function(e){return jQuery.dir(e,"previousSibling")},nextUntil:function(e,t,n){return jQuery.dir(e,"nextSibling",n)},prevUntil:function(e,t,n){return jQuery.dir(e,"previousSibling",n)},siblings:function(e){return jQuery.sibling((e.parentNode||{}).firstChild,e)},children:function(e){return jQuery.sibling(e.firstChild)},contents:function(e){return e.contentDocument||jQuery.merge([],e.childNodes)}},function(e,t){jQuery.fn[e]=function(n,r){var i=jQuery.map(this,t,n);return e.slice(-5)!=="Until"&&(r=n),r&&typeof r=="string"&&(i=jQuery.filter(r,i)),this.length>1&&(guaranteedUnique[e]||jQuery.unique(i),rparentsprev.test(e)&&i.reverse()),this.pushStack(i)}});var rnotwhite=/\S+/g,optionsCache={};jQuery.Callbacks=function(e){e=typeof e=="string"?optionsCache[e]||createOptions(e):jQuery.extend({},e);var t,n,r,i,s,o,u=[],a=!e.once&&[],f=function(c){t=e.memory&&c,n=!0,o=i||0,i=0,s=u.length,r=!0;for(;u&&o<s;o++)if(u[o].apply(c[0],c[1])===!1&&e.stopOnFalse){t=!1;break}r=!1,u&&(a?a.length&&f(a.shift()):t?u=[]:l.disable())},l={add:function(){if(u){var n=u.length;(function o(t){jQuery.each(t,function(t,n){var r=jQuery.type(n);r==="function"?(!e.unique||!l.has(n))&&u.push(n):n&&n.length&&r!=="string"&&o(n)})})(arguments),r?s=u.length:t&&(i=n,f(t))}return this},remove:function(){return u&&jQuery.each(arguments,function(e,t){var n;while((n=jQuery.inArray(t,u,n))>-1)u.splice(n,1),r&&(n<=s&&s--,n<=o&&o--)}),this},has:function(e){return e?jQuery.inArray(e,u)>-1:!!u&&!!u.length},empty:function(){return u=[],s=0,this},disable:function(){return u=a=t=undefined,this},disabled:function(){return!u},lock:function(){return a=undefined,t||l.disable(),this},locked:function(){return!a},fireWith:function(e,t){return u&&(!n||a)&&(t=t||[],t=[e,t.slice?t.slice():t],r?a.push(t):f(t)),this},fire:function(){return l.fireWith(this,arguments),this},fired:function(){return!!n}};return l},jQuery.extend({Deferred:function(e){var t=[["resolve","done",jQuery.Callbacks("once memory"),"resolved"],["reject","fail",jQuery.Callbacks("once memory"),"rejected"],["notify","progress",jQuery.Callbacks("memory")]],n="pending",r={state:function(){return n},always:function(){return i.done(arguments).fail(arguments),this},then:function(){var e=arguments;return jQuery.Deferred(function(n){jQuery.each(t,function(t,s){var o=jQuery.isFunction(e[t])&&e[t];i[s[1]](function(){var e=o&&o.apply(this,arguments);e&&jQuery.isFunction(e.promise)?e.promise().done(n.resolve).fail(n.reject).progress(n.notify):n[s[0]+"With"](this===r?n.promise():this,o?[e]:arguments)})}),e=null}).promise()},promise:function(e){return e!=null?jQuery.extend(e,r):r}},i={};return r.pipe=r.then,jQuery.each(t,function(e,s){var o=s[2],u=s[3];r[s[1]]=o.add,u&&o.add(function(){n=u},t[e^1][2].disable,t[2][2].lock),i[s[0]]=function(){return i[s[0]+"With"](this===i?r:this,arguments),this},i[s[0]+"With"]=o.fireWith}),r.promise(i),e&&e.call(i,i),i},when:function(e){var t=0,n=slice.call(arguments),r=n.length,i=r!==1||e&&jQuery.isFunction(e.promise)?r:0,s=i===1?e:jQuery.Deferred(),o=function(e,t,n){return function(r){t[e]=this,n[e]=arguments.length>1?slice.call(arguments):r,n===u?s.notifyWith(t,n):--i||s.resolveWith(t,n)}},u,a,f;if(r>1){u=new Array(r),a=new Array(r),f=new Array(r);for(;t<r;t++)n[t]&&jQuery.isFunction(n[t].promise)?n[t].promise().done(o(t,f,n)).fail(s.reject).progress(o(t,a,u)):--i}return i||s.resolveWith(f,n),s.promise()}});var readyList;jQuery.fn.ready=function(e){return jQuery.ready.promise().done(e),this},jQuery.extend({isReady:!1,readyWait:1,holdReady:function(e){e?jQuery.readyWait++:jQuery.ready(!0)},ready:function(e){if(e===!0?--jQuery.readyWait:jQuery.isReady)return;jQuery.isReady=!0;if(e!==!0&&--jQuery.readyWait>0)return;readyList.resolveWith(document,[jQuery]),jQuery.fn.trigger&&jQuery(document).trigger("ready").off("ready")}}),jQuery.ready.promise=function(e){return readyList||(readyList=jQuery.Deferred(),document.readyState==="complete"?setTimeout(jQuery.ready):(document.addEventListener("DOMContentLoaded",completed,!1),window.addEventListener("load",completed,!1))),readyList.promise(e)},jQuery.ready.promise();var access=jQuery.access=function(e,t,n,r,i,s,o){var u=0,a=e.length,f=n==null;if(jQuery.type(n)==="object"){i=!0;for(u in n)jQuery.access(e,t,u,n[u],!0,s,o)}else if(r!==undefined){i=!0,jQuery.isFunction(r)||(o=!0),f&&(o?(t.call(e,r),t=null):(f=t,t=function(e,t,n){return f.call(jQuery(e),n)}));if(t)for(;u<a;u++)t(e[u],n,o?r:r.call(e[u],u,t(e[u],n)))}return i?e:f?t.call(e):a?t(e[0],n):s};jQuery.acceptData=function(e){return e.nodeType===1||e.nodeType===9||!+e.nodeType},Data.uid=1,Data.accepts=jQuery.acceptData,Data.prototype={key:function(e){if(!Data.accepts(e))return 0;var t={},n=e[this.expando];if(!n){n=Data.uid++;try{t[this.expando]={value:n},Object.defineProperties(e,t)}catch(r){t[this.expando]=n,jQuery.extend(e,t)}}return this.cache[n]||(this.cache[n]={}),n},set:function(e,t,n){var r,i=this.key(e),s=this.cache[i];if(typeof t=="string")s[t]=n;else if(jQuery.isEmptyObject(s))jQuery.extend(this.cache[i],t);else for(r in t)s[r]=t[r];return s},get:function(e,t){var n=this.cache[this.key(e)];return t===undefined?n:n[t]},access:function(e,t,n){var r;return t===undefined||t&&typeof t=="string"&&n===undefined?(r=this.get(e,t),r!==undefined?r:this.get(e,jQuery.camelCase(t))):(this.set(e,t,n),n!==undefined?n:t)},remove:function(e,t){var n,r,i,s=this.key(e),o=this.cache[s];if(t===undefined)this.cache[s]={};else{jQuery.isArray(t)?r=t.concat(t.map(jQuery.camelCase)):(i=jQuery.camelCase(t),t in o?r=[t,i]:(r=i,r=r in o?[r]:r.match(rnotwhite)||[])),n=r.length;while(n--)delete o[r[n]]}},hasData:function(e){return!jQuery.isEmptyObject(this.cache[e[this.expando]]||{})},discard:function(e){e[this.expando]&&delete this.cache[e[this.expando]]}};var data_priv=new Data,data_user=new Data,rbrace=/^(?:\{[\w\W]*\}|\[[\w\W]*\])$/,rmultiDash=/([A-Z])/g;jQuery.extend({hasData:function(e){return data_user.hasData(e)||data_priv.hasData(e)},data:function(e,t,n){return data_user.access(e,t,n)},removeData:function(e,t){data_user.remove(e,t)},_data:function(e,t,n){return data_priv.access(e,t,n)},_removeData:function(e,t){data_priv.remove(e,t)}}),jQuery.fn.extend({data:function(e,t){var n,r,i,s=this[0],o=s&&s.attributes;if(e===undefined){if(this.length){i=data_user.get(s);if(s.nodeType===1&&!data_priv.get(s,"hasDataAttrs")){n=o.length;while(n--)r=o[n].name,r.indexOf("data-")===0&&(r=jQuery.camelCase(r.slice(5)),dataAttr(s,r,i[r]));data_priv.set(s,"hasDataAttrs",!0)}}return i}return typeof e=="object"?this.each(function(){data_user.set(this,e)}):access(this,function(t){var n,r=jQuery.camelCase(e);if(s&&t===undefined){n=data_user.get(s,e);if(n!==undefined)return n;n=data_user.get(s,r);if(n!==undefined)return n;n=dataAttr(s,r,undefined);if(n!==undefined)return n;return}this.each(function(){var n=data_user.get(this,r);data_user.set(this,r,t),e.indexOf("-")!==-1&&n!==undefined&&data_user.set(this,e,t)})},null,t,arguments.length>1,null,!0)},removeData:function(e){return this.each(function(){data_user.remove(this,e)})}}),jQuery.extend({queue:function(e,t,n){var r;if(e)return t=(t||"fx")+"queue",r=data_priv.get(e,t),n&&(!r||jQuery.isArray(n)?r=data_priv.access(e,t,jQuery.makeArray(n)):r.push(n)),r||[]},dequeue:function(e,t){t=t||"fx";var n=jQuery.queue(e,t),r=n.length,i=n.shift(),s=jQuery._queueHooks(e,t),o=function(){jQuery.dequeue(e,t)};i==="inprogress"&&(i=n.shift(),r--),i&&(t==="fx"&&n.unshift("inprogress"),delete s.stop,i.call(e,o,s)),!r&&s&&s.empty.fire()},_queueHooks:function(e,t){var n=t+"queueHooks";return data_priv.get(e,n)||data_priv.access(e,n,{empty:jQuery.Callbacks("once memory").add(function(){data_priv.remove(e,[t+"queue",n])})})}}),jQuery.fn.extend({queue:function(e,t){var n=2;return typeof e!="string"&&(t=e,e="fx",n--),arguments.length<n?jQuery.queue(this[0],e):t===undefined?this:this.each(function(){var n=jQuery.queue(this,e,t);jQuery._queueHooks(this,e),e==="fx"&&n[0]!=="inprogress"&&jQuery.dequeue(this,e)})},dequeue:function(e){return this.each(function(){jQuery.dequeue(this,e)})},clearQueue:function(e){return this.queue(e||"fx",[])},promise:function(e,t){var n,r=1,i=jQuery.Deferred(),s=this,o=this.length,u=function(){--r||i.resolveWith(s,[s])};typeof e!="string"&&(t=e,e=undefined),e=e||"fx";while(o--)n=data_priv.get(s[o],e+"queueHooks"),n&&n.empty&&(r++,n.empty.add(u));return u(),i.promise(t)}});var pnum=/[+-]?(?:\d*\.|)\d+(?:[eE][+-]?\d+|)/.source,cssExpand=["Top","Right","Bottom","Left"],isHidden=function(e,t){return e=t||e,jQuery.css(e,"display")==="none"||!jQuery.contains(e.ownerDocument,e)},rcheckableType=/^(?:checkbox|radio)$/i;(function(){var e=document.createDocumentFragment(),t=e.appendChild(document.createElement("div"));t.innerHTML="<input type='radio' checked='checked' name='t'/>",support.checkClone=t.cloneNode(!0).cloneNode(!0).lastChild.checked,t.innerHTML="<textarea>x</textarea>",support.noCloneChecked=!!t.cloneNode(!0).lastChild.defaultValue})();var strundefined=typeof undefined;support.focusinBubbles="onfocusin"in window;var rkeyEvent=/^key/,rmouseEvent=/^(?:mouse|contextmenu)|click/,rfocusMorph=/^(?:focusinfocus|focusoutblur)$/,rtypenamespace=/^([^.]*)(?:\.(.+)|)$/;jQuery.event={global:{},add:function(e,t,n,r,i){var s,o,u,a,f,l,c,h,p,d,v,m=data_priv.get(e);if(!m)return;n.handler&&(s=n,n=s.handler,i=s.selector),n.guid||(n.guid=jQuery.guid++),(a=m.events)||(a=m.events={}),(o=m.handle)||(o=m.handle=function(t){return typeof jQuery!==strundefined&&jQuery.event.triggered!==t.type?jQuery.event.dispatch.apply(e,arguments):undefined}),t=(t||"").match(rnotwhite)||[""],f=t.length;while(f--){u=rtypenamespace.exec(t[f])||[],p=v=u[1],d=(u[2]||"").split(".").sort();if(!p)continue;c=jQuery.event.special[p]||{},p=(i?c.delegateType:c.bindType)||p,c=jQuery.event.special[p]||{},l=jQuery.extend({type:p,origType:v,data:r,handler:n,guid:n.guid,selector:i,needsContext:i&&jQuery.expr.match.needsContext.test(i),namespace:d.join(".")},s),(h=a[p])||(h=a[p]=[],h.delegateCount=0,(!c.setup||c.setup.call(e,r,d,o)===!1)&&e.addEventListener&&e.addEventListener(p,o,!1)),c.add&&(c.add.call(e,l),l.handler.guid||(l.handler.guid=n.guid)),i?h.splice(h.delegateCount++,0,l):h.push(l),jQuery.event.global[p]=!0}},remove:function(e,t,n,r,i){var s,o,u,a,f,l,c,h,p,d,v,m=data_priv.hasData(e)&&data_priv.get(e);if(!m||!(a=m.events))return;t=(t||"").match(rnotwhite)||[""],f=t.length;while(f--){u=rtypenamespace.exec(t[f])||[],p=v=u[1],d=(u[2]||"").split(".").sort();if(!p){for(p in a)jQuery.event.remove(e,p+t[f],n,r,!0);continue}c=jQuery.event.special[p]||{},p=(r?c.delegateType:c.bindType)||p,h=a[p]||[],u=u[2]&&new RegExp("(^|\\.)"+d.join("\\.(?:.*\\.|)")+"(\\.|$)"),o=s=h.length;while(s--)l=h[s],(i||v===l.origType)&&(!n||n.guid===l.guid)&&(!u||u.test(l.namespace))&&(!r||r===l.selector||r==="**"&&l.selector)&&(h.splice(s,1),l.selector&&h.delegateCount--,c.remove&&c.remove.call(e,l));o&&!h.length&&((!c.teardown||c.teardown.call(e,d,m.handle)===!1)&&jQuery.removeEvent(e,p,m.handle),delete a[p])}jQuery.isEmptyObject(a)&&(delete m.handle,data_priv.remove(e,"events"))},trigger:function(e,t,n,r){var i,s,o,u,a,f,l,c=[n||document],h=hasOwn.call(e,"type")?e.type:e,p=hasOwn.call(e,"namespace")?e.namespace.split("."):[];s=o=n=n||document;if(n.nodeType===3||n.nodeType===8)return;if(rfocusMorph.test(h+jQuery.event.triggered))return;h.indexOf(".")>=0&&(p=h.split("."),h=p.shift(),p.sort()),a=h.indexOf(":")<0&&"on"+h,e=e[jQuery.expando]?e:new jQuery.Event(h,typeof e=="object"&&e),e.isTrigger=r?2:3,e.namespace=p.join("."),e.namespace_re=e.namespace?new RegExp("(^|\\.)"+p.join("\\.(?:.*\\.|)")+"(\\.|$)"):null,e.result=undefined,e.target||(e.target=n),t=t==null?[e]:jQuery.makeArray(t,[e]),l=jQuery.event.special[h]||{};if(!r&&l.trigger&&l.trigger.apply(n,t)===!1)return;if(!r&&!l.noBubble&&!jQuery.isWindow(n)){u=l.delegateType||h,rfocusMorph.test(u+h)||(s=s.parentNode);for(;s;s=s.parentNode)c.push(s),o=s;o===(n.ownerDocument||document)&&c.push(o.defaultView||o.parentWindow||window)}i=0;while((s=c[i++])&&!e.isPropagationStopped())e.type=i>1?u:l.bindType||h,f=(data_priv.get(s,"events")||{})[e.type]&&data_priv.get(s,"handle"),f&&f.apply(s,t),f=a&&s[a],f&&f.apply&&jQuery.acceptData(s)&&(e.result=f.apply(s,t),e.result===!1&&e.preventDefault());return e.type=h,!r&&!e.isDefaultPrevented()&&(!l._default||l._default.apply(c.pop(),t)===!1)&&jQuery.acceptData(n)&&a&&jQuery.isFunction(n[h])&&!jQuery.isWindow(n)&&(o=n[a],o&&(n[a]=null),jQuery.event.triggered=h,n[h](),jQuery.event.triggered=undefined,o&&(n[a]=o)),e.result},dispatch:function(e){e=jQuery.event.fix(e);var t,n,r,i,s,o=[],u=slice.call(arguments),a=(data_priv.get(this,"events")||{})[e.type]||[],f=jQuery.event.special[e.type]||{};u[0]=e,e.delegateTarget=this;if(f.preDispatch&&f.preDispatch.call(this,e)===!1)return;o=jQuery.event.handlers.call(this,e,a),t=0;while((i=o[t++])&&!e.isPropagationStopped()){e.currentTarget=i.elem,n=0;while((s=i.handlers[n++])&&!e.isImmediatePropagationStopped())if(!e.namespace_re||e.namespace_re.test(s.namespace))e.handleObj=s,e.data=s.data,r=((jQuery.event.special[s.origType]||{}).handle||s.handler).apply(i.elem,u),r!==undefined&&(e.result=r)===!1&&(e.preventDefault(),e.stopPropagation())}return f.postDispatch&&f.postDispatch.call(this,e),e.result},handlers:function(e,t){var n,r,i,s,o=[],u=t.delegateCount,a=e.target;if(u&&a.nodeType&&(!e.button||e.type!=="click"))for(;a!==this;a=a.parentNode||this)if(a.disabled!==!0||e.type!=="click"){r=[];for(n=0;n<u;n++)s=t[n],i=s.selector+" ",r[i]===undefined&&(r[i]=s.needsContext?jQuery(i,this).index(a)>=0:jQuery.find(i,this,null,[a]).length),r[i]&&r.push(s);r.length&&o.push({elem:a,handlers:r})}return u<t.length&&o.push({elem:this,handlers:t.slice(u)}),o},props:"altKey bubbles cancelable ctrlKey currentTarget eventPhase metaKey relatedTarget shiftKey target timeStamp view which".split(" "),fixHooks:{},keyHooks:{props:"char charCode key keyCode".split(" "),filter:function(e,t){return e.which==null&&(e.which=t.charCode!=null?t.charCode:t.keyCode),e}},mouseHooks:{props:"button buttons clientX clientY offsetX offsetY pageX pageY screenX screenY toElement".split(" "),filter:function(e,t){var n,r,i,s=t.button;return e.pageX==null&&t.clientX!=null&&(n=e.target.ownerDocument||document,r=n.documentElement,i=n.body,e.pageX=t.clientX+(r&&r.scrollLeft||i&&i.scrollLeft||0)-(r&&r.clientLeft||i&&i.clientLeft||0),e.pageY=t.clientY+(r&&r.scrollTop||i&&i.scrollTop||0)-(r&&r.clientTop||i&&i.clientTop||0)),!e.which&&s!==undefined&&(e.which=s&1?1:s&2?3:s&4?2:0),e}},fix:function(e){if(e[jQuery.expando])return e;var t,n,r,i=e.type,s=e,o=this.fixHooks[i];o||(this.fixHooks[i]=o=rmouseEvent.test(i)?this.mouseHooks:rkeyEvent.test(i)?this.keyHooks:{}),r=o.props?this.props.concat(o.props):this.props,e=new jQuery.Event(s),t=r.length;while(t--)n=r[t],e[n]=s[n];return e.target||(e.target=document),e.target.nodeType===3&&(e.target=e.target.parentNode),o.filter?o.filter(e,s):e},special:{load:{noBubble:!0},focus:{trigger:function(){if(this!==safeActiveElement()&&this.focus)return this.focus(),!1},delegateType:"focusin"},blur:{trigger:function(){if(this===safeActiveElement()&&this.blur)return this.blur(),!1},delegateType:"focusout"},click:{trigger:function(){if(this.type==="checkbox"&&this.click&&jQuery.nodeName(this,"input"))return this.click(),!1},_default:function(e){return jQuery.nodeName(e.target,"a")}},beforeunload:{postDispatch:function(e){e.result!==undefined&&(e.originalEvent.returnValue=e.result)}}},simulate:function(e,t,n,r){var i=jQuery.extend(new jQuery.Event,n,{type:e,isSimulated:!0,originalEvent:{}});r?jQuery.event.trigger(i,null,t):jQuery.event.dispatch.call(t,i),i.isDefaultPrevented()&&n.preventDefault()}},jQuery.removeEvent=function(e,t,n){e.removeEventListener&&e.removeEventListener(t,n,!1)},jQuery.Event=function(e,t){if(!(this instanceof jQuery.Event))return new jQuery.Event(e,t);e&&e.type?(this.originalEvent=e,this.type=e.type,this.isDefaultPrevented=e.defaultPrevented||e.defaultPrevented===undefined&&e.getPreventDefault&&e.getPreventDefault()?returnTrue:returnFalse):this.type=e,t&&jQuery.extend(this,t),this.timeStamp=e&&e.timeStamp||jQuery.now(),this[jQuery.expando]=!0},jQuery.Event.prototype={isDefaultPrevented:returnFalse,isPropagationStopped:returnFalse,isImmediatePropagationStopped:returnFalse,preventDefault:function(){var e=this.originalEvent;this.isDefaultPrevented=returnTrue,e&&e.preventDefault&&e.preventDefault()},stopPropagation:function(){var e=this.originalEvent;this.isPropagationStopped=returnTrue,e&&e.stopPropagation&&e.stopPropagation()},stopImmediatePropagation:function(){this.isImmediatePropagationStopped=returnTrue,this.stopPropagation()}},jQuery.each({mouseenter:"mouseover",mouseleave:"mouseout"},function(e,t){jQuery.event.special[e]={delegateType:t,bindType:t,handle:function(e){var n,r=this,i=e.relatedTarget,s=e.handleObj;if(!i||i!==r&&!jQuery.contains(r,i))e.type=s.origType,n=s.handler.apply(this,arguments),e.type=t;return n}}}),support.focusinBubbles||jQuery.each({focus:"focusin",blur:"focusout"},function(e,t){var n=function(e){jQuery.event.simulate(t,e.target,jQuery.event.fix(e),!0)};jQuery.event.special[t]={setup:function(){var r=this.ownerDocument||this,i=data_priv.access(r,t);i||r.addEventListener(e,n,!0),data_priv.access(r,t,(i||0)+1)},teardown:function(){var r=this.ownerDocument||this,i=data_priv.access(r,t)-1;i?data_priv.access(r,t,i):(r.removeEventListener(e,n,!0),data_priv.remove(r,t))}}}),jQuery.fn.extend({on:function(e,t,n,r,i){var s,o;if(typeof e=="object"){typeof t!="string"&&(n=n||t,t=undefined);for(o in e)this.on(o,t,n,e[o],i);return this}n==null&&r==null?(r=t,n=t=undefined):r==null&&(typeof t=="string"?(r=n,n=undefined):(r=n,n=t,t=undefined));if(r===!1)r=returnFalse;else if(!r)return this;return i===1&&(s=r,r=function(e){return jQuery().off(e),s.apply(this,arguments)},r.guid=s.guid||(s.guid=jQuery.guid++)),this.each(function(){jQuery.event.add(this,e,r,n,t)})},one:function(e,t,n,r){return this.on(e,t,n,r,1)},off:function(e,t,n){var r,i;if(e&&e.preventDefault&&e.handleObj)return r=e.handleObj,jQuery(e.delegateTarget).off(r.namespace?r.origType+"."+r.namespace:r.origType,r.selector,r.handler),this;if(typeof e=="object"){for(i in e)this.off(i,t,e[i]);return this}if(t===!1||typeof t=="function")n=t,t=undefined;return n===!1&&(n=returnFalse),this.each(function(){jQuery.event.remove(this,e,n,t)})},trigger:function(e,t){return this.each(function(){jQuery.event.trigger(e,t,this)})},triggerHandler:function(e,t){var n=this[0];if(n)return jQuery.event.trigger(e,t,n,!0)}});var rxhtmlTag=/<(?!area|br|col|embed|hr|img|input|link|meta|param)(([\w:]+)[^>]*)\/>/gi,rtagName=/<([\w:]+)/,rhtml=/<|&#?\w+;/,rnoInnerhtml=/<(?:script|style|link)/i,rchecked=/checked\s*(?:[^=]|=\s*.checked.)/i,rscriptType=/^$|\/(?:java|ecma)script/i,rscriptTypeMasked=/^true\/(.*)/,rcleanScript=/^\s*<!(?:\[CDATA\[|--)|(?:\]\]|--)>\s*$/g,wrapMap={option:[1,"<select multiple='multiple'>","</select>"],thead:[1,"<table>","</table>"],col:[2,"<table><colgroup>","</colgroup></table>"],tr:[2,"<table><tbody>","</tbody></table>"],td:[3,"<table><tbody><tr>","</tr></tbody></table>"],_default:[0,"",""]};wrapMap.optgroup=wrapMap.option,wrapMap.tbody=wrapMap.tfoot=wrapMap.colgroup=wrapMap.caption=wrapMap.thead,wrapMap.th=wrapMap.td,jQuery.extend({clone:function(e,t,n){var r,i,s,o,u=e.cloneNode(!0),a=jQuery.contains(e.ownerDocument,e);if(!support.noCloneChecked&&(e.nodeType===1||e.nodeType===11)&&!jQuery.isXMLDoc(e)){o=getAll(u),s=getAll(e);for(r=0,i=s.length;r<i;r++)fixInput(s[r],o[r])}if(t)if(n){s=s||getAll(e),o=o||getAll(u);for(r=0,i=s.length;r<i;r++)cloneCopyEvent(s[r],o[r])}else cloneCopyEvent(e,u);return o=getAll(u,"script"),o.length>0&&setGlobalEval(o,!a&&getAll(e,"script")),u},buildFragment:function(e,t,n,r){var i,s,o,u,a,f,l=t.createDocumentFragment(),c=[],h=0,p=e.length;for(;h<p;h++){i=e[h];if(i||i===0)if(jQuery.type(i)==="object")jQuery.merge(c,i.nodeType?[i]:i);else if(!rhtml.test(i))c.push(t.createTextNode(i));else{s=s||l.appendChild(t.createElement("div")),o=(rtagName.exec(i)||["",""])[1].toLowerCase(),u=wrapMap[o]||wrapMap._default,s.innerHTML=u[1]+i.replace(rxhtmlTag,"<$1></$2>")+u[2],f=u[0];while(f--)s=s.lastChild;jQuery.merge(c,s.childNodes),s=l.firstChild,s.textContent=""}}l.textContent="",h=0;while(i=c[h++]){if(r&&jQuery.inArray(i,r)!==-1)continue;a=jQuery.contains(i.ownerDocument,i),s=getAll(l.appendChild(i),"script"),a&&setGlobalEval(s);if(n){f=0;while(i=s[f++])rscriptType.test(i.type||"")&&n.push(i)}}return l},cleanData:function(e){var t,n,r,i,s,o,u=jQuery.event.special,a=0;for(;(n=e[a])!==undefined;a++){if(jQuery.acceptData(n)){s=n[data_priv.expando];if(s&&(t=data_priv.cache[s])){r=Object.keys(t.events||{});if(r.length)for(o=0;(i=r[o])!==undefined;o++)u[i]?jQuery.event.remove(n,i):jQuery.removeEvent(n,i,t.handle);data_priv.cache[s]&&delete data_priv.cache[s]}}delete data_user.cache[n[data_user.expando]]}}}),jQuery.fn.extend({text:function(e){return access(this,function(e){return e===undefined?jQuery.text(this):this.empty().each(function(){if(this.nodeType===1||this.nodeType===11||this.nodeType===9)this.textContent=e})},null,e,arguments.length)},append:function(){return this.domManip(arguments,function(e){if(this.nodeType===1||this.nodeType===11||this.nodeType===9){var t=manipulationTarget(this,e);t.appendChild(e)}})},prepend:function(){return this.domManip(arguments,function(e){if(this.nodeType===1||this.nodeType===11||this.nodeType===9){var t=manipulationTarget(this,e);t.insertBefore(e,t.firstChild)}})},before:function(){return this.domManip(arguments,function(e){this.parentNode&&this.parentNode.insertBefore(e,this)})},after:function(){return this.domManip(arguments,function(e){this.parentNode&&this.parentNode.insertBefore(e,this.nextSibling)})},remove:function(e,t){var n,r=e?jQuery.filter(e,this):this,i=0;for(;(n=r[i])!=null;i++)!t&&n.nodeType===1&&jQuery.cleanData(getAll(n)),n.parentNode&&(t&&jQuery.contains(n.ownerDocument,n)&&setGlobalEval(getAll(n,"script")),n.parentNode.removeChild(n));return this},empty:function(){var e,t=0;for(;(e=this[t])!=null;t++)e.nodeType===1&&(jQuery.cleanData(getAll(e,!1)),e.textContent="");return this},clone:function(e,t){return e=e==null?!1:e,t=t==null?e:t,this.map(function(){return jQuery.clone(this,e,t)})},html:function(e){return access(this,function(e){var t=this[0]||{},n=0,r=this.length;if(e===undefined&&t.nodeType===1)return t.innerHTML;if(typeof e=="string"&&!rnoInnerhtml.test(e)&&!wrapMap[(rtagName.exec(e)||["",""])[1].toLowerCase()]){e=e.replace(rxhtmlTag,"<$1></$2>");try{for(;n<r;n++)t=this[n]||{},t.nodeType===1&&(jQuery.cleanData(getAll(t,!1)),t.innerHTML=e);t=0}catch(i){}}t&&this.empty().append(e)},null,e,arguments.length)},replaceWith:function(){var e=arguments[0];return this.domManip(arguments,function(t){e=this.parentNode,jQuery.cleanData(getAll(this)),e&&e.replaceChild(t,this)}),e&&(e.length||e.nodeType)?this:this.remove()},detach:function(e){return this.remove(e,!0)},domManip:function(e,t){e=concat.apply([],e);var n,r,i,s,o,u,a=0,f=this.length,l=this,c=f-1,h=e[0],p=jQuery.isFunction(h);if(p||f>1&&typeof h=="string"&&!support.checkClone&&rchecked.test(h))return this.each(function(n){var r=l.eq(n);p&&(e[0]=h.call(this,n,r.html())),r.domManip(e,t)});if(f){n=jQuery.buildFragment(e,this[0].ownerDocument,!1,this),r=n.firstChild,n.childNodes.length===1&&(n=r);if(r){i=jQuery.map(getAll(n,"script"),disableScript),s=i.length;for(;a<f;a++)o=n,a!==c&&(o=jQuery.clone(o,!0,!0),s&&jQuery.merge(i,getAll(o,"script"))),t.call(this[a],o,a);if(s){u=i[i.length-1].ownerDocument,jQuery.map(i,restoreScript);for(a=0;a<s;a++)o=i[a],rscriptType.test(o.type||"")&&!data_priv.access(o,"globalEval")&&jQuery.contains(u,o)&&(o.src?jQuery._evalUrl&&jQuery._evalUrl(o.src):jQuery.globalEval(o.textContent.replace(rcleanScript,"")))}}}return this}}),jQuery.each({appendTo:"append",prependTo:"prepend",insertBefore:"before",insertAfter:"after",replaceAll:"replaceWith"},function(e,t){jQuery.fn[e]=function(e){var n,r=[],i=jQuery(e),s=i.length-1,o=0;for(;o<=s;o++)n=o===s?this:this.clone(!0),jQuery(i[o])[t](n),push.apply(r,n.get());return this.pushStack(r)}});var iframe,elemdisplay={},rmargin=/^margin/,rnumnonpx=new RegExp("^("+pnum+")(?!px)[a-z%]+$","i"),getStyles=function(e){return e.ownerDocument.defaultView.getComputedStyle(e,null)};(function(){function o(){s.style.cssText="-webkit-box-sizing:border-box;-moz-box-sizing:border-box;box-sizing:border-box;padding:1px;border:1px;display:block;width:4px;margin-top:1%;position:absolute;top:1%",r.appendChild(i);var n=window.getComputedStyle(s,null);e=n.top!=="1%",t=n.width==="4px",r.removeChild(i)}var e,t,n="padding:0;margin:0;border:0;display:block;-webkit-box-sizing:content-box;-moz-box-sizing:content-box;box-sizing:content-box",r=document.documentElement,i=document.createElement("div"),s=document.createElement("div");s.style.backgroundClip="content-box",s.cloneNode(!0).style.backgroundClip="",support.clearCloneStyle=s.style.backgroundClip==="content-box",i.style.cssText="border:0;width:0;height:0;position:absolute;top:0;left:-9999px;margin-top:1px",i.appendChild(s),window.getComputedStyle&&jQuery.extend(support,{pixelPosition:function(){return o(),e},boxSizingReliable:function(){return t==null&&o(),t},reliableMarginRight:function(){var e,t=s.appendChild(document.createElement("div"));return t.style.cssText=s.style.cssText=n,t.style.marginRight=t.style.width="0",s.style.width="1px",r.appendChild(i),e=!parseFloat(window.getComputedStyle(t,null).marginRight),r.removeChild(i),s.innerHTML="",e}})})(),jQuery.swap=function(e,t,n,r){var i,s,o={};for(s in t)o[s]=e.style[s],e.style[s]=t[s];i=n.apply(e,r||[]);for(s in t)e.style[s]=o[s];return i};var rdisplayswap=/^(none|table(?!-c[ea]).+)/,rnumsplit=new RegExp("^("+pnum+")(.*)$","i"),rrelNum=new RegExp("^([+-])=("+pnum+")","i"),cssShow={position:"absolute",visibility:"hidden",display:"block"},cssNormalTransform={letterSpacing:0,fontWeight:400},cssPrefixes=["Webkit","O","Moz","ms"];jQuery.extend({cssHooks:{opacity:{get:function(e,t){if(t){var n=curCSS(e,"opacity");return n===""?"1":n}}}},cssNumber:{columnCount:!0,fillOpacity:!0,fontWeight:!0,lineHeight:!0,opacity:!0,order:!0,orphans:!0,widows:!0,zIndex:!0,zoom:!0},cssProps:{"float":"cssFloat"},style:function(e,t,n,r){if(!e||e.nodeType===3||e.nodeType===8||!e.style)return;var i,s,o,u=jQuery.camelCase(t),a=e.style;t=jQuery.cssProps[u]||(jQuery.cssProps[u]=vendorPropName(a,u)),o=jQuery.cssHooks[t]||jQuery.cssHooks[u];if(n===undefined)return o&&"get"in o&&(i=o.get(e,!1,r))!==undefined?i:a[t];s=typeof n,s==="string"&&(i=rrelNum.exec(n))&&(n=(i[1]+1)*i[2]+parseFloat(jQuery.css(e,t)),s="number");if(n==null||n!==n)return;s==="number"&&!jQuery.cssNumber[u]&&(n+="px"),!support.clearCloneStyle&&n===""&&t.indexOf("background")===0&&(a[t]="inherit");if(!o||!("set"in o)||(n=o.set(e,n,r))!==undefined)a[t]="",a[t]=n},css:function(e,t,n,r){var i,s,o,u=jQuery.camelCase(t);return t=jQuery.cssProps[u]||(jQuery.cssProps[u]=vendorPropName(e.style,u)),o=jQuery.cssHooks[t]||jQuery.cssHooks[u],o&&"get"in o&&(i=o.get(e,!0,n)),i===undefined&&(i=curCSS(e,t,r)),i==="normal"&&t in cssNormalTransform&&(i=cssNormalTransform[t]),n===""||n?(s=parseFloat(i),n===!0||jQuery.isNumeric(s)?s||0:i):i}}),jQuery.each(["height","width"],function(e,t){jQuery.cssHooks[t]={get:function(e,n,r){if(n)return e.offsetWidth===0&&rdisplayswap.test(jQuery.css(e,"display"))?jQuery.swap(e,cssShow,function(){return getWidthOrHeight(e,t,r)}):getWidthOrHeight(e,t,r)},set:function(e,n,r){var i=r&&getStyles(e);return setPositiveNumber(e,n,r?augmentWidthOrHeight(e,t,r,jQuery.css(e,"boxSizing",!1,i)==="border-box",i):0)}}}),jQuery.cssHooks.marginRight=addGetHookIf(support.reliableMarginRight,function(e,t){if(t)return jQuery.swap(e,{display:"inline-block"},curCSS,[e,"marginRight"])}),jQuery.each({margin:"",padding:"",border:"Width"},function(e,t){jQuery.cssHooks[e+t]={expand:function(n){var r=0,i={},s=typeof n=="string"?n.split(" "):[n];for(;r<4;r++)i[e+cssExpand[r]+t]=s[r]||s[r-2]||s[0];return i}},rmargin.test(e)||(jQuery.cssHooks[e+t].set=setPositiveNumber)}),jQuery.fn.extend({css:function(e,t){return access(this,function(e,t,n){var r,i,s={},o=0;if(jQuery.isArray(t)){r=getStyles(e),i=t.length;for(;o<i;o++)s[t[o]]=jQuery.css(e,t[o],!1,r);return s}return n!==undefined?jQuery.style(e,t,n):jQuery.css(e,t)},e,t,arguments.length>1)},show:function(){return showHide(this,!0)},hide:function(){return showHide(this)},toggle:function(e){return typeof e=="boolean"?e?this.show():this.hide():this.each(function(){isHidden(this)?jQuery(this).show():jQuery(this).hide()})}}),jQuery.Tween=Tween,Tween.prototype={constructor:Tween,init:function(e,t,n,r,i,s){this.elem=e,this.prop=n,this.easing=i||"swing",this.options=t,this.start=this.now=this.cur(),this.end=r,this.unit=s||(jQuery.cssNumber[n]?"":"px")},cur:function(){var e=Tween.propHooks[this.prop];return e&&e.get?e.get(this):Tween.propHooks._default.get(this)},run:function(e){var t,n=Tween.propHooks[this.prop];return this.options.duration?this.pos=t=jQuery.easing[this.easing](e,this.options.duration*e,0,1,this.options.duration):this.pos=t=e,this.now=(this.end-this.start)*t+this.start,this.options.step&&this.options.step.call(this.elem,this.now,this),n&&n.set?n.set(this):Tween.propHooks._default.set(this),this}},Tween.prototype.init.prototype=Tween.prototype,Tween.propHooks={_default:{get:function(e){var t;return e.elem[e.prop]==null||!!e.elem.style&&e.elem.style[e.prop]!=null?(t=jQuery.css(e.elem,e.prop,""),!t||t==="auto"?0:t):e.elem[e.prop]},set:function(e){jQuery.fx.step[e.prop]?jQuery.fx.step[e.prop](e):e.elem.style&&(e.elem.style[jQuery.cssProps[e.prop]]!=null||jQuery.cssHooks[e.prop])?jQuery.style(e.elem,e.prop,e.now+e.unit):e.elem[e.prop]=e.now}}},Tween.propHooks.scrollTop=Tween.propHooks.scrollLeft={set:function(e){e.elem.nodeType&&e.elem.parentNode&&(e.elem[e.prop]=e.now)}},jQuery.easing={linear:function(e){return e},swing:function(e){return.5-Math.cos(e*Math.PI)/2}},jQuery.fx=Tween.prototype.init,jQuery.fx.step={};var fxNow,timerId,rfxtypes=/^(?:toggle|show|hide)$/,rfxnum=new RegExp("^(?:([+-])=|)("+pnum+")([a-z%]*)$","i"),rrun=/queueHooks$/,animationPrefilters=[defaultPrefilter],tweeners={"*":[function(e,t){var n=this.createTween(e,t),r=n.cur(),i=rfxnum.exec(t),s=i&&i[3]||(jQuery.cssNumber[e]?"":"px"),o=(jQuery.cssNumber[e]||s!=="px"&&+r)&&rfxnum.exec(jQuery.css(n.elem,e)),u=1,a=20;if(o&&o[3]!==s){s=s||o[3],i=i||[],o=+r||1;do u=u||".5",o/=u,jQuery.style(n.elem,e,o+s);while(u!==(u=n.cur()/r)&&u!==1&&--a)}return i&&(o=n.start=+o||+r||0,n.unit=s,n.end=i[1]?o+(i[1]+1)*i[2]:+i[2]),n}]};jQuery.Animation=jQuery.extend(Animation,{tweener:function(e,t){jQuery.isFunction(e)?(t=e,e=["*"]):e=e.split(" ");var n,r=0,i=e.length;for(;r<i;r++)n=e[r],tweeners[n]=tweeners[n]||[],tweeners[n].unshift(t)},prefilter:function(e,t){t?animationPrefilters.unshift(e):animationPrefilters.push(e)}}),jQuery.speed=function(e,t,n){var r=e&&typeof e=="object"?jQuery.extend({},e):{complete:n||!n&&t||jQuery.isFunction(e)&&e,duration:e,easing:n&&t||t&&!jQuery.isFunction(t)&&t};r.duration=jQuery.fx.off?0:typeof r.duration=="number"?r.duration:r.duration in jQuery.fx.speeds?jQuery.fx.speeds[r.duration]:jQuery.fx.speeds._default;if(r.queue==null||r.queue===!0)r.queue="fx";return r.old=r.complete,r.complete=function(){jQuery.isFunction(r.old)&&r.old.call(this),r.queue&&jQuery.dequeue(this,r.queue)},r},jQuery.fn.extend({fadeTo:function(e,t,n,r){return this.filter(isHidden).css("opacity",0).show().end().animate({opacity:t},e,n,r)},animate:function(e,t,n,r){var i=jQuery.isEmptyObject(e),s=jQuery.speed(t,n,r),o=function(){var t=Animation(this,jQuery.extend({},e),s);(i||data_priv.get(this,"finish"))&&t.stop(!0)};return o.finish=o,i||s.queue===!1?this.each(o):this.queue(s.queue,o)},stop:function(e,t,n){var r=function(e){var t=e.stop;delete e.stop,t(n)};return typeof e!="string"&&(n=t,t=e,e=undefined),t&&e!==!1&&this.queue(e||"fx",[]),this.each(function(){var t=!0,i=e!=null&&e+"queueHooks",s=jQuery.timers,o=data_priv.get(this);if(i)o[i]&&o[i].stop&&r(o[i]);else for(i in o)o[i]&&o[i].stop&&rrun.test(i)&&r(o[i]);for(i=s.length;i--;)s[i].elem===this&&(e==null||s[i].queue===e)&&(s[i].anim.stop(n),t=!1,s.splice(i,1));(t||!n)&&jQuery.dequeue(this,e)})},finish:function(e){return e!==!1&&(e=e||"fx"),this.each(function(){var t,n=data_priv.get(this),r=n[e+"queue"],i=n[e+"queueHooks"],s=jQuery.timers,o=r?r.length:0;n.finish=!0,jQuery.queue(this,e,[]),i&&i.stop&&i.stop.call(this,!0);for(t=s.length;t--;)s[t].elem===this&&s[t].queue===e&&(s[t].anim.stop(!0),s.splice(t,1));for(t=0;t<o;t++)r[t]&&r[t].finish&&r[t].finish.call(this);delete n.finish})}}),jQuery.each(["toggle","show","hide"],function(e,t){var n=jQuery.fn[t];jQuery.fn[t]=function(e,r,i){return e==null||typeof e=="boolean"?n.apply(this,arguments):this.animate(genFx(t,!0),e,r,i)}}),jQuery.each({slideDown:genFx("show"),slideUp:genFx("hide"),slideToggle:genFx("toggle"),fadeIn:{opacity:"show"},fadeOut:{opacity:"hide"},fadeToggle:{opacity:"toggle"}},function(e,t){jQuery.fn[e]=function(e,n,r){return this.animate(t,e,n,r)}}),jQuery.timers=[],jQuery.fx.tick=function(){var e,t=0,n=jQuery.timers;fxNow=jQuery.now();for(;t<n.length;t++)e=n[t],!e()&&n[t]===e&&n.splice(t--,1);n.length||jQuery.fx.stop(),fxNow=undefined},jQuery.fx.timer=function(e){jQuery.timers.push(e),e()?jQuery.fx.start():jQuery.timers.pop()},jQuery.fx.interval=13,jQuery.fx.start=function(){timerId||(timerId=setInterval(jQuery.fx.tick,jQuery.fx.interval))},jQuery.fx.stop=function(){clearInterval(timerId),timerId=null},jQuery.fx.speeds={slow:600,fast:200,_default:400},jQuery.fn.delay=function(e,t){return e=jQuery.fx?jQuery.fx.speeds[e]||e:e,t=t||"fx",this.queue(t,function(t,n){var r=setTimeout(t,e);n.stop=function(){clearTimeout(r)}})},function(){var e=document.createElement("input"),t=document.createElement("select"),n=t.appendChild(document.createElement("option"));e.type="checkbox",support.checkOn=e.value!=="",support.optSelected=n.selected,t.disabled=!0,support.optDisabled=!n.disabled,e=document.createElement("input"),e.value="t",e.type="radio",support.radioValue=e.value==="t"}();var nodeHook,boolHook,attrHandle=jQuery.expr.attrHandle;jQuery.fn.extend({attr:function(e,t){return access(this,jQuery.attr,e,t,arguments.length>1)},removeAttr:function(e){return this.each(function(){jQuery.removeAttr(this,e)})}}),jQuery.extend({attr:function(e,t,n){var r,i,s=e.nodeType;if(!e||s===3||s===8||s===2)return;if(typeof e.getAttribute===strundefined)return jQuery.prop(e,t,n);if(s!==1||!jQuery.isXMLDoc(e))t=t.toLowerCase(),r=jQuery.attrHooks[t]||(jQuery.expr.match.bool.test(t)?boolHook:nodeHook);if(n===undefined)return r&&"get"in r&&(i=r.get(e,t))!==null?i:(i=jQuery.find.attr(e,t),i==null?undefined:i);if(n!==null)return r&&"set"in r&&(i=r.set(e,n,t))!==undefined?i:(e.setAttribute(t,n+""),n);jQuery.removeAttr(e,t)},removeAttr:function(e,t){var n,r,i=0,s=t&&t.match(rnotwhite);if(s&&e.nodeType===1)while(n=s[i++])r=jQuery.propFix[n]||n,jQuery.expr.match.bool.test(n)&&(e[r]=!1),e.removeAttribute(n)},attrHooks:{type:{set:function(e,t){if(!support.radioValue&&t==="radio"&&jQuery.nodeName(e,"input")){var n=e.value;return e.setAttribute("type",t),n&&(e.value=n),t}}}}}),boolHook={set:function(e,t,n){return t===!1?jQuery.removeAttr(e,n):e.setAttribute(n,n),n}},jQuery.each(jQuery.expr.match.bool.source.match(/\w+/g),function(e,t){var n=attrHandle[t]||jQuery.find.attr;attrHandle[t]=function(e,t,r){var i,s;return r||(s=attrHandle[t],attrHandle[t]=i,i=n(e,t,r)!=null?t.toLowerCase():null,attrHandle[t]=s),i}});var rfocusable=/^(?:input|select|textarea|button)$/i;jQuery.fn.extend({prop:function(e,t){return access(this,jQuery.prop,e,t,arguments.length>1)},removeProp:function(e){return this.each(function(){delete this[jQuery.propFix[e]||e]})}}),jQuery.extend({propFix:{"for":"htmlFor","class":"className"},prop:function(e,t,n){var r,i,s,o=e.nodeType;if(!e||o===3||o===8||o===2)return;return s=o!==1||!jQuery.isXMLDoc(e),s&&(t=jQuery.propFix[t]||t,i=jQuery.propHooks[t]),n!==undefined?i&&"set"in i&&(r=i.set(e,n,t))!==undefined?r:e[t]=n:i&&"get"in i&&(r=i.get(e,t))!==null?r:e[t]},propHooks:{tabIndex:{get:function(e){return e.hasAttribute("tabindex")||rfocusable.test(e.nodeName)||e.href?e.tabIndex:-1}}}}),support.optSelected||(jQuery.propHooks.selected={get:function(e){var t=e.parentNode;return t&&t.parentNode&&t.parentNode.selectedIndex,null}}),jQuery.each(["tabIndex","readOnly","maxLength","cellSpacing","cellPadding","rowSpan","colSpan","useMap","frameBorder","contentEditable"],function(){jQuery.propFix[this.toLowerCase()]=this});var rclass=/[\t\r\n\f]/g;jQuery.fn.extend({addClass:function(e){var t,n,r,i,s,o,u=typeof e=="string"&&e,a=0,f=this.length;if(jQuery.isFunction(e))return this.each(function(t){jQuery(this).addClass(e.call(this,t,this.className))});if(u){t=(e||"").match(rnotwhite)||[];for(;a<f;a++){n=this[a],r=n.nodeType===1&&(n.className?(" "+n.className+" ").replace(rclass," "):" ");if(r){s=0;while(i=t[s++])r.indexOf(" "+i+" ")<0&&(r+=i+" ");o=jQuery.trim(r),n.className!==o&&(n.className=o)}}}return this},removeClass:function(e){var t,n,r,i,s,o,u=arguments.length===0||typeof e=="string"&&e,a=0,f=this.length;if(jQuery.isFunction(e))return this.each(function(t){jQuery(this).removeClass(e.call(this,t,this.className))});if(u){t=(e||"").match(rnotwhite)||[];for(;a<f;a++){n=this[a],r=n.nodeType===1&&(n.className?(" "+n.className+" ").replace(rclass," "):"");if(r){s=0;while(i=t[s++])while(r.indexOf(" "+i+" ")>=0)r=r.replace(" "+i+" "," ");o=e?jQuery.trim(r):"",n.className!==o&&(n.className=o)}}}return this},toggleClass:function(e,t){var n=typeof e;return typeof t=="boolean"&&n==="string"?t?this.addClass(e):this.removeClass(e):jQuery.isFunction(e)?this.each(function(n){jQuery(this).toggleClass(e.call(this,n,this.className,t),t)}):this.each(function(){if(n==="string"){var t,r=0,i=jQuery(this),s=e.match(rnotwhite)||[];while(t=s[r++])i.hasClass(t)?i.removeClass(t):i.addClass(t)}else if(n===strundefined||n==="boolean")this.className&&data_priv.set(this,"__className__",this.className),this.className=this.className||e===!1?"":data_priv.get(this,"__className__")||""})},hasClass:function(e){var t=" "+e+" ",n=0,r=this.length;for(;n<r;n++)if(this[n].nodeType===1&&(" "+this[n].className+" ").replace(rclass," ").indexOf(t)>=0)return!0;return!1}});var rreturn=/\r/g;jQuery.fn.extend({val:function(e){var t,n,r,i=this[0];if(!arguments.length){if(i)return t=jQuery.valHooks[i.type]||jQuery.valHooks[i.nodeName.toLowerCase()],t&&"get"in t&&(n=t.get(i,"value"))!==undefined?n:(n=i.value,typeof n=="string"?n.replace(rreturn,""):n==null?"":n);return}return r=jQuery.isFunction(e),this.each(function(n){var i;if(this.nodeType!==1)return;r?i=e.call(this,n,jQuery(this).val()):i=e,i==null?i="":typeof i=="number"?i+="":jQuery.isArray(i)&&(i=jQuery.map(i,function(e){return e==null?"":e+""})),t=jQuery.valHooks[this.type]||jQuery.valHooks[this.nodeName.toLowerCase()];if(!t||!("set"in t)||t.set(this,i,"value")===undefined)this.value=i})}}),jQuery.extend({valHooks:{select:{get:function(e){var t,n,r=e.options,i=e.selectedIndex,s=e.type==="select-one"||i<0,o=s?null:[],u=s?i+1:r.length,a=i<0?u:s?i:0;for(;a<u;a++){n=r[a];if((n.selected||a===i)&&(support.optDisabled?!n.disabled:n.getAttribute("disabled")===null)&&(!n.parentNode.disabled||!jQuery.nodeName(n.parentNode,"optgroup"))){t=jQuery(n).val();if(s)return t;o.push(t)}}return o},set:function(e,t){var n,r,i=e.options,s=jQuery.makeArray(t),o=i.length;while(o--){r=i[o];if(r.selected=jQuery.inArray(jQuery(r).val(),s)>=0)n=!0}return n||(e.selectedIndex=-1),s}}}}),jQuery.each(["radio","checkbox"],function(){jQuery.valHooks[this]={set:function(e,t){if(jQuery.isArray(t))return e.checked=jQuery.inArray(jQuery(e).val(),t)>=0}},support.checkOn||(jQuery.valHooks[this].get=function(e){return e.getAttribute("value")===null?"on":e.value})}),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(e,t){jQuery.fn[t]=function(e,n){return arguments.length>0?this.on(t,null,e,n):this.trigger(t)}}),jQuery.fn.extend({hover:function(e,t){return this.mouseenter(e).mouseleave(t||e)},bind:function(e,t,n){return this.on(e,null,t,n)},unbind:function(e,t){return this.off(e,null,t)},delegate:function(e,t,n,r){return this.on(t,e,n,r)},undelegate:function(e,t,n){return arguments.length===1?this.off(e,"**"):this.off(t,e||"**",n)}});var nonce=jQuery.now(),rquery=/\?/;jQuery.parseJSON=function(e){return JSON.parse(e+"")},jQuery.parseXML=function(e){var t,n;if(!e||typeof e!="string")return null;try{n=new DOMParser,t=n.parseFromString(e,"text/xml")}catch(r){t=undefined}return(!t||t.getElementsByTagName("parsererror").length)&&jQuery.error("Invalid XML: "+e),t};var ajaxLocParts,ajaxLocation,rhash=/#.*$/,rts=/([?&])_=[^&]*/,rheaders=/^(.*?):[ \t]*([^\r\n]*)$/mg,rlocalProtocol=/^(?:about|app|app-storage|.+-extension|file|res|widget):$/,rnoContent=/^(?:GET|HEAD)$/,rprotocol=/^\/\//,rurl=/^([\w.+-]+:)(?:\/\/(?:[^\/?#]*@|)([^\/?#:]*)(?::(\d+)|)|)/,prefilters={},transports={},allTypes="*/".concat("*");try{ajaxLocation=location.href}catch(e){ajaxLocation=document.createElement("a"),ajaxLocation.href="",ajaxLocation=ajaxLocation.href}ajaxLocParts=rurl.exec(ajaxLocation.toLowerCase())||[],jQuery.extend({active:0,lastModified:{},etag:{},ajaxSettings:{url:ajaxLocation,type:"GET",isLocal:rlocalProtocol.test(ajaxLocParts[1]),global:!0,processData:!0,async:!0,contentType:"application/x-www-form-urlencoded; charset=UTF-8",accepts:{"*":allTypes,text:"text/plain",html:"text/html",xml:"application/xml, text/xml",json:"application/json, text/javascript"},contents:{xml:/xml/,html:/html/,json:/json/},responseFields:{xml:"responseXML",text:"responseText",json:"responseJSON"},converters:{"* text":String,"text html":!0,"text json":jQuery.parseJSON,"text xml":jQuery.parseXML},flatOptions:{url:!0,context:!0}},ajaxSetup:function(e,t){return t?ajaxExtend(ajaxExtend(e,jQuery.ajaxSettings),t):ajaxExtend(jQuery.ajaxSettings,e)},ajaxPrefilter:addToPrefiltersOrTransports(prefilters),ajaxTransport:addToPrefiltersOrTransports(transports),ajax:function(e,t){function S(e,t,s,u){var f,m,g,b,E,S=t;if(y===2)return;y=2,o&&clearTimeout(o),n=undefined,i=u||"",w.readyState=e>0?4:0,f=e>=200&&e<300||e===304,s&&(b=ajaxHandleResponses(l,w,s)),b=ajaxConvert(l,b,w,f);if(f)l.ifModified&&(E=w.getResponseHeader("Last-Modified"),E&&(jQuery.lastModified[r]=E),E=w.getResponseHeader("etag"),E&&(jQuery.etag[r]=E)),e===204||l.type==="HEAD"?S="nocontent":e===304?S="notmodified":(S=b.state,m=b.data,g=b.error,f=!g);else{g=S;if(e||!S)S="error",e<0&&(e=0)}w.status=e,w.statusText=(t||S)+"",f?p.resolveWith(c,[m,S,w]):p.rejectWith(c,[w,S,g]),w.statusCode(v),v=undefined,a&&h.trigger(f?"ajaxSuccess":"ajaxError",[w,l,f?m:g]),d.fireWith(c,[w,S]),a&&(h.trigger("ajaxComplete",[w,l]),--jQuery.active||jQuery.event.trigger("ajaxStop"))}typeof e=="object"&&(t=e,e=undefined),t=t||{};var n,r,i,s,o,u,a,f,l=jQuery.ajaxSetup({},t),c=l.context||l,h=l.context&&(c.nodeType||c.jquery)?jQuery(c):jQuery.event,p=jQuery.Deferred(),d=jQuery.Callbacks("once memory"),v=l.statusCode||{},m={},g={},y=0,b="canceled",w={readyState:0,getResponseHeader:function(e){var t;if(y===2){if(!s){s={};while(t=rheaders.exec(i))s[t[1].toLowerCase()]=t[2]}t=s[e.toLowerCase()]}return t==null?null:t},getAllResponseHeaders:function(){return y===2?i:null},setRequestHeader:function(e,t){var n=e.toLowerCase();return y||(e=g[n]=g[n]||e,m[e]=t),this},overrideMimeType:function(e){return y||(l.mimeType=e),this},statusCode:function(e){var t;if(e)if(y<2)for(t in e)v[t]=[v[t],e[t]];else w.always(e[w.status]);return this},abort:function(e){var t=e||b;return n&&n.abort(t),S(0,t),this}};p.promise(w).complete=d.add,w.success=w.done,w.error=w.fail,l.url=((e||l.url||ajaxLocation)+"").replace(rhash,"").replace(rprotocol,ajaxLocParts[1]+"//"),l.type=t.method||t.type||l.method||l.type,l.dataTypes=jQuery.trim(l.dataType||"*").toLowerCase().match(rnotwhite)||[""],l.crossDomain==null&&(u=rurl.exec(l.url.toLowerCase()),l.crossDomain=!(!u||u[1]===ajaxLocParts[1]&&u[2]===ajaxLocParts[2]&&(u[3]||(u[1]==="http:"?"80":"443"))===(ajaxLocParts[3]||(ajaxLocParts[1]==="http:"?"80":"443")))),l.data&&l.processData&&typeof l.data!="string"&&(l.data=jQuery.param(l.data,l.traditional)),inspectPrefiltersOrTransports(prefilters,l,t,w);if(y===2)return w;a=l.global,a&&jQuery.active++===0&&jQuery.event.trigger("ajaxStart"),l.type=l.type.toUpperCase(),l.hasContent=!rnoContent.test(l.type),r=l.url,l.hasContent||(l.data&&(r=l.url+=(rquery.test(r)?"&":"?")+l.data,delete l.data),l.cache===!1&&(l.url=rts.test(r)?r.replace(rts,"$1_="+nonce++):r+(rquery.test(r)?"&":"?")+"_="+nonce++)),l.ifModified&&(jQuery.lastModified[r]&&w.setRequestHeader("If-Modified-Since",jQuery.lastModified[r]),jQuery.etag[r]&&w.setRequestHeader("If-None-Match",jQuery.etag[r])),(l.data&&l.hasContent&&l.contentType!==!1||t.contentType)&&w.setRequestHeader("Content-Type",l.contentType),w.setRequestHeader("Accept",l.dataTypes[0]&&l.accepts[l.dataTypes[0]]?l.accepts[l.dataTypes[0]]+(l.dataTypes[0]!=="*"?", "+allTypes+"; q=0.01":""):l.accepts["*"]);for(f in l.headers)w.setRequestHeader(f,l.headers[f]);if(!l.beforeSend||l.beforeSend.call(c,w,l)!==!1&&y!==2){b="abort";for(f in{success:1,error:1,complete:1})w[f](l[f]);n=inspectPrefiltersOrTransports(transports,l,t,w);if(!n)S(-1,"No Transport");else{w.readyState=1,a&&h.trigger("ajaxSend",[w,l]),l.async&&l.timeout>0&&(o=setTimeout(function(){w.abort("timeout")},l.timeout));try{y=1,n.send(m,S)}catch(E){if(!(y<2))throw E;S(-1,E)}}return w}return w.abort()},getJSON:function(e,t,n){return jQuery.get(e,t,n,"json")},getScript:function(e,t){return jQuery.get(e,undefined,t,"script")}}),jQuery.each(["get","post"],function(e,t){jQuery[t]=function(e,n,r,i){return jQuery.isFunction(n)&&(i=i||r,r=n,n=undefined),jQuery.ajax({url:e,type:t,dataType:i,data:n,success:r})}}),jQuery.each(["ajaxStart","ajaxStop","ajaxComplete","ajaxError","ajaxSuccess","ajaxSend"],function(e,t){jQuery.fn[t]=function(e){return this.on(t,e)}}),jQuery._evalUrl=function(e){return jQuery.ajax({url:e,type:"GET",dataType:"script",async:!1,global:!1,"throws":!0})},jQuery.fn.extend({wrapAll:function(e){var t;return jQuery.isFunction(e)?this.each(function(t){jQuery(this).wrapAll(e.call(this,t))}):(this[0]&&(t=jQuery(e,this[0].ownerDocument).eq(0).clone(!0),this[0].parentNode&&t.insertBefore(this[0]),t.map(function(){var e=this;while(e.firstElementChild)e=e.firstElementChild;return e}).append(this)),this)},wrapInner:function(e){return jQuery.isFunction(e)?this.each(function(t){jQuery(this).wrapInner(e.call(this,t))}):this.each(function(){var t=jQuery(this),n=t.contents();n.length?n.wrapAll(e):t.append(e)})},wrap:function(e){var t=jQuery.isFunction(e);return this.each(function(n){jQuery(this).wrapAll(t?e.call(this,n):e)})},unwrap:function(){return this.parent().each(function(){jQuery.nodeName(this,"body")||jQuery(this).replaceWith(this.childNodes)}).end()}}),jQuery.expr.filters.hidden=function(e){return e.offsetWidth<=0&&e.offsetHeight<=0},jQuery.expr.filters.visible=function(e){return!jQuery.expr.filters.hidden(e)};var r20=/%20/g,rbracket=/\[\]$/,rCRLF=/\r?\n/g,rsubmitterTypes=/^(?:submit|button|image|reset|file)$/i,rsubmittable=/^(?:input|select|textarea|keygen)/i;jQuery.param=function(e,t){var n,r=[],i=function(e,t){t=jQuery.isFunction(t)?t():t==null?"":t,r[r.length]=encodeURIComponent(e)+"="+encodeURIComponent(t)};t===undefined&&(t=jQuery.ajaxSettings&&jQuery.ajaxSettings.traditional);if(jQuery.isArray(e)||e.jquery&&!jQuery.isPlainObject(e))jQuery.each(e,function(){i(this.name,this.value)});else for(n in e)buildParams(n,e[n],t,i);return r.join("&").replace(r20,"+")},jQuery.fn.extend({serialize:function(){return jQuery.param(this.serializeArray())},serializeArray:function(){return this.map(function(){var e=jQuery.prop(this,"elements");return e?jQuery.makeArray(e):this}).filter(function(){var e=this.type;return this.name&&!jQuery(this).is(":disabled")&&rsubmittable.test(this.nodeName)&&!rsubmitterTypes.test(e)&&(this.checked||!rcheckableType.test(e))}).map(function(e,t){var n=jQuery(this).val();return n==null?null:jQuery.isArray(n)?jQuery.map(n,function(e){return{name:t.name,value:e.replace(rCRLF,"\r\n")}}):{name:t.name,value:n.replace(rCRLF,"\r\n")}}).get()}}),jQuery.ajaxSettings.xhr=function(){try{return new XMLHttpRequest}catch(e){}};var xhrId=0,xhrCallbacks={},xhrSuccessStatus={0:200,1223:204},xhrSupported=jQuery.ajaxSettings.xhr();window.ActiveXObject&&jQuery(window).on("unload",function(){for(var e in xhrCallbacks)xhrCallbacks[e]()}),support.cors=!!xhrSupported&&"withCredentials"in xhrSupported,support.ajax=xhrSupported=!!xhrSupported,jQuery.ajaxTransport(function(e){var t;if(support.cors||xhrSupported&&!e.crossDomain)return{send:function(n,r){var i,s=e.xhr(),o=++xhrId;s.open(e.type,e.url,e.async,e.username,e.password);if(e.xhrFields)for(i in e.xhrFields)s[i]=e.xhrFields[i];e.mimeType&&s.overrideMimeType&&s.overrideMimeType(e.mimeType),!e.crossDomain&&!n["X-Requested-With"]&&(n["X-Requested-With"]="XMLHttpRequest");for(i in n)s.setRequestHeader(i,n[i]);t=function(e){return function(){t&&(delete xhrCallbacks[o],t=s.onload=s.onerror=null,e==="abort"?s.abort():e==="error"?r(s.status,s.statusText):r(xhrSuccessStatus[s.status]||s.status,s.statusText,typeof s.responseText=="string"?{text:s.responseText}:undefined,s.getAllResponseHeaders()))}},s.onload=t(),s.onerror=t("error"),t=xhrCallbacks[o]=t("abort"),s.send(e.hasContent&&e.data||null)},abort:function(){t&&t()}}}),jQuery.ajaxSetup({accepts:{script:"text/javascript, application/javascript, application/ecmascript, application/x-ecmascript"},contents:{script:/(?:java|ecma)script/},converters:{"text script":function(e){return jQuery.globalEval(e),e}}}),jQuery.ajaxPrefilter("script",function(e){e.cache===undefined&&(e.cache=!1),e.crossDomain&&(e.type="GET")}),jQuery.ajaxTransport("script",function(e){if(e.crossDomain){var t,n;return{send:function(r,i){t=jQuery("<script>").prop({async:!0,charset:e.scriptCharset,src:e.url}).on("load error",n=function(e){t.remove(),n=null,e&&i(e.type==="error"?404:200,e.type)}),document.head.appendChild(t[0])},abort:function(){n&&n()}}}});var oldCallbacks=[],rjsonp=/(=)\?(?=&|$)|\?\?/;jQuery.ajaxSetup({jsonp:"callback",jsonpCallback:function(){var e=oldCallbacks.pop()||jQuery.expando+"_"+nonce++;return this[e]=!0,e}}),jQuery.ajaxPrefilter("json jsonp",function(e,t,n){var r,i,s,o=e.jsonp!==!1&&(rjsonp.test(e.url)?"url":typeof e.data=="string"&&!(e.contentType||"").indexOf("application/x-www-form-urlencoded")&&rjsonp.test(e.data)&&"data");if(o||e.dataTypes[0]==="jsonp")return r=e.jsonpCallback=jQuery.isFunction(e.jsonpCallback)?e.jsonpCallback():e.jsonpCallback,o?e[o]=e[o].replace(rjsonp,"$1"+r):e.jsonp!==!1&&(e.url+=(rquery.test(e.url)?"&":"?")+e.jsonp+"="+r),e.converters["script json"]=function(){return s||jQuery.error(r+" was not called"),s[0]},e.dataTypes[0]="json",i=window[r],window[r]=function(){s=arguments},n.always(function(){window[r]=i,e[r]&&(e.jsonpCallback=t.jsonpCallback,oldCallbacks.push(r)),s&&jQuery.isFunction(i)&&i(s[0]),s=i=undefined}),"script"}),jQuery.parseHTML=function(e,t,n){if(!e||typeof e!="string")return null;typeof t=="boolean"&&(n=t,t=!1),t=t||document;var r=rsingleTag.exec(e),i=!n&&[];return r?[t.createElement(r[1])]:(r=jQuery.buildFragment([e],t,i),i&&i.length&&jQuery(i).remove(),jQuery.merge([],r.childNodes))};var _load=jQuery.fn.load;jQuery.fn.load=function(e,t,n){if(typeof e!="string"&&_load)return _load.apply(this,arguments);var r,i,s,o=this,u=e.indexOf(" ");return u>=0&&(r=e.slice(u),e=e.slice(0,u)),jQuery.isFunction(t)?(n=t,t=undefined):t&&typeof t=="object"&&(i="POST"),o.length>0&&jQuery.ajax({url:e,type:i,dataType:"html",data:t}).done(function(e){s=arguments,o.html(r?jQuery("<div>").append(jQuery.parseHTML(e)).find(r):e)}).complete(n&&function(e,t){o.each(n,s||[e.responseText,t,e])}),this},jQuery.expr.filters.animated=function(e){return jQuery.grep(jQuery.timers,function(t){return e===t.elem}).length};var docElem=window.document.documentElement;jQuery.offset={setOffset:function(e,t,n){var r,i,s,o,u,a,f,l=jQuery.css(e,"position"),c=jQuery(e),h={};l==="static"&&(e.style.position="relative"),u=c.offset(),s=jQuery.css(e,"top"),a=jQuery.css(e,"left"),f=(l==="absolute"||l==="fixed")&&(s+a).indexOf("auto")>-1,f?(r=c.position(),o=r.top,i=r.left):(o=parseFloat(s)||0,i=parseFloat(a)||0),jQuery.isFunction(t)&&(t=t.call(e,n,u)),t.top!=null&&(h.top=t.top-u.top+o),t.left!=null&&(h.left=t.left-u.left+i),"using"in t?t.using.call(e,h):c.css(h)}},jQuery.fn.extend({offset:function(e){if(arguments.length)return e===undefined?this:this.each(function(t){jQuery.offset.setOffset(this,e,t)});var t,n,r=this[0],i={top:0,left:0},s=r&&r.ownerDocument;if(!s)return;return t=s.documentElement,jQuery.contains(t,r)?(typeof r.getBoundingClientRect!==strundefined&&(i=r.getBoundingClientRect()),n=getWindow(s),{top:i.top+n.pageYOffset-t.clientTop,left:i.left+n.pageXOffset-t.clientLeft}):i},position:function(){if(!this[0])return;var e,t,n=this[0],r={top:0,left:0};return jQuery.css(n,"position")==="fixed"?t=n.getBoundingClientRect():(e=this.offsetParent(),t=this.offset(),jQuery.nodeName(e[0],"html")||(r=e.offset()),r.top+=jQuery.css(e[0],"borderTopWidth",!0),r.left+=jQuery.css(e[0],"borderLeftWidth",!0)),{top:t.top-r.top-jQuery.css(n,"marginTop",!0),left:t.left-r.left-jQuery.css(n,"marginLeft",!0)}},offsetParent:function(){return this.map(function(){var e=this.offsetParent||docElem;while(e&&!jQuery.nodeName(e,"html")&&jQuery.css(e,"position")==="static")e=e.offsetParent;return e||docElem})}}),jQuery.each({scrollLeft:"pageXOffset",scrollTop:"pageYOffset"},function(e,t){var n="pageYOffset"===t;jQuery.fn[e]=function(r){return access(this,function(e,r,i){var s=getWindow(e);if(i===undefined)return s?s[t]:e[r];s?s.scrollTo(n?window.pageXOffset:i,n?i:window.pageYOffset):e[r]=i},e,r,arguments.length,null)}}),jQuery.each(["top","left"],function(e,t){jQuery.cssHooks[t]=addGetHookIf(support.pixelPosition,function(e,n){if(n)return n=curCSS(e,t),rnumnonpx.test(n)?jQuery(e).position()[t]+"px":n})}),jQuery.each({Height:"height",Width:"width"},function(e,t){jQuery.each({padding:"inner"+e,content:t,"":"outer"+e},function(n,r){jQuery.fn[r]=function(r,i){var s=arguments.length&&(n||typeof r!="boolean"),o=n||(r===!0||i===!0?"margin":"border");return access(this,function(t,n,r){var i;return jQuery.isWindow(t)?t.document.documentElement["client"+e]:t.nodeType===9?(i=t.documentElement,Math.max(t.body["scroll"+e],i["scroll"+e],t.body["offset"+e],i["offset"+e],i["client"+e])):r===undefined?jQuery.css(t,n,o):jQuery.style(t,n,r,o)},t,s?r:undefined,s,null)}})}),jQuery.fn.size=function(){return this.length},jQuery.fn.andSelf=jQuery.fn.addBack,typeof define=="function"&&define.amd&&define("jquery",[],function(){return jQuery});var _jQuery=window.jQuery,_$=window.$;return jQuery.noConflict=function(e){return window.$===jQuery&&(window.$=_$),e&&window.jQuery===jQuery&&(window.jQuery=_jQuery),jQuery},typeof noGlobal===strundefined&&(window.jQuery=window.$=jQuery),jQuery});
\ No newline at end of file
--- /dev/null
+(function(e){function t(t){this.browser=t,this.propertyInput=t.parents(".property-font-family-select"),this.hiddenInput=this.propertyInput.find("input.property-hidden-input"),this.setup=function(){var t=this;this.browser.find(".tab-content").each(function(){var n=e(this).find(".fonts-list ul"),r=_.debounce(function(){t.scrollWebFontLoader(n)},100);n.bind("scroll",r),t.initQuickSearch(e(this)),t.initPreview(e(this)),t.initSorting(e(this)),n.delegate(".use-font","click",function(){var n=e(this).parents("li").first(),r=e(this).parents(".tab-content").data("font-webfont-provider"),i=n.data("value"),s=e(this).siblings(".font-family").text(),o=n.css("font-family"),u=n.data("variants"),a="";u&&u.indexOf("regular")===-1&&(a="|"+u.join(","));var f=r!=0?r+"|"+i+a:i,l=t.propertyInput.find(".font-name");l.css("font-family",o),l.text(s),t.browser.find(".selected-font").removeClass("selected-font"),n.addClass("selected-font"),fontBrowserClose({data:{fontBrowser:t.browser}}),dataHandleDesignEditorInput({hiddenInput:t.hiddenInput,value:f,stack:o})})}),this.browser.tabs({selected:0,activate:function(n,r){var i=e(r.newPanel);if(i.data("fonts-loaded"))return;t.retrieveRemoteFonts(i,"popularity",!0,!0)}}),this.changeToSelectedFontProviderTab()},this.retrieveRemoteFonts=function(t,n,r,i){if(!t.data("font-load-with-ajax"))return;var s=this;createCog(t.find(".fonts-loading"),!0),t.find(".fonts-list ul").fadeOut(300),t.find(".fonts-loading").fadeIn(300),t.find(".fonts-filter").attr("disabled","disabled"),e.post(Headway.ajaxURL,{security:Headway.security,action:"headway_visual_editor",method:"fonts_list",sortby:n,provider:t.data("font-webfont-provider")},function(e){t.find(".fonts-loading").fadeOut(300),t.find("ul").hide().html(e).fadeIn(300,function(){s.scrollWebFontLoader(t.find("ul"))}),t.find(".fonts-filter").val(""),t.data("quicksearch").cache(),t.find(".fonts-filter").removeAttr("disabled");if(typeof i!="undefined"&&i&&s.hiddenInput.val().match(/\|/g)){var n=t.find('li[data-value="'+s.hiddenInput.val().split("|")[1]+'"]');n.length&&(n.addClass("selected-font"),t.find(".fonts-list ul").scrollTop(n.position().top))}else t.find(".fonts-list ul").scrollTop(0);t.data("fonts-loaded",!0)})},this.scrollWebFontLoader=function(t){var n=e(t.parents(".tab-content").get(0)),r=n.data("font-webfont-provider");if(t.parents(".font-provider-tab-content.ui-tabs-hide").length||!r)return;var i=[],s=t.scrollTop(),o=s+t.outerHeight();t.find("li").each(function(){var n=e(this).position().top+t.scrollTop(),r=n+e(this).outerHeight();if(!e(this).is(":visible")||e(this).data("loadedFont"))return;if(!(n<=o))return;if(!(r>=s))return;if(r>o)return!1;var u="";e(this).data("variants").indexOf("regular")===-1&&(u=":"+e(this).data("variants").join(",")),i.push(e(this).data("value")+u)});if(i.length){var u={},a="";_.each(i,function(e){var n=t.find('li[data-value="'+e+'"]');n.data("loadedFont",!0),a+=e.replace(" ","+")+"|"}),e("<link>").attr("type","text/css").attr("rel","stylesheet").attr("href","http://fonts.googleapis.com/css?family="+a.substr(0,a.length-1)).appendTo("head").bind("load",function(){_.each(i,function(e){var n=t.find('li[data-value="'+e.split(":")[0]+'"]');n.find("span.font-family, span.font-preview-text").show().css("opacity",1)})})}},this.initQuickSearch=function(e){var t=e.attr("id"),n=e.find(".fonts-filter").quicksearch("#"+t+" .fonts-list ul li",{delay:750,noResults:"#"+t+" .fonts-list .fonts-noresults",loader:"#"+t+" .fonts-list .fonts-loading",bind:"keyup",onBefore:function(){e.find(".fonts-list ul").fadeOut(100)},onAfter:function(){e.find(".fonts-list ul").trigger("scroll").fadeIn(100)},prepareQuery:function(e){return new RegExp(e,"i")},testQuery:function(e,t,n){return e.test(jQuery.trim(t.replace("the quick brown fox jumps over the lazy dog.","")))}});e.data("quicksearch",n)},this.initPreview=function(t){var n=this;previewHtml=e('<div class="font-preview-overlay" style="display:none;"><span class="close-preview"></span><header><h4></h4><p><i class="icon-edit"> </i><strong>click anywhere</strong> in preview text to edit and add your own</p></header><div class="editable allow-backspace-key" contenteditable="true"></div><footer><div class="tools"><span title="Reset Preview Text" class="reset-preview"></span><span title="Decrease Preview Size" class="size-down"></span><span title="Increase Preview Size" class="size-up"></span><span title="Use This Font" class="use-font"></span></div></footer></div>'),t.find(".fonts-list").after(previewHtml),this.defaultPreviewText="The quick brown fox jumps over the lazy dog.",this.defaultPreviewSize="24px",this.previewResize=function(e,t){var n=e.find(".editable"),r=n.css("font-size"),i=parseFloat(r,10)*t;n.css("font-size",i),localStorage.fontPreviewSize=n.css("font-size")},this.previewLoadFromStorage=function(e){var t=e.find(".editable");localStorage.getItem("fontPreviewText")?t.html(localStorage.fontPreviewText):t.html(n.defaultPreviewText),localStorage.getItem("fontPreviewSize")&&t.css("font-size",localStorage.fontPreviewSize)},this.previewSaveText=function(){localStorage.fontPreviewText=e(this).text()},this.previewReset=function(e){e.find(".editable").html(n.defaultPreviewText),e.find(".editable").css("font-size",n.defaultPreviewSize),localStorage.fontPreviewText=n.defaultPreviewText,localStorage.fontPreviewSize=n.defaultPreviewSize},t.find(".fonts-list ul").delegate("li .preview-font","click",function(){var t=e(this).parents("li").data("value"),r=e(this).parents("li").css("font-family"),i=e(this).parents(".fonts-list").siblings(".font-preview-overlay");i.data("font-value",t),i.data("font-name",e(this).parent().find(".font-family").text()),i.data("font-variants",e(this).parents("li").data("variants")),i.fadeIn(750),i.css("font-family",r),i.find("h4").html(e(this).parent().find(".font-family").text()+" <span>(Preview)</span>"),n.previewLoadFromStorage(i)}),t.find(".font-preview-overlay .size-up").on("click",function(){n.previewResize(e(this).parents(".font-preview-overlay"),1.1)}),t.find(".font-preview-overlay .size-down").on("click",function(){n.previewResize(e(this).parents(".font-preview-overlay"),.9)}),t.find(".font-preview-overlay .reset-preview").on("click",function(){n.previewReset(e(this).parents(".font-preview-overlay"))}),t.find(".font-preview-overlay .close-preview").on("click",function(){e(this).parents(".font-preview-overlay").fadeOut(750)}),t.find(".font-preview-overlay .editable").on("blur",this.previewSaveText),t.find(".font-preview-overlay .use-font").on("click",function(){var t=e(this).parents(".tab-content").data("font-webfont-provider"),r=e(this).parents(".font-preview-overlay").data("font-value"),i=e(this).parents(".font-preview-overlay").data("font-name"),s=e(this).parents(".font-preview-overlay").css("font-family"),o=e(this).parents(".font-preview-overlay").data("font-variants"),u="";o&&o.indexOf("regular")===-1&&(u="|"+o.join(","));var a=t!=0?t+"|"+r+u:r,f=n.propertyInput.find(".font-name");f.css("font-family",s),f.text(i),n.browser.find(".selected-font").removeClass("selected-font"),n.browser.find('li[data-value="'+r+'"]').addClass("selected-font"),fontBrowserClose({data:{fontBrowser:n.browser}}),dataHandleDesignEditorInput({hiddenInput:n.hiddenInput,value:a,stack:s})})},this.initSorting=function(t){var n=this;t.find(".fonts-search select").bind("change",function(){var t=e(this).val();n.retrieveRemoteFonts(e(this).parents(".tab-content"),t,!0)})},this.changeToSelectedFontProviderTab=function(){var e=this.hiddenInput.val();if(!e||!e.match(/\|/g)){var t=this.browser.find("#traditional-fonts"),n=t.find('li[data-value="'+e+'"]');n.length&&(n.addClass("selected-font"),setTimeout(function(){t.find(".fonts-list ul").scrollTop(n.position().top)},100))}else{var r=e.split("|");selectTab(+r[0]+"-fonts",this.browser)}}}(function(e,t,n,r){e.fn.quicksearch=function(n,r){var i,s,o,u,a="",f=this,l=e.extend({delay:100,selector:null,stripeRows:null,loader:null,noResults:"",matchedResultsCount:0,bind:"keyup",onBefore:function(){return},onAfter:function(){return},show:function(){this.style.display=""},hide:function(){this.style.display="none"},prepareQuery:function(e){return e.toLowerCase().split(" ")},testQuery:function(e,t,n){for(var r=0;r<e.length;r+=1)if(t.indexOf(e[r])===-1)return!1;return!0}},r);return this.go=function(){var e=0,t=0,n=!0,r=l.prepareQuery(a),i=a.replace(" ","").length===0;for(var e=0,u=o.length;e<u;e++)i||l.testQuery(r,s[e],o[e])?(l.show.apply(o[e]),n=!1,t++):l.hide.apply(o[e]);return n?this.results(!1):(this.results(!0),this.stripe()),this.matchedResultsCount=t,this.loader(!1),l.onAfter(),this},this.search=function(e){a=e,f.trigger()},this.currentMatchedResults=function(){return this.matchedResultsCount},this.stripe=function(){if(typeof l.stripeRows=="object"&&l.stripeRows!==null){var t=l.stripeRows.join(" "),n=l.stripeRows.length;u.not(":hidden").each(function(r){e(this).removeClass(t).addClass(l.stripeRows[r%n])})}return this},this.strip_html=function(t){var n=t.replace(new RegExp("<[^<]+>","g"),"");return n=e.trim(n.toLowerCase()),n},this.results=function(t){return typeof l.noResults=="string"&&l.noResults!==""&&(t?e(l.noResults).hide():e(l.noResults).show()),this},this.loader=function(t){return typeof l.loader=="string"&&l.loader!==""&&(t?e(l.loader).show():e(l.loader).hide()),this},this.cache=function(){u=e(n),typeof l.noResults=="string"&&l.noResults!==""&&(u=u.not(l.noResults));var t=typeof l.selector=="string"?u.find(l.selector):e(n).not(l.noResults);return s=t.map(function(){return f.strip_html(this.innerHTML)}),o=u.map(function(){return this}),a=a||this.val()||"",!0},this.trigger=function(){return this.loader(!0),l.onBefore(),t.clearTimeout(i),i=t.setTimeout(function(){f.go()},l.delay),this},this.cache(),this.results(!0),this.stripe(),this.loader(!1),this.each(function(){e(this).bind(l.bind,function(){a=e(this).val(),f.trigger()})})}})(jQuery,this,document),fontBrowserOpen=function(n){var r=e(this).siblings(".font-browser"),i=e(this).parents(".design-editor-property-font-family").offset();r.css({top:i.top-r.outerHeight(!0),left:i.left});var s=parseInt(r.css("left").replace("px","")),o=s+r.outerWidth(!0);if(o>e(window).width()){var u=e(window).width()-o;r.css({left:s+u-20})}e("div.sub-tabs-content-container").css("overflow-y","hidden"),r.data("setup")!==!0&&(r.data("obj",new t(r)),r.data("obj").setup(),r.data("setup",!0)),r.data("visible")!==!0?(r.fadeIn(150),r.data("visible",!0),e(document).bind("mousedown",{fontBrowser:r},fontBrowserClose),Headway.iframe.contents().bind("mousedown",{fontBrowser:r},fontBrowserClose),e(window).bind("resize",{fontBrowser:r},fontBrowserClose)):(r.fadeOut(150),r.data("visible",!1),e("div.sub-tabs-content-container").css("overflow-y","auto"),e(document).unbind("mousedown",fontBrowserClose),Headway.iframe.contents().unbind("mousedown",fontBrowserClose),e(window).unbind("resize",fontBrowserClose))},fontBrowserClose=function(t){if(e(t.target).parents(".design-editor-property-font-family").length===1)return;var n=t.data.fontBrowser;n.fadeOut(150),n.data("visible",!1),e("div.sub-tabs-content-container").css("overflow-y","auto"),e(document).unbind("mousedown",fontBrowserClose),Headway.iframe.contents().unbind("mousedown",fontBrowserClose),e(window).unbind("resize",fontBrowserClose)},webFontQuickLoad=function(e){if(!e.match(/\|/g))return;var t=e.split("|"),n=e,r=t[0],e=t[1],i="";if(typeof t[2]!="undefined"&&t[2])var i=":"+t[2];var s={fontactive:function(e,t){jQuery("span.font-name[data-webfont-value='"+n+"']").animate({opacity:1})}};return s[r]={families:[e+i]},WebFont.load(s)}})(jQuery);
\ No newline at end of file
--- /dev/null
+$("#menu").bind("touchmove",function(e){e.preventDefault()});
\ No newline at end of file
--- /dev/null
+require.config({
+ paths: {
+ ko: 'deps/knockout',
+ underscore: 'deps/underscore',
+
+ /* jQuery Plugins */
+ jqueryUI: 'deps/jquery.ui',
+ qtip: 'deps/jquery.qtip'
+ },
+ shim: {
+ underscore: {
+ exports: '_'
+ }
+ }
+});
+
+require(['jquery', 'util.loader'], function($) {
+
+ /* Start loading indidcator */
+ startTitleActivityIndicator();
+ //iframe.showIframeLoadingOverlay();
+
+ /* Parse the JSON in the Headway l10n array */
+ Headway.blockTypeURLs = $.parseJSON(Headway.blockTypeURLs.replace(/"/g, '"'));
+ Headway.allBlockTypes = $.parseJSON(Headway.allBlockTypes.replace(/"/g, '"'));
+ Headway.ranTour = $.parseJSON(Headway.ranTour.replace(/"/g, '"'));
+
+ Headway.designEditorProperties = $.parseJSON(Headway.designEditorProperties.replace(/"/g, '"'));
+
+ /* Setup modules */
+ require(['modules/layout-selector'], function(layoutSelector) {
+ layoutSelector.init();
+ });
+
+ require(['modules/panel', 'modules/iframe'], function(panel, iframe) {
+ panel.init();
+ iframe.init();
+ });
+
+ require(['modules/menu'], function(menu) {
+ menu.init();
+ });
+
+ require(['modules/snapshots'], function(snapshots) {
+ snapshots.init();
+ });
+
+ /* Init tour */
+ require(['util.tour'], function (tour) {
+
+ if ( Headway.ranTour[Headway.mode] == false && Headway.ranTour.legacy == false ) {
+ tour.start();
+ }
+
+ });
+
+
+ /* Load helpers all at once since they're used everywhere */
+ require(['helper.data', 'helper.blocks', 'helper.wrappers', 'helper.context-menus', 'helper.notifications', 'helper.boxes', 'helper.history'], function(data, blocks, wrappers, contextMenus, notifications, boxes, history) {
+ history.init();
+ });
+
+ /* Load in the appropriate modules depending on the mode */
+ switch ( Headway.mode ) {
+
+ case 'grid':
+
+ require(['modules/grid/mode-grid', 'modules/iframe'], function(modeGrid) {
+ Headway.instance = modeGrid;
+
+ modeGrid.init();
+ waitForIframeLoad(modeGrid.iframeCallback);
+ });
+
+ break;
+
+ case 'design':
+
+ require(['modules/design/mode-design', 'modules/iframe'], function(modeDesign) {
+ Headway.instance = modeDesign;
+
+ modeDesign.init();
+ waitForIframeLoad(modeDesign.iframeCallback);
+ });
+
+ break;
+
+ }
+
+ /* After everything is loaded show the Visual Editor */
+ $(document).ready(function() {
+
+ $('body').addClass('show-ve');
+
+
+
+ });
+
+ $(window).bind('load', function() {
+
+ /* Remove VE loader overlay after we know page has loaded */
+ setTimeout(function () {
+ $('div#ve-loading-overlay').remove();
+ }, 1000);
+
+ });
+
+
+});
\ No newline at end of file
--- /dev/null
+//Node: node r.js -o build.js
+({
+ appDir: "../",
+ baseUrl: ".",
+ dir: '../../scripts-min',
+ findNestedDependencies: true,
+ removeCombined: true,
+ preserveLicenseComments: false,
+ paths: {
+ jquery: 'deps/require-and-jquery',
+ ko: 'deps/knockout',
+ underscore: 'deps/underscore',
+
+ /* jQuery Plugins */
+ jqueryUI: 'deps/jquery.ui',
+ qtip: 'deps/jquery.qtip'
+ },
+ shim: {
+ underscore: {
+ exports: '_'
+ }
+ },
+ modules: [
+ {
+ name: "app",
+ exclude: ["jquery"]
+ }
+ ]
+})
\ No newline at end of file
--- /dev/null
+/**
+ * @license r.js 2.1.11 Copyright (c) 2010-2014, The Dojo Foundation All Rights Reserved.
+ * Available via the MIT or new BSD license.
+ * see: http://github.com/jrburke/requirejs for details
+ */
+
+/*
+ * This is a bootstrap script to allow running RequireJS in the command line
+ * in either a Java/Rhino or Node environment. It is modified by the top-level
+ * dist.js file to inject other files to completely enable this file. It is
+ * the shell of the r.js file.
+ */
+
+/*jslint evil: true, nomen: true, sloppy: true */
+/*global readFile: true, process: false, Packages: false, print: false,
+console: false, java: false, module: false, requirejsVars, navigator,
+document, importScripts, self, location, Components, FileUtils */
+
+var requirejs, require, define, xpcUtil;
+(function (console, args, readFileFunc) {
+ var fileName, env, fs, vm, path, exec, rhinoContext, dir, nodeRequire,
+ nodeDefine, exists, reqMain, loadedOptimizedLib, existsForNode, Cc, Ci,
+ version = '2.1.11',
+ jsSuffixRegExp = /\.js$/,
+ commandOption = '',
+ useLibLoaded = {},
+ //Used by jslib/rhino/args.js
+ rhinoArgs = args,
+ //Used by jslib/xpconnect/args.js
+ xpconnectArgs = args,
+ readFile = typeof readFileFunc !== 'undefined' ? readFileFunc : null;
+
+ function showHelp() {
+ console.log('See https://github.com/jrburke/r.js for usage.');
+ }
+
+ if ((typeof navigator !== 'undefined' && typeof document !== 'undefined') ||
+ (typeof importScripts !== 'undefined' && typeof self !== 'undefined')) {
+ env = 'browser';
+
+ readFile = function (path) {
+ return fs.readFileSync(path, 'utf8');
+ };
+
+ exec = function (string) {
+ return eval(string);
+ };
+
+ exists = function () {
+ console.log('x.js exists not applicable in browser env');
+ return false;
+ };
+
+ } else if (typeof Packages !== 'undefined') {
+ env = 'rhino';
+
+ fileName = args[0];
+
+ if (fileName && fileName.indexOf('-') === 0) {
+ commandOption = fileName.substring(1);
+ fileName = args[1];
+ }
+
+ //Set up execution context.
+ rhinoContext = Packages.org.mozilla.javascript.ContextFactory.getGlobal().enterContext();
+
+ exec = function (string, name) {
+ return rhinoContext.evaluateString(this, string, name, 0, null);
+ };
+
+ exists = function (fileName) {
+ return (new java.io.File(fileName)).exists();
+ };
+
+ //Define a console.log for easier logging. Don't
+ //get fancy though.
+ if (typeof console === 'undefined') {
+ console = {
+ log: function () {
+ print.apply(undefined, arguments);
+ }
+ };
+ }
+ } else if (typeof process !== 'undefined' && process.versions && !!process.versions.node) {
+ env = 'node';
+
+ //Get the fs module via Node's require before it
+ //gets replaced. Used in require/node.js
+ fs = require('fs');
+ vm = require('vm');
+ path = require('path');
+ //In Node 0.7+ existsSync is on fs.
+ existsForNode = fs.existsSync || path.existsSync;
+
+ nodeRequire = require;
+ nodeDefine = define;
+ reqMain = require.main;
+
+ //Temporarily hide require and define to allow require.js to define
+ //them.
+ require = undefined;
+ define = undefined;
+
+ readFile = function (path) {
+ return fs.readFileSync(path, 'utf8');
+ };
+
+ exec = function (string, name) {
+ return vm.runInThisContext(this.requirejsVars.require.makeNodeWrapper(string),
+ name ? fs.realpathSync(name) : '');
+ };
+
+ exists = function (fileName) {
+ return existsForNode(fileName);
+ };
+
+
+ fileName = process.argv[2];
+
+ if (fileName && fileName.indexOf('-') === 0) {
+ commandOption = fileName.substring(1);
+ fileName = process.argv[3];
+ }
+ } else if (typeof Components !== 'undefined' && Components.classes && Components.interfaces) {
+ env = 'xpconnect';
+
+ Components.utils['import']('resource://gre/modules/FileUtils.jsm');
+ Cc = Components.classes;
+ Ci = Components.interfaces;
+
+ fileName = args[0];
+
+ if (fileName && fileName.indexOf('-') === 0) {
+ commandOption = fileName.substring(1);
+ fileName = args[1];
+ }
+
+ xpcUtil = {
+ isWindows: ('@mozilla.org/windows-registry-key;1' in Cc),
+ cwd: function () {
+ return FileUtils.getFile("CurWorkD", []).path;
+ },
+
+ //Remove . and .. from paths, normalize on front slashes
+ normalize: function (path) {
+ //There has to be an easier way to do this.
+ var i, part, ary,
+ firstChar = path.charAt(0);
+
+ if (firstChar !== '/' &&
+ firstChar !== '\\' &&
+ path.indexOf(':') === -1) {
+ //A relative path. Use the current working directory.
+ path = xpcUtil.cwd() + '/' + path;
+ }
+
+ ary = path.replace(/\\/g, '/').split('/');
+
+ for (i = 0; i < ary.length; i += 1) {
+ part = ary[i];
+ if (part === '.') {
+ ary.splice(i, 1);
+ i -= 1;
+ } else if (part === '..') {
+ ary.splice(i - 1, 2);
+ i -= 2;
+ }
+ }
+ return ary.join('/');
+ },
+
+ xpfile: function (path) {
+ var fullPath;
+ try {
+ fullPath = xpcUtil.normalize(path);
+ if (xpcUtil.isWindows) {
+ fullPath = fullPath.replace(/\//g, '\\');
+ }
+ return new FileUtils.File(fullPath);
+ } catch (e) {
+ throw new Error((fullPath || path) + ' failed: ' + e);
+ }
+ },
+
+ readFile: function (/*String*/path, /*String?*/encoding) {
+ //A file read function that can deal with BOMs
+ encoding = encoding || "utf-8";
+
+ var inStream, convertStream,
+ readData = {},
+ fileObj = xpcUtil.xpfile(path);
+
+ //XPCOM, you so crazy
+ try {
+ inStream = Cc['@mozilla.org/network/file-input-stream;1']
+ .createInstance(Ci.nsIFileInputStream);
+ inStream.init(fileObj, 1, 0, false);
+
+ convertStream = Cc['@mozilla.org/intl/converter-input-stream;1']
+ .createInstance(Ci.nsIConverterInputStream);
+ convertStream.init(inStream, encoding, inStream.available(),
+ Ci.nsIConverterInputStream.DEFAULT_REPLACEMENT_CHARACTER);
+
+ convertStream.readString(inStream.available(), readData);
+ return readData.value;
+ } catch (e) {
+ throw new Error((fileObj && fileObj.path || '') + ': ' + e);
+ } finally {
+ if (convertStream) {
+ convertStream.close();
+ }
+ if (inStream) {
+ inStream.close();
+ }
+ }
+ }
+ };
+
+ readFile = xpcUtil.readFile;
+
+ exec = function (string) {
+ return eval(string);
+ };
+
+ exists = function (fileName) {
+ return xpcUtil.xpfile(fileName).exists();
+ };
+
+ //Define a console.log for easier logging. Don't
+ //get fancy though.
+ if (typeof console === 'undefined') {
+ console = {
+ log: function () {
+ print.apply(undefined, arguments);
+ }
+ };
+ }
+ }
+
+ /** vim: et:ts=4:sw=4:sts=4
+ * @license RequireJS 2.1.11 Copyright (c) 2010-2014, The Dojo Foundation All Rights Reserved.
+ * Available via the MIT or new BSD license.
+ * see: http://github.com/jrburke/requirejs for details
+ */
+//Not using strict: uneven strict support in browsers, #392, and causes
+//problems with requirejs.exec()/transpiler plugins that may not be strict.
+/*jslint regexp: true, nomen: true, sloppy: true */
+/*global window, navigator, document, importScripts, setTimeout, opera */
+
+
+(function (global) {
+ var req, s, head, baseElement, dataMain, src,
+ interactiveScript, currentlyAddingScript, mainScript, subPath,
+ version = '2.1.11',
+ commentRegExp = /(\/\*([\s\S]*?)\*\/|([^:]|^)\/\/(.*)$)/mg,
+ cjsRequireRegExp = /[^.]\s*require\s*\(\s*["']([^'"\s]+)["']\s*\)/g,
+ jsSuffixRegExp = /\.js$/,
+ currDirRegExp = /^\.\//,
+ op = Object.prototype,
+ ostring = op.toString,
+ hasOwn = op.hasOwnProperty,
+ ap = Array.prototype,
+ apsp = ap.splice,
+ isBrowser = !!(typeof window !== 'undefined' && typeof navigator !== 'undefined' && window.document),
+ isWebWorker = !isBrowser && typeof importScripts !== 'undefined',
+ //PS3 indicates loaded and complete, but need to wait for complete
+ //specifically. Sequence is 'loading', 'loaded', execution,
+ // then 'complete'. The UA check is unfortunate, but not sure how
+ //to feature test w/o causing perf issues.
+ readyRegExp = isBrowser && navigator.platform === 'PLAYSTATION 3' ?
+ /^complete$/ : /^(complete|loaded)$/,
+ defContextName = '_',
+ //Oh the tragedy, detecting opera. See the usage of isOpera for reason.
+ isOpera = typeof opera !== 'undefined' && opera.toString() === '[object Opera]',
+ contexts = {},
+ cfg = {},
+ globalDefQueue = [],
+ useInteractive = false;
+
+ function isFunction(it) {
+ return ostring.call(it) === '[object Function]';
+ }
+
+ function isArray(it) {
+ return ostring.call(it) === '[object Array]';
+ }
+
+ /**
+ * Helper function for iterating over an array. If the func returns
+ * a true value, it will break out of the loop.
+ */
+ function each(ary, func) {
+ if (ary) {
+ var i;
+ for (i = 0; i < ary.length; i += 1) {
+ if (ary[i] && func(ary[i], i, ary)) {
+ break;
+ }
+ }
+ }
+ }
+
+ /**
+ * Helper function for iterating over an array backwards. If the func
+ * returns a true value, it will break out of the loop.
+ */
+ function eachReverse(ary, func) {
+ if (ary) {
+ var i;
+ for (i = ary.length - 1; i > -1; i -= 1) {
+ if (ary[i] && func(ary[i], i, ary)) {
+ break;
+ }
+ }
+ }
+ }
+
+ function hasProp(obj, prop) {
+ return hasOwn.call(obj, prop);
+ }
+
+ function getOwn(obj, prop) {
+ return hasProp(obj, prop) && obj[prop];
+ }
+
+ /**
+ * Cycles over properties in an object and calls a function for each
+ * property value. If the function returns a truthy value, then the
+ * iteration is stopped.
+ */
+ function eachProp(obj, func) {
+ var prop;
+ for (prop in obj) {
+ if (hasProp(obj, prop)) {
+ if (func(obj[prop], prop)) {
+ break;
+ }
+ }
+ }
+ }
+
+ /**
+ * Simple function to mix in properties from source into target,
+ * but only if target does not already have a property of the same name.
+ */
+ function mixin(target, source, force, deepStringMixin) {
+ if (source) {
+ eachProp(source, function (value, prop) {
+ if (force || !hasProp(target, prop)) {
+ if (deepStringMixin && typeof value === 'object' && value &&
+ !isArray(value) && !isFunction(value) &&
+ !(value instanceof RegExp)) {
+
+ if (!target[prop]) {
+ target[prop] = {};
+ }
+ mixin(target[prop], value, force, deepStringMixin);
+ } else {
+ target[prop] = value;
+ }
+ }
+ });
+ }
+ return target;
+ }
+
+ //Similar to Function.prototype.bind, but the 'this' object is specified
+ //first, since it is easier to read/figure out what 'this' will be.
+ function bind(obj, fn) {
+ return function () {
+ return fn.apply(obj, arguments);
+ };
+ }
+
+ function scripts() {
+ return document.getElementsByTagName('script');
+ }
+
+ function defaultOnError(err) {
+ throw err;
+ }
+
+ //Allow getting a global that is expressed in
+ //dot notation, like 'a.b.c'.
+ function getGlobal(value) {
+ if (!value) {
+ return value;
+ }
+ var g = global;
+ each(value.split('.'), function (part) {
+ g = g[part];
+ });
+ return g;
+ }
+
+ /**
+ * Constructs an error with a pointer to an URL with more information.
+ * @param {String} id the error ID that maps to an ID on a web page.
+ * @param {String} message human readable error.
+ * @param {Error} [err] the original error, if there is one.
+ *
+ * @returns {Error}
+ */
+ function makeError(id, msg, err, requireModules) {
+ var e = new Error(msg + '\nhttp://requirejs.org/docs/errors.html#' + id);
+ e.requireType = id;
+ e.requireModules = requireModules;
+ if (err) {
+ e.originalError = err;
+ }
+ return e;
+ }
+
+ if (typeof define !== 'undefined') {
+ //If a define is already in play via another AMD loader,
+ //do not overwrite.
+ return;
+ }
+
+ if (typeof requirejs !== 'undefined') {
+ if (isFunction(requirejs)) {
+ //Do not overwrite and existing requirejs instance.
+ return;
+ }
+ cfg = requirejs;
+ requirejs = undefined;
+ }
+
+ //Allow for a require config object
+ if (typeof require !== 'undefined' && !isFunction(require)) {
+ //assume it is a config object.
+ cfg = require;
+ require = undefined;
+ }
+
+ function newContext(contextName) {
+ var inCheckLoaded, Module, context, handlers,
+ checkLoadedTimeoutId,
+ config = {
+ //Defaults. Do not set a default for map
+ //config to speed up normalize(), which
+ //will run faster if there is no default.
+ waitSeconds: 7,
+ baseUrl: './',
+ paths: {},
+ bundles: {},
+ pkgs: {},
+ shim: {},
+ config: {}
+ },
+ registry = {},
+ //registry of just enabled modules, to speed
+ //cycle breaking code when lots of modules
+ //are registered, but not activated.
+ enabledRegistry = {},
+ undefEvents = {},
+ defQueue = [],
+ defined = {},
+ urlFetched = {},
+ bundlesMap = {},
+ requireCounter = 1,
+ unnormalizedCounter = 1;
+
+ /**
+ * Trims the . and .. from an array of path segments.
+ * It will keep a leading path segment if a .. will become
+ * the first path segment, to help with module name lookups,
+ * which act like paths, but can be remapped. But the end result,
+ * all paths that use this function should look normalized.
+ * NOTE: this method MODIFIES the input array.
+ * @param {Array} ary the array of path segments.
+ */
+ function trimDots(ary) {
+ var i, part, length = ary.length;
+ for (i = 0; i < length; i++) {
+ part = ary[i];
+ if (part === '.') {
+ ary.splice(i, 1);
+ i -= 1;
+ } else if (part === '..') {
+ if (i === 1 && (ary[2] === '..' || ary[0] === '..')) {
+ //End of the line. Keep at least one non-dot
+ //path segment at the front so it can be mapped
+ //correctly to disk. Otherwise, there is likely
+ //no path mapping for a path starting with '..'.
+ //This can still fail, but catches the most reasonable
+ //uses of ..
+ break;
+ } else if (i > 0) {
+ ary.splice(i - 1, 2);
+ i -= 2;
+ }
+ }
+ }
+ }
+
+ /**
+ * Given a relative module name, like ./something, normalize it to
+ * a real name that can be mapped to a path.
+ * @param {String} name the relative name
+ * @param {String} baseName a real name that the name arg is relative
+ * to.
+ * @param {Boolean} applyMap apply the map config to the value. Should
+ * only be done if this normalization is for a dependency ID.
+ * @returns {String} normalized name
+ */
+ function normalize(name, baseName, applyMap) {
+ var pkgMain, mapValue, nameParts, i, j, nameSegment, lastIndex,
+ foundMap, foundI, foundStarMap, starI,
+ baseParts = baseName && baseName.split('/'),
+ normalizedBaseParts = baseParts,
+ map = config.map,
+ starMap = map && map['*'];
+
+ //Adjust any relative paths.
+ if (name && name.charAt(0) === '.') {
+ //If have a base name, try to normalize against it,
+ //otherwise, assume it is a top-level require that will
+ //be relative to baseUrl in the end.
+ if (baseName) {
+ //Convert baseName to array, and lop off the last part,
+ //so that . matches that 'directory' and not name of the baseName's
+ //module. For instance, baseName of 'one/two/three', maps to
+ //'one/two/three.js', but we want the directory, 'one/two' for
+ //this normalization.
+ normalizedBaseParts = baseParts.slice(0, baseParts.length - 1);
+ name = name.split('/');
+ lastIndex = name.length - 1;
+
+ // If wanting node ID compatibility, strip .js from end
+ // of IDs. Have to do this here, and not in nameToUrl
+ // because node allows either .js or non .js to map
+ // to same file.
+ if (config.nodeIdCompat && jsSuffixRegExp.test(name[lastIndex])) {
+ name[lastIndex] = name[lastIndex].replace(jsSuffixRegExp, '');
+ }
+
+ name = normalizedBaseParts.concat(name);
+ trimDots(name);
+ name = name.join('/');
+ } else if (name.indexOf('./') === 0) {
+ // No baseName, so this is ID is resolved relative
+ // to baseUrl, pull off the leading dot.
+ name = name.substring(2);
+ }
+ }
+
+ //Apply map config if available.
+ if (applyMap && map && (baseParts || starMap)) {
+ nameParts = name.split('/');
+
+ outerLoop: for (i = nameParts.length; i > 0; i -= 1) {
+ nameSegment = nameParts.slice(0, i).join('/');
+
+ if (baseParts) {
+ //Find the longest baseName segment match in the config.
+ //So, do joins on the biggest to smallest lengths of baseParts.
+ for (j = baseParts.length; j > 0; j -= 1) {
+ mapValue = getOwn(map, baseParts.slice(0, j).join('/'));
+
+ //baseName segment has config, find if it has one for
+ //this name.
+ if (mapValue) {
+ mapValue = getOwn(mapValue, nameSegment);
+ if (mapValue) {
+ //Match, update name to the new value.
+ foundMap = mapValue;
+ foundI = i;
+ break outerLoop;
+ }
+ }
+ }
+ }
+
+ //Check for a star map match, but just hold on to it,
+ //if there is a shorter segment match later in a matching
+ //config, then favor over this star map.
+ if (!foundStarMap && starMap && getOwn(starMap, nameSegment)) {
+ foundStarMap = getOwn(starMap, nameSegment);
+ starI = i;
+ }
+ }
+
+ if (!foundMap && foundStarMap) {
+ foundMap = foundStarMap;
+ foundI = starI;
+ }
+
+ if (foundMap) {
+ nameParts.splice(0, foundI, foundMap);
+ name = nameParts.join('/');
+ }
+ }
+
+ // If the name points to a package's name, use
+ // the package main instead.
+ pkgMain = getOwn(config.pkgs, name);
+
+ return pkgMain ? pkgMain : name;
+ }
+
+ function removeScript(name) {
+ if (isBrowser) {
+ each(scripts(), function (scriptNode) {
+ if (scriptNode.getAttribute('data-requiremodule') === name &&
+ scriptNode.getAttribute('data-requirecontext') === context.contextName) {
+ scriptNode.parentNode.removeChild(scriptNode);
+ return true;
+ }
+ });
+ }
+ }
+
+ function hasPathFallback(id) {
+ var pathConfig = getOwn(config.paths, id);
+ if (pathConfig && isArray(pathConfig) && pathConfig.length > 1) {
+ //Pop off the first array value, since it failed, and
+ //retry
+ pathConfig.shift();
+ context.require.undef(id);
+ context.require([id]);
+ return true;
+ }
+ }
+
+ //Turns a plugin!resource to [plugin, resource]
+ //with the plugin being undefined if the name
+ //did not have a plugin prefix.
+ function splitPrefix(name) {
+ var prefix,
+ index = name ? name.indexOf('!') : -1;
+ if (index > -1) {
+ prefix = name.substring(0, index);
+ name = name.substring(index + 1, name.length);
+ }
+ return [prefix, name];
+ }
+
+ /**
+ * Creates a module mapping that includes plugin prefix, module
+ * name, and path. If parentModuleMap is provided it will
+ * also normalize the name via require.normalize()
+ *
+ * @param {String} name the module name
+ * @param {String} [parentModuleMap] parent module map
+ * for the module name, used to resolve relative names.
+ * @param {Boolean} isNormalized: is the ID already normalized.
+ * This is true if this call is done for a define() module ID.
+ * @param {Boolean} applyMap: apply the map config to the ID.
+ * Should only be true if this map is for a dependency.
+ *
+ * @returns {Object}
+ */
+ function makeModuleMap(name, parentModuleMap, isNormalized, applyMap) {
+ var url, pluginModule, suffix, nameParts,
+ prefix = null,
+ parentName = parentModuleMap ? parentModuleMap.name : null,
+ originalName = name,
+ isDefine = true,
+ normalizedName = '';
+
+ //If no name, then it means it is a require call, generate an
+ //internal name.
+ if (!name) {
+ isDefine = false;
+ name = '_@r' + (requireCounter += 1);
+ }
+
+ nameParts = splitPrefix(name);
+ prefix = nameParts[0];
+ name = nameParts[1];
+
+ if (prefix) {
+ prefix = normalize(prefix, parentName, applyMap);
+ pluginModule = getOwn(defined, prefix);
+ }
+
+ //Account for relative paths if there is a base name.
+ if (name) {
+ if (prefix) {
+ if (pluginModule && pluginModule.normalize) {
+ //Plugin is loaded, use its normalize method.
+ normalizedName = pluginModule.normalize(name, function (name) {
+ return normalize(name, parentName, applyMap);
+ });
+ } else {
+ normalizedName = normalize(name, parentName, applyMap);
+ }
+ } else {
+ //A regular module.
+ normalizedName = normalize(name, parentName, applyMap);
+
+ //Normalized name may be a plugin ID due to map config
+ //application in normalize. The map config values must
+ //already be normalized, so do not need to redo that part.
+ nameParts = splitPrefix(normalizedName);
+ prefix = nameParts[0];
+ normalizedName = nameParts[1];
+ isNormalized = true;
+
+ url = context.nameToUrl(normalizedName);
+ }
+ }
+
+ //If the id is a plugin id that cannot be determined if it needs
+ //normalization, stamp it with a unique ID so two matching relative
+ //ids that may conflict can be separate.
+ suffix = prefix && !pluginModule && !isNormalized ?
+ '_unnormalized' + (unnormalizedCounter += 1) :
+ '';
+
+ return {
+ prefix: prefix,
+ name: normalizedName,
+ parentMap: parentModuleMap,
+ unnormalized: !!suffix,
+ url: url,
+ originalName: originalName,
+ isDefine: isDefine,
+ id: (prefix ?
+ prefix + '!' + normalizedName :
+ normalizedName) + suffix
+ };
+ }
+
+ function getModule(depMap) {
+ var id = depMap.id,
+ mod = getOwn(registry, id);
+
+ if (!mod) {
+ mod = registry[id] = new context.Module(depMap);
+ }
+
+ return mod;
+ }
+
+ function on(depMap, name, fn) {
+ var id = depMap.id,
+ mod = getOwn(registry, id);
+
+ if (hasProp(defined, id) &&
+ (!mod || mod.defineEmitComplete)) {
+ if (name === 'defined') {
+ fn(defined[id]);
+ }
+ } else {
+ mod = getModule(depMap);
+ if (mod.error && name === 'error') {
+ fn(mod.error);
+ } else {
+ mod.on(name, fn);
+ }
+ }
+ }
+
+ function onError(err, errback) {
+ var ids = err.requireModules,
+ notified = false;
+
+ if (errback) {
+ errback(err);
+ } else {
+ each(ids, function (id) {
+ var mod = getOwn(registry, id);
+ if (mod) {
+ //Set error on module, so it skips timeout checks.
+ mod.error = err;
+ if (mod.events.error) {
+ notified = true;
+ mod.emit('error', err);
+ }
+ }
+ });
+
+ if (!notified) {
+ req.onError(err);
+ }
+ }
+ }
+
+ /**
+ * Internal method to transfer globalQueue items to this context's
+ * defQueue.
+ */
+ function takeGlobalQueue() {
+ //Push all the globalDefQueue items into the context's defQueue
+ if (globalDefQueue.length) {
+ //Array splice in the values since the context code has a
+ //local var ref to defQueue, so cannot just reassign the one
+ //on context.
+ apsp.apply(defQueue,
+ [defQueue.length, 0].concat(globalDefQueue));
+ globalDefQueue = [];
+ }
+ }
+
+ handlers = {
+ 'require': function (mod) {
+ if (mod.require) {
+ return mod.require;
+ } else {
+ return (mod.require = context.makeRequire(mod.map));
+ }
+ },
+ 'exports': function (mod) {
+ mod.usingExports = true;
+ if (mod.map.isDefine) {
+ if (mod.exports) {
+ return (defined[mod.map.id] = mod.exports);
+ } else {
+ return (mod.exports = defined[mod.map.id] = {});
+ }
+ }
+ },
+ 'module': function (mod) {
+ if (mod.module) {
+ return mod.module;
+ } else {
+ return (mod.module = {
+ id: mod.map.id,
+ uri: mod.map.url,
+ config: function () {
+ return getOwn(config.config, mod.map.id) || {};
+ },
+ exports: mod.exports || (mod.exports = {})
+ });
+ }
+ }
+ };
+
+ function cleanRegistry(id) {
+ //Clean up machinery used for waiting modules.
+ delete registry[id];
+ delete enabledRegistry[id];
+ }
+
+ function breakCycle(mod, traced, processed) {
+ var id = mod.map.id;
+
+ if (mod.error) {
+ mod.emit('error', mod.error);
+ } else {
+ traced[id] = true;
+ each(mod.depMaps, function (depMap, i) {
+ var depId = depMap.id,
+ dep = getOwn(registry, depId);
+
+ //Only force things that have not completed
+ //being defined, so still in the registry,
+ //and only if it has not been matched up
+ //in the module already.
+ if (dep && !mod.depMatched[i] && !processed[depId]) {
+ if (getOwn(traced, depId)) {
+ mod.defineDep(i, defined[depId]);
+ mod.check(); //pass false?
+ } else {
+ breakCycle(dep, traced, processed);
+ }
+ }
+ });
+ processed[id] = true;
+ }
+ }
+
+ function checkLoaded() {
+ var err, usingPathFallback,
+ waitInterval = config.waitSeconds * 1000,
+ //It is possible to disable the wait interval by using waitSeconds of 0.
+ expired = waitInterval && (context.startTime + waitInterval) < new Date().getTime(),
+ noLoads = [],
+ reqCalls = [],
+ stillLoading = false,
+ needCycleCheck = true;
+
+ //Do not bother if this call was a result of a cycle break.
+ if (inCheckLoaded) {
+ return;
+ }
+
+ inCheckLoaded = true;
+
+ //Figure out the state of all the modules.
+ eachProp(enabledRegistry, function (mod) {
+ var map = mod.map,
+ modId = map.id;
+
+ //Skip things that are not enabled or in error state.
+ if (!mod.enabled) {
+ return;
+ }
+
+ if (!map.isDefine) {
+ reqCalls.push(mod);
+ }
+
+ if (!mod.error) {
+ //If the module should be executed, and it has not
+ //been inited and time is up, remember it.
+ if (!mod.inited && expired) {
+ if (hasPathFallback(modId)) {
+ usingPathFallback = true;
+ stillLoading = true;
+ } else {
+ noLoads.push(modId);
+ removeScript(modId);
+ }
+ } else if (!mod.inited && mod.fetched && map.isDefine) {
+ stillLoading = true;
+ if (!map.prefix) {
+ //No reason to keep looking for unfinished
+ //loading. If the only stillLoading is a
+ //plugin resource though, keep going,
+ //because it may be that a plugin resource
+ //is waiting on a non-plugin cycle.
+ return (needCycleCheck = false);
+ }
+ }
+ }
+ });
+
+ if (expired && noLoads.length) {
+ //If wait time expired, throw error of unloaded modules.
+ err = makeError('timeout', 'Load timeout for modules: ' + noLoads, null, noLoads);
+ err.contextName = context.contextName;
+ return onError(err);
+ }
+
+ //Not expired, check for a cycle.
+ if (needCycleCheck) {
+ each(reqCalls, function (mod) {
+ breakCycle(mod, {}, {});
+ });
+ }
+
+ //If still waiting on loads, and the waiting load is something
+ //other than a plugin resource, or there are still outstanding
+ //scripts, then just try back later.
+ if ((!expired || usingPathFallback) && stillLoading) {
+ //Something is still waiting to load. Wait for it, but only
+ //if a timeout is not already in effect.
+ if ((isBrowser || isWebWorker) && !checkLoadedTimeoutId) {
+ checkLoadedTimeoutId = setTimeout(function () {
+ checkLoadedTimeoutId = 0;
+ checkLoaded();
+ }, 50);
+ }
+ }
+
+ inCheckLoaded = false;
+ }
+
+ Module = function (map) {
+ this.events = getOwn(undefEvents, map.id) || {};
+ this.map = map;
+ this.shim = getOwn(config.shim, map.id);
+ this.depExports = [];
+ this.depMaps = [];
+ this.depMatched = [];
+ this.pluginMaps = {};
+ this.depCount = 0;
+
+ /* this.exports this.factory
+ this.depMaps = [],
+ this.enabled, this.fetched
+ */
+ };
+
+ Module.prototype = {
+ init: function (depMaps, factory, errback, options) {
+ options = options || {};
+
+ //Do not do more inits if already done. Can happen if there
+ //are multiple define calls for the same module. That is not
+ //a normal, common case, but it is also not unexpected.
+ if (this.inited) {
+ return;
+ }
+
+ this.factory = factory;
+
+ if (errback) {
+ //Register for errors on this module.
+ this.on('error', errback);
+ } else if (this.events.error) {
+ //If no errback already, but there are error listeners
+ //on this module, set up an errback to pass to the deps.
+ errback = bind(this, function (err) {
+ this.emit('error', err);
+ });
+ }
+
+ //Do a copy of the dependency array, so that
+ //source inputs are not modified. For example
+ //"shim" deps are passed in here directly, and
+ //doing a direct modification of the depMaps array
+ //would affect that config.
+ this.depMaps = depMaps && depMaps.slice(0);
+
+ this.errback = errback;
+
+ //Indicate this module has be initialized
+ this.inited = true;
+
+ this.ignore = options.ignore;
+
+ //Could have option to init this module in enabled mode,
+ //or could have been previously marked as enabled. However,
+ //the dependencies are not known until init is called. So
+ //if enabled previously, now trigger dependencies as enabled.
+ if (options.enabled || this.enabled) {
+ //Enable this module and dependencies.
+ //Will call this.check()
+ this.enable();
+ } else {
+ this.check();
+ }
+ },
+
+ defineDep: function (i, depExports) {
+ //Because of cycles, defined callback for a given
+ //export can be called more than once.
+ if (!this.depMatched[i]) {
+ this.depMatched[i] = true;
+ this.depCount -= 1;
+ this.depExports[i] = depExports;
+ }
+ },
+
+ fetch: function () {
+ if (this.fetched) {
+ return;
+ }
+ this.fetched = true;
+
+ context.startTime = (new Date()).getTime();
+
+ var map = this.map;
+
+ //If the manager is for a plugin managed resource,
+ //ask the plugin to load it now.
+ if (this.shim) {
+ context.makeRequire(this.map, {
+ enableBuildCallback: true
+ })(this.shim.deps || [], bind(this, function () {
+ return map.prefix ? this.callPlugin() : this.load();
+ }));
+ } else {
+ //Regular dependency.
+ return map.prefix ? this.callPlugin() : this.load();
+ }
+ },
+
+ load: function () {
+ var url = this.map.url;
+
+ //Regular dependency.
+ if (!urlFetched[url]) {
+ urlFetched[url] = true;
+ context.load(this.map.id, url);
+ }
+ },
+
+ /**
+ * Checks if the module is ready to define itself, and if so,
+ * define it.
+ */
+ check: function () {
+ if (!this.enabled || this.enabling) {
+ return;
+ }
+
+ var err, cjsModule,
+ id = this.map.id,
+ depExports = this.depExports,
+ exports = this.exports,
+ factory = this.factory;
+
+ if (!this.inited) {
+ this.fetch();
+ } else if (this.error) {
+ this.emit('error', this.error);
+ } else if (!this.defining) {
+ //The factory could trigger another require call
+ //that would result in checking this module to
+ //define itself again. If already in the process
+ //of doing that, skip this work.
+ this.defining = true;
+
+ if (this.depCount < 1 && !this.defined) {
+ if (isFunction(factory)) {
+ //If there is an error listener, favor passing
+ //to that instead of throwing an error. However,
+ //only do it for define()'d modules. require
+ //errbacks should not be called for failures in
+ //their callbacks (#699). However if a global
+ //onError is set, use that.
+ if ((this.events.error && this.map.isDefine) ||
+ req.onError !== defaultOnError) {
+ try {
+ exports = context.execCb(id, factory, depExports, exports);
+ } catch (e) {
+ err = e;
+ }
+ } else {
+ exports = context.execCb(id, factory, depExports, exports);
+ }
+
+ // Favor return value over exports. If node/cjs in play,
+ // then will not have a return value anyway. Favor
+ // module.exports assignment over exports object.
+ if (this.map.isDefine && exports === undefined) {
+ cjsModule = this.module;
+ if (cjsModule) {
+ exports = cjsModule.exports;
+ } else if (this.usingExports) {
+ //exports already set the defined value.
+ exports = this.exports;
+ }
+ }
+
+ if (err) {
+ err.requireMap = this.map;
+ err.requireModules = this.map.isDefine ? [this.map.id] : null;
+ err.requireType = this.map.isDefine ? 'define' : 'require';
+ return onError((this.error = err));
+ }
+
+ } else {
+ //Just a literal value
+ exports = factory;
+ }
+
+ this.exports = exports;
+
+ if (this.map.isDefine && !this.ignore) {
+ defined[id] = exports;
+
+ if (req.onResourceLoad) {
+ req.onResourceLoad(context, this.map, this.depMaps);
+ }
+ }
+
+ //Clean up
+ cleanRegistry(id);
+
+ this.defined = true;
+ }
+
+ //Finished the define stage. Allow calling check again
+ //to allow define notifications below in the case of a
+ //cycle.
+ this.defining = false;
+
+ if (this.defined && !this.defineEmitted) {
+ this.defineEmitted = true;
+ this.emit('defined', this.exports);
+ this.defineEmitComplete = true;
+ }
+
+ }
+ },
+
+ callPlugin: function () {
+ var map = this.map,
+ id = map.id,
+ //Map already normalized the prefix.
+ pluginMap = makeModuleMap(map.prefix);
+
+ //Mark this as a dependency for this plugin, so it
+ //can be traced for cycles.
+ this.depMaps.push(pluginMap);
+
+ on(pluginMap, 'defined', bind(this, function (plugin) {
+ var load, normalizedMap, normalizedMod,
+ bundleId = getOwn(bundlesMap, this.map.id),
+ name = this.map.name,
+ parentName = this.map.parentMap ? this.map.parentMap.name : null,
+ localRequire = context.makeRequire(map.parentMap, {
+ enableBuildCallback: true
+ });
+
+ //If current map is not normalized, wait for that
+ //normalized name to load instead of continuing.
+ if (this.map.unnormalized) {
+ //Normalize the ID if the plugin allows it.
+ if (plugin.normalize) {
+ name = plugin.normalize(name, function (name) {
+ return normalize(name, parentName, true);
+ }) || '';
+ }
+
+ //prefix and name should already be normalized, no need
+ //for applying map config again either.
+ normalizedMap = makeModuleMap(map.prefix + '!' + name,
+ this.map.parentMap);
+ on(normalizedMap,
+ 'defined', bind(this, function (value) {
+ this.init([], function () { return value; }, null, {
+ enabled: true,
+ ignore: true
+ });
+ }));
+
+ normalizedMod = getOwn(registry, normalizedMap.id);
+ if (normalizedMod) {
+ //Mark this as a dependency for this plugin, so it
+ //can be traced for cycles.
+ this.depMaps.push(normalizedMap);
+
+ if (this.events.error) {
+ normalizedMod.on('error', bind(this, function (err) {
+ this.emit('error', err);
+ }));
+ }
+ normalizedMod.enable();
+ }
+
+ return;
+ }
+
+ //If a paths config, then just load that file instead to
+ //resolve the plugin, as it is built into that paths layer.
+ if (bundleId) {
+ this.map.url = context.nameToUrl(bundleId);
+ this.load();
+ return;
+ }
+
+ load = bind(this, function (value) {
+ this.init([], function () { return value; }, null, {
+ enabled: true
+ });
+ });
+
+ load.error = bind(this, function (err) {
+ this.inited = true;
+ this.error = err;
+ err.requireModules = [id];
+
+ //Remove temp unnormalized modules for this module,
+ //since they will never be resolved otherwise now.
+ eachProp(registry, function (mod) {
+ if (mod.map.id.indexOf(id + '_unnormalized') === 0) {
+ cleanRegistry(mod.map.id);
+ }
+ });
+
+ onError(err);
+ });
+
+ //Allow plugins to load other code without having to know the
+ //context or how to 'complete' the load.
+ load.fromText = bind(this, function (text, textAlt) {
+ /*jslint evil: true */
+ var moduleName = map.name,
+ moduleMap = makeModuleMap(moduleName),
+ hasInteractive = useInteractive;
+
+ //As of 2.1.0, support just passing the text, to reinforce
+ //fromText only being called once per resource. Still
+ //support old style of passing moduleName but discard
+ //that moduleName in favor of the internal ref.
+ if (textAlt) {
+ text = textAlt;
+ }
+
+ //Turn off interactive script matching for IE for any define
+ //calls in the text, then turn it back on at the end.
+ if (hasInteractive) {
+ useInteractive = false;
+ }
+
+ //Prime the system by creating a module instance for
+ //it.
+ getModule(moduleMap);
+
+ //Transfer any config to this other module.
+ if (hasProp(config.config, id)) {
+ config.config[moduleName] = config.config[id];
+ }
+
+ try {
+ req.exec(text);
+ } catch (e) {
+ return onError(makeError('fromtexteval',
+ 'fromText eval for ' + id +
+ ' failed: ' + e,
+ e,
+ [id]));
+ }
+
+ if (hasInteractive) {
+ useInteractive = true;
+ }
+
+ //Mark this as a dependency for the plugin
+ //resource
+ this.depMaps.push(moduleMap);
+
+ //Support anonymous modules.
+ context.completeLoad(moduleName);
+
+ //Bind the value of that module to the value for this
+ //resource ID.
+ localRequire([moduleName], load);
+ });
+
+ //Use parentName here since the plugin's name is not reliable,
+ //could be some weird string with no path that actually wants to
+ //reference the parentName's path.
+ plugin.load(map.name, localRequire, load, config);
+ }));
+
+ context.enable(pluginMap, this);
+ this.pluginMaps[pluginMap.id] = pluginMap;
+ },
+
+ enable: function () {
+ enabledRegistry[this.map.id] = this;
+ this.enabled = true;
+
+ //Set flag mentioning that the module is enabling,
+ //so that immediate calls to the defined callbacks
+ //for dependencies do not trigger inadvertent load
+ //with the depCount still being zero.
+ this.enabling = true;
+
+ //Enable each dependency
+ each(this.depMaps, bind(this, function (depMap, i) {
+ var id, mod, handler;
+
+ if (typeof depMap === 'string') {
+ //Dependency needs to be converted to a depMap
+ //and wired up to this module.
+ depMap = makeModuleMap(depMap,
+ (this.map.isDefine ? this.map : this.map.parentMap),
+ false,
+ !this.skipMap);
+ this.depMaps[i] = depMap;
+
+ handler = getOwn(handlers, depMap.id);
+
+ if (handler) {
+ this.depExports[i] = handler(this);
+ return;
+ }
+
+ this.depCount += 1;
+
+ on(depMap, 'defined', bind(this, function (depExports) {
+ this.defineDep(i, depExports);
+ this.check();
+ }));
+
+ if (this.errback) {
+ on(depMap, 'error', bind(this, this.errback));
+ }
+ }
+
+ id = depMap.id;
+ mod = registry[id];
+
+ //Skip special modules like 'require', 'exports', 'module'
+ //Also, don't call enable if it is already enabled,
+ //important in circular dependency cases.
+ if (!hasProp(handlers, id) && mod && !mod.enabled) {
+ context.enable(depMap, this);
+ }
+ }));
+
+ //Enable each plugin that is used in
+ //a dependency
+ eachProp(this.pluginMaps, bind(this, function (pluginMap) {
+ var mod = getOwn(registry, pluginMap.id);
+ if (mod && !mod.enabled) {
+ context.enable(pluginMap, this);
+ }
+ }));
+
+ this.enabling = false;
+
+ this.check();
+ },
+
+ on: function (name, cb) {
+ var cbs = this.events[name];
+ if (!cbs) {
+ cbs = this.events[name] = [];
+ }
+ cbs.push(cb);
+ },
+
+ emit: function (name, evt) {
+ each(this.events[name], function (cb) {
+ cb(evt);
+ });
+ if (name === 'error') {
+ //Now that the error handler was triggered, remove
+ //the listeners, since this broken Module instance
+ //can stay around for a while in the registry.
+ delete this.events[name];
+ }
+ }
+ };
+
+ function callGetModule(args) {
+ //Skip modules already defined.
+ if (!hasProp(defined, args[0])) {
+ getModule(makeModuleMap(args[0], null, true)).init(args[1], args[2]);
+ }
+ }
+
+ function removeListener(node, func, name, ieName) {
+ //Favor detachEvent because of IE9
+ //issue, see attachEvent/addEventListener comment elsewhere
+ //in this file.
+ if (node.detachEvent && !isOpera) {
+ //Probably IE. If not it will throw an error, which will be
+ //useful to know.
+ if (ieName) {
+ node.detachEvent(ieName, func);
+ }
+ } else {
+ node.removeEventListener(name, func, false);
+ }
+ }
+
+ /**
+ * Given an event from a script node, get the requirejs info from it,
+ * and then removes the event listeners on the node.
+ * @param {Event} evt
+ * @returns {Object}
+ */
+ function getScriptData(evt) {
+ //Using currentTarget instead of target for Firefox 2.0's sake. Not
+ //all old browsers will be supported, but this one was easy enough
+ //to support and still makes sense.
+ var node = evt.currentTarget || evt.srcElement;
+
+ //Remove the listeners once here.
+ removeListener(node, context.onScriptLoad, 'load', 'onreadystatechange');
+ removeListener(node, context.onScriptError, 'error');
+
+ return {
+ node: node,
+ id: node && node.getAttribute('data-requiremodule')
+ };
+ }
+
+ function intakeDefines() {
+ var args;
+
+ //Any defined modules in the global queue, intake them now.
+ takeGlobalQueue();
+
+ //Make sure any remaining defQueue items get properly processed.
+ while (defQueue.length) {
+ args = defQueue.shift();
+ if (args[0] === null) {
+ return onError(makeError('mismatch', 'Mismatched anonymous define() module: ' + args[args.length - 1]));
+ } else {
+ //args are id, deps, factory. Should be normalized by the
+ //define() function.
+ callGetModule(args);
+ }
+ }
+ }
+
+ context = {
+ config: config,
+ contextName: contextName,
+ registry: registry,
+ defined: defined,
+ urlFetched: urlFetched,
+ defQueue: defQueue,
+ Module: Module,
+ makeModuleMap: makeModuleMap,
+ nextTick: req.nextTick,
+ onError: onError,
+
+ /**
+ * Set a configuration for the context.
+ * @param {Object} cfg config object to integrate.
+ */
+ configure: function (cfg) {
+ //Make sure the baseUrl ends in a slash.
+ if (cfg.baseUrl) {
+ if (cfg.baseUrl.charAt(cfg.baseUrl.length - 1) !== '/') {
+ cfg.baseUrl += '/';
+ }
+ }
+
+ //Save off the paths since they require special processing,
+ //they are additive.
+ var shim = config.shim,
+ objs = {
+ paths: true,
+ bundles: true,
+ config: true,
+ map: true
+ };
+
+ eachProp(cfg, function (value, prop) {
+ if (objs[prop]) {
+ if (!config[prop]) {
+ config[prop] = {};
+ }
+ mixin(config[prop], value, true, true);
+ } else {
+ config[prop] = value;
+ }
+ });
+
+ //Reverse map the bundles
+ if (cfg.bundles) {
+ eachProp(cfg.bundles, function (value, prop) {
+ each(value, function (v) {
+ if (v !== prop) {
+ bundlesMap[v] = prop;
+ }
+ });
+ });
+ }
+
+ //Merge shim
+ if (cfg.shim) {
+ eachProp(cfg.shim, function (value, id) {
+ //Normalize the structure
+ if (isArray(value)) {
+ value = {
+ deps: value
+ };
+ }
+ if ((value.exports || value.init) && !value.exportsFn) {
+ value.exportsFn = context.makeShimExports(value);
+ }
+ shim[id] = value;
+ });
+ config.shim = shim;
+ }
+
+ //Adjust packages if necessary.
+ if (cfg.packages) {
+ each(cfg.packages, function (pkgObj) {
+ var location, name;
+
+ pkgObj = typeof pkgObj === 'string' ? { name: pkgObj } : pkgObj;
+
+ name = pkgObj.name;
+ location = pkgObj.location;
+ if (location) {
+ config.paths[name] = pkgObj.location;
+ }
+
+ //Save pointer to main module ID for pkg name.
+ //Remove leading dot in main, so main paths are normalized,
+ //and remove any trailing .js, since different package
+ //envs have different conventions: some use a module name,
+ //some use a file name.
+ config.pkgs[name] = pkgObj.name + '/' + (pkgObj.main || 'main')
+ .replace(currDirRegExp, '')
+ .replace(jsSuffixRegExp, '');
+ });
+ }
+
+ //If there are any "waiting to execute" modules in the registry,
+ //update the maps for them, since their info, like URLs to load,
+ //may have changed.
+ eachProp(registry, function (mod, id) {
+ //If module already has init called, since it is too
+ //late to modify them, and ignore unnormalized ones
+ //since they are transient.
+ if (!mod.inited && !mod.map.unnormalized) {
+ mod.map = makeModuleMap(id);
+ }
+ });
+
+ //If a deps array or a config callback is specified, then call
+ //require with those args. This is useful when require is defined as a
+ //config object before require.js is loaded.
+ if (cfg.deps || cfg.callback) {
+ context.require(cfg.deps || [], cfg.callback);
+ }
+ },
+
+ makeShimExports: function (value) {
+ function fn() {
+ var ret;
+ if (value.init) {
+ ret = value.init.apply(global, arguments);
+ }
+ return ret || (value.exports && getGlobal(value.exports));
+ }
+ return fn;
+ },
+
+ makeRequire: function (relMap, options) {
+ options = options || {};
+
+ function localRequire(deps, callback, errback) {
+ var id, map, requireMod;
+
+ if (options.enableBuildCallback && callback && isFunction(callback)) {
+ callback.__requireJsBuild = true;
+ }
+
+ if (typeof deps === 'string') {
+ if (isFunction(callback)) {
+ //Invalid call
+ return onError(makeError('requireargs', 'Invalid require call'), errback);
+ }
+
+ //If require|exports|module are requested, get the
+ //value for them from the special handlers. Caveat:
+ //this only works while module is being defined.
+ if (relMap && hasProp(handlers, deps)) {
+ return handlers[deps](registry[relMap.id]);
+ }
+
+ //Synchronous access to one module. If require.get is
+ //available (as in the Node adapter), prefer that.
+ if (req.get) {
+ return req.get(context, deps, relMap, localRequire);
+ }
+
+ //Normalize module name, if it contains . or ..
+ map = makeModuleMap(deps, relMap, false, true);
+ id = map.id;
+
+ if (!hasProp(defined, id)) {
+ return onError(makeError('notloaded', 'Module name "' +
+ id +
+ '" has not been loaded yet for context: ' +
+ contextName +
+ (relMap ? '' : '. Use require([])')));
+ }
+ return defined[id];
+ }
+
+ //Grab defines waiting in the global queue.
+ intakeDefines();
+
+ //Mark all the dependencies as needing to be loaded.
+ context.nextTick(function () {
+ //Some defines could have been added since the
+ //require call, collect them.
+ intakeDefines();
+
+ requireMod = getModule(makeModuleMap(null, relMap));
+
+ //Store if map config should be applied to this require
+ //call for dependencies.
+ requireMod.skipMap = options.skipMap;
+
+ requireMod.init(deps, callback, errback, {
+ enabled: true
+ });
+
+ checkLoaded();
+ });
+
+ return localRequire;
+ }
+
+ mixin(localRequire, {
+ isBrowser: isBrowser,
+
+ /**
+ * Converts a module name + .extension into an URL path.
+ * *Requires* the use of a module name. It does not support using
+ * plain URLs like nameToUrl.
+ */
+ toUrl: function (moduleNamePlusExt) {
+ var ext,
+ index = moduleNamePlusExt.lastIndexOf('.'),
+ segment = moduleNamePlusExt.split('/')[0],
+ isRelative = segment === '.' || segment === '..';
+
+ //Have a file extension alias, and it is not the
+ //dots from a relative path.
+ if (index !== -1 && (!isRelative || index > 1)) {
+ ext = moduleNamePlusExt.substring(index, moduleNamePlusExt.length);
+ moduleNamePlusExt = moduleNamePlusExt.substring(0, index);
+ }
+
+ return context.nameToUrl(normalize(moduleNamePlusExt,
+ relMap && relMap.id, true), ext, true);
+ },
+
+ defined: function (id) {
+ return hasProp(defined, makeModuleMap(id, relMap, false, true).id);
+ },
+
+ specified: function (id) {
+ id = makeModuleMap(id, relMap, false, true).id;
+ return hasProp(defined, id) || hasProp(registry, id);
+ }
+ });
+
+ //Only allow undef on top level require calls
+ if (!relMap) {
+ localRequire.undef = function (id) {
+ //Bind any waiting define() calls to this context,
+ //fix for #408
+ takeGlobalQueue();
+
+ var map = makeModuleMap(id, relMap, true),
+ mod = getOwn(registry, id);
+
+ removeScript(id);
+
+ delete defined[id];
+ delete urlFetched[map.url];
+ delete undefEvents[id];
+
+ //Clean queued defines too. Go backwards
+ //in array so that the splices do not
+ //mess up the iteration.
+ eachReverse(defQueue, function(args, i) {
+ if(args[0] === id) {
+ defQueue.splice(i, 1);
+ }
+ });
+
+ if (mod) {
+ //Hold on to listeners in case the
+ //module will be attempted to be reloaded
+ //using a different config.
+ if (mod.events.defined) {
+ undefEvents[id] = mod.events;
+ }
+
+ cleanRegistry(id);
+ }
+ };
+ }
+
+ return localRequire;
+ },
+
+ /**
+ * Called to enable a module if it is still in the registry
+ * awaiting enablement. A second arg, parent, the parent module,
+ * is passed in for context, when this method is overridden by
+ * the optimizer. Not shown here to keep code compact.
+ */
+ enable: function (depMap) {
+ var mod = getOwn(registry, depMap.id);
+ if (mod) {
+ getModule(depMap).enable();
+ }
+ },
+
+ /**
+ * Internal method used by environment adapters to complete a load event.
+ * A load event could be a script load or just a load pass from a synchronous
+ * load call.
+ * @param {String} moduleName the name of the module to potentially complete.
+ */
+ completeLoad: function (moduleName) {
+ var found, args, mod,
+ shim = getOwn(config.shim, moduleName) || {},
+ shExports = shim.exports;
+
+ takeGlobalQueue();
+
+ while (defQueue.length) {
+ args = defQueue.shift();
+ if (args[0] === null) {
+ args[0] = moduleName;
+ //If already found an anonymous module and bound it
+ //to this name, then this is some other anon module
+ //waiting for its completeLoad to fire.
+ if (found) {
+ break;
+ }
+ found = true;
+ } else if (args[0] === moduleName) {
+ //Found matching define call for this script!
+ found = true;
+ }
+
+ callGetModule(args);
+ }
+
+ //Do this after the cycle of callGetModule in case the result
+ //of those calls/init calls changes the registry.
+ mod = getOwn(registry, moduleName);
+
+ if (!found && !hasProp(defined, moduleName) && mod && !mod.inited) {
+ if (config.enforceDefine && (!shExports || !getGlobal(shExports))) {
+ if (hasPathFallback(moduleName)) {
+ return;
+ } else {
+ return onError(makeError('nodefine',
+ 'No define call for ' + moduleName,
+ null,
+ [moduleName]));
+ }
+ } else {
+ //A script that does not call define(), so just simulate
+ //the call for it.
+ callGetModule([moduleName, (shim.deps || []), shim.exportsFn]);
+ }
+ }
+
+ checkLoaded();
+ },
+
+ /**
+ * Converts a module name to a file path. Supports cases where
+ * moduleName may actually be just an URL.
+ * Note that it **does not** call normalize on the moduleName,
+ * it is assumed to have already been normalized. This is an
+ * internal API, not a public one. Use toUrl for the public API.
+ */
+ nameToUrl: function (moduleName, ext, skipExt) {
+ var paths, syms, i, parentModule, url,
+ parentPath, bundleId,
+ pkgMain = getOwn(config.pkgs, moduleName);
+
+ if (pkgMain) {
+ moduleName = pkgMain;
+ }
+
+ bundleId = getOwn(bundlesMap, moduleName);
+
+ if (bundleId) {
+ return context.nameToUrl(bundleId, ext, skipExt);
+ }
+
+ //If a colon is in the URL, it indicates a protocol is used and it is just
+ //an URL to a file, or if it starts with a slash, contains a query arg (i.e. ?)
+ //or ends with .js, then assume the user meant to use an url and not a module id.
+ //The slash is important for protocol-less URLs as well as full paths.
+ if (req.jsExtRegExp.test(moduleName)) {
+ //Just a plain path, not module name lookup, so just return it.
+ //Add extension if it is included. This is a bit wonky, only non-.js things pass
+ //an extension, this method probably needs to be reworked.
+ url = moduleName + (ext || '');
+ } else {
+ //A module that needs to be converted to a path.
+ paths = config.paths;
+
+ syms = moduleName.split('/');
+ //For each module name segment, see if there is a path
+ //registered for it. Start with most specific name
+ //and work up from it.
+ for (i = syms.length; i > 0; i -= 1) {
+ parentModule = syms.slice(0, i).join('/');
+
+ parentPath = getOwn(paths, parentModule);
+ if (parentPath) {
+ //If an array, it means there are a few choices,
+ //Choose the one that is desired
+ if (isArray(parentPath)) {
+ parentPath = parentPath[0];
+ }
+ syms.splice(0, i, parentPath);
+ break;
+ }
+ }
+
+ //Join the path parts together, then figure out if baseUrl is needed.
+ url = syms.join('/');
+ url += (ext || (/^data\:|\?/.test(url) || skipExt ? '' : '.js'));
+ url = (url.charAt(0) === '/' || url.match(/^[\w\+\.\-]+:/) ? '' : config.baseUrl) + url;
+ }
+
+ return config.urlArgs ? url +
+ ((url.indexOf('?') === -1 ? '?' : '&') +
+ config.urlArgs) : url;
+ },
+
+ //Delegates to req.load. Broken out as a separate function to
+ //allow overriding in the optimizer.
+ load: function (id, url) {
+ req.load(context, id, url);
+ },
+
+ /**
+ * Executes a module callback function. Broken out as a separate function
+ * solely to allow the build system to sequence the files in the built
+ * layer in the right sequence.
+ *
+ * @private
+ */
+ execCb: function (name, callback, args, exports) {
+ return callback.apply(exports, args);
+ },
+
+ /**
+ * callback for script loads, used to check status of loading.
+ *
+ * @param {Event} evt the event from the browser for the script
+ * that was loaded.
+ */
+ onScriptLoad: function (evt) {
+ //Using currentTarget instead of target for Firefox 2.0's sake. Not
+ //all old browsers will be supported, but this one was easy enough
+ //to support and still makes sense.
+ if (evt.type === 'load' ||
+ (readyRegExp.test((evt.currentTarget || evt.srcElement).readyState))) {
+ //Reset interactive script so a script node is not held onto for
+ //to long.
+ interactiveScript = null;
+
+ //Pull out the name of the module and the context.
+ var data = getScriptData(evt);
+ context.completeLoad(data.id);
+ }
+ },
+
+ /**
+ * Callback for script errors.
+ */
+ onScriptError: function (evt) {
+ var data = getScriptData(evt);
+ if (!hasPathFallback(data.id)) {
+ return onError(makeError('scripterror', 'Script error for: ' + data.id, evt, [data.id]));
+ }
+ }
+ };
+
+ context.require = context.makeRequire();
+ return context;
+ }
+
+ /**
+ * Main entry point.
+ *
+ * If the only argument to require is a string, then the module that
+ * is represented by that string is fetched for the appropriate context.
+ *
+ * If the first argument is an array, then it will be treated as an array
+ * of dependency string names to fetch. An optional function callback can
+ * be specified to execute when all of those dependencies are available.
+ *
+ * Make a local req variable to help Caja compliance (it assumes things
+ * on a require that are not standardized), and to give a short
+ * name for minification/local scope use.
+ */
+ req = requirejs = function (deps, callback, errback, optional) {
+
+ //Find the right context, use default
+ var context, config,
+ contextName = defContextName;
+
+ // Determine if have config object in the call.
+ if (!isArray(deps) && typeof deps !== 'string') {
+ // deps is a config object
+ config = deps;
+ if (isArray(callback)) {
+ // Adjust args if there are dependencies
+ deps = callback;
+ callback = errback;
+ errback = optional;
+ } else {
+ deps = [];
+ }
+ }
+
+ if (config && config.context) {
+ contextName = config.context;
+ }
+
+ context = getOwn(contexts, contextName);
+ if (!context) {
+ context = contexts[contextName] = req.s.newContext(contextName);
+ }
+
+ if (config) {
+ context.configure(config);
+ }
+
+ return context.require(deps, callback, errback);
+ };
+
+ /**
+ * Support require.config() to make it easier to cooperate with other
+ * AMD loaders on globally agreed names.
+ */
+ req.config = function (config) {
+ return req(config);
+ };
+
+ /**
+ * Execute something after the current tick
+ * of the event loop. Override for other envs
+ * that have a better solution than setTimeout.
+ * @param {Function} fn function to execute later.
+ */
+ req.nextTick = typeof setTimeout !== 'undefined' ? function (fn) {
+ setTimeout(fn, 4);
+ } : function (fn) { fn(); };
+
+ /**
+ * Export require as a global, but only if it does not already exist.
+ */
+ if (!require) {
+ require = req;
+ }
+
+ req.version = version;
+
+ //Used to filter out dependencies that are already paths.
+ req.jsExtRegExp = /^\/|:|\?|\.js$/;
+ req.isBrowser = isBrowser;
+ s = req.s = {
+ contexts: contexts,
+ newContext: newContext
+ };
+
+ //Create default context.
+ req({});
+
+ //Exports some context-sensitive methods on global require.
+ each([
+ 'toUrl',
+ 'undef',
+ 'defined',
+ 'specified'
+ ], function (prop) {
+ //Reference from contexts instead of early binding to default context,
+ //so that during builds, the latest instance of the default context
+ //with its config gets used.
+ req[prop] = function () {
+ var ctx = contexts[defContextName];
+ return ctx.require[prop].apply(ctx, arguments);
+ };
+ });
+
+ if (isBrowser) {
+ head = s.head = document.getElementsByTagName('head')[0];
+ //If BASE tag is in play, using appendChild is a problem for IE6.
+ //When that browser dies, this can be removed. Details in this jQuery bug:
+ //http://dev.jquery.com/ticket/2709
+ baseElement = document.getElementsByTagName('base')[0];
+ if (baseElement) {
+ head = s.head = baseElement.parentNode;
+ }
+ }
+
+ /**
+ * Any errors that require explicitly generates will be passed to this
+ * function. Intercept/override it if you want custom error handling.
+ * @param {Error} err the error object.
+ */
+ req.onError = defaultOnError;
+
+ /**
+ * Creates the node for the load command. Only used in browser envs.
+ */
+ req.createNode = function (config, moduleName, url) {
+ var node = config.xhtml ?
+ document.createElementNS('http://www.w3.org/1999/xhtml', 'html:script') :
+ document.createElement('script');
+ node.type = config.scriptType || 'text/javascript';
+ node.charset = 'utf-8';
+ node.async = true;
+ return node;
+ };
+
+ /**
+ * Does the request to load a module for the browser case.
+ * Make this a separate function to allow other environments
+ * to override it.
+ *
+ * @param {Object} context the require context to find state.
+ * @param {String} moduleName the name of the module.
+ * @param {Object} url the URL to the module.
+ */
+ req.load = function (context, moduleName, url) {
+ var config = (context && context.config) || {},
+ node;
+ if (isBrowser) {
+ //In the browser so use a script tag
+ node = req.createNode(config, moduleName, url);
+
+ node.setAttribute('data-requirecontext', context.contextName);
+ node.setAttribute('data-requiremodule', moduleName);
+
+ //Set up load listener. Test attachEvent first because IE9 has
+ //a subtle issue in its addEventListener and script onload firings
+ //that do not match the behavior of all other browsers with
+ //addEventListener support, which fire the onload event for a
+ //script right after the script execution. See:
+ //https://connect.microsoft.com/IE/feedback/details/648057/script-onload-event-is-not-fired-immediately-after-script-execution
+ //UNFORTUNATELY Opera implements attachEvent but does not follow the script
+ //script execution mode.
+ if (node.attachEvent &&
+ //Check if node.attachEvent is artificially added by custom script or
+ //natively supported by browser
+ //read https://github.com/jrburke/requirejs/issues/187
+ //if we can NOT find [native code] then it must NOT natively supported.
+ //in IE8, node.attachEvent does not have toString()
+ //Note the test for "[native code" with no closing brace, see:
+ //https://github.com/jrburke/requirejs/issues/273
+ !(node.attachEvent.toString && node.attachEvent.toString().indexOf('[native code') < 0) &&
+ !isOpera) {
+ //Probably IE. IE (at least 6-8) do not fire
+ //script onload right after executing the script, so
+ //we cannot tie the anonymous define call to a name.
+ //However, IE reports the script as being in 'interactive'
+ //readyState at the time of the define call.
+ useInteractive = true;
+
+ node.attachEvent('onreadystatechange', context.onScriptLoad);
+ //It would be great to add an error handler here to catch
+ //404s in IE9+. However, onreadystatechange will fire before
+ //the error handler, so that does not help. If addEventListener
+ //is used, then IE will fire error before load, but we cannot
+ //use that pathway given the connect.microsoft.com issue
+ //mentioned above about not doing the 'script execute,
+ //then fire the script load event listener before execute
+ //next script' that other browsers do.
+ //Best hope: IE10 fixes the issues,
+ //and then destroys all installs of IE 6-9.
+ //node.attachEvent('onerror', context.onScriptError);
+ } else {
+ node.addEventListener('load', context.onScriptLoad, false);
+ node.addEventListener('error', context.onScriptError, false);
+ }
+ node.src = url;
+
+ //For some cache cases in IE 6-8, the script executes before the end
+ //of the appendChild execution, so to tie an anonymous define
+ //call to the module name (which is stored on the node), hold on
+ //to a reference to this node, but clear after the DOM insertion.
+ currentlyAddingScript = node;
+ if (baseElement) {
+ head.insertBefore(node, baseElement);
+ } else {
+ head.appendChild(node);
+ }
+ currentlyAddingScript = null;
+
+ return node;
+ } else if (isWebWorker) {
+ try {
+ //In a web worker, use importScripts. This is not a very
+ //efficient use of importScripts, importScripts will block until
+ //its script is downloaded and evaluated. However, if web workers
+ //are in play, the expectation that a build has been done so that
+ //only one script needs to be loaded anyway. This may need to be
+ //reevaluated if other use cases become common.
+ importScripts(url);
+
+ //Account for anonymous modules
+ context.completeLoad(moduleName);
+ } catch (e) {
+ context.onError(makeError('importscripts',
+ 'importScripts failed for ' +
+ moduleName + ' at ' + url,
+ e,
+ [moduleName]));
+ }
+ }
+ };
+
+ function getInteractiveScript() {
+ if (interactiveScript && interactiveScript.readyState === 'interactive') {
+ return interactiveScript;
+ }
+
+ eachReverse(scripts(), function (script) {
+ if (script.readyState === 'interactive') {
+ return (interactiveScript = script);
+ }
+ });
+ return interactiveScript;
+ }
+
+ //Look for a data-main script attribute, which could also adjust the baseUrl.
+ if (isBrowser && !cfg.skipDataMain) {
+ //Figure out baseUrl. Get it from the script tag with require.js in it.
+ eachReverse(scripts(), function (script) {
+ //Set the 'head' where we can append children by
+ //using the script's parent.
+ if (!head) {
+ head = script.parentNode;
+ }
+
+ //Look for a data-main attribute to set main script for the page
+ //to load. If it is there, the path to data main becomes the
+ //baseUrl, if it is not already set.
+ dataMain = script.getAttribute('data-main');
+ if (dataMain) {
+ //Preserve dataMain in case it is a path (i.e. contains '?')
+ mainScript = dataMain;
+
+ //Set final baseUrl if there is not already an explicit one.
+ if (!cfg.baseUrl) {
+ //Pull off the directory of data-main for use as the
+ //baseUrl.
+ src = mainScript.split('/');
+ mainScript = src.pop();
+ subPath = src.length ? src.join('/') + '/' : './';
+
+ cfg.baseUrl = subPath;
+ }
+
+ //Strip off any trailing .js since mainScript is now
+ //like a module name.
+ mainScript = mainScript.replace(jsSuffixRegExp, '');
+
+ //If mainScript is still a path, fall back to dataMain
+ if (req.jsExtRegExp.test(mainScript)) {
+ mainScript = dataMain;
+ }
+
+ //Put the data-main script in the files to load.
+ cfg.deps = cfg.deps ? cfg.deps.concat(mainScript) : [mainScript];
+
+ return true;
+ }
+ });
+ }
+
+ /**
+ * The function that handles definitions of modules. Differs from
+ * require() in that a string for the module should be the first argument,
+ * and the function to execute after dependencies are loaded should
+ * return a value to define the module corresponding to the first argument's
+ * name.
+ */
+ define = function (name, deps, callback) {
+ var node, context;
+
+ //Allow for anonymous modules
+ if (typeof name !== 'string') {
+ //Adjust args appropriately
+ callback = deps;
+ deps = name;
+ name = null;
+ }
+
+ //This module may not have dependencies
+ if (!isArray(deps)) {
+ callback = deps;
+ deps = null;
+ }
+
+ //If no name, and callback is a function, then figure out if it a
+ //CommonJS thing with dependencies.
+ if (!deps && isFunction(callback)) {
+ deps = [];
+ //Remove comments from the callback string,
+ //look for require calls, and pull them into the dependencies,
+ //but only if there are function args.
+ if (callback.length) {
+ callback
+ .toString()
+ .replace(commentRegExp, '')
+ .replace(cjsRequireRegExp, function (match, dep) {
+ deps.push(dep);
+ });
+
+ //May be a CommonJS thing even without require calls, but still
+ //could use exports, and module. Avoid doing exports and module
+ //work though if it just needs require.
+ //REQUIRES the function to expect the CommonJS variables in the
+ //order listed below.
+ deps = (callback.length === 1 ? ['require'] : ['require', 'exports', 'module']).concat(deps);
+ }
+ }
+
+ //If in IE 6-8 and hit an anonymous define() call, do the interactive
+ //work.
+ if (useInteractive) {
+ node = currentlyAddingScript || getInteractiveScript();
+ if (node) {
+ if (!name) {
+ name = node.getAttribute('data-requiremodule');
+ }
+ context = contexts[node.getAttribute('data-requirecontext')];
+ }
+ }
+
+ //Always save off evaluating the def call until the script onload handler.
+ //This allows multiple modules to be in a file without prematurely
+ //tracing dependencies, and allows for anonymous module support,
+ //where the module name is not known until the script onload event
+ //occurs. If no context, use the global queue, and get it processed
+ //in the onscript load callback.
+ (context ? context.defQueue : globalDefQueue).push([name, deps, callback]);
+ };
+
+ define.amd = {
+ jQuery: true
+ };
+
+
+ /**
+ * Executes the text. Normally just uses eval, but can be modified
+ * to use a better, environment-specific call. Only used for transpiling
+ * loader plugins, not for plain JS modules.
+ * @param {String} text the text to execute/evaluate.
+ */
+ req.exec = function (text) {
+ /*jslint evil: true */
+ return eval(text);
+ };
+
+ //Set up with config info.
+ req(cfg);
+}(this));
+
+
+
+ this.requirejsVars = {
+ require: require,
+ requirejs: require,
+ define: define
+ };
+
+ if (env === 'browser') {
+ /**
+ * @license RequireJS rhino Copyright (c) 2012-2014, The Dojo Foundation All Rights Reserved.
+ * Available via the MIT or new BSD license.
+ * see: http://github.com/jrburke/requirejs for details
+ */
+
+//sloppy since eval enclosed with use strict causes problems if the source
+//text is not strict-compliant.
+/*jslint sloppy: true, evil: true */
+/*global require, XMLHttpRequest */
+
+(function () {
+ require.load = function (context, moduleName, url) {
+ var xhr = new XMLHttpRequest();
+
+ xhr.open('GET', url, true);
+ xhr.send();
+
+ xhr.onreadystatechange = function () {
+ if (xhr.readyState === 4) {
+ eval(xhr.responseText);
+
+ //Support anonymous modules.
+ context.completeLoad(moduleName);
+ }
+ };
+ };
+}());
+ } else if (env === 'rhino') {
+ /**
+ * @license RequireJS rhino Copyright (c) 2010-2014, The Dojo Foundation All Rights Reserved.
+ * Available via the MIT or new BSD license.
+ * see: http://github.com/jrburke/requirejs for details
+ */
+
+/*jslint */
+/*global require: false, java: false, load: false */
+
+(function () {
+ 'use strict';
+ require.load = function (context, moduleName, url) {
+
+ load(url);
+
+ //Support anonymous modules.
+ context.completeLoad(moduleName);
+ };
+
+}());
+ } else if (env === 'node') {
+ this.requirejsVars.nodeRequire = nodeRequire;
+ require.nodeRequire = nodeRequire;
+
+ /**
+ * @license RequireJS node Copyright (c) 2010-2014, The Dojo Foundation All Rights Reserved.
+ * Available via the MIT or new BSD license.
+ * see: http://github.com/jrburke/requirejs for details
+ */
+
+/*jslint regexp: false */
+/*global require: false, define: false, requirejsVars: false, process: false */
+
+/**
+ * This adapter assumes that x.js has loaded it and set up
+ * some variables. This adapter just allows limited RequireJS
+ * usage from within the requirejs directory. The general
+ * node adapater is r.js.
+ */
+
+(function () {
+ 'use strict';
+
+ var nodeReq = requirejsVars.nodeRequire,
+ req = requirejsVars.require,
+ def = requirejsVars.define,
+ fs = nodeReq('fs'),
+ path = nodeReq('path'),
+ vm = nodeReq('vm'),
+ //In Node 0.7+ existsSync is on fs.
+ exists = fs.existsSync || path.existsSync,
+ hasOwn = Object.prototype.hasOwnProperty;
+
+ function hasProp(obj, prop) {
+ return hasOwn.call(obj, prop);
+ }
+
+ function syncTick(fn) {
+ fn();
+ }
+
+ function makeError(message, moduleName) {
+ var err = new Error(message);
+ err.requireModules = [moduleName];
+ return err;
+ }
+
+ //Supply an implementation that allows synchronous get of a module.
+ req.get = function (context, moduleName, relModuleMap, localRequire) {
+ if (moduleName === "require" || moduleName === "exports" || moduleName === "module") {
+ context.onError(makeError("Explicit require of " + moduleName + " is not allowed.", moduleName));
+ }
+
+ var ret, oldTick,
+ moduleMap = context.makeModuleMap(moduleName, relModuleMap, false, true);
+
+ //Normalize module name, if it contains . or ..
+ moduleName = moduleMap.id;
+
+ if (hasProp(context.defined, moduleName)) {
+ ret = context.defined[moduleName];
+ } else {
+ if (ret === undefined) {
+ //Make sure nextTick for this type of call is sync-based.
+ oldTick = context.nextTick;
+ context.nextTick = syncTick;
+ try {
+ if (moduleMap.prefix) {
+ //A plugin, call requirejs to handle it. Now that
+ //nextTick is syncTick, the require will complete
+ //synchronously.
+ localRequire([moduleMap.originalName]);
+
+ //Now that plugin is loaded, can regenerate the moduleMap
+ //to get the final, normalized ID.
+ moduleMap = context.makeModuleMap(moduleMap.originalName, relModuleMap, false, true);
+ moduleName = moduleMap.id;
+ } else {
+ //Try to dynamically fetch it.
+ req.load(context, moduleName, moduleMap.url);
+
+ //Enable the module
+ context.enable(moduleMap, relModuleMap);
+ }
+
+ //Break any cycles by requiring it normally, but this will
+ //finish synchronously
+ require([moduleName]);
+
+ //The above calls are sync, so can do the next thing safely.
+ ret = context.defined[moduleName];
+ } finally {
+ context.nextTick = oldTick;
+ }
+ }
+ }
+
+ return ret;
+ };
+
+ req.nextTick = function (fn) {
+ process.nextTick(fn);
+ };
+
+ //Add wrapper around the code so that it gets the requirejs
+ //API instead of the Node API, and it is done lexically so
+ //that it survives later execution.
+ req.makeNodeWrapper = function (contents) {
+ return '(function (require, requirejs, define) { ' +
+ contents +
+ '\n}(requirejsVars.require, requirejsVars.requirejs, requirejsVars.define));';
+ };
+
+ req.load = function (context, moduleName, url) {
+ var contents, err,
+ config = context.config;
+
+ if (config.shim[moduleName] && (!config.suppress || !config.suppress.nodeShim)) {
+ console.warn('Shim config not supported in Node, may or may not work. Detected ' +
+ 'for module: ' + moduleName);
+ }
+
+ if (exists(url)) {
+ contents = fs.readFileSync(url, 'utf8');
+
+ contents = req.makeNodeWrapper(contents);
+ try {
+ vm.runInThisContext(contents, fs.realpathSync(url));
+ } catch (e) {
+ err = new Error('Evaluating ' + url + ' as module "' +
+ moduleName + '" failed with error: ' + e);
+ err.originalError = e;
+ err.moduleName = moduleName;
+ err.requireModules = [moduleName];
+ err.fileName = url;
+ return context.onError(err);
+ }
+ } else {
+ def(moduleName, function () {
+ //Get the original name, since relative requires may be
+ //resolved differently in node (issue #202). Also, if relative,
+ //make it relative to the URL of the item requesting it
+ //(issue #393)
+ var dirName,
+ map = hasProp(context.registry, moduleName) &&
+ context.registry[moduleName].map,
+ parentMap = map && map.parentMap,
+ originalName = map && map.originalName;
+
+ if (originalName.charAt(0) === '.' && parentMap) {
+ dirName = parentMap.url.split('/');
+ dirName.pop();
+ originalName = dirName.join('/') + '/' + originalName;
+ }
+
+ try {
+ return (context.config.nodeRequire || req.nodeRequire)(originalName);
+ } catch (e) {
+ err = new Error('Tried loading "' + moduleName + '" at ' +
+ url + ' then tried node\'s require("' +
+ originalName + '") and it failed ' +
+ 'with error: ' + e);
+ err.originalError = e;
+ err.moduleName = originalName;
+ err.requireModules = [moduleName];
+ throw err;
+ }
+ });
+ }
+
+ //Support anonymous modules.
+ context.completeLoad(moduleName);
+ };
+
+ //Override to provide the function wrapper for define/require.
+ req.exec = function (text) {
+ /*jslint evil: true */
+ text = req.makeNodeWrapper(text);
+ return eval(text);
+ };
+}());
+
+ } else if (env === 'xpconnect') {
+ /**
+ * @license RequireJS xpconnect Copyright (c) 2013-2014, The Dojo Foundation All Rights Reserved.
+ * Available via the MIT or new BSD license.
+ * see: http://github.com/jrburke/requirejs for details
+ */
+
+/*jslint */
+/*global require, load */
+
+(function () {
+ 'use strict';
+ require.load = function (context, moduleName, url) {
+
+ load(url);
+
+ //Support anonymous modules.
+ context.completeLoad(moduleName);
+ };
+
+}());
+
+ }
+
+ //Support a default file name to execute. Useful for hosted envs
+ //like Joyent where it defaults to a server.js as the only executed
+ //script. But only do it if this is not an optimization run.
+ if (commandOption !== 'o' && (!fileName || !jsSuffixRegExp.test(fileName))) {
+ fileName = 'main.js';
+ }
+
+ /**
+ * Loads the library files that can be used for the optimizer, or for other
+ * tasks.
+ */
+ function loadLib() {
+ /**
+ * @license Copyright (c) 2010-2014, The Dojo Foundation All Rights Reserved.
+ * Available via the MIT or new BSD license.
+ * see: http://github.com/jrburke/requirejs for details
+ */
+
+/*jslint strict: false */
+/*global Packages: false, process: false, window: false, navigator: false,
+ document: false, define: false */
+
+/**
+ * A plugin that modifies any /env/ path to be the right path based on
+ * the host environment. Right now only works for Node, Rhino and browser.
+ */
+(function () {
+ var pathRegExp = /(\/|^)env\/|\{env\}/,
+ env = 'unknown';
+
+ if (typeof Packages !== 'undefined') {
+ env = 'rhino';
+ } else if (typeof process !== 'undefined' && process.versions && !!process.versions.node) {
+ env = 'node';
+ } else if ((typeof navigator !== 'undefined' && typeof document !== 'undefined') ||
+ (typeof importScripts !== 'undefined' && typeof self !== 'undefined')) {
+ env = 'browser';
+ } else if (typeof Components !== 'undefined' && Components.classes && Components.interfaces) {
+ env = 'xpconnect';
+ }
+
+ define('env', {
+ get: function () {
+ return env;
+ },
+
+ load: function (name, req, load, config) {
+ //Allow override in the config.
+ if (config.env) {
+ env = config.env;
+ }
+
+ name = name.replace(pathRegExp, function (match, prefix) {
+ if (match.indexOf('{') === -1) {
+ return prefix + env + '/';
+ } else {
+ return env;
+ }
+ });
+
+ req([name], function (mod) {
+ load(mod);
+ });
+ }
+ });
+}());/**
+ * @license Copyright (c) 2010-2014, The Dojo Foundation All Rights Reserved.
+ * Available via the MIT or new BSD license.
+ * see: http://github.com/jrburke/requirejs for details
+ */
+
+/*jslint plusplus: true */
+/*global define, java */
+
+define('lang', function () {
+ 'use strict';
+
+ var lang, isJavaObj,
+ hasOwn = Object.prototype.hasOwnProperty;
+
+ function hasProp(obj, prop) {
+ return hasOwn.call(obj, prop);
+ }
+
+ isJavaObj = function () {
+ return false;
+ };
+
+ if (typeof java !== 'undefined' && java.lang && java.lang.Object) {
+ isJavaObj = function (obj) {
+ return obj instanceof java.lang.Object;
+ };
+ }
+
+ lang = {
+ backSlashRegExp: /\\/g,
+ ostring: Object.prototype.toString,
+
+ isArray: Array.isArray || function (it) {
+ return lang.ostring.call(it) === "[object Array]";
+ },
+
+ isFunction: function(it) {
+ return lang.ostring.call(it) === "[object Function]";
+ },
+
+ isRegExp: function(it) {
+ return it && it instanceof RegExp;
+ },
+
+ hasProp: hasProp,
+
+ //returns true if the object does not have an own property prop,
+ //or if it does, it is a falsy value.
+ falseProp: function (obj, prop) {
+ return !hasProp(obj, prop) || !obj[prop];
+ },
+
+ //gets own property value for given prop on object
+ getOwn: function (obj, prop) {
+ return hasProp(obj, prop) && obj[prop];
+ },
+
+ _mixin: function(dest, source, override){
+ var name;
+ for (name in source) {
+ if(source.hasOwnProperty(name) &&
+ (override || !dest.hasOwnProperty(name))) {
+ dest[name] = source[name];
+ }
+ }
+
+ return dest; // Object
+ },
+
+ /**
+ * mixin({}, obj1, obj2) is allowed. If the last argument is a boolean,
+ * then the source objects properties are force copied over to dest.
+ */
+ mixin: function(dest){
+ var parameters = Array.prototype.slice.call(arguments),
+ override, i, l;
+
+ if (!dest) { dest = {}; }
+
+ if (parameters.length > 2 && typeof arguments[parameters.length-1] === 'boolean') {
+ override = parameters.pop();
+ }
+
+ for (i = 1, l = parameters.length; i < l; i++) {
+ lang._mixin(dest, parameters[i], override);
+ }
+ return dest; // Object
+ },
+
+
+ /**
+ * Does a type of deep copy. Do not give it anything fancy, best
+ * for basic object copies of objects that also work well as
+ * JSON-serialized things, or has properties pointing to functions.
+ * For non-array/object values, just returns the same object.
+ * @param {Object} obj copy properties from this object
+ * @param {Object} [result] optional result object to use
+ * @return {Object}
+ */
+ deeplikeCopy: function (obj) {
+ var type, result;
+
+ if (lang.isArray(obj)) {
+ result = [];
+ obj.forEach(function(value) {
+ result.push(lang.deeplikeCopy(value));
+ });
+ return result;
+ }
+
+ type = typeof obj;
+ if (obj === null || obj === undefined || type === 'boolean' ||
+ type === 'string' || type === 'number' || lang.isFunction(obj) ||
+ lang.isRegExp(obj)|| isJavaObj(obj)) {
+ return obj;
+ }
+
+ //Anything else is an object, hopefully.
+ result = {};
+ lang.eachProp(obj, function(value, key) {
+ result[key] = lang.deeplikeCopy(value);
+ });
+ return result;
+ },
+
+ delegate: (function () {
+ // boodman/crockford delegation w/ cornford optimization
+ function TMP() {}
+ return function (obj, props) {
+ TMP.prototype = obj;
+ var tmp = new TMP();
+ TMP.prototype = null;
+ if (props) {
+ lang.mixin(tmp, props);
+ }
+ return tmp; // Object
+ };
+ }()),
+
+ /**
+ * Helper function for iterating over an array. If the func returns
+ * a true value, it will break out of the loop.
+ */
+ each: function each(ary, func) {
+ if (ary) {
+ var i;
+ for (i = 0; i < ary.length; i += 1) {
+ if (func(ary[i], i, ary)) {
+ break;
+ }
+ }
+ }
+ },
+
+ /**
+ * Cycles over properties in an object and calls a function for each
+ * property value. If the function returns a truthy value, then the
+ * iteration is stopped.
+ */
+ eachProp: function eachProp(obj, func) {
+ var prop;
+ for (prop in obj) {
+ if (hasProp(obj, prop)) {
+ if (func(obj[prop], prop)) {
+ break;
+ }
+ }
+ }
+ },
+
+ //Similar to Function.prototype.bind, but the "this" object is specified
+ //first, since it is easier to read/figure out what "this" will be.
+ bind: function bind(obj, fn) {
+ return function () {
+ return fn.apply(obj, arguments);
+ };
+ },
+
+ //Escapes a content string to be be a string that has characters escaped
+ //for inclusion as part of a JS string.
+ jsEscape: function (content) {
+ return content.replace(/(["'\\])/g, '\\$1')
+ .replace(/[\f]/g, "\\f")
+ .replace(/[\b]/g, "\\b")
+ .replace(/[\n]/g, "\\n")
+ .replace(/[\t]/g, "\\t")
+ .replace(/[\r]/g, "\\r");
+ }
+ };
+ return lang;
+});
+/**
+ * prim 0.0.1 Copyright (c) 2012-2014, The Dojo Foundation All Rights Reserved.
+ * Available via the MIT or new BSD license.
+ * see: http://github.com/requirejs/prim for details
+ */
+
+/*global setImmediate, process, setTimeout, define, module */
+
+//Set prime.hideResolutionConflict = true to allow "resolution-races"
+//in promise-tests to pass.
+//Since the goal of prim is to be a small impl for trusted code, it is
+//more important to normally throw in this case so that we can find
+//logic errors quicker.
+
+var prim;
+(function () {
+ 'use strict';
+ var op = Object.prototype,
+ hasOwn = op.hasOwnProperty;
+
+ function hasProp(obj, prop) {
+ return hasOwn.call(obj, prop);
+ }
+
+ /**
+ * Helper function for iterating over an array. If the func returns
+ * a true value, it will break out of the loop.
+ */
+ function each(ary, func) {
+ if (ary) {
+ var i;
+ for (i = 0; i < ary.length; i += 1) {
+ if (ary[i]) {
+ func(ary[i], i, ary);
+ }
+ }
+ }
+ }
+
+ function check(p) {
+ if (hasProp(p, 'e') || hasProp(p, 'v')) {
+ if (!prim.hideResolutionConflict) {
+ throw new Error('nope');
+ }
+ return false;
+ }
+ return true;
+ }
+
+ function notify(ary, value) {
+ prim.nextTick(function () {
+ each(ary, function (item) {
+ item(value);
+ });
+ });
+ }
+
+ prim = function prim() {
+ var p,
+ ok = [],
+ fail = [];
+
+ return (p = {
+ callback: function (yes, no) {
+ if (no) {
+ p.errback(no);
+ }
+
+ if (hasProp(p, 'v')) {
+ prim.nextTick(function () {
+ yes(p.v);
+ });
+ } else {
+ ok.push(yes);
+ }
+ },
+
+ errback: function (no) {
+ if (hasProp(p, 'e')) {
+ prim.nextTick(function () {
+ no(p.e);
+ });
+ } else {
+ fail.push(no);
+ }
+ },
+
+ finished: function () {
+ return hasProp(p, 'e') || hasProp(p, 'v');
+ },
+
+ rejected: function () {
+ return hasProp(p, 'e');
+ },
+
+ resolve: function (v) {
+ if (check(p)) {
+ p.v = v;
+ notify(ok, v);
+ }
+ return p;
+ },
+ reject: function (e) {
+ if (check(p)) {
+ p.e = e;
+ notify(fail, e);
+ }
+ return p;
+ },
+
+ start: function (fn) {
+ p.resolve();
+ return p.promise.then(fn);
+ },
+
+ promise: {
+ then: function (yes, no) {
+ var next = prim();
+
+ p.callback(function (v) {
+ try {
+ if (yes && typeof yes === 'function') {
+ v = yes(v);
+ }
+
+ if (v && v.then) {
+ v.then(next.resolve, next.reject);
+ } else {
+ next.resolve(v);
+ }
+ } catch (e) {
+ next.reject(e);
+ }
+ }, function (e) {
+ var err;
+
+ try {
+ if (!no || typeof no !== 'function') {
+ next.reject(e);
+ } else {
+ err = no(e);
+
+ if (err && err.then) {
+ err.then(next.resolve, next.reject);
+ } else {
+ next.resolve(err);
+ }
+ }
+ } catch (e2) {
+ next.reject(e2);
+ }
+ });
+
+ return next.promise;
+ },
+
+ fail: function (no) {
+ return p.promise.then(null, no);
+ },
+
+ end: function () {
+ p.errback(function (e) {
+ throw e;
+ });
+ }
+ }
+ });
+ };
+
+ prim.serial = function (ary) {
+ var result = prim().resolve().promise;
+ each(ary, function (item) {
+ result = result.then(function () {
+ return item();
+ });
+ });
+ return result;
+ };
+
+ prim.nextTick = typeof setImmediate === 'function' ? setImmediate :
+ (typeof process !== 'undefined' && process.nextTick ?
+ process.nextTick : (typeof setTimeout !== 'undefined' ?
+ function (fn) {
+ setTimeout(fn, 0);
+ } : function (fn) {
+ fn();
+ }));
+
+ if (typeof define === 'function' && define.amd) {
+ define('prim', function () { return prim; });
+ } else if (typeof module !== 'undefined' && module.exports) {
+ module.exports = prim;
+ }
+}());
+if(env === 'browser') {
+/**
+ * @license RequireJS Copyright (c) 2012-2014, The Dojo Foundation All Rights Reserved.
+ * Available via the MIT or new BSD license.
+ * see: http://github.com/jrburke/requirejs for details
+ */
+
+/*jslint strict: false */
+/*global define: false, load: false */
+
+//Just a stub for use with uglify's consolidator.js
+define('browser/assert', function () {
+ return {};
+});
+
+}
+
+if(env === 'node') {
+/**
+ * @license RequireJS Copyright (c) 2012-2014, The Dojo Foundation All Rights Reserved.
+ * Available via the MIT or new BSD license.
+ * see: http://github.com/jrburke/requirejs for details
+ */
+
+/*jslint strict: false */
+/*global define: false, load: false */
+
+//Needed so that rhino/assert can return a stub for uglify's consolidator.js
+define('node/assert', ['assert'], function (assert) {
+ return assert;
+});
+
+}
+
+if(env === 'rhino') {
+/**
+ * @license RequireJS Copyright (c) 2013-2014, The Dojo Foundation All Rights Reserved.
+ * Available via the MIT or new BSD license.
+ * see: http://github.com/jrburke/requirejs for details
+ */
+
+/*jslint strict: false */
+/*global define: false, load: false */
+
+//Just a stub for use with uglify's consolidator.js
+define('rhino/assert', function () {
+ return {};
+});
+
+}
+
+if(env === 'xpconnect') {
+/**
+ * @license RequireJS Copyright (c) 2013-2014, The Dojo Foundation All Rights Reserved.
+ * Available via the MIT or new BSD license.
+ * see: http://github.com/jrburke/requirejs for details
+ */
+
+/*jslint strict: false */
+/*global define: false, load: false */
+
+//Just a stub for use with uglify's consolidator.js
+define('xpconnect/assert', function () {
+ return {};
+});
+
+}
+
+if(env === 'browser') {
+/**
+ * @license Copyright (c) 2010-2014, The Dojo Foundation All Rights Reserved.
+ * Available via the MIT or new BSD license.
+ * see: http://github.com/jrburke/requirejs for details
+ */
+
+/*jslint strict: false */
+/*global define: false, process: false */
+
+define('browser/args', function () {
+ //Always expect config via an API call
+ return [];
+});
+
+}
+
+if(env === 'node') {
+/**
+ * @license Copyright (c) 2010-2014, The Dojo Foundation All Rights Reserved.
+ * Available via the MIT or new BSD license.
+ * see: http://github.com/jrburke/requirejs for details
+ */
+
+/*jslint strict: false */
+/*global define: false, process: false */
+
+define('node/args', function () {
+ //Do not return the "node" or "r.js" arguments
+ var args = process.argv.slice(2);
+
+ //Ignore any command option used for main x.js branching
+ if (args[0] && args[0].indexOf('-') === 0) {
+ args = args.slice(1);
+ }
+
+ return args;
+});
+
+}
+
+if(env === 'rhino') {
+/**
+ * @license Copyright (c) 2010-2014, The Dojo Foundation All Rights Reserved.
+ * Available via the MIT or new BSD license.
+ * see: http://github.com/jrburke/requirejs for details
+ */
+
+/*jslint strict: false */
+/*global define: false, process: false */
+
+var jsLibRhinoArgs = (typeof rhinoArgs !== 'undefined' && rhinoArgs) || [].concat(Array.prototype.slice.call(arguments, 0));
+
+define('rhino/args', function () {
+ var args = jsLibRhinoArgs;
+
+ //Ignore any command option used for main x.js branching
+ if (args[0] && args[0].indexOf('-') === 0) {
+ args = args.slice(1);
+ }
+
+ return args;
+});
+
+}
+
+if(env === 'xpconnect') {
+/**
+ * @license Copyright (c) 2013-2014, The Dojo Foundation All Rights Reserved.
+ * Available via the MIT or new BSD license.
+ * see: http://github.com/jrburke/requirejs for details
+ */
+
+/*jslint strict: false */
+/*global define, xpconnectArgs */
+
+var jsLibXpConnectArgs = (typeof xpconnectArgs !== 'undefined' && xpconnectArgs) || [].concat(Array.prototype.slice.call(arguments, 0));
+
+define('xpconnect/args', function () {
+ var args = jsLibXpConnectArgs;
+
+ //Ignore any command option used for main x.js branching
+ if (args[0] && args[0].indexOf('-') === 0) {
+ args = args.slice(1);
+ }
+
+ return args;
+});
+
+}
+
+if(env === 'browser') {
+/**
+ * @license RequireJS Copyright (c) 2010-2014, The Dojo Foundation All Rights Reserved.
+ * Available via the MIT or new BSD license.
+ * see: http://github.com/jrburke/requirejs for details
+ */
+
+/*jslint strict: false */
+/*global define: false, console: false */
+
+define('browser/load', ['./file'], function (file) {
+ function load(fileName) {
+ eval(file.readFile(fileName));
+ }
+
+ return load;
+});
+
+}
+
+if(env === 'node') {
+/**
+ * @license RequireJS Copyright (c) 2010-2014, The Dojo Foundation All Rights Reserved.
+ * Available via the MIT or new BSD license.
+ * see: http://github.com/jrburke/requirejs for details
+ */
+
+/*jslint strict: false */
+/*global define: false, console: false */
+
+define('node/load', ['fs'], function (fs) {
+ function load(fileName) {
+ var contents = fs.readFileSync(fileName, 'utf8');
+ process.compile(contents, fileName);
+ }
+
+ return load;
+});
+
+}
+
+if(env === 'rhino') {
+/**
+ * @license RequireJS Copyright (c) 2010-2014, The Dojo Foundation All Rights Reserved.
+ * Available via the MIT or new BSD license.
+ * see: http://github.com/jrburke/requirejs for details
+ */
+
+/*jslint strict: false */
+/*global define: false, load: false */
+
+define('rhino/load', function () {
+ return load;
+});
+
+}
+
+if(env === 'xpconnect') {
+/**
+ * @license RequireJS Copyright (c) 2013-2014, The Dojo Foundation All Rights Reserved.
+ * Available via the MIT or new BSD license.
+ * see: http://github.com/jrburke/requirejs for details
+ */
+
+/*jslint strict: false */
+/*global define: false, load: false */
+
+define('xpconnect/load', function () {
+ return load;
+});
+
+}
+
+if(env === 'browser') {
+/**
+ * @license Copyright (c) 2012-2014, The Dojo Foundation All Rights Reserved.
+ * Available via the MIT or new BSD license.
+ * see: http://github.com/jrburke/requirejs for details
+ */
+
+/*jslint sloppy: true, nomen: true */
+/*global require, define, console, XMLHttpRequest, requirejs, location */
+
+define('browser/file', ['prim'], function (prim) {
+
+ var file,
+ currDirRegExp = /^\.(\/|$)/;
+
+ function frontSlash(path) {
+ return path.replace(/\\/g, '/');
+ }
+
+ function exists(path) {
+ var status, xhr = new XMLHttpRequest();
+
+ //Oh yeah, that is right SYNC IO. Behold its glory
+ //and horrible blocking behavior.
+ xhr.open('HEAD', path, false);
+ xhr.send();
+ status = xhr.status;
+
+ return status === 200 || status === 304;
+ }
+
+ function mkDir(dir) {
+ console.log('mkDir is no-op in browser');
+ }
+
+ function mkFullDir(dir) {
+ console.log('mkFullDir is no-op in browser');
+ }
+
+ file = {
+ backSlashRegExp: /\\/g,
+ exclusionRegExp: /^\./,
+ getLineSeparator: function () {
+ return '/';
+ },
+
+ exists: function (fileName) {
+ return exists(fileName);
+ },
+
+ parent: function (fileName) {
+ var parts = fileName.split('/');
+ parts.pop();
+ return parts.join('/');
+ },
+
+ /**
+ * Gets the absolute file path as a string, normalized
+ * to using front slashes for path separators.
+ * @param {String} fileName
+ */
+ absPath: function (fileName) {
+ var dir;
+ if (currDirRegExp.test(fileName)) {
+ dir = frontSlash(location.href);
+ if (dir.indexOf('/') !== -1) {
+ dir = dir.split('/');
+
+ //Pull off protocol and host, just want
+ //to allow paths (other build parts, like
+ //require._isSupportedBuildUrl do not support
+ //full URLs), but a full path from
+ //the root.
+ dir.splice(0, 3);
+
+ dir.pop();
+ dir = '/' + dir.join('/');
+ }
+
+ fileName = dir + fileName.substring(1);
+ }
+
+ return fileName;
+ },
+
+ normalize: function (fileName) {
+ return fileName;
+ },
+
+ isFile: function (path) {
+ return true;
+ },
+
+ isDirectory: function (path) {
+ return false;
+ },
+
+ getFilteredFileList: function (startDir, regExpFilters, makeUnixPaths) {
+ console.log('file.getFilteredFileList is no-op in browser');
+ },
+
+ copyDir: function (srcDir, destDir, regExpFilter, onlyCopyNew) {
+ console.log('file.copyDir is no-op in browser');
+
+ },
+
+ copyFile: function (srcFileName, destFileName, onlyCopyNew) {
+ console.log('file.copyFile is no-op in browser');
+ },
+
+ /**
+ * Renames a file. May fail if "to" already exists or is on another drive.
+ */
+ renameFile: function (from, to) {
+ console.log('file.renameFile is no-op in browser');
+ },
+
+ /**
+ * Reads a *text* file.
+ */
+ readFile: function (path, encoding) {
+ var xhr = new XMLHttpRequest();
+
+ //Oh yeah, that is right SYNC IO. Behold its glory
+ //and horrible blocking behavior.
+ xhr.open('GET', path, false);
+ xhr.send();
+
+ return xhr.responseText;
+ },
+
+ readFileAsync: function (path, encoding) {
+ var xhr = new XMLHttpRequest(),
+ d = prim();
+
+ xhr.open('GET', path, true);
+ xhr.send();
+
+ xhr.onreadystatechange = function () {
+ if (xhr.readyState === 4) {
+ if (xhr.status > 400) {
+ d.reject(new Error('Status: ' + xhr.status + ': ' + xhr.statusText));
+ } else {
+ d.resolve(xhr.responseText);
+ }
+ }
+ };
+
+ return d.promise;
+ },
+
+ saveUtf8File: function (fileName, fileContents) {
+ //summary: saves a *text* file using UTF-8 encoding.
+ file.saveFile(fileName, fileContents, "utf8");
+ },
+
+ saveFile: function (fileName, fileContents, encoding) {
+ requirejs.browser.saveFile(fileName, fileContents, encoding);
+ },
+
+ deleteFile: function (fileName) {
+ console.log('file.deleteFile is no-op in browser');
+ },
+
+ /**
+ * Deletes any empty directories under the given directory.
+ */
+ deleteEmptyDirs: function (startDir) {
+ console.log('file.deleteEmptyDirs is no-op in browser');
+ }
+ };
+
+ return file;
+
+});
+
+}
+
+if(env === 'node') {
+/**
+ * @license Copyright (c) 2010-2014, The Dojo Foundation All Rights Reserved.
+ * Available via the MIT or new BSD license.
+ * see: http://github.com/jrburke/requirejs for details
+ */
+
+/*jslint plusplus: false, octal:false, strict: false */
+/*global define: false, process: false */
+
+define('node/file', ['fs', 'path', 'prim'], function (fs, path, prim) {
+
+ var isWindows = process.platform === 'win32',
+ windowsDriveRegExp = /^[a-zA-Z]\:\/$/,
+ file;
+
+ function frontSlash(path) {
+ return path.replace(/\\/g, '/');
+ }
+
+ function exists(path) {
+ if (isWindows && path.charAt(path.length - 1) === '/' &&
+ path.charAt(path.length - 2) !== ':') {
+ path = path.substring(0, path.length - 1);
+ }
+
+ try {
+ fs.statSync(path);
+ return true;
+ } catch (e) {
+ return false;
+ }
+ }
+
+ function mkDir(dir) {
+ if (!exists(dir) && (!isWindows || !windowsDriveRegExp.test(dir))) {
+ fs.mkdirSync(dir, 511);
+ }
+ }
+
+ function mkFullDir(dir) {
+ var parts = dir.split('/'),
+ currDir = '',
+ first = true;
+
+ parts.forEach(function (part) {
+ //First part may be empty string if path starts with a slash.
+ currDir += part + '/';
+ first = false;
+
+ if (part) {
+ mkDir(currDir);
+ }
+ });
+ }
+
+ file = {
+ backSlashRegExp: /\\/g,
+ exclusionRegExp: /^\./,
+ getLineSeparator: function () {
+ return '/';
+ },
+
+ exists: function (fileName) {
+ return exists(fileName);
+ },
+
+ parent: function (fileName) {
+ var parts = fileName.split('/');
+ parts.pop();
+ return parts.join('/');
+ },
+
+ /**
+ * Gets the absolute file path as a string, normalized
+ * to using front slashes for path separators.
+ * @param {String} fileName
+ */
+ absPath: function (fileName) {
+ return frontSlash(path.normalize(frontSlash(fs.realpathSync(fileName))));
+ },
+
+ normalize: function (fileName) {
+ return frontSlash(path.normalize(fileName));
+ },
+
+ isFile: function (path) {
+ return fs.statSync(path).isFile();
+ },
+
+ isDirectory: function (path) {
+ return fs.statSync(path).isDirectory();
+ },
+
+ getFilteredFileList: function (/*String*/startDir, /*RegExp*/regExpFilters, /*boolean?*/makeUnixPaths) {
+ //summary: Recurses startDir and finds matches to the files that match regExpFilters.include
+ //and do not match regExpFilters.exclude. Or just one regexp can be passed in for regExpFilters,
+ //and it will be treated as the "include" case.
+ //Ignores files/directories that start with a period (.) unless exclusionRegExp
+ //is set to another value.
+ var files = [], topDir, regExpInclude, regExpExclude, dirFileArray,
+ i, stat, filePath, ok, dirFiles, fileName;
+
+ topDir = startDir;
+
+ regExpInclude = regExpFilters.include || regExpFilters;
+ regExpExclude = regExpFilters.exclude || null;
+
+ if (file.exists(topDir)) {
+ dirFileArray = fs.readdirSync(topDir);
+ for (i = 0; i < dirFileArray.length; i++) {
+ fileName = dirFileArray[i];
+ filePath = path.join(topDir, fileName);
+ stat = fs.statSync(filePath);
+ if (stat.isFile()) {
+ if (makeUnixPaths) {
+ //Make sure we have a JS string.
+ if (filePath.indexOf("/") === -1) {
+ filePath = frontSlash(filePath);
+ }
+ }
+
+ ok = true;
+ if (regExpInclude) {
+ ok = filePath.match(regExpInclude);
+ }
+ if (ok && regExpExclude) {
+ ok = !filePath.match(regExpExclude);
+ }
+
+ if (ok && (!file.exclusionRegExp ||
+ !file.exclusionRegExp.test(fileName))) {
+ files.push(filePath);
+ }
+ } else if (stat.isDirectory() &&
+ (!file.exclusionRegExp || !file.exclusionRegExp.test(fileName))) {
+ dirFiles = this.getFilteredFileList(filePath, regExpFilters, makeUnixPaths);
+ files.push.apply(files, dirFiles);
+ }
+ }
+ }
+
+ return files; //Array
+ },
+
+ copyDir: function (/*String*/srcDir, /*String*/destDir, /*RegExp?*/regExpFilter, /*boolean?*/onlyCopyNew) {
+ //summary: copies files from srcDir to destDir using the regExpFilter to determine if the
+ //file should be copied. Returns a list file name strings of the destinations that were copied.
+ regExpFilter = regExpFilter || /\w/;
+
+ //Normalize th directory names, but keep front slashes.
+ //path module on windows now returns backslashed paths.
+ srcDir = frontSlash(path.normalize(srcDir));
+ destDir = frontSlash(path.normalize(destDir));
+
+ var fileNames = file.getFilteredFileList(srcDir, regExpFilter, true),
+ copiedFiles = [], i, srcFileName, destFileName;
+
+ for (i = 0; i < fileNames.length; i++) {
+ srcFileName = fileNames[i];
+ destFileName = srcFileName.replace(srcDir, destDir);
+
+ if (file.copyFile(srcFileName, destFileName, onlyCopyNew)) {
+ copiedFiles.push(destFileName);
+ }
+ }
+
+ return copiedFiles.length ? copiedFiles : null; //Array or null
+ },
+
+ copyFile: function (/*String*/srcFileName, /*String*/destFileName, /*boolean?*/onlyCopyNew) {
+ //summary: copies srcFileName to destFileName. If onlyCopyNew is set, it only copies the file if
+ //srcFileName is newer than destFileName. Returns a boolean indicating if the copy occurred.
+ var parentDir;
+
+ //logger.trace("Src filename: " + srcFileName);
+ //logger.trace("Dest filename: " + destFileName);
+
+ //If onlyCopyNew is true, then compare dates and only copy if the src is newer
+ //than dest.
+ if (onlyCopyNew) {
+ if (file.exists(destFileName) && fs.statSync(destFileName).mtime.getTime() >= fs.statSync(srcFileName).mtime.getTime()) {
+ return false; //Boolean
+ }
+ }
+
+ //Make sure destination dir exists.
+ parentDir = path.dirname(destFileName);
+ if (!file.exists(parentDir)) {
+ mkFullDir(parentDir);
+ }
+
+ fs.writeFileSync(destFileName, fs.readFileSync(srcFileName, 'binary'), 'binary');
+
+ return true; //Boolean
+ },
+
+ /**
+ * Renames a file. May fail if "to" already exists or is on another drive.
+ */
+ renameFile: function (from, to) {
+ return fs.renameSync(from, to);
+ },
+
+ /**
+ * Reads a *text* file.
+ */
+ readFile: function (/*String*/path, /*String?*/encoding) {
+ if (encoding === 'utf-8') {
+ encoding = 'utf8';
+ }
+ if (!encoding) {
+ encoding = 'utf8';
+ }
+
+ var text = fs.readFileSync(path, encoding);
+
+ //Hmm, would not expect to get A BOM, but it seems to happen,
+ //remove it just in case.
+ if (text.indexOf('\uFEFF') === 0) {
+ text = text.substring(1, text.length);
+ }
+
+ return text;
+ },
+
+ readFileAsync: function (path, encoding) {
+ var d = prim();
+ try {
+ d.resolve(file.readFile(path, encoding));
+ } catch (e) {
+ d.reject(e);
+ }
+ return d.promise;
+ },
+
+ saveUtf8File: function (/*String*/fileName, /*String*/fileContents) {
+ //summary: saves a *text* file using UTF-8 encoding.
+ file.saveFile(fileName, fileContents, "utf8");
+ },
+
+ saveFile: function (/*String*/fileName, /*String*/fileContents, /*String?*/encoding) {
+ //summary: saves a *text* file.
+ var parentDir;
+
+ if (encoding === 'utf-8') {
+ encoding = 'utf8';
+ }
+ if (!encoding) {
+ encoding = 'utf8';
+ }
+
+ //Make sure destination directories exist.
+ parentDir = path.dirname(fileName);
+ if (!file.exists(parentDir)) {
+ mkFullDir(parentDir);
+ }
+
+ fs.writeFileSync(fileName, fileContents, encoding);
+ },
+
+ deleteFile: function (/*String*/fileName) {
+ //summary: deletes a file or directory if it exists.
+ var files, i, stat;
+ if (file.exists(fileName)) {
+ stat = fs.lstatSync(fileName);
+ if (stat.isDirectory()) {
+ files = fs.readdirSync(fileName);
+ for (i = 0; i < files.length; i++) {
+ this.deleteFile(path.join(fileName, files[i]));
+ }
+ fs.rmdirSync(fileName);
+ } else {
+ fs.unlinkSync(fileName);
+ }
+ }
+ },
+
+
+ /**
+ * Deletes any empty directories under the given directory.
+ */
+ deleteEmptyDirs: function (startDir) {
+ var dirFileArray, i, fileName, filePath, stat;
+
+ if (file.exists(startDir)) {
+ dirFileArray = fs.readdirSync(startDir);
+ for (i = 0; i < dirFileArray.length; i++) {
+ fileName = dirFileArray[i];
+ filePath = path.join(startDir, fileName);
+ stat = fs.lstatSync(filePath);
+ if (stat.isDirectory()) {
+ file.deleteEmptyDirs(filePath);
+ }
+ }
+
+ //If directory is now empty, remove it.
+ if (fs.readdirSync(startDir).length === 0) {
+ file.deleteFile(startDir);
+ }
+ }
+ }
+ };
+
+ return file;
+
+});
+
+}
+
+if(env === 'rhino') {
+/**
+ * @license RequireJS Copyright (c) 2010-2014, The Dojo Foundation All Rights Reserved.
+ * Available via the MIT or new BSD license.
+ * see: http://github.com/jrburke/requirejs for details
+ */
+//Helper functions to deal with file I/O.
+
+/*jslint plusplus: false */
+/*global java: false, define: false */
+
+define('rhino/file', ['prim'], function (prim) {
+ var file = {
+ backSlashRegExp: /\\/g,
+
+ exclusionRegExp: /^\./,
+
+ getLineSeparator: function () {
+ return file.lineSeparator;
+ },
+
+ lineSeparator: java.lang.System.getProperty("line.separator"), //Java String
+
+ exists: function (fileName) {
+ return (new java.io.File(fileName)).exists();
+ },
+
+ parent: function (fileName) {
+ return file.absPath((new java.io.File(fileName)).getParentFile());
+ },
+
+ normalize: function (fileName) {
+ return file.absPath(fileName);
+ },
+
+ isFile: function (path) {
+ return (new java.io.File(path)).isFile();
+ },
+
+ isDirectory: function (path) {
+ return (new java.io.File(path)).isDirectory();
+ },
+
+ /**
+ * Gets the absolute file path as a string, normalized
+ * to using front slashes for path separators.
+ * @param {java.io.File||String} file
+ */
+ absPath: function (fileObj) {
+ if (typeof fileObj === "string") {
+ fileObj = new java.io.File(fileObj);
+ }
+ return (fileObj.getCanonicalPath() + "").replace(file.backSlashRegExp, "/");
+ },
+
+ getFilteredFileList: function (/*String*/startDir, /*RegExp*/regExpFilters, /*boolean?*/makeUnixPaths, /*boolean?*/startDirIsJavaObject) {
+ //summary: Recurses startDir and finds matches to the files that match regExpFilters.include
+ //and do not match regExpFilters.exclude. Or just one regexp can be passed in for regExpFilters,
+ //and it will be treated as the "include" case.
+ //Ignores files/directories that start with a period (.) unless exclusionRegExp
+ //is set to another value.
+ var files = [], topDir, regExpInclude, regExpExclude, dirFileArray,
+ i, fileObj, filePath, ok, dirFiles;
+
+ topDir = startDir;
+ if (!startDirIsJavaObject) {
+ topDir = new java.io.File(startDir);
+ }
+
+ regExpInclude = regExpFilters.include || regExpFilters;
+ regExpExclude = regExpFilters.exclude || null;
+
+ if (topDir.exists()) {
+ dirFileArray = topDir.listFiles();
+ for (i = 0; i < dirFileArray.length; i++) {
+ fileObj = dirFileArray[i];
+ if (fileObj.isFile()) {
+ filePath = fileObj.getPath();
+ if (makeUnixPaths) {
+ //Make sure we have a JS string.
+ filePath = String(filePath);
+ if (filePath.indexOf("/") === -1) {
+ filePath = filePath.replace(/\\/g, "/");
+ }
+ }
+
+ ok = true;
+ if (regExpInclude) {
+ ok = filePath.match(regExpInclude);
+ }
+ if (ok && regExpExclude) {
+ ok = !filePath.match(regExpExclude);
+ }
+
+ if (ok && (!file.exclusionRegExp ||
+ !file.exclusionRegExp.test(fileObj.getName()))) {
+ files.push(filePath);
+ }
+ } else if (fileObj.isDirectory() &&
+ (!file.exclusionRegExp || !file.exclusionRegExp.test(fileObj.getName()))) {
+ dirFiles = this.getFilteredFileList(fileObj, regExpFilters, makeUnixPaths, true);
+ files.push.apply(files, dirFiles);
+ }
+ }
+ }
+
+ return files; //Array
+ },
+
+ copyDir: function (/*String*/srcDir, /*String*/destDir, /*RegExp?*/regExpFilter, /*boolean?*/onlyCopyNew) {
+ //summary: copies files from srcDir to destDir using the regExpFilter to determine if the
+ //file should be copied. Returns a list file name strings of the destinations that were copied.
+ regExpFilter = regExpFilter || /\w/;
+
+ var fileNames = file.getFilteredFileList(srcDir, regExpFilter, true),
+ copiedFiles = [], i, srcFileName, destFileName;
+
+ for (i = 0; i < fileNames.length; i++) {
+ srcFileName = fileNames[i];
+ destFileName = srcFileName.replace(srcDir, destDir);
+
+ if (file.copyFile(srcFileName, destFileName, onlyCopyNew)) {
+ copiedFiles.push(destFileName);
+ }
+ }
+
+ return copiedFiles.length ? copiedFiles : null; //Array or null
+ },
+
+ copyFile: function (/*String*/srcFileName, /*String*/destFileName, /*boolean?*/onlyCopyNew) {
+ //summary: copies srcFileName to destFileName. If onlyCopyNew is set, it only copies the file if
+ //srcFileName is newer than destFileName. Returns a boolean indicating if the copy occurred.
+ var destFile = new java.io.File(destFileName), srcFile, parentDir,
+ srcChannel, destChannel;
+
+ //logger.trace("Src filename: " + srcFileName);
+ //logger.trace("Dest filename: " + destFileName);
+
+ //If onlyCopyNew is true, then compare dates and only copy if the src is newer
+ //than dest.
+ if (onlyCopyNew) {
+ srcFile = new java.io.File(srcFileName);
+ if (destFile.exists() && destFile.lastModified() >= srcFile.lastModified()) {
+ return false; //Boolean
+ }
+ }
+
+ //Make sure destination dir exists.
+ parentDir = destFile.getParentFile();
+ if (!parentDir.exists()) {
+ if (!parentDir.mkdirs()) {
+ throw "Could not create directory: " + parentDir.getCanonicalPath();
+ }
+ }
+
+ //Java's version of copy file.
+ srcChannel = new java.io.FileInputStream(srcFileName).getChannel();
+ destChannel = new java.io.FileOutputStream(destFileName).getChannel();
+ destChannel.transferFrom(srcChannel, 0, srcChannel.size());
+ srcChannel.close();
+ destChannel.close();
+
+ return true; //Boolean
+ },
+
+ /**
+ * Renames a file. May fail if "to" already exists or is on another drive.
+ */
+ renameFile: function (from, to) {
+ return (new java.io.File(from)).renameTo((new java.io.File(to)));
+ },
+
+ readFile: function (/*String*/path, /*String?*/encoding) {
+ //A file read function that can deal with BOMs
+ encoding = encoding || "utf-8";
+ var fileObj = new java.io.File(path),
+ input = new java.io.BufferedReader(new java.io.InputStreamReader(new java.io.FileInputStream(fileObj), encoding)),
+ stringBuffer, line;
+ try {
+ stringBuffer = new java.lang.StringBuffer();
+ line = input.readLine();
+
+ // Byte Order Mark (BOM) - The Unicode Standard, version 3.0, page 324
+ // http://www.unicode.org/faq/utf_bom.html
+
+ // Note that when we use utf-8, the BOM should appear as "EF BB BF", but it doesn't due to this bug in the JDK:
+ // http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=4508058
+ if (line && line.length() && line.charAt(0) === 0xfeff) {
+ // Eat the BOM, since we've already found the encoding on this file,
+ // and we plan to concatenating this buffer with others; the BOM should
+ // only appear at the top of a file.
+ line = line.substring(1);
+ }
+ while (line !== null) {
+ stringBuffer.append(line);
+ stringBuffer.append(file.lineSeparator);
+ line = input.readLine();
+ }
+ //Make sure we return a JavaScript string and not a Java string.
+ return String(stringBuffer.toString()); //String
+ } finally {
+ input.close();
+ }
+ },
+
+ readFileAsync: function (path, encoding) {
+ var d = prim();
+ try {
+ d.resolve(file.readFile(path, encoding));
+ } catch (e) {
+ d.reject(e);
+ }
+ return d.promise;
+ },
+
+ saveUtf8File: function (/*String*/fileName, /*String*/fileContents) {
+ //summary: saves a file using UTF-8 encoding.
+ file.saveFile(fileName, fileContents, "utf-8");
+ },
+
+ saveFile: function (/*String*/fileName, /*String*/fileContents, /*String?*/encoding) {
+ //summary: saves a file.
+ var outFile = new java.io.File(fileName), outWriter, parentDir, os;
+
+ parentDir = outFile.getAbsoluteFile().getParentFile();
+ if (!parentDir.exists()) {
+ if (!parentDir.mkdirs()) {
+ throw "Could not create directory: " + parentDir.getAbsolutePath();
+ }
+ }
+
+ if (encoding) {
+ outWriter = new java.io.OutputStreamWriter(new java.io.FileOutputStream(outFile), encoding);
+ } else {
+ outWriter = new java.io.OutputStreamWriter(new java.io.FileOutputStream(outFile));
+ }
+
+ os = new java.io.BufferedWriter(outWriter);
+ try {
+ os.write(fileContents);
+ } finally {
+ os.close();
+ }
+ },
+
+ deleteFile: function (/*String*/fileName) {
+ //summary: deletes a file or directory if it exists.
+ var fileObj = new java.io.File(fileName), files, i;
+ if (fileObj.exists()) {
+ if (fileObj.isDirectory()) {
+ files = fileObj.listFiles();
+ for (i = 0; i < files.length; i++) {
+ this.deleteFile(files[i]);
+ }
+ }
+ fileObj["delete"]();
+ }
+ },
+
+ /**
+ * Deletes any empty directories under the given directory.
+ * The startDirIsJavaObject is private to this implementation's
+ * recursion needs.
+ */
+ deleteEmptyDirs: function (startDir, startDirIsJavaObject) {
+ var topDir = startDir,
+ dirFileArray, i, fileObj;
+
+ if (!startDirIsJavaObject) {
+ topDir = new java.io.File(startDir);
+ }
+
+ if (topDir.exists()) {
+ dirFileArray = topDir.listFiles();
+ for (i = 0; i < dirFileArray.length; i++) {
+ fileObj = dirFileArray[i];
+ if (fileObj.isDirectory()) {
+ file.deleteEmptyDirs(fileObj, true);
+ }
+ }
+
+ //If the directory is empty now, delete it.
+ if (topDir.listFiles().length === 0) {
+ file.deleteFile(String(topDir.getPath()));
+ }
+ }
+ }
+ };
+
+ return file;
+});
+
+}
+
+if(env === 'xpconnect') {
+/**
+ * @license RequireJS Copyright (c) 2013-2014, The Dojo Foundation All Rights Reserved.
+ * Available via the MIT or new BSD license.
+ * see: http://github.com/jrburke/requirejs for details
+ */
+//Helper functions to deal with file I/O.
+
+/*jslint plusplus: false */
+/*global define, Components, xpcUtil */
+
+define('xpconnect/file', ['prim'], function (prim) {
+ var file,
+ Cc = Components.classes,
+ Ci = Components.interfaces,
+ //Depends on xpcUtil which is set up in x.js
+ xpfile = xpcUtil.xpfile;
+
+ function mkFullDir(dirObj) {
+ //1 is DIRECTORY_TYPE, 511 is 0777 permissions
+ if (!dirObj.exists()) {
+ dirObj.create(1, 511);
+ }
+ }
+
+ file = {
+ backSlashRegExp: /\\/g,
+
+ exclusionRegExp: /^\./,
+
+ getLineSeparator: function () {
+ return file.lineSeparator;
+ },
+
+ lineSeparator: ('@mozilla.org/windows-registry-key;1' in Cc) ?
+ '\r\n' : '\n',
+
+ exists: function (fileName) {
+ return xpfile(fileName).exists();
+ },
+
+ parent: function (fileName) {
+ return xpfile(fileName).parent;
+ },
+
+ normalize: function (fileName) {
+ return file.absPath(fileName);
+ },
+
+ isFile: function (path) {
+ return xpfile(path).isFile();
+ },
+
+ isDirectory: function (path) {
+ return xpfile(path).isDirectory();
+ },
+
+ /**
+ * Gets the absolute file path as a string, normalized
+ * to using front slashes for path separators.
+ * @param {java.io.File||String} file
+ */
+ absPath: function (fileObj) {
+ if (typeof fileObj === "string") {
+ fileObj = xpfile(fileObj);
+ }
+ return fileObj.path;
+ },
+
+ getFilteredFileList: function (/*String*/startDir, /*RegExp*/regExpFilters, /*boolean?*/makeUnixPaths, /*boolean?*/startDirIsObject) {
+ //summary: Recurses startDir and finds matches to the files that match regExpFilters.include
+ //and do not match regExpFilters.exclude. Or just one regexp can be passed in for regExpFilters,
+ //and it will be treated as the "include" case.
+ //Ignores files/directories that start with a period (.) unless exclusionRegExp
+ //is set to another value.
+ var files = [], topDir, regExpInclude, regExpExclude, dirFileArray,
+ fileObj, filePath, ok, dirFiles;
+
+ topDir = startDir;
+ if (!startDirIsObject) {
+ topDir = xpfile(startDir);
+ }
+
+ regExpInclude = regExpFilters.include || regExpFilters;
+ regExpExclude = regExpFilters.exclude || null;
+
+ if (topDir.exists()) {
+ dirFileArray = topDir.directoryEntries;
+ while (dirFileArray.hasMoreElements()) {
+ fileObj = dirFileArray.getNext().QueryInterface(Ci.nsILocalFile);
+ if (fileObj.isFile()) {
+ filePath = fileObj.path;
+ if (makeUnixPaths) {
+ if (filePath.indexOf("/") === -1) {
+ filePath = filePath.replace(/\\/g, "/");
+ }
+ }
+
+ ok = true;
+ if (regExpInclude) {
+ ok = filePath.match(regExpInclude);
+ }
+ if (ok && regExpExclude) {
+ ok = !filePath.match(regExpExclude);
+ }
+
+ if (ok && (!file.exclusionRegExp ||
+ !file.exclusionRegExp.test(fileObj.leafName))) {
+ files.push(filePath);
+ }
+ } else if (fileObj.isDirectory() &&
+ (!file.exclusionRegExp || !file.exclusionRegExp.test(fileObj.leafName))) {
+ dirFiles = this.getFilteredFileList(fileObj, regExpFilters, makeUnixPaths, true);
+ files.push.apply(files, dirFiles);
+ }
+ }
+ }
+
+ return files; //Array
+ },
+
+ copyDir: function (/*String*/srcDir, /*String*/destDir, /*RegExp?*/regExpFilter, /*boolean?*/onlyCopyNew) {
+ //summary: copies files from srcDir to destDir using the regExpFilter to determine if the
+ //file should be copied. Returns a list file name strings of the destinations that were copied.
+ regExpFilter = regExpFilter || /\w/;
+
+ var fileNames = file.getFilteredFileList(srcDir, regExpFilter, true),
+ copiedFiles = [], i, srcFileName, destFileName;
+
+ for (i = 0; i < fileNames.length; i += 1) {
+ srcFileName = fileNames[i];
+ destFileName = srcFileName.replace(srcDir, destDir);
+
+ if (file.copyFile(srcFileName, destFileName, onlyCopyNew)) {
+ copiedFiles.push(destFileName);
+ }
+ }
+
+ return copiedFiles.length ? copiedFiles : null; //Array or null
+ },
+
+ copyFile: function (/*String*/srcFileName, /*String*/destFileName, /*boolean?*/onlyCopyNew) {
+ //summary: copies srcFileName to destFileName. If onlyCopyNew is set, it only copies the file if
+ //srcFileName is newer than destFileName. Returns a boolean indicating if the copy occurred.
+ var destFile = xpfile(destFileName),
+ srcFile = xpfile(srcFileName);
+
+ //logger.trace("Src filename: " + srcFileName);
+ //logger.trace("Dest filename: " + destFileName);
+
+ //If onlyCopyNew is true, then compare dates and only copy if the src is newer
+ //than dest.
+ if (onlyCopyNew) {
+ if (destFile.exists() && destFile.lastModifiedTime >= srcFile.lastModifiedTime) {
+ return false; //Boolean
+ }
+ }
+
+ srcFile.copyTo(destFile.parent, destFile.leafName);
+
+ return true; //Boolean
+ },
+
+ /**
+ * Renames a file. May fail if "to" already exists or is on another drive.
+ */
+ renameFile: function (from, to) {
+ var toFile = xpfile(to);
+ return xpfile(from).moveTo(toFile.parent, toFile.leafName);
+ },
+
+ readFile: xpcUtil.readFile,
+
+ readFileAsync: function (path, encoding) {
+ var d = prim();
+ try {
+ d.resolve(file.readFile(path, encoding));
+ } catch (e) {
+ d.reject(e);
+ }
+ return d.promise;
+ },
+
+ saveUtf8File: function (/*String*/fileName, /*String*/fileContents) {
+ //summary: saves a file using UTF-8 encoding.
+ file.saveFile(fileName, fileContents, "utf-8");
+ },
+
+ saveFile: function (/*String*/fileName, /*String*/fileContents, /*String?*/encoding) {
+ var outStream, convertStream,
+ fileObj = xpfile(fileName);
+
+ mkFullDir(fileObj.parent);
+
+ try {
+ outStream = Cc['@mozilla.org/network/file-output-stream;1']
+ .createInstance(Ci.nsIFileOutputStream);
+ //438 is decimal for 0777
+ outStream.init(fileObj, 0x02 | 0x08 | 0x20, 511, 0);
+
+ convertStream = Cc['@mozilla.org/intl/converter-output-stream;1']
+ .createInstance(Ci.nsIConverterOutputStream);
+
+ convertStream.init(outStream, encoding, 0, 0);
+ convertStream.writeString(fileContents);
+ } catch (e) {
+ throw new Error((fileObj && fileObj.path || '') + ': ' + e);
+ } finally {
+ if (convertStream) {
+ convertStream.close();
+ }
+ if (outStream) {
+ outStream.close();
+ }
+ }
+ },
+
+ deleteFile: function (/*String*/fileName) {
+ //summary: deletes a file or directory if it exists.
+ var fileObj = xpfile(fileName);
+ if (fileObj.exists()) {
+ fileObj.remove(true);
+ }
+ },
+
+ /**
+ * Deletes any empty directories under the given directory.
+ * The startDirIsJavaObject is private to this implementation's
+ * recursion needs.
+ */
+ deleteEmptyDirs: function (startDir, startDirIsObject) {
+ var topDir = startDir,
+ dirFileArray, fileObj;
+
+ if (!startDirIsObject) {
+ topDir = xpfile(startDir);
+ }
+
+ if (topDir.exists()) {
+ dirFileArray = topDir.directoryEntries;
+ while (dirFileArray.hasMoreElements()) {
+ fileObj = dirFileArray.getNext().QueryInterface(Ci.nsILocalFile);
+
+ if (fileObj.isDirectory()) {
+ file.deleteEmptyDirs(fileObj, true);
+ }
+ }
+
+ //If the directory is empty now, delete it.
+ dirFileArray = topDir.directoryEntries;
+ if (!dirFileArray.hasMoreElements()) {
+ file.deleteFile(topDir.path);
+ }
+ }
+ }
+ };
+
+ return file;
+});
+
+}
+
+if(env === 'browser') {
+/*global process */
+define('browser/quit', function () {
+ 'use strict';
+ return function (code) {
+ };
+});
+}
+
+if(env === 'node') {
+/*global process */
+define('node/quit', function () {
+ 'use strict';
+ return function (code) {
+ var draining = 0;
+ var exit = function () {
+ if (draining === 0) {
+ process.exit(code);
+ } else {
+ draining -= 1;
+ }
+ };
+ if (process.stdout.bufferSize) {
+ draining += 1;
+ process.stdout.once('drain', exit);
+ }
+ if (process.stderr.bufferSize) {
+ draining += 1;
+ process.stderr.once('drain', exit);
+ }
+ exit();
+ };
+});
+
+}
+
+if(env === 'rhino') {
+/*global quit */
+define('rhino/quit', function () {
+ 'use strict';
+ return function (code) {
+ return quit(code);
+ };
+});
+
+}
+
+if(env === 'xpconnect') {
+/*global quit */
+define('xpconnect/quit', function () {
+ 'use strict';
+ return function (code) {
+ return quit(code);
+ };
+});
+
+}
+
+if(env === 'browser') {
+/**
+ * @license RequireJS Copyright (c) 2010-2014, The Dojo Foundation All Rights Reserved.
+ * Available via the MIT or new BSD license.
+ * see: http://github.com/jrburke/requirejs for details
+ */
+
+/*jslint strict: false */
+/*global define: false, console: false */
+
+define('browser/print', function () {
+ function print(msg) {
+ console.log(msg);
+ }
+
+ return print;
+});
+
+}
+
+if(env === 'node') {
+/**
+ * @license RequireJS Copyright (c) 2010-2014, The Dojo Foundation All Rights Reserved.
+ * Available via the MIT or new BSD license.
+ * see: http://github.com/jrburke/requirejs for details
+ */
+
+/*jslint strict: false */
+/*global define: false, console: false */
+
+define('node/print', function () {
+ function print(msg) {
+ console.log(msg);
+ }
+
+ return print;
+});
+
+}
+
+if(env === 'rhino') {
+/**
+ * @license RequireJS Copyright (c) 2010-2014, The Dojo Foundation All Rights Reserved.
+ * Available via the MIT or new BSD license.
+ * see: http://github.com/jrburke/requirejs for details
+ */
+
+/*jslint strict: false */
+/*global define: false, print: false */
+
+define('rhino/print', function () {
+ return print;
+});
+
+}
+
+if(env === 'xpconnect') {
+/**
+ * @license RequireJS Copyright (c) 2013-2014, The Dojo Foundation All Rights Reserved.
+ * Available via the MIT or new BSD license.
+ * see: http://github.com/jrburke/requirejs for details
+ */
+
+/*jslint strict: false */
+/*global define: false, print: false */
+
+define('xpconnect/print', function () {
+ return print;
+});
+
+}
+/**
+ * @license RequireJS Copyright (c) 2010-2014, The Dojo Foundation All Rights Reserved.
+ * Available via the MIT or new BSD license.
+ * see: http://github.com/jrburke/requirejs for details
+ */
+
+/*jslint nomen: false, strict: false */
+/*global define: false */
+
+define('logger', ['env!env/print'], function (print) {
+ var logger = {
+ TRACE: 0,
+ INFO: 1,
+ WARN: 2,
+ ERROR: 3,
+ SILENT: 4,
+ level: 0,
+ logPrefix: "",
+
+ logLevel: function( level ) {
+ this.level = level;
+ },
+
+ trace: function (message) {
+ if (this.level <= this.TRACE) {
+ this._print(message);
+ }
+ },
+
+ info: function (message) {
+ if (this.level <= this.INFO) {
+ this._print(message);
+ }
+ },
+
+ warn: function (message) {
+ if (this.level <= this.WARN) {
+ this._print(message);
+ }
+ },
+
+ error: function (message) {
+ if (this.level <= this.ERROR) {
+ this._print(message);
+ }
+ },
+
+ _print: function (message) {
+ this._sysPrint((this.logPrefix ? (this.logPrefix + " ") : "") + message);
+ },
+
+ _sysPrint: function (message) {
+ print(message);
+ }
+ };
+
+ return logger;
+});
+//Just a blank file to use when building the optimizer with the optimizer,
+//so that the build does not attempt to inline some env modules,
+//like Node's fs and path.
+
+/*
+ Copyright (C) 2012 Ariya Hidayat <ariya.hidayat@gmail.com>
+ Copyright (C) 2012 Mathias Bynens <mathias@qiwi.be>
+ Copyright (C) 2012 Joost-Wim Boekesteijn <joost-wim@boekesteijn.nl>
+ Copyright (C) 2012 Kris Kowal <kris.kowal@cixar.com>
+ Copyright (C) 2012 Yusuke Suzuki <utatane.tea@gmail.com>
+ Copyright (C) 2012 Arpad Borsos <arpad.borsos@googlemail.com>
+ Copyright (C) 2011 Ariya Hidayat <ariya.hidayat@gmail.com>
+
+ Redistribution and use in source and binary forms, with or without
+ modification, are permitted provided that the following conditions are met:
+
+ * Redistributions of source code must retain the above copyright
+ notice, this list of conditions and the following disclaimer.
+ * Redistributions in binary form must reproduce the above copyright
+ notice, this list of conditions and the following disclaimer in the
+ documentation and/or other materials provided with the distribution.
+
+ THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
+ AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ ARE DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY
+ DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
+ (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
+ LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
+ ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
+ THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+*/
+
+/*jslint bitwise:true plusplus:true */
+/*global esprima:true, define:true, exports:true, window: true,
+throwError: true, createLiteral: true, generateStatement: true,
+parseAssignmentExpression: true, parseBlock: true, parseExpression: true,
+parseFunctionDeclaration: true, parseFunctionExpression: true,
+parseFunctionSourceElements: true, parseVariableIdentifier: true,
+parseLeftHandSideExpression: true,
+parseStatement: true, parseSourceElement: true */
+
+(function (root, factory) {
+ 'use strict';
+
+ // Universal Module Definition (UMD) to support AMD, CommonJS/Node.js,
+ // Rhino, and plain browser loading.
+ if (typeof define === 'function' && define.amd) {
+ define('esprima', ['exports'], factory);
+ } else if (typeof exports !== 'undefined') {
+ factory(exports);
+ } else {
+ factory((root.esprima = {}));
+ }
+}(this, function (exports) {
+ 'use strict';
+
+ var Token,
+ TokenName,
+ Syntax,
+ PropertyKind,
+ Messages,
+ Regex,
+ source,
+ strict,
+ index,
+ lineNumber,
+ lineStart,
+ length,
+ buffer,
+ state,
+ extra;
+
+ Token = {
+ BooleanLiteral: 1,
+ EOF: 2,
+ Identifier: 3,
+ Keyword: 4,
+ NullLiteral: 5,
+ NumericLiteral: 6,
+ Punctuator: 7,
+ StringLiteral: 8
+ };
+
+ TokenName = {};
+ TokenName[Token.BooleanLiteral] = 'Boolean';
+ TokenName[Token.EOF] = '<end>';
+ TokenName[Token.Identifier] = 'Identifier';
+ TokenName[Token.Keyword] = 'Keyword';
+ TokenName[Token.NullLiteral] = 'Null';
+ TokenName[Token.NumericLiteral] = 'Numeric';
+ TokenName[Token.Punctuator] = 'Punctuator';
+ TokenName[Token.StringLiteral] = 'String';
+
+ Syntax = {
+ AssignmentExpression: 'AssignmentExpression',
+ ArrayExpression: 'ArrayExpression',
+ BlockStatement: 'BlockStatement',
+ BinaryExpression: 'BinaryExpression',
+ BreakStatement: 'BreakStatement',
+ CallExpression: 'CallExpression',
+ CatchClause: 'CatchClause',
+ ConditionalExpression: 'ConditionalExpression',
+ ContinueStatement: 'ContinueStatement',
+ DoWhileStatement: 'DoWhileStatement',
+ DebuggerStatement: 'DebuggerStatement',
+ EmptyStatement: 'EmptyStatement',
+ ExpressionStatement: 'ExpressionStatement',
+ ForStatement: 'ForStatement',
+ ForInStatement: 'ForInStatement',
+ FunctionDeclaration: 'FunctionDeclaration',
+ FunctionExpression: 'FunctionExpression',
+ Identifier: 'Identifier',
+ IfStatement: 'IfStatement',
+ Literal: 'Literal',
+ LabeledStatement: 'LabeledStatement',
+ LogicalExpression: 'LogicalExpression',
+ MemberExpression: 'MemberExpression',
+ NewExpression: 'NewExpression',
+ ObjectExpression: 'ObjectExpression',
+ Program: 'Program',
+ Property: 'Property',
+ ReturnStatement: 'ReturnStatement',
+ SequenceExpression: 'SequenceExpression',
+ SwitchStatement: 'SwitchStatement',
+ SwitchCase: 'SwitchCase',
+ ThisExpression: 'ThisExpression',
+ ThrowStatement: 'ThrowStatement',
+ TryStatement: 'TryStatement',
+ UnaryExpression: 'UnaryExpression',
+ UpdateExpression: 'UpdateExpression',
+ VariableDeclaration: 'VariableDeclaration',
+ VariableDeclarator: 'VariableDeclarator',
+ WhileStatement: 'WhileStatement',
+ WithStatement: 'WithStatement'
+ };
+
+ PropertyKind = {
+ Data: 1,
+ Get: 2,
+ Set: 4
+ };
+
+ // Error messages should be identical to V8.
+ Messages = {
+ UnexpectedToken: 'Unexpected token %0',
+ UnexpectedNumber: 'Unexpected number',
+ UnexpectedString: 'Unexpected string',
+ UnexpectedIdentifier: 'Unexpected identifier',
+ UnexpectedReserved: 'Unexpected reserved word',
+ UnexpectedEOS: 'Unexpected end of input',
+ NewlineAfterThrow: 'Illegal newline after throw',
+ InvalidRegExp: 'Invalid regular expression',
+ UnterminatedRegExp: 'Invalid regular expression: missing /',
+ InvalidLHSInAssignment: 'Invalid left-hand side in assignment',
+ InvalidLHSInForIn: 'Invalid left-hand side in for-in',
+ MultipleDefaultsInSwitch: 'More than one default clause in switch statement',
+ NoCatchOrFinally: 'Missing catch or finally after try',
+ UnknownLabel: 'Undefined label \'%0\'',
+ Redeclaration: '%0 \'%1\' has already been declared',
+ IllegalContinue: 'Illegal continue statement',
+ IllegalBreak: 'Illegal break statement',
+ IllegalReturn: 'Illegal return statement',
+ StrictModeWith: 'Strict mode code may not include a with statement',
+ StrictCatchVariable: 'Catch variable may not be eval or arguments in strict mode',
+ StrictVarName: 'Variable name may not be eval or arguments in strict mode',
+ StrictParamName: 'Parameter name eval or arguments is not allowed in strict mode',
+ StrictParamDupe: 'Strict mode function may not have duplicate parameter names',
+ StrictFunctionName: 'Function name may not be eval or arguments in strict mode',
+ StrictOctalLiteral: 'Octal literals are not allowed in strict mode.',
+ StrictDelete: 'Delete of an unqualified identifier in strict mode.',
+ StrictDuplicateProperty: 'Duplicate data property in object literal not allowed in strict mode',
+ AccessorDataProperty: 'Object literal may not have data and accessor property with the same name',
+ AccessorGetSet: 'Object literal may not have multiple get/set accessors with the same name',
+ StrictLHSAssignment: 'Assignment to eval or arguments is not allowed in strict mode',
+ StrictLHSPostfix: 'Postfix increment/decrement may not have eval or arguments operand in strict mode',
+ StrictLHSPrefix: 'Prefix increment/decrement may not have eval or arguments operand in strict mode',
+ StrictReservedWord: 'Use of future reserved word in strict mode'
+ };
+
+ // See also tools/generate-unicode-regex.py.
+ Regex = {
+ NonAsciiIdentifierStart: new RegExp('[\xaa\xb5\xba\xc0-\xd6\xd8-\xf6\xf8-\u02c1\u02c6-\u02d1\u02e0-\u02e4\u02ec\u02ee\u0370-\u0374\u0376\u0377\u037a-\u037d\u0386\u0388-\u038a\u038c\u038e-\u03a1\u03a3-\u03f5\u03f7-\u0481\u048a-\u0527\u0531-\u0556\u0559\u0561-\u0587\u05d0-\u05ea\u05f0-\u05f2\u0620-\u064a\u066e\u066f\u0671-\u06d3\u06d5\u06e5\u06e6\u06ee\u06ef\u06fa-\u06fc\u06ff\u0710\u0712-\u072f\u074d-\u07a5\u07b1\u07ca-\u07ea\u07f4\u07f5\u07fa\u0800-\u0815\u081a\u0824\u0828\u0840-\u0858\u08a0\u08a2-\u08ac\u0904-\u0939\u093d\u0950\u0958-\u0961\u0971-\u0977\u0979-\u097f\u0985-\u098c\u098f\u0990\u0993-\u09a8\u09aa-\u09b0\u09b2\u09b6-\u09b9\u09bd\u09ce\u09dc\u09dd\u09df-\u09e1\u09f0\u09f1\u0a05-\u0a0a\u0a0f\u0a10\u0a13-\u0a28\u0a2a-\u0a30\u0a32\u0a33\u0a35\u0a36\u0a38\u0a39\u0a59-\u0a5c\u0a5e\u0a72-\u0a74\u0a85-\u0a8d\u0a8f-\u0a91\u0a93-\u0aa8\u0aaa-\u0ab0\u0ab2\u0ab3\u0ab5-\u0ab9\u0abd\u0ad0\u0ae0\u0ae1\u0b05-\u0b0c\u0b0f\u0b10\u0b13-\u0b28\u0b2a-\u0b30\u0b32\u0b33\u0b35-\u0b39\u0b3d\u0b5c\u0b5d\u0b5f-\u0b61\u0b71\u0b83\u0b85-\u0b8a\u0b8e-\u0b90\u0b92-\u0b95\u0b99\u0b9a\u0b9c\u0b9e\u0b9f\u0ba3\u0ba4\u0ba8-\u0baa\u0bae-\u0bb9\u0bd0\u0c05-\u0c0c\u0c0e-\u0c10\u0c12-\u0c28\u0c2a-\u0c33\u0c35-\u0c39\u0c3d\u0c58\u0c59\u0c60\u0c61\u0c85-\u0c8c\u0c8e-\u0c90\u0c92-\u0ca8\u0caa-\u0cb3\u0cb5-\u0cb9\u0cbd\u0cde\u0ce0\u0ce1\u0cf1\u0cf2\u0d05-\u0d0c\u0d0e-\u0d10\u0d12-\u0d3a\u0d3d\u0d4e\u0d60\u0d61\u0d7a-\u0d7f\u0d85-\u0d96\u0d9a-\u0db1\u0db3-\u0dbb\u0dbd\u0dc0-\u0dc6\u0e01-\u0e30\u0e32\u0e33\u0e40-\u0e46\u0e81\u0e82\u0e84\u0e87\u0e88\u0e8a\u0e8d\u0e94-\u0e97\u0e99-\u0e9f\u0ea1-\u0ea3\u0ea5\u0ea7\u0eaa\u0eab\u0ead-\u0eb0\u0eb2\u0eb3\u0ebd\u0ec0-\u0ec4\u0ec6\u0edc-\u0edf\u0f00\u0f40-\u0f47\u0f49-\u0f6c\u0f88-\u0f8c\u1000-\u102a\u103f\u1050-\u1055\u105a-\u105d\u1061\u1065\u1066\u106e-\u1070\u1075-\u1081\u108e\u10a0-\u10c5\u10c7\u10cd\u10d0-\u10fa\u10fc-\u1248\u124a-\u124d\u1250-\u1256\u1258\u125a-\u125d\u1260-\u1288\u128a-\u128d\u1290-\u12b0\u12b2-\u12b5\u12b8-\u12be\u12c0\u12c2-\u12c5\u12c8-\u12d6\u12d8-\u1310\u1312-\u1315\u1318-\u135a\u1380-\u138f\u13a0-\u13f4\u1401-\u166c\u166f-\u167f\u1681-\u169a\u16a0-\u16ea\u16ee-\u16f0\u1700-\u170c\u170e-\u1711\u1720-\u1731\u1740-\u1751\u1760-\u176c\u176e-\u1770\u1780-\u17b3\u17d7\u17dc\u1820-\u1877\u1880-\u18a8\u18aa\u18b0-\u18f5\u1900-\u191c\u1950-\u196d\u1970-\u1974\u1980-\u19ab\u19c1-\u19c7\u1a00-\u1a16\u1a20-\u1a54\u1aa7\u1b05-\u1b33\u1b45-\u1b4b\u1b83-\u1ba0\u1bae\u1baf\u1bba-\u1be5\u1c00-\u1c23\u1c4d-\u1c4f\u1c5a-\u1c7d\u1ce9-\u1cec\u1cee-\u1cf1\u1cf5\u1cf6\u1d00-\u1dbf\u1e00-\u1f15\u1f18-\u1f1d\u1f20-\u1f45\u1f48-\u1f4d\u1f50-\u1f57\u1f59\u1f5b\u1f5d\u1f5f-\u1f7d\u1f80-\u1fb4\u1fb6-\u1fbc\u1fbe\u1fc2-\u1fc4\u1fc6-\u1fcc\u1fd0-\u1fd3\u1fd6-\u1fdb\u1fe0-\u1fec\u1ff2-\u1ff4\u1ff6-\u1ffc\u2071\u207f\u2090-\u209c\u2102\u2107\u210a-\u2113\u2115\u2119-\u211d\u2124\u2126\u2128\u212a-\u212d\u212f-\u2139\u213c-\u213f\u2145-\u2149\u214e\u2160-\u2188\u2c00-\u2c2e\u2c30-\u2c5e\u2c60-\u2ce4\u2ceb-\u2cee\u2cf2\u2cf3\u2d00-\u2d25\u2d27\u2d2d\u2d30-\u2d67\u2d6f\u2d80-\u2d96\u2da0-\u2da6\u2da8-\u2dae\u2db0-\u2db6\u2db8-\u2dbe\u2dc0-\u2dc6\u2dc8-\u2dce\u2dd0-\u2dd6\u2dd8-\u2dde\u2e2f\u3005-\u3007\u3021-\u3029\u3031-\u3035\u3038-\u303c\u3041-\u3096\u309d-\u309f\u30a1-\u30fa\u30fc-\u30ff\u3105-\u312d\u3131-\u318e\u31a0-\u31ba\u31f0-\u31ff\u3400-\u4db5\u4e00-\u9fcc\ua000-\ua48c\ua4d0-\ua4fd\ua500-\ua60c\ua610-\ua61f\ua62a\ua62b\ua640-\ua66e\ua67f-\ua697\ua6a0-\ua6ef\ua717-\ua71f\ua722-\ua788\ua78b-\ua78e\ua790-\ua793\ua7a0-\ua7aa\ua7f8-\ua801\ua803-\ua805\ua807-\ua80a\ua80c-\ua822\ua840-\ua873\ua882-\ua8b3\ua8f2-\ua8f7\ua8fb\ua90a-\ua925\ua930-\ua946\ua960-\ua97c\ua984-\ua9b2\ua9cf\uaa00-\uaa28\uaa40-\uaa42\uaa44-\uaa4b\uaa60-\uaa76\uaa7a\uaa80-\uaaaf\uaab1\uaab5\uaab6\uaab9-\uaabd\uaac0\uaac2\uaadb-\uaadd\uaae0-\uaaea\uaaf2-\uaaf4\uab01-\uab06\uab09-\uab0e\uab11-\uab16\uab20-\uab26\uab28-\uab2e\uabc0-\uabe2\uac00-\ud7a3\ud7b0-\ud7c6\ud7cb-\ud7fb\uf900-\ufa6d\ufa70-\ufad9\ufb00-\ufb06\ufb13-\ufb17\ufb1d\ufb1f-\ufb28\ufb2a-\ufb36\ufb38-\ufb3c\ufb3e\ufb40\ufb41\ufb43\ufb44\ufb46-\ufbb1\ufbd3-\ufd3d\ufd50-\ufd8f\ufd92-\ufdc7\ufdf0-\ufdfb\ufe70-\ufe74\ufe76-\ufefc\uff21-\uff3a\uff41-\uff5a\uff66-\uffbe\uffc2-\uffc7\uffca-\uffcf\uffd2-\uffd7\uffda-\uffdc]'),
+ NonAsciiIdentifierPart: new RegExp('[\xaa\xb5\xba\xc0-\xd6\xd8-\xf6\xf8-\u02c1\u02c6-\u02d1\u02e0-\u02e4\u02ec\u02ee\u0300-\u0374\u0376\u0377\u037a-\u037d\u0386\u0388-\u038a\u038c\u038e-\u03a1\u03a3-\u03f5\u03f7-\u0481\u0483-\u0487\u048a-\u0527\u0531-\u0556\u0559\u0561-\u0587\u0591-\u05bd\u05bf\u05c1\u05c2\u05c4\u05c5\u05c7\u05d0-\u05ea\u05f0-\u05f2\u0610-\u061a\u0620-\u0669\u066e-\u06d3\u06d5-\u06dc\u06df-\u06e8\u06ea-\u06fc\u06ff\u0710-\u074a\u074d-\u07b1\u07c0-\u07f5\u07fa\u0800-\u082d\u0840-\u085b\u08a0\u08a2-\u08ac\u08e4-\u08fe\u0900-\u0963\u0966-\u096f\u0971-\u0977\u0979-\u097f\u0981-\u0983\u0985-\u098c\u098f\u0990\u0993-\u09a8\u09aa-\u09b0\u09b2\u09b6-\u09b9\u09bc-\u09c4\u09c7\u09c8\u09cb-\u09ce\u09d7\u09dc\u09dd\u09df-\u09e3\u09e6-\u09f1\u0a01-\u0a03\u0a05-\u0a0a\u0a0f\u0a10\u0a13-\u0a28\u0a2a-\u0a30\u0a32\u0a33\u0a35\u0a36\u0a38\u0a39\u0a3c\u0a3e-\u0a42\u0a47\u0a48\u0a4b-\u0a4d\u0a51\u0a59-\u0a5c\u0a5e\u0a66-\u0a75\u0a81-\u0a83\u0a85-\u0a8d\u0a8f-\u0a91\u0a93-\u0aa8\u0aaa-\u0ab0\u0ab2\u0ab3\u0ab5-\u0ab9\u0abc-\u0ac5\u0ac7-\u0ac9\u0acb-\u0acd\u0ad0\u0ae0-\u0ae3\u0ae6-\u0aef\u0b01-\u0b03\u0b05-\u0b0c\u0b0f\u0b10\u0b13-\u0b28\u0b2a-\u0b30\u0b32\u0b33\u0b35-\u0b39\u0b3c-\u0b44\u0b47\u0b48\u0b4b-\u0b4d\u0b56\u0b57\u0b5c\u0b5d\u0b5f-\u0b63\u0b66-\u0b6f\u0b71\u0b82\u0b83\u0b85-\u0b8a\u0b8e-\u0b90\u0b92-\u0b95\u0b99\u0b9a\u0b9c\u0b9e\u0b9f\u0ba3\u0ba4\u0ba8-\u0baa\u0bae-\u0bb9\u0bbe-\u0bc2\u0bc6-\u0bc8\u0bca-\u0bcd\u0bd0\u0bd7\u0be6-\u0bef\u0c01-\u0c03\u0c05-\u0c0c\u0c0e-\u0c10\u0c12-\u0c28\u0c2a-\u0c33\u0c35-\u0c39\u0c3d-\u0c44\u0c46-\u0c48\u0c4a-\u0c4d\u0c55\u0c56\u0c58\u0c59\u0c60-\u0c63\u0c66-\u0c6f\u0c82\u0c83\u0c85-\u0c8c\u0c8e-\u0c90\u0c92-\u0ca8\u0caa-\u0cb3\u0cb5-\u0cb9\u0cbc-\u0cc4\u0cc6-\u0cc8\u0cca-\u0ccd\u0cd5\u0cd6\u0cde\u0ce0-\u0ce3\u0ce6-\u0cef\u0cf1\u0cf2\u0d02\u0d03\u0d05-\u0d0c\u0d0e-\u0d10\u0d12-\u0d3a\u0d3d-\u0d44\u0d46-\u0d48\u0d4a-\u0d4e\u0d57\u0d60-\u0d63\u0d66-\u0d6f\u0d7a-\u0d7f\u0d82\u0d83\u0d85-\u0d96\u0d9a-\u0db1\u0db3-\u0dbb\u0dbd\u0dc0-\u0dc6\u0dca\u0dcf-\u0dd4\u0dd6\u0dd8-\u0ddf\u0df2\u0df3\u0e01-\u0e3a\u0e40-\u0e4e\u0e50-\u0e59\u0e81\u0e82\u0e84\u0e87\u0e88\u0e8a\u0e8d\u0e94-\u0e97\u0e99-\u0e9f\u0ea1-\u0ea3\u0ea5\u0ea7\u0eaa\u0eab\u0ead-\u0eb9\u0ebb-\u0ebd\u0ec0-\u0ec4\u0ec6\u0ec8-\u0ecd\u0ed0-\u0ed9\u0edc-\u0edf\u0f00\u0f18\u0f19\u0f20-\u0f29\u0f35\u0f37\u0f39\u0f3e-\u0f47\u0f49-\u0f6c\u0f71-\u0f84\u0f86-\u0f97\u0f99-\u0fbc\u0fc6\u1000-\u1049\u1050-\u109d\u10a0-\u10c5\u10c7\u10cd\u10d0-\u10fa\u10fc-\u1248\u124a-\u124d\u1250-\u1256\u1258\u125a-\u125d\u1260-\u1288\u128a-\u128d\u1290-\u12b0\u12b2-\u12b5\u12b8-\u12be\u12c0\u12c2-\u12c5\u12c8-\u12d6\u12d8-\u1310\u1312-\u1315\u1318-\u135a\u135d-\u135f\u1380-\u138f\u13a0-\u13f4\u1401-\u166c\u166f-\u167f\u1681-\u169a\u16a0-\u16ea\u16ee-\u16f0\u1700-\u170c\u170e-\u1714\u1720-\u1734\u1740-\u1753\u1760-\u176c\u176e-\u1770\u1772\u1773\u1780-\u17d3\u17d7\u17dc\u17dd\u17e0-\u17e9\u180b-\u180d\u1810-\u1819\u1820-\u1877\u1880-\u18aa\u18b0-\u18f5\u1900-\u191c\u1920-\u192b\u1930-\u193b\u1946-\u196d\u1970-\u1974\u1980-\u19ab\u19b0-\u19c9\u19d0-\u19d9\u1a00-\u1a1b\u1a20-\u1a5e\u1a60-\u1a7c\u1a7f-\u1a89\u1a90-\u1a99\u1aa7\u1b00-\u1b4b\u1b50-\u1b59\u1b6b-\u1b73\u1b80-\u1bf3\u1c00-\u1c37\u1c40-\u1c49\u1c4d-\u1c7d\u1cd0-\u1cd2\u1cd4-\u1cf6\u1d00-\u1de6\u1dfc-\u1f15\u1f18-\u1f1d\u1f20-\u1f45\u1f48-\u1f4d\u1f50-\u1f57\u1f59\u1f5b\u1f5d\u1f5f-\u1f7d\u1f80-\u1fb4\u1fb6-\u1fbc\u1fbe\u1fc2-\u1fc4\u1fc6-\u1fcc\u1fd0-\u1fd3\u1fd6-\u1fdb\u1fe0-\u1fec\u1ff2-\u1ff4\u1ff6-\u1ffc\u200c\u200d\u203f\u2040\u2054\u2071\u207f\u2090-\u209c\u20d0-\u20dc\u20e1\u20e5-\u20f0\u2102\u2107\u210a-\u2113\u2115\u2119-\u211d\u2124\u2126\u2128\u212a-\u212d\u212f-\u2139\u213c-\u213f\u2145-\u2149\u214e\u2160-\u2188\u2c00-\u2c2e\u2c30-\u2c5e\u2c60-\u2ce4\u2ceb-\u2cf3\u2d00-\u2d25\u2d27\u2d2d\u2d30-\u2d67\u2d6f\u2d7f-\u2d96\u2da0-\u2da6\u2da8-\u2dae\u2db0-\u2db6\u2db8-\u2dbe\u2dc0-\u2dc6\u2dc8-\u2dce\u2dd0-\u2dd6\u2dd8-\u2dde\u2de0-\u2dff\u2e2f\u3005-\u3007\u3021-\u302f\u3031-\u3035\u3038-\u303c\u3041-\u3096\u3099\u309a\u309d-\u309f\u30a1-\u30fa\u30fc-\u30ff\u3105-\u312d\u3131-\u318e\u31a0-\u31ba\u31f0-\u31ff\u3400-\u4db5\u4e00-\u9fcc\ua000-\ua48c\ua4d0-\ua4fd\ua500-\ua60c\ua610-\ua62b\ua640-\ua66f\ua674-\ua67d\ua67f-\ua697\ua69f-\ua6f1\ua717-\ua71f\ua722-\ua788\ua78b-\ua78e\ua790-\ua793\ua7a0-\ua7aa\ua7f8-\ua827\ua840-\ua873\ua880-\ua8c4\ua8d0-\ua8d9\ua8e0-\ua8f7\ua8fb\ua900-\ua92d\ua930-\ua953\ua960-\ua97c\ua980-\ua9c0\ua9cf-\ua9d9\uaa00-\uaa36\uaa40-\uaa4d\uaa50-\uaa59\uaa60-\uaa76\uaa7a\uaa7b\uaa80-\uaac2\uaadb-\uaadd\uaae0-\uaaef\uaaf2-\uaaf6\uab01-\uab06\uab09-\uab0e\uab11-\uab16\uab20-\uab26\uab28-\uab2e\uabc0-\uabea\uabec\uabed\uabf0-\uabf9\uac00-\ud7a3\ud7b0-\ud7c6\ud7cb-\ud7fb\uf900-\ufa6d\ufa70-\ufad9\ufb00-\ufb06\ufb13-\ufb17\ufb1d-\ufb28\ufb2a-\ufb36\ufb38-\ufb3c\ufb3e\ufb40\ufb41\ufb43\ufb44\ufb46-\ufbb1\ufbd3-\ufd3d\ufd50-\ufd8f\ufd92-\ufdc7\ufdf0-\ufdfb\ufe00-\ufe0f\ufe20-\ufe26\ufe33\ufe34\ufe4d-\ufe4f\ufe70-\ufe74\ufe76-\ufefc\uff10-\uff19\uff21-\uff3a\uff3f\uff41-\uff5a\uff66-\uffbe\uffc2-\uffc7\uffca-\uffcf\uffd2-\uffd7\uffda-\uffdc]')
+ };
+
+ // Ensure the condition is true, otherwise throw an error.
+ // This is only to have a better contract semantic, i.e. another safety net
+ // to catch a logic error. The condition shall be fulfilled in normal case.
+ // Do NOT use this to enforce a certain condition on any user input.
+
+ function assert(condition, message) {
+ if (!condition) {
+ throw new Error('ASSERT: ' + message);
+ }
+ }
+
+ function sliceSource(from, to) {
+ return source.slice(from, to);
+ }
+
+ if (typeof 'esprima'[0] === 'undefined') {
+ sliceSource = function sliceArraySource(from, to) {
+ return source.slice(from, to).join('');
+ };
+ }
+
+ function isDecimalDigit(ch) {
+ return '0123456789'.indexOf(ch) >= 0;
+ }
+
+ function isHexDigit(ch) {
+ return '0123456789abcdefABCDEF'.indexOf(ch) >= 0;
+ }
+
+ function isOctalDigit(ch) {
+ return '01234567'.indexOf(ch) >= 0;
+ }
+
+
+ // 7.2 White Space
+
+ function isWhiteSpace(ch) {
+ return (ch === ' ') || (ch === '\u0009') || (ch === '\u000B') ||
+ (ch === '\u000C') || (ch === '\u00A0') ||
+ (ch.charCodeAt(0) >= 0x1680 &&
+ '\u1680\u180E\u2000\u2001\u2002\u2003\u2004\u2005\u2006\u2007\u2008\u2009\u200A\u202F\u205F\u3000\uFEFF'.indexOf(ch) >= 0);
+ }
+
+ // 7.3 Line Terminators
+
+ function isLineTerminator(ch) {
+ return (ch === '\n' || ch === '\r' || ch === '\u2028' || ch === '\u2029');
+ }
+
+ // 7.6 Identifier Names and Identifiers
+
+ function isIdentifierStart(ch) {
+ return (ch === '$') || (ch === '_') || (ch === '\\') ||
+ (ch >= 'a' && ch <= 'z') || (ch >= 'A' && ch <= 'Z') ||
+ ((ch.charCodeAt(0) >= 0x80) && Regex.NonAsciiIdentifierStart.test(ch));
+ }
+
+ function isIdentifierPart(ch) {
+ return (ch === '$') || (ch === '_') || (ch === '\\') ||
+ (ch >= 'a' && ch <= 'z') || (ch >= 'A' && ch <= 'Z') ||
+ ((ch >= '0') && (ch <= '9')) ||
+ ((ch.charCodeAt(0) >= 0x80) && Regex.NonAsciiIdentifierPart.test(ch));
+ }
+
+ // 7.6.1.2 Future Reserved Words
+
+ function isFutureReservedWord(id) {
+ switch (id) {
+
+ // Future reserved words.
+ case 'class':
+ case 'enum':
+ case 'export':
+ case 'extends':
+ case 'import':
+ case 'super':
+ return true;
+ }
+
+ return false;
+ }
+
+ function isStrictModeReservedWord(id) {
+ switch (id) {
+
+ // Strict Mode reserved words.
+ case 'implements':
+ case 'interface':
+ case 'package':
+ case 'private':
+ case 'protected':
+ case 'public':
+ case 'static':
+ case 'yield':
+ case 'let':
+ return true;
+ }
+
+ return false;
+ }
+
+ function isRestrictedWord(id) {
+ return id === 'eval' || id === 'arguments';
+ }
+
+ // 7.6.1.1 Keywords
+
+ function isKeyword(id) {
+ var keyword = false;
+ switch (id.length) {
+ case 2:
+ keyword = (id === 'if') || (id === 'in') || (id === 'do');
+ break;
+ case 3:
+ keyword = (id === 'var') || (id === 'for') || (id === 'new') || (id === 'try');
+ break;
+ case 4:
+ keyword = (id === 'this') || (id === 'else') || (id === 'case') || (id === 'void') || (id === 'with');
+ break;
+ case 5:
+ keyword = (id === 'while') || (id === 'break') || (id === 'catch') || (id === 'throw');
+ break;
+ case 6:
+ keyword = (id === 'return') || (id === 'typeof') || (id === 'delete') || (id === 'switch');
+ break;
+ case 7:
+ keyword = (id === 'default') || (id === 'finally');
+ break;
+ case 8:
+ keyword = (id === 'function') || (id === 'continue') || (id === 'debugger');
+ break;
+ case 10:
+ keyword = (id === 'instanceof');
+ break;
+ }
+
+ if (keyword) {
+ return true;
+ }
+
+ switch (id) {
+ // Future reserved words.
+ // 'const' is specialized as Keyword in V8.
+ case 'const':
+ return true;
+
+ // For compatiblity to SpiderMonkey and ES.next
+ case 'yield':
+ case 'let':
+ return true;
+ }
+
+ if (strict && isStrictModeReservedWord(id)) {
+ return true;
+ }
+
+ return isFutureReservedWord(id);
+ }
+
+ // 7.4 Comments
+
+ function skipComment() {
+ var ch, blockComment, lineComment;
+
+ blockComment = false;
+ lineComment = false;
+
+ while (index < length) {
+ ch = source[index];
+
+ if (lineComment) {
+ ch = source[index++];
+ if (isLineTerminator(ch)) {
+ lineComment = false;
+ if (ch === '\r' && source[index] === '\n') {
+ ++index;
+ }
+ ++lineNumber;
+ lineStart = index;
+ }
+ } else if (blockComment) {
+ if (isLineTerminator(ch)) {
+ if (ch === '\r' && source[index + 1] === '\n') {
+ ++index;
+ }
+ ++lineNumber;
+ ++index;
+ lineStart = index;
+ if (index >= length) {
+ throwError({}, Messages.UnexpectedToken, 'ILLEGAL');
+ }
+ } else {
+ ch = source[index++];
+ if (index >= length) {
+ throwError({}, Messages.UnexpectedToken, 'ILLEGAL');
+ }
+ if (ch === '*') {
+ ch = source[index];
+ if (ch === '/') {
+ ++index;
+ blockComment = false;
+ }
+ }
+ }
+ } else if (ch === '/') {
+ ch = source[index + 1];
+ if (ch === '/') {
+ index += 2;
+ lineComment = true;
+ } else if (ch === '*') {
+ index += 2;
+ blockComment = true;
+ if (index >= length) {
+ throwError({}, Messages.UnexpectedToken, 'ILLEGAL');
+ }
+ } else {
+ break;
+ }
+ } else if (isWhiteSpace(ch)) {
+ ++index;
+ } else if (isLineTerminator(ch)) {
+ ++index;
+ if (ch === '\r' && source[index] === '\n') {
+ ++index;
+ }
+ ++lineNumber;
+ lineStart = index;
+ } else {
+ break;
+ }
+ }
+ }
+
+ function scanHexEscape(prefix) {
+ var i, len, ch, code = 0;
+
+ len = (prefix === 'u') ? 4 : 2;
+ for (i = 0; i < len; ++i) {
+ if (index < length && isHexDigit(source[index])) {
+ ch = source[index++];
+ code = code * 16 + '0123456789abcdef'.indexOf(ch.toLowerCase());
+ } else {
+ return '';
+ }
+ }
+ return String.fromCharCode(code);
+ }
+
+ function scanIdentifier() {
+ var ch, start, id, restore;
+
+ ch = source[index];
+ if (!isIdentifierStart(ch)) {
+ return;
+ }
+
+ start = index;
+ if (ch === '\\') {
+ ++index;
+ if (source[index] !== 'u') {
+ return;
+ }
+ ++index;
+ restore = index;
+ ch = scanHexEscape('u');
+ if (ch) {
+ if (ch === '\\' || !isIdentifierStart(ch)) {
+ return;
+ }
+ id = ch;
+ } else {
+ index = restore;
+ id = 'u';
+ }
+ } else {
+ id = source[index++];
+ }
+
+ while (index < length) {
+ ch = source[index];
+ if (!isIdentifierPart(ch)) {
+ break;
+ }
+ if (ch === '\\') {
+ ++index;
+ if (source[index] !== 'u') {
+ return;
+ }
+ ++index;
+ restore = index;
+ ch = scanHexEscape('u');
+ if (ch) {
+ if (ch === '\\' || !isIdentifierPart(ch)) {
+ return;
+ }
+ id += ch;
+ } else {
+ index = restore;
+ id += 'u';
+ }
+ } else {
+ id += source[index++];
+ }
+ }
+
+ // There is no keyword or literal with only one character.
+ // Thus, it must be an identifier.
+ if (id.length === 1) {
+ return {
+ type: Token.Identifier,
+ value: id,
+ lineNumber: lineNumber,
+ lineStart: lineStart,
+ range: [start, index]
+ };
+ }
+
+ if (isKeyword(id)) {
+ return {
+ type: Token.Keyword,
+ value: id,
+ lineNumber: lineNumber,
+ lineStart: lineStart,
+ range: [start, index]
+ };
+ }
+
+ // 7.8.1 Null Literals
+
+ if (id === 'null') {
+ return {
+ type: Token.NullLiteral,
+ value: id,
+ lineNumber: lineNumber,
+ lineStart: lineStart,
+ range: [start, index]
+ };
+ }
+
+ // 7.8.2 Boolean Literals
+
+ if (id === 'true' || id === 'false') {
+ return {
+ type: Token.BooleanLiteral,
+ value: id,
+ lineNumber: lineNumber,
+ lineStart: lineStart,
+ range: [start, index]
+ };
+ }
+
+ return {
+ type: Token.Identifier,
+ value: id,
+ lineNumber: lineNumber,
+ lineStart: lineStart,
+ range: [start, index]
+ };
+ }
+
+ // 7.7 Punctuators
+
+ function scanPunctuator() {
+ var start = index,
+ ch1 = source[index],
+ ch2,
+ ch3,
+ ch4;
+
+ // Check for most common single-character punctuators.
+
+ if (ch1 === ';' || ch1 === '{' || ch1 === '}') {
+ ++index;
+ return {
+ type: Token.Punctuator,
+ value: ch1,
+ lineNumber: lineNumber,
+ lineStart: lineStart,
+ range: [start, index]
+ };
+ }
+
+ if (ch1 === ',' || ch1 === '(' || ch1 === ')') {
+ ++index;
+ return {
+ type: Token.Punctuator,
+ value: ch1,
+ lineNumber: lineNumber,
+ lineStart: lineStart,
+ range: [start, index]
+ };
+ }
+
+ // Dot (.) can also start a floating-point number, hence the need
+ // to check the next character.
+
+ ch2 = source[index + 1];
+ if (ch1 === '.' && !isDecimalDigit(ch2)) {
+ return {
+ type: Token.Punctuator,
+ value: source[index++],
+ lineNumber: lineNumber,
+ lineStart: lineStart,
+ range: [start, index]
+ };
+ }
+
+ // Peek more characters.
+
+ ch3 = source[index + 2];
+ ch4 = source[index + 3];
+
+ // 4-character punctuator: >>>=
+
+ if (ch1 === '>' && ch2 === '>' && ch3 === '>') {
+ if (ch4 === '=') {
+ index += 4;
+ return {
+ type: Token.Punctuator,
+ value: '>>>=',
+ lineNumber: lineNumber,
+ lineStart: lineStart,
+ range: [start, index]
+ };
+ }
+ }
+
+ // 3-character punctuators: === !== >>> <<= >>=
+
+ if (ch1 === '=' && ch2 === '=' && ch3 === '=') {
+ index += 3;
+ return {
+ type: Token.Punctuator,
+ value: '===',
+ lineNumber: lineNumber,
+ lineStart: lineStart,
+ range: [start, index]
+ };
+ }
+
+ if (ch1 === '!' && ch2 === '=' && ch3 === '=') {
+ index += 3;
+ return {
+ type: Token.Punctuator,
+ value: '!==',
+ lineNumber: lineNumber,
+ lineStart: lineStart,
+ range: [start, index]
+ };
+ }
+
+ if (ch1 === '>' && ch2 === '>' && ch3 === '>') {
+ index += 3;
+ return {
+ type: Token.Punctuator,
+ value: '>>>',
+ lineNumber: lineNumber,
+ lineStart: lineStart,
+ range: [start, index]
+ };
+ }
+
+ if (ch1 === '<' && ch2 === '<' && ch3 === '=') {
+ index += 3;
+ return {
+ type: Token.Punctuator,
+ value: '<<=',
+ lineNumber: lineNumber,
+ lineStart: lineStart,
+ range: [start, index]
+ };
+ }
+
+ if (ch1 === '>' && ch2 === '>' && ch3 === '=') {
+ index += 3;
+ return {
+ type: Token.Punctuator,
+ value: '>>=',
+ lineNumber: lineNumber,
+ lineStart: lineStart,
+ range: [start, index]
+ };
+ }
+
+ // 2-character punctuators: <= >= == != ++ -- << >> && ||
+ // += -= *= %= &= |= ^= /=
+
+ if (ch2 === '=') {
+ if ('<>=!+-*%&|^/'.indexOf(ch1) >= 0) {
+ index += 2;
+ return {
+ type: Token.Punctuator,
+ value: ch1 + ch2,
+ lineNumber: lineNumber,
+ lineStart: lineStart,
+ range: [start, index]
+ };
+ }
+ }
+
+ if (ch1 === ch2 && ('+-<>&|'.indexOf(ch1) >= 0)) {
+ if ('+-<>&|'.indexOf(ch2) >= 0) {
+ index += 2;
+ return {
+ type: Token.Punctuator,
+ value: ch1 + ch2,
+ lineNumber: lineNumber,
+ lineStart: lineStart,
+ range: [start, index]
+ };
+ }
+ }
+
+ // The remaining 1-character punctuators.
+
+ if ('[]<>+-*%&|^!~?:=/'.indexOf(ch1) >= 0) {
+ return {
+ type: Token.Punctuator,
+ value: source[index++],
+ lineNumber: lineNumber,
+ lineStart: lineStart,
+ range: [start, index]
+ };
+ }
+ }
+
+ // 7.8.3 Numeric Literals
+
+ function scanNumericLiteral() {
+ var number, start, ch;
+
+ ch = source[index];
+ assert(isDecimalDigit(ch) || (ch === '.'),
+ 'Numeric literal must start with a decimal digit or a decimal point');
+
+ start = index;
+ number = '';
+ if (ch !== '.') {
+ number = source[index++];
+ ch = source[index];
+
+ // Hex number starts with '0x'.
+ // Octal number starts with '0'.
+ if (number === '0') {
+ if (ch === 'x' || ch === 'X') {
+ number += source[index++];
+ while (index < length) {
+ ch = source[index];
+ if (!isHexDigit(ch)) {
+ break;
+ }
+ number += source[index++];
+ }
+
+ if (number.length <= 2) {
+ // only 0x
+ throwError({}, Messages.UnexpectedToken, 'ILLEGAL');
+ }
+
+ if (index < length) {
+ ch = source[index];
+ if (isIdentifierStart(ch)) {
+ throwError({}, Messages.UnexpectedToken, 'ILLEGAL');
+ }
+ }
+ return {
+ type: Token.NumericLiteral,
+ value: parseInt(number, 16),
+ lineNumber: lineNumber,
+ lineStart: lineStart,
+ range: [start, index]
+ };
+ } else if (isOctalDigit(ch)) {
+ number += source[index++];
+ while (index < length) {
+ ch = source[index];
+ if (!isOctalDigit(ch)) {
+ break;
+ }
+ number += source[index++];
+ }
+
+ if (index < length) {
+ ch = source[index];
+ if (isIdentifierStart(ch) || isDecimalDigit(ch)) {
+ throwError({}, Messages.UnexpectedToken, 'ILLEGAL');
+ }
+ }
+ return {
+ type: Token.NumericLiteral,
+ value: parseInt(number, 8),
+ octal: true,
+ lineNumber: lineNumber,
+ lineStart: lineStart,
+ range: [start, index]
+ };
+ }
+
+ // decimal number starts with '0' such as '09' is illegal.
+ if (isDecimalDigit(ch)) {
+ throwError({}, Messages.UnexpectedToken, 'ILLEGAL');
+ }
+ }
+
+ while (index < length) {
+ ch = source[index];
+ if (!isDecimalDigit(ch)) {
+ break;
+ }
+ number += source[index++];
+ }
+ }
+
+ if (ch === '.') {
+ number += source[index++];
+ while (index < length) {
+ ch = source[index];
+ if (!isDecimalDigit(ch)) {
+ break;
+ }
+ number += source[index++];
+ }
+ }
+
+ if (ch === 'e' || ch === 'E') {
+ number += source[index++];
+
+ ch = source[index];
+ if (ch === '+' || ch === '-') {
+ number += source[index++];
+ }
+
+ ch = source[index];
+ if (isDecimalDigit(ch)) {
+ number += source[index++];
+ while (index < length) {
+ ch = source[index];
+ if (!isDecimalDigit(ch)) {
+ break;
+ }
+ number += source[index++];
+ }
+ } else {
+ ch = 'character ' + ch;
+ if (index >= length) {
+ ch = '<end>';
+ }
+ throwError({}, Messages.UnexpectedToken, 'ILLEGAL');
+ }
+ }
+
+ if (index < length) {
+ ch = source[index];
+ if (isIdentifierStart(ch)) {
+ throwError({}, Messages.UnexpectedToken, 'ILLEGAL');
+ }
+ }
+
+ return {
+ type: Token.NumericLiteral,
+ value: parseFloat(number),
+ lineNumber: lineNumber,
+ lineStart: lineStart,
+ range: [start, index]
+ };
+ }
+
+ // 7.8.4 String Literals
+
+ function scanStringLiteral() {
+ var str = '', quote, start, ch, code, unescaped, restore, octal = false;
+
+ quote = source[index];
+ assert((quote === '\'' || quote === '"'),
+ 'String literal must starts with a quote');
+
+ start = index;
+ ++index;
+
+ while (index < length) {
+ ch = source[index++];
+
+ if (ch === quote) {
+ quote = '';
+ break;
+ } else if (ch === '\\') {
+ ch = source[index++];
+ if (!isLineTerminator(ch)) {
+ switch (ch) {
+ case 'n':
+ str += '\n';
+ break;
+ case 'r':
+ str += '\r';
+ break;
+ case 't':
+ str += '\t';
+ break;
+ case 'u':
+ case 'x':
+ restore = index;
+ unescaped = scanHexEscape(ch);
+ if (unescaped) {
+ str += unescaped;
+ } else {
+ index = restore;
+ str += ch;
+ }
+ break;
+ case 'b':
+ str += '\b';
+ break;
+ case 'f':
+ str += '\f';
+ break;
+ case 'v':
+ str += '\x0B';
+ break;
+
+ default:
+ if (isOctalDigit(ch)) {
+ code = '01234567'.indexOf(ch);
+
+ // \0 is not octal escape sequence
+ if (code !== 0) {
+ octal = true;
+ }
+
+ if (index < length && isOctalDigit(source[index])) {
+ octal = true;
+ code = code * 8 + '01234567'.indexOf(source[index++]);
+
+ // 3 digits are only allowed when string starts
+ // with 0, 1, 2, 3
+ if ('0123'.indexOf(ch) >= 0 &&
+ index < length &&
+ isOctalDigit(source[index])) {
+ code = code * 8 + '01234567'.indexOf(source[index++]);
+ }
+ }
+ str += String.fromCharCode(code);
+ } else {
+ str += ch;
+ }
+ break;
+ }
+ } else {
+ ++lineNumber;
+ if (ch === '\r' && source[index] === '\n') {
+ ++index;
+ }
+ }
+ } else if (isLineTerminator(ch)) {
+ break;
+ } else {
+ str += ch;
+ }
+ }
+
+ if (quote !== '') {
+ throwError({}, Messages.UnexpectedToken, 'ILLEGAL');
+ }
+
+ return {
+ type: Token.StringLiteral,
+ value: str,
+ octal: octal,
+ lineNumber: lineNumber,
+ lineStart: lineStart,
+ range: [start, index]
+ };
+ }
+
+ function scanRegExp() {
+ var str, ch, start, pattern, flags, value, classMarker = false, restore, terminated = false;
+
+ buffer = null;
+ skipComment();
+
+ start = index;
+ ch = source[index];
+ assert(ch === '/', 'Regular expression literal must start with a slash');
+ str = source[index++];
+
+ while (index < length) {
+ ch = source[index++];
+ str += ch;
+ if (ch === '\\') {
+ ch = source[index++];
+ // ECMA-262 7.8.5
+ if (isLineTerminator(ch)) {
+ throwError({}, Messages.UnterminatedRegExp);
+ }
+ str += ch;
+ } else if (classMarker) {
+ if (ch === ']') {
+ classMarker = false;
+ }
+ } else {
+ if (ch === '/') {
+ terminated = true;
+ break;
+ } else if (ch === '[') {
+ classMarker = true;
+ } else if (isLineTerminator(ch)) {
+ throwError({}, Messages.UnterminatedRegExp);
+ }
+ }
+ }
+
+ if (!terminated) {
+ throwError({}, Messages.UnterminatedRegExp);
+ }
+
+ // Exclude leading and trailing slash.
+ pattern = str.substr(1, str.length - 2);
+
+ flags = '';
+ while (index < length) {
+ ch = source[index];
+ if (!isIdentifierPart(ch)) {
+ break;
+ }
+
+ ++index;
+ if (ch === '\\' && index < length) {
+ ch = source[index];
+ if (ch === 'u') {
+ ++index;
+ restore = index;
+ ch = scanHexEscape('u');
+ if (ch) {
+ flags += ch;
+ str += '\\u';
+ for (; restore < index; ++restore) {
+ str += source[restore];
+ }
+ } else {
+ index = restore;
+ flags += 'u';
+ str += '\\u';
+ }
+ } else {
+ str += '\\';
+ }
+ } else {
+ flags += ch;
+ str += ch;
+ }
+ }
+
+ try {
+ value = new RegExp(pattern, flags);
+ } catch (e) {
+ throwError({}, Messages.InvalidRegExp);
+ }
+
+ return {
+ literal: str,
+ value: value,
+ range: [start, index]
+ };
+ }
+
+ function isIdentifierName(token) {
+ return token.type === Token.Identifier ||
+ token.type === Token.Keyword ||
+ token.type === Token.BooleanLiteral ||
+ token.type === Token.NullLiteral;
+ }
+
+ function advance() {
+ var ch, token;
+
+ skipComment();
+
+ if (index >= length) {
+ return {
+ type: Token.EOF,
+ lineNumber: lineNumber,
+ lineStart: lineStart,
+ range: [index, index]
+ };
+ }
+
+ token = scanPunctuator();
+ if (typeof token !== 'undefined') {
+ return token;
+ }
+
+ ch = source[index];
+
+ if (ch === '\'' || ch === '"') {
+ return scanStringLiteral();
+ }
+
+ if (ch === '.' || isDecimalDigit(ch)) {
+ return scanNumericLiteral();
+ }
+
+ token = scanIdentifier();
+ if (typeof token !== 'undefined') {
+ return token;
+ }
+
+ throwError({}, Messages.UnexpectedToken, 'ILLEGAL');
+ }
+
+ function lex() {
+ var token;
+
+ if (buffer) {
+ index = buffer.range[1];
+ lineNumber = buffer.lineNumber;
+ lineStart = buffer.lineStart;
+ token = buffer;
+ buffer = null;
+ return token;
+ }
+
+ buffer = null;
+ return advance();
+ }
+
+ function lookahead() {
+ var pos, line, start;
+
+ if (buffer !== null) {
+ return buffer;
+ }
+
+ pos = index;
+ line = lineNumber;
+ start = lineStart;
+ buffer = advance();
+ index = pos;
+ lineNumber = line;
+ lineStart = start;
+
+ return buffer;
+ }
+
+ // Return true if there is a line terminator before the next token.
+
+ function peekLineTerminator() {
+ var pos, line, start, found;
+
+ pos = index;
+ line = lineNumber;
+ start = lineStart;
+ skipComment();
+ found = lineNumber !== line;
+ index = pos;
+ lineNumber = line;
+ lineStart = start;
+
+ return found;
+ }
+
+ // Throw an exception
+
+ function throwError(token, messageFormat) {
+ var error,
+ args = Array.prototype.slice.call(arguments, 2),
+ msg = messageFormat.replace(
+ /%(\d)/g,
+ function (whole, index) {
+ return args[index] || '';
+ }
+ );
+
+ if (typeof token.lineNumber === 'number') {
+ error = new Error('Line ' + token.lineNumber + ': ' + msg);
+ error.index = token.range[0];
+ error.lineNumber = token.lineNumber;
+ error.column = token.range[0] - lineStart + 1;
+ } else {
+ error = new Error('Line ' + lineNumber + ': ' + msg);
+ error.index = index;
+ error.lineNumber = lineNumber;
+ error.column = index - lineStart + 1;
+ }
+
+ throw error;
+ }
+
+ function throwErrorTolerant() {
+ try {
+ throwError.apply(null, arguments);
+ } catch (e) {
+ if (extra.errors) {
+ extra.errors.push(e);
+ } else {
+ throw e;
+ }
+ }
+ }
+
+
+ // Throw an exception because of the token.
+
+ function throwUnexpected(token) {
+ if (token.type === Token.EOF) {
+ throwError(token, Messages.UnexpectedEOS);
+ }
+
+ if (token.type === Token.NumericLiteral) {
+ throwError(token, Messages.UnexpectedNumber);
+ }
+
+ if (token.type === Token.StringLiteral) {
+ throwError(token, Messages.UnexpectedString);
+ }
+
+ if (token.type === Token.Identifier) {
+ throwError(token, Messages.UnexpectedIdentifier);
+ }
+
+ if (token.type === Token.Keyword) {
+ if (isFutureReservedWord(token.value)) {
+ throwError(token, Messages.UnexpectedReserved);
+ } else if (strict && isStrictModeReservedWord(token.value)) {
+ throwErrorTolerant(token, Messages.StrictReservedWord);
+ return;
+ }
+ throwError(token, Messages.UnexpectedToken, token.value);
+ }
+
+ // BooleanLiteral, NullLiteral, or Punctuator.
+ throwError(token, Messages.UnexpectedToken, token.value);
+ }
+
+ // Expect the next token to match the specified punctuator.
+ // If not, an exception will be thrown.
+
+ function expect(value) {
+ var token = lex();
+ if (token.type !== Token.Punctuator || token.value !== value) {
+ throwUnexpected(token);
+ }
+ }
+
+ // Expect the next token to match the specified keyword.
+ // If not, an exception will be thrown.
+
+ function expectKeyword(keyword) {
+ var token = lex();
+ if (token.type !== Token.Keyword || token.value !== keyword) {
+ throwUnexpected(token);
+ }
+ }
+
+ // Return true if the next token matches the specified punctuator.
+
+ function match(value) {
+ var token = lookahead();
+ return token.type === Token.Punctuator && token.value === value;
+ }
+
+ // Return true if the next token matches the specified keyword
+
+ function matchKeyword(keyword) {
+ var token = lookahead();
+ return token.type === Token.Keyword && token.value === keyword;
+ }
+
+ // Return true if the next token is an assignment operator
+
+ function matchAssign() {
+ var token = lookahead(),
+ op = token.value;
+
+ if (token.type !== Token.Punctuator) {
+ return false;
+ }
+ return op === '=' ||
+ op === '*=' ||
+ op === '/=' ||
+ op === '%=' ||
+ op === '+=' ||
+ op === '-=' ||
+ op === '<<=' ||
+ op === '>>=' ||
+ op === '>>>=' ||
+ op === '&=' ||
+ op === '^=' ||
+ op === '|=';
+ }
+
+ function consumeSemicolon() {
+ var token, line;
+
+ // Catch the very common case first.
+ if (source[index] === ';') {
+ lex();
+ return;
+ }
+
+ line = lineNumber;
+ skipComment();
+ if (lineNumber !== line) {
+ return;
+ }
+
+ if (match(';')) {
+ lex();
+ return;
+ }
+
+ token = lookahead();
+ if (token.type !== Token.EOF && !match('}')) {
+ throwUnexpected(token);
+ }
+ }
+
+ // Return true if provided expression is LeftHandSideExpression
+
+ function isLeftHandSide(expr) {
+ return expr.type === Syntax.Identifier || expr.type === Syntax.MemberExpression;
+ }
+
+ // 11.1.4 Array Initialiser
+
+ function parseArrayInitialiser() {
+ var elements = [];
+
+ expect('[');
+
+ while (!match(']')) {
+ if (match(',')) {
+ lex();
+ elements.push(null);
+ } else {
+ elements.push(parseAssignmentExpression());
+
+ if (!match(']')) {
+ expect(',');
+ }
+ }
+ }
+
+ expect(']');
+
+ return {
+ type: Syntax.ArrayExpression,
+ elements: elements
+ };
+ }
+
+ // 11.1.5 Object Initialiser
+
+ function parsePropertyFunction(param, first) {
+ var previousStrict, body;
+
+ previousStrict = strict;
+ body = parseFunctionSourceElements();
+ if (first && strict && isRestrictedWord(param[0].name)) {
+ throwErrorTolerant(first, Messages.StrictParamName);
+ }
+ strict = previousStrict;
+
+ return {
+ type: Syntax.FunctionExpression,
+ id: null,
+ params: param,
+ defaults: [],
+ body: body,
+ rest: null,
+ generator: false,
+ expression: false
+ };
+ }
+
+ function parseObjectPropertyKey() {
+ var token = lex();
+
+ // Note: This function is called only from parseObjectProperty(), where
+ // EOF and Punctuator tokens are already filtered out.
+
+ if (token.type === Token.StringLiteral || token.type === Token.NumericLiteral) {
+ if (strict && token.octal) {
+ throwErrorTolerant(token, Messages.StrictOctalLiteral);
+ }
+ return createLiteral(token);
+ }
+
+ return {
+ type: Syntax.Identifier,
+ name: token.value
+ };
+ }
+
+ function parseObjectProperty() {
+ var token, key, id, param;
+
+ token = lookahead();
+
+ if (token.type === Token.Identifier) {
+
+ id = parseObjectPropertyKey();
+
+ // Property Assignment: Getter and Setter.
+
+ if (token.value === 'get' && !match(':')) {
+ key = parseObjectPropertyKey();
+ expect('(');
+ expect(')');
+ return {
+ type: Syntax.Property,
+ key: key,
+ value: parsePropertyFunction([]),
+ kind: 'get'
+ };
+ } else if (token.value === 'set' && !match(':')) {
+ key = parseObjectPropertyKey();
+ expect('(');
+ token = lookahead();
+ if (token.type !== Token.Identifier) {
+ expect(')');
+ throwErrorTolerant(token, Messages.UnexpectedToken, token.value);
+ return {
+ type: Syntax.Property,
+ key: key,
+ value: parsePropertyFunction([]),
+ kind: 'set'
+ };
+ } else {
+ param = [ parseVariableIdentifier() ];
+ expect(')');
+ return {
+ type: Syntax.Property,
+ key: key,
+ value: parsePropertyFunction(param, token),
+ kind: 'set'
+ };
+ }
+ } else {
+ expect(':');
+ return {
+ type: Syntax.Property,
+ key: id,
+ value: parseAssignmentExpression(),
+ kind: 'init'
+ };
+ }
+ } else if (token.type === Token.EOF || token.type === Token.Punctuator) {
+ throwUnexpected(token);
+ } else {
+ key = parseObjectPropertyKey();
+ expect(':');
+ return {
+ type: Syntax.Property,
+ key: key,
+ value: parseAssignmentExpression(),
+ kind: 'init'
+ };
+ }
+ }
+
+ function parseObjectInitialiser() {
+ var properties = [], property, name, kind, map = {}, toString = String;
+
+ expect('{');
+
+ while (!match('}')) {
+ property = parseObjectProperty();
+
+ if (property.key.type === Syntax.Identifier) {
+ name = property.key.name;
+ } else {
+ name = toString(property.key.value);
+ }
+ kind = (property.kind === 'init') ? PropertyKind.Data : (property.kind === 'get') ? PropertyKind.Get : PropertyKind.Set;
+ if (Object.prototype.hasOwnProperty.call(map, name)) {
+ if (map[name] === PropertyKind.Data) {
+ if (strict && kind === PropertyKind.Data) {
+ throwErrorTolerant({}, Messages.StrictDuplicateProperty);
+ } else if (kind !== PropertyKind.Data) {
+ throwErrorTolerant({}, Messages.AccessorDataProperty);
+ }
+ } else {
+ if (kind === PropertyKind.Data) {
+ throwErrorTolerant({}, Messages.AccessorDataProperty);
+ } else if (map[name] & kind) {
+ throwErrorTolerant({}, Messages.AccessorGetSet);
+ }
+ }
+ map[name] |= kind;
+ } else {
+ map[name] = kind;
+ }
+
+ properties.push(property);
+
+ if (!match('}')) {
+ expect(',');
+ }
+ }
+
+ expect('}');
+
+ return {
+ type: Syntax.ObjectExpression,
+ properties: properties
+ };
+ }
+
+ // 11.1.6 The Grouping Operator
+
+ function parseGroupExpression() {
+ var expr;
+
+ expect('(');
+
+ expr = parseExpression();
+
+ expect(')');
+
+ return expr;
+ }
+
+
+ // 11.1 Primary Expressions
+
+ function parsePrimaryExpression() {
+ var token = lookahead(),
+ type = token.type;
+
+ if (type === Token.Identifier) {
+ return {
+ type: Syntax.Identifier,
+ name: lex().value
+ };
+ }
+
+ if (type === Token.StringLiteral || type === Token.NumericLiteral) {
+ if (strict && token.octal) {
+ throwErrorTolerant(token, Messages.StrictOctalLiteral);
+ }
+ return createLiteral(lex());
+ }
+
+ if (type === Token.Keyword) {
+ if (matchKeyword('this')) {
+ lex();
+ return {
+ type: Syntax.ThisExpression
+ };
+ }
+
+ if (matchKeyword('function')) {
+ return parseFunctionExpression();
+ }
+ }
+
+ if (type === Token.BooleanLiteral) {
+ lex();
+ token.value = (token.value === 'true');
+ return createLiteral(token);
+ }
+
+ if (type === Token.NullLiteral) {
+ lex();
+ token.value = null;
+ return createLiteral(token);
+ }
+
+ if (match('[')) {
+ return parseArrayInitialiser();
+ }
+
+ if (match('{')) {
+ return parseObjectInitialiser();
+ }
+
+ if (match('(')) {
+ return parseGroupExpression();
+ }
+
+ if (match('/') || match('/=')) {
+ return createLiteral(scanRegExp());
+ }
+
+ return throwUnexpected(lex());
+ }
+
+ // 11.2 Left-Hand-Side Expressions
+
+ function parseArguments() {
+ var args = [];
+
+ expect('(');
+
+ if (!match(')')) {
+ while (index < length) {
+ args.push(parseAssignmentExpression());
+ if (match(')')) {
+ break;
+ }
+ expect(',');
+ }
+ }
+
+ expect(')');
+
+ return args;
+ }
+
+ function parseNonComputedProperty() {
+ var token = lex();
+
+ if (!isIdentifierName(token)) {
+ throwUnexpected(token);
+ }
+
+ return {
+ type: Syntax.Identifier,
+ name: token.value
+ };
+ }
+
+ function parseNonComputedMember() {
+ expect('.');
+
+ return parseNonComputedProperty();
+ }
+
+ function parseComputedMember() {
+ var expr;
+
+ expect('[');
+
+ expr = parseExpression();
+
+ expect(']');
+
+ return expr;
+ }
+
+ function parseNewExpression() {
+ var expr;
+
+ expectKeyword('new');
+
+ expr = {
+ type: Syntax.NewExpression,
+ callee: parseLeftHandSideExpression(),
+ 'arguments': []
+ };
+
+ if (match('(')) {
+ expr['arguments'] = parseArguments();
+ }
+
+ return expr;
+ }
+
+ function parseLeftHandSideExpressionAllowCall() {
+ var expr;
+
+ expr = matchKeyword('new') ? parseNewExpression() : parsePrimaryExpression();
+
+ while (match('.') || match('[') || match('(')) {
+ if (match('(')) {
+ expr = {
+ type: Syntax.CallExpression,
+ callee: expr,
+ 'arguments': parseArguments()
+ };
+ } else if (match('[')) {
+ expr = {
+ type: Syntax.MemberExpression,
+ computed: true,
+ object: expr,
+ property: parseComputedMember()
+ };
+ } else {
+ expr = {
+ type: Syntax.MemberExpression,
+ computed: false,
+ object: expr,
+ property: parseNonComputedMember()
+ };
+ }
+ }
+
+ return expr;
+ }
+
+
+ function parseLeftHandSideExpression() {
+ var expr;
+
+ expr = matchKeyword('new') ? parseNewExpression() : parsePrimaryExpression();
+
+ while (match('.') || match('[')) {
+ if (match('[')) {
+ expr = {
+ type: Syntax.MemberExpression,
+ computed: true,
+ object: expr,
+ property: parseComputedMember()
+ };
+ } else {
+ expr = {
+ type: Syntax.MemberExpression,
+ computed: false,
+ object: expr,
+ property: parseNonComputedMember()
+ };
+ }
+ }
+
+ return expr;
+ }
+
+ // 11.3 Postfix Expressions
+
+ function parsePostfixExpression() {
+ var expr = parseLeftHandSideExpressionAllowCall(), token;
+
+ token = lookahead();
+ if (token.type !== Token.Punctuator) {
+ return expr;
+ }
+
+ if ((match('++') || match('--')) && !peekLineTerminator()) {
+ // 11.3.1, 11.3.2
+ if (strict && expr.type === Syntax.Identifier && isRestrictedWord(expr.name)) {
+ throwErrorTolerant({}, Messages.StrictLHSPostfix);
+ }
+ if (!isLeftHandSide(expr)) {
+ throwErrorTolerant({}, Messages.InvalidLHSInAssignment);
+ }
+
+ expr = {
+ type: Syntax.UpdateExpression,
+ operator: lex().value,
+ argument: expr,
+ prefix: false
+ };
+ }
+
+ return expr;
+ }
+
+ // 11.4 Unary Operators
+
+ function parseUnaryExpression() {
+ var token, expr;
+
+ token = lookahead();
+ if (token.type !== Token.Punctuator && token.type !== Token.Keyword) {
+ return parsePostfixExpression();
+ }
+
+ if (match('++') || match('--')) {
+ token = lex();
+ expr = parseUnaryExpression();
+ // 11.4.4, 11.4.5
+ if (strict && expr.type === Syntax.Identifier && isRestrictedWord(expr.name)) {
+ throwErrorTolerant({}, Messages.StrictLHSPrefix);
+ }
+
+ if (!isLeftHandSide(expr)) {
+ throwErrorTolerant({}, Messages.InvalidLHSInAssignment);
+ }
+
+ expr = {
+ type: Syntax.UpdateExpression,
+ operator: token.value,
+ argument: expr,
+ prefix: true
+ };
+ return expr;
+ }
+
+ if (match('+') || match('-') || match('~') || match('!')) {
+ expr = {
+ type: Syntax.UnaryExpression,
+ operator: lex().value,
+ argument: parseUnaryExpression(),
+ prefix: true
+ };
+ return expr;
+ }
+
+ if (matchKeyword('delete') || matchKeyword('void') || matchKeyword('typeof')) {
+ expr = {
+ type: Syntax.UnaryExpression,
+ operator: lex().value,
+ argument: parseUnaryExpression(),
+ prefix: true
+ };
+ if (strict && expr.operator === 'delete' && expr.argument.type === Syntax.Identifier) {
+ throwErrorTolerant({}, Messages.StrictDelete);
+ }
+ return expr;
+ }
+
+ return parsePostfixExpression();
+ }
+
+ // 11.5 Multiplicative Operators
+
+ function parseMultiplicativeExpression() {
+ var expr = parseUnaryExpression();
+
+ while (match('*') || match('/') || match('%')) {
+ expr = {
+ type: Syntax.BinaryExpression,
+ operator: lex().value,
+ left: expr,
+ right: parseUnaryExpression()
+ };
+ }
+
+ return expr;
+ }
+
+ // 11.6 Additive Operators
+
+ function parseAdditiveExpression() {
+ var expr = parseMultiplicativeExpression();
+
+ while (match('+') || match('-')) {
+ expr = {
+ type: Syntax.BinaryExpression,
+ operator: lex().value,
+ left: expr,
+ right: parseMultiplicativeExpression()
+ };
+ }
+
+ return expr;
+ }
+
+ // 11.7 Bitwise Shift Operators
+
+ function parseShiftExpression() {
+ var expr = parseAdditiveExpression();
+
+ while (match('<<') || match('>>') || match('>>>')) {
+ expr = {
+ type: Syntax.BinaryExpression,
+ operator: lex().value,
+ left: expr,
+ right: parseAdditiveExpression()
+ };
+ }
+
+ return expr;
+ }
+ // 11.8 Relational Operators
+
+ function parseRelationalExpression() {
+ var expr, previousAllowIn;
+
+ previousAllowIn = state.allowIn;
+ state.allowIn = true;
+
+ expr = parseShiftExpression();
+
+ while (match('<') || match('>') || match('<=') || match('>=') || (previousAllowIn && matchKeyword('in')) || matchKeyword('instanceof')) {
+ expr = {
+ type: Syntax.BinaryExpression,
+ operator: lex().value,
+ left: expr,
+ right: parseShiftExpression()
+ };
+ }
+
+ state.allowIn = previousAllowIn;
+ return expr;
+ }
+
+ // 11.9 Equality Operators
+
+ function parseEqualityExpression() {
+ var expr = parseRelationalExpression();
+
+ while (match('==') || match('!=') || match('===') || match('!==')) {
+ expr = {
+ type: Syntax.BinaryExpression,
+ operator: lex().value,
+ left: expr,
+ right: parseRelationalExpression()
+ };
+ }
+
+ return expr;
+ }
+
+ // 11.10 Binary Bitwise Operators
+
+ function parseBitwiseANDExpression() {
+ var expr = parseEqualityExpression();
+
+ while (match('&')) {
+ lex();
+ expr = {
+ type: Syntax.BinaryExpression,
+ operator: '&',
+ left: expr,
+ right: parseEqualityExpression()
+ };
+ }
+
+ return expr;
+ }
+
+ function parseBitwiseXORExpression() {
+ var expr = parseBitwiseANDExpression();
+
+ while (match('^')) {
+ lex();
+ expr = {
+ type: Syntax.BinaryExpression,
+ operator: '^',
+ left: expr,
+ right: parseBitwiseANDExpression()
+ };
+ }
+
+ return expr;
+ }
+
+ function parseBitwiseORExpression() {
+ var expr = parseBitwiseXORExpression();
+
+ while (match('|')) {
+ lex();
+ expr = {
+ type: Syntax.BinaryExpression,
+ operator: '|',
+ left: expr,
+ right: parseBitwiseXORExpression()
+ };
+ }
+
+ return expr;
+ }
+
+ // 11.11 Binary Logical Operators
+
+ function parseLogicalANDExpression() {
+ var expr = parseBitwiseORExpression();
+
+ while (match('&&')) {
+ lex();
+ expr = {
+ type: Syntax.LogicalExpression,
+ operator: '&&',
+ left: expr,
+ right: parseBitwiseORExpression()
+ };
+ }
+
+ return expr;
+ }
+
+ function parseLogicalORExpression() {
+ var expr = parseLogicalANDExpression();
+
+ while (match('||')) {
+ lex();
+ expr = {
+ type: Syntax.LogicalExpression,
+ operator: '||',
+ left: expr,
+ right: parseLogicalANDExpression()
+ };
+ }
+
+ return expr;
+ }
+
+ // 11.12 Conditional Operator
+
+ function parseConditionalExpression() {
+ var expr, previousAllowIn, consequent;
+
+ expr = parseLogicalORExpression();
+
+ if (match('?')) {
+ lex();
+ previousAllowIn = state.allowIn;
+ state.allowIn = true;
+ consequent = parseAssignmentExpression();
+ state.allowIn = previousAllowIn;
+ expect(':');
+
+ expr = {
+ type: Syntax.ConditionalExpression,
+ test: expr,
+ consequent: consequent,
+ alternate: parseAssignmentExpression()
+ };
+ }
+
+ return expr;
+ }
+
+ // 11.13 Assignment Operators
+
+ function parseAssignmentExpression() {
+ var token, expr;
+
+ token = lookahead();
+ expr = parseConditionalExpression();
+
+ if (matchAssign()) {
+ // LeftHandSideExpression
+ if (!isLeftHandSide(expr)) {
+ throwErrorTolerant({}, Messages.InvalidLHSInAssignment);
+ }
+
+ // 11.13.1
+ if (strict && expr.type === Syntax.Identifier && isRestrictedWord(expr.name)) {
+ throwErrorTolerant(token, Messages.StrictLHSAssignment);
+ }
+
+ expr = {
+ type: Syntax.AssignmentExpression,
+ operator: lex().value,
+ left: expr,
+ right: parseAssignmentExpression()
+ };
+ }
+
+ return expr;
+ }
+
+ // 11.14 Comma Operator
+
+ function parseExpression() {
+ var expr = parseAssignmentExpression();
+
+ if (match(',')) {
+ expr = {
+ type: Syntax.SequenceExpression,
+ expressions: [ expr ]
+ };
+
+ while (index < length) {
+ if (!match(',')) {
+ break;
+ }
+ lex();
+ expr.expressions.push(parseAssignmentExpression());
+ }
+
+ }
+ return expr;
+ }
+
+ // 12.1 Block
+
+ function parseStatementList() {
+ var list = [],
+ statement;
+
+ while (index < length) {
+ if (match('}')) {
+ break;
+ }
+ statement = parseSourceElement();
+ if (typeof statement === 'undefined') {
+ break;
+ }
+ list.push(statement);
+ }
+
+ return list;
+ }
+
+ function parseBlock() {
+ var block;
+
+ expect('{');
+
+ block = parseStatementList();
+
+ expect('}');
+
+ return {
+ type: Syntax.BlockStatement,
+ body: block
+ };
+ }
+
+ // 12.2 Variable Statement
+
+ function parseVariableIdentifier() {
+ var token = lex();
+
+ if (token.type !== Token.Identifier) {
+ throwUnexpected(token);
+ }
+
+ return {
+ type: Syntax.Identifier,
+ name: token.value
+ };
+ }
+
+ function parseVariableDeclaration(kind) {
+ var id = parseVariableIdentifier(),
+ init = null;
+
+ // 12.2.1
+ if (strict && isRestrictedWord(id.name)) {
+ throwErrorTolerant({}, Messages.StrictVarName);
+ }
+
+ if (kind === 'const') {
+ expect('=');
+ init = parseAssignmentExpression();
+ } else if (match('=')) {
+ lex();
+ init = parseAssignmentExpression();
+ }
+
+ return {
+ type: Syntax.VariableDeclarator,
+ id: id,
+ init: init
+ };
+ }
+
+ function parseVariableDeclarationList(kind) {
+ var list = [];
+
+ do {
+ list.push(parseVariableDeclaration(kind));
+ if (!match(',')) {
+ break;
+ }
+ lex();
+ } while (index < length);
+
+ return list;
+ }
+
+ function parseVariableStatement() {
+ var declarations;
+
+ expectKeyword('var');
+
+ declarations = parseVariableDeclarationList();
+
+ consumeSemicolon();
+
+ return {
+ type: Syntax.VariableDeclaration,
+ declarations: declarations,
+ kind: 'var'
+ };
+ }
+
+ // kind may be `const` or `let`
+ // Both are experimental and not in the specification yet.
+ // see http://wiki.ecmascript.org/doku.php?id=harmony:const
+ // and http://wiki.ecmascript.org/doku.php?id=harmony:let
+ function parseConstLetDeclaration(kind) {
+ var declarations;
+
+ expectKeyword(kind);
+
+ declarations = parseVariableDeclarationList(kind);
+
+ consumeSemicolon();
+
+ return {
+ type: Syntax.VariableDeclaration,
+ declarations: declarations,
+ kind: kind
+ };
+ }
+
+ // 12.3 Empty Statement
+
+ function parseEmptyStatement() {
+ expect(';');
+
+ return {
+ type: Syntax.EmptyStatement
+ };
+ }
+
+ // 12.4 Expression Statement
+
+ function parseExpressionStatement() {
+ var expr = parseExpression();
+
+ consumeSemicolon();
+
+ return {
+ type: Syntax.ExpressionStatement,
+ expression: expr
+ };
+ }
+
+ // 12.5 If statement
+
+ function parseIfStatement() {
+ var test, consequent, alternate;
+
+ expectKeyword('if');
+
+ expect('(');
+
+ test = parseExpression();
+
+ expect(')');
+
+ consequent = parseStatement();
+
+ if (matchKeyword('else')) {
+ lex();
+ alternate = parseStatement();
+ } else {
+ alternate = null;
+ }
+
+ return {
+ type: Syntax.IfStatement,
+ test: test,
+ consequent: consequent,
+ alternate: alternate
+ };
+ }
+
+ // 12.6 Iteration Statements
+
+ function parseDoWhileStatement() {
+ var body, test, oldInIteration;
+
+ expectKeyword('do');
+
+ oldInIteration = state.inIteration;
+ state.inIteration = true;
+
+ body = parseStatement();
+
+ state.inIteration = oldInIteration;
+
+ expectKeyword('while');
+
+ expect('(');
+
+ test = parseExpression();
+
+ expect(')');
+
+ if (match(';')) {
+ lex();
+ }
+
+ return {
+ type: Syntax.DoWhileStatement,
+ body: body,
+ test: test
+ };
+ }
+
+ function parseWhileStatement() {
+ var test, body, oldInIteration;
+
+ expectKeyword('while');
+
+ expect('(');
+
+ test = parseExpression();
+
+ expect(')');
+
+ oldInIteration = state.inIteration;
+ state.inIteration = true;
+
+ body = parseStatement();
+
+ state.inIteration = oldInIteration;
+
+ return {
+ type: Syntax.WhileStatement,
+ test: test,
+ body: body
+ };
+ }
+
+ function parseForVariableDeclaration() {
+ var token = lex();
+
+ return {
+ type: Syntax.VariableDeclaration,
+ declarations: parseVariableDeclarationList(),
+ kind: token.value
+ };
+ }
+
+ function parseForStatement() {
+ var init, test, update, left, right, body, oldInIteration;
+
+ init = test = update = null;
+
+ expectKeyword('for');
+
+ expect('(');
+
+ if (match(';')) {
+ lex();
+ } else {
+ if (matchKeyword('var') || matchKeyword('let')) {
+ state.allowIn = false;
+ init = parseForVariableDeclaration();
+ state.allowIn = true;
+
+ if (init.declarations.length === 1 && matchKeyword('in')) {
+ lex();
+ left = init;
+ right = parseExpression();
+ init = null;
+ }
+ } else {
+ state.allowIn = false;
+ init = parseExpression();
+ state.allowIn = true;
+
+ if (matchKeyword('in')) {
+ // LeftHandSideExpression
+ if (!isLeftHandSide(init)) {
+ throwErrorTolerant({}, Messages.InvalidLHSInForIn);
+ }
+
+ lex();
+ left = init;
+ right = parseExpression();
+ init = null;
+ }
+ }
+
+ if (typeof left === 'undefined') {
+ expect(';');
+ }
+ }
+
+ if (typeof left === 'undefined') {
+
+ if (!match(';')) {
+ test = parseExpression();
+ }
+ expect(';');
+
+ if (!match(')')) {
+ update = parseExpression();
+ }
+ }
+
+ expect(')');
+
+ oldInIteration = state.inIteration;
+ state.inIteration = true;
+
+ body = parseStatement();
+
+ state.inIteration = oldInIteration;
+
+ if (typeof left === 'undefined') {
+ return {
+ type: Syntax.ForStatement,
+ init: init,
+ test: test,
+ update: update,
+ body: body
+ };
+ }
+
+ return {
+ type: Syntax.ForInStatement,
+ left: left,
+ right: right,
+ body: body,
+ each: false
+ };
+ }
+
+ // 12.7 The continue statement
+
+ function parseContinueStatement() {
+ var token, label = null;
+
+ expectKeyword('continue');
+
+ // Optimize the most common form: 'continue;'.
+ if (source[index] === ';') {
+ lex();
+
+ if (!state.inIteration) {
+ throwError({}, Messages.IllegalContinue);
+ }
+
+ return {
+ type: Syntax.ContinueStatement,
+ label: null
+ };
+ }
+
+ if (peekLineTerminator()) {
+ if (!state.inIteration) {
+ throwError({}, Messages.IllegalContinue);
+ }
+
+ return {
+ type: Syntax.ContinueStatement,
+ label: null
+ };
+ }
+
+ token = lookahead();
+ if (token.type === Token.Identifier) {
+ label = parseVariableIdentifier();
+
+ if (!Object.prototype.hasOwnProperty.call(state.labelSet, label.name)) {
+ throwError({}, Messages.UnknownLabel, label.name);
+ }
+ }
+
+ consumeSemicolon();
+
+ if (label === null && !state.inIteration) {
+ throwError({}, Messages.IllegalContinue);
+ }
+
+ return {
+ type: Syntax.ContinueStatement,
+ label: label
+ };
+ }
+
+ // 12.8 The break statement
+
+ function parseBreakStatement() {
+ var token, label = null;
+
+ expectKeyword('break');
+
+ // Optimize the most common form: 'break;'.
+ if (source[index] === ';') {
+ lex();
+
+ if (!(state.inIteration || state.inSwitch)) {
+ throwError({}, Messages.IllegalBreak);
+ }
+
+ return {
+ type: Syntax.BreakStatement,
+ label: null
+ };
+ }
+
+ if (peekLineTerminator()) {
+ if (!(state.inIteration || state.inSwitch)) {
+ throwError({}, Messages.IllegalBreak);
+ }
+
+ return {
+ type: Syntax.BreakStatement,
+ label: null
+ };
+ }
+
+ token = lookahead();
+ if (token.type === Token.Identifier) {
+ label = parseVariableIdentifier();
+
+ if (!Object.prototype.hasOwnProperty.call(state.labelSet, label.name)) {
+ throwError({}, Messages.UnknownLabel, label.name);
+ }
+ }
+
+ consumeSemicolon();
+
+ if (label === null && !(state.inIteration || state.inSwitch)) {
+ throwError({}, Messages.IllegalBreak);
+ }
+
+ return {
+ type: Syntax.BreakStatement,
+ label: label
+ };
+ }
+
+ // 12.9 The return statement
+
+ function parseReturnStatement() {
+ var token, argument = null;
+
+ expectKeyword('return');
+
+ if (!state.inFunctionBody) {
+ throwErrorTolerant({}, Messages.IllegalReturn);
+ }
+
+ // 'return' followed by a space and an identifier is very common.
+ if (source[index] === ' ') {
+ if (isIdentifierStart(source[index + 1])) {
+ argument = parseExpression();
+ consumeSemicolon();
+ return {
+ type: Syntax.ReturnStatement,
+ argument: argument
+ };
+ }
+ }
+
+ if (peekLineTerminator()) {
+ return {
+ type: Syntax.ReturnStatement,
+ argument: null
+ };
+ }
+
+ if (!match(';')) {
+ token = lookahead();
+ if (!match('}') && token.type !== Token.EOF) {
+ argument = parseExpression();
+ }
+ }
+
+ consumeSemicolon();
+
+ return {
+ type: Syntax.ReturnStatement,
+ argument: argument
+ };
+ }
+
+ // 12.10 The with statement
+
+ function parseWithStatement() {
+ var object, body;
+
+ if (strict) {
+ throwErrorTolerant({}, Messages.StrictModeWith);
+ }
+
+ expectKeyword('with');
+
+ expect('(');
+
+ object = parseExpression();
+
+ expect(')');
+
+ body = parseStatement();
+
+ return {
+ type: Syntax.WithStatement,
+ object: object,
+ body: body
+ };
+ }
+
+ // 12.10 The swith statement
+
+ function parseSwitchCase() {
+ var test,
+ consequent = [],
+ statement;
+
+ if (matchKeyword('default')) {
+ lex();
+ test = null;
+ } else {
+ expectKeyword('case');
+ test = parseExpression();
+ }
+ expect(':');
+
+ while (index < length) {
+ if (match('}') || matchKeyword('default') || matchKeyword('case')) {
+ break;
+ }
+ statement = parseStatement();
+ if (typeof statement === 'undefined') {
+ break;
+ }
+ consequent.push(statement);
+ }
+
+ return {
+ type: Syntax.SwitchCase,
+ test: test,
+ consequent: consequent
+ };
+ }
+
+ function parseSwitchStatement() {
+ var discriminant, cases, clause, oldInSwitch, defaultFound;
+
+ expectKeyword('switch');
+
+ expect('(');
+
+ discriminant = parseExpression();
+
+ expect(')');
+
+ expect('{');
+
+ cases = [];
+
+ if (match('}')) {
+ lex();
+ return {
+ type: Syntax.SwitchStatement,
+ discriminant: discriminant,
+ cases: cases
+ };
+ }
+
+ oldInSwitch = state.inSwitch;
+ state.inSwitch = true;
+ defaultFound = false;
+
+ while (index < length) {
+ if (match('}')) {
+ break;
+ }
+ clause = parseSwitchCase();
+ if (clause.test === null) {
+ if (defaultFound) {
+ throwError({}, Messages.MultipleDefaultsInSwitch);
+ }
+ defaultFound = true;
+ }
+ cases.push(clause);
+ }
+
+ state.inSwitch = oldInSwitch;
+
+ expect('}');
+
+ return {
+ type: Syntax.SwitchStatement,
+ discriminant: discriminant,
+ cases: cases
+ };
+ }
+
+ // 12.13 The throw statement
+
+ function parseThrowStatement() {
+ var argument;
+
+ expectKeyword('throw');
+
+ if (peekLineTerminator()) {
+ throwError({}, Messages.NewlineAfterThrow);
+ }
+
+ argument = parseExpression();
+
+ consumeSemicolon();
+
+ return {
+ type: Syntax.ThrowStatement,
+ argument: argument
+ };
+ }
+
+ // 12.14 The try statement
+
+ function parseCatchClause() {
+ var param;
+
+ expectKeyword('catch');
+
+ expect('(');
+ if (match(')')) {
+ throwUnexpected(lookahead());
+ }
+
+ param = parseVariableIdentifier();
+ // 12.14.1
+ if (strict && isRestrictedWord(param.name)) {
+ throwErrorTolerant({}, Messages.StrictCatchVariable);
+ }
+
+ expect(')');
+
+ return {
+ type: Syntax.CatchClause,
+ param: param,
+ body: parseBlock()
+ };
+ }
+
+ function parseTryStatement() {
+ var block, handlers = [], finalizer = null;
+
+ expectKeyword('try');
+
+ block = parseBlock();
+
+ if (matchKeyword('catch')) {
+ handlers.push(parseCatchClause());
+ }
+
+ if (matchKeyword('finally')) {
+ lex();
+ finalizer = parseBlock();
+ }
+
+ if (handlers.length === 0 && !finalizer) {
+ throwError({}, Messages.NoCatchOrFinally);
+ }
+
+ return {
+ type: Syntax.TryStatement,
+ block: block,
+ guardedHandlers: [],
+ handlers: handlers,
+ finalizer: finalizer
+ };
+ }
+
+ // 12.15 The debugger statement
+
+ function parseDebuggerStatement() {
+ expectKeyword('debugger');
+
+ consumeSemicolon();
+
+ return {
+ type: Syntax.DebuggerStatement
+ };
+ }
+
+ // 12 Statements
+
+ function parseStatement() {
+ var token = lookahead(),
+ expr,
+ labeledBody;
+
+ if (token.type === Token.EOF) {
+ throwUnexpected(token);
+ }
+
+ if (token.type === Token.Punctuator) {
+ switch (token.value) {
+ case ';':
+ return parseEmptyStatement();
+ case '{':
+ return parseBlock();
+ case '(':
+ return parseExpressionStatement();
+ default:
+ break;
+ }
+ }
+
+ if (token.type === Token.Keyword) {
+ switch (token.value) {
+ case 'break':
+ return parseBreakStatement();
+ case 'continue':
+ return parseContinueStatement();
+ case 'debugger':
+ return parseDebuggerStatement();
+ case 'do':
+ return parseDoWhileStatement();
+ case 'for':
+ return parseForStatement();
+ case 'function':
+ return parseFunctionDeclaration();
+ case 'if':
+ return parseIfStatement();
+ case 'return':
+ return parseReturnStatement();
+ case 'switch':
+ return parseSwitchStatement();
+ case 'throw':
+ return parseThrowStatement();
+ case 'try':
+ return parseTryStatement();
+ case 'var':
+ return parseVariableStatement();
+ case 'while':
+ return parseWhileStatement();
+ case 'with':
+ return parseWithStatement();
+ default:
+ break;
+ }
+ }
+
+ expr = parseExpression();
+
+ // 12.12 Labelled Statements
+ if ((expr.type === Syntax.Identifier) && match(':')) {
+ lex();
+
+ if (Object.prototype.hasOwnProperty.call(state.labelSet, expr.name)) {
+ throwError({}, Messages.Redeclaration, 'Label', expr.name);
+ }
+
+ state.labelSet[expr.name] = true;
+ labeledBody = parseStatement();
+ delete state.labelSet[expr.name];
+
+ return {
+ type: Syntax.LabeledStatement,
+ label: expr,
+ body: labeledBody
+ };
+ }
+
+ consumeSemicolon();
+
+ return {
+ type: Syntax.ExpressionStatement,
+ expression: expr
+ };
+ }
+
+ // 13 Function Definition
+
+ function parseFunctionSourceElements() {
+ var sourceElement, sourceElements = [], token, directive, firstRestricted,
+ oldLabelSet, oldInIteration, oldInSwitch, oldInFunctionBody;
+
+ expect('{');
+
+ while (index < length) {
+ token = lookahead();
+ if (token.type !== Token.StringLiteral) {
+ break;
+ }
+
+ sourceElement = parseSourceElement();
+ sourceElements.push(sourceElement);
+ if (sourceElement.expression.type !== Syntax.Literal) {
+ // this is not directive
+ break;
+ }
+ directive = sliceSource(token.range[0] + 1, token.range[1] - 1);
+ if (directive === 'use strict') {
+ strict = true;
+ if (firstRestricted) {
+ throwErrorTolerant(firstRestricted, Messages.StrictOctalLiteral);
+ }
+ } else {
+ if (!firstRestricted && token.octal) {
+ firstRestricted = token;
+ }
+ }
+ }
+
+ oldLabelSet = state.labelSet;
+ oldInIteration = state.inIteration;
+ oldInSwitch = state.inSwitch;
+ oldInFunctionBody = state.inFunctionBody;
+
+ state.labelSet = {};
+ state.inIteration = false;
+ state.inSwitch = false;
+ state.inFunctionBody = true;
+
+ while (index < length) {
+ if (match('}')) {
+ break;
+ }
+ sourceElement = parseSourceElement();
+ if (typeof sourceElement === 'undefined') {
+ break;
+ }
+ sourceElements.push(sourceElement);
+ }
+
+ expect('}');
+
+ state.labelSet = oldLabelSet;
+ state.inIteration = oldInIteration;
+ state.inSwitch = oldInSwitch;
+ state.inFunctionBody = oldInFunctionBody;
+
+ return {
+ type: Syntax.BlockStatement,
+ body: sourceElements
+ };
+ }
+
+ function parseFunctionDeclaration() {
+ var id, param, params = [], body, token, stricted, firstRestricted, message, previousStrict, paramSet;
+
+ expectKeyword('function');
+ token = lookahead();
+ id = parseVariableIdentifier();
+ if (strict) {
+ if (isRestrictedWord(token.value)) {
+ throwErrorTolerant(token, Messages.StrictFunctionName);
+ }
+ } else {
+ if (isRestrictedWord(token.value)) {
+ firstRestricted = token;
+ message = Messages.StrictFunctionName;
+ } else if (isStrictModeReservedWord(token.value)) {
+ firstRestricted = token;
+ message = Messages.StrictReservedWord;
+ }
+ }
+
+ expect('(');
+
+ if (!match(')')) {
+ paramSet = {};
+ while (index < length) {
+ token = lookahead();
+ param = parseVariableIdentifier();
+ if (strict) {
+ if (isRestrictedWord(token.value)) {
+ stricted = token;
+ message = Messages.StrictParamName;
+ }
+ if (Object.prototype.hasOwnProperty.call(paramSet, token.value)) {
+ stricted = token;
+ message = Messages.StrictParamDupe;
+ }
+ } else if (!firstRestricted) {
+ if (isRestrictedWord(token.value)) {
+ firstRestricted = token;
+ message = Messages.StrictParamName;
+ } else if (isStrictModeReservedWord(token.value)) {
+ firstRestricted = token;
+ message = Messages.StrictReservedWord;
+ } else if (Object.prototype.hasOwnProperty.call(paramSet, token.value)) {
+ firstRestricted = token;
+ message = Messages.StrictParamDupe;
+ }
+ }
+ params.push(param);
+ paramSet[param.name] = true;
+ if (match(')')) {
+ break;
+ }
+ expect(',');
+ }
+ }
+
+ expect(')');
+
+ previousStrict = strict;
+ body = parseFunctionSourceElements();
+ if (strict && firstRestricted) {
+ throwError(firstRestricted, message);
+ }
+ if (strict && stricted) {
+ throwErrorTolerant(stricted, message);
+ }
+ strict = previousStrict;
+
+ return {
+ type: Syntax.FunctionDeclaration,
+ id: id,
+ params: params,
+ defaults: [],
+ body: body,
+ rest: null,
+ generator: false,
+ expression: false
+ };
+ }
+
+ function parseFunctionExpression() {
+ var token, id = null, stricted, firstRestricted, message, param, params = [], body, previousStrict, paramSet;
+
+ expectKeyword('function');
+
+ if (!match('(')) {
+ token = lookahead();
+ id = parseVariableIdentifier();
+ if (strict) {
+ if (isRestrictedWord(token.value)) {
+ throwErrorTolerant(token, Messages.StrictFunctionName);
+ }
+ } else {
+ if (isRestrictedWord(token.value)) {
+ firstRestricted = token;
+ message = Messages.StrictFunctionName;
+ } else if (isStrictModeReservedWord(token.value)) {
+ firstRestricted = token;
+ message = Messages.StrictReservedWord;
+ }
+ }
+ }
+
+ expect('(');
+
+ if (!match(')')) {
+ paramSet = {};
+ while (index < length) {
+ token = lookahead();
+ param = parseVariableIdentifier();
+ if (strict) {
+ if (isRestrictedWord(token.value)) {
+ stricted = token;
+ message = Messages.StrictParamName;
+ }
+ if (Object.prototype.hasOwnProperty.call(paramSet, token.value)) {
+ stricted = token;
+ message = Messages.StrictParamDupe;
+ }
+ } else if (!firstRestricted) {
+ if (isRestrictedWord(token.value)) {
+ firstRestricted = token;
+ message = Messages.StrictParamName;
+ } else if (isStrictModeReservedWord(token.value)) {
+ firstRestricted = token;
+ message = Messages.StrictReservedWord;
+ } else if (Object.prototype.hasOwnProperty.call(paramSet, token.value)) {
+ firstRestricted = token;
+ message = Messages.StrictParamDupe;
+ }
+ }
+ params.push(param);
+ paramSet[param.name] = true;
+ if (match(')')) {
+ break;
+ }
+ expect(',');
+ }
+ }
+
+ expect(')');
+
+ previousStrict = strict;
+ body = parseFunctionSourceElements();
+ if (strict && firstRestricted) {
+ throwError(firstRestricted, message);
+ }
+ if (strict && stricted) {
+ throwErrorTolerant(stricted, message);
+ }
+ strict = previousStrict;
+
+ return {
+ type: Syntax.FunctionExpression,
+ id: id,
+ params: params,
+ defaults: [],
+ body: body,
+ rest: null,
+ generator: false,
+ expression: false
+ };
+ }
+
+ // 14 Program
+
+ function parseSourceElement() {
+ var token = lookahead();
+
+ if (token.type === Token.Keyword) {
+ switch (token.value) {
+ case 'const':
+ case 'let':
+ return parseConstLetDeclaration(token.value);
+ case 'function':
+ return parseFunctionDeclaration();
+ default:
+ return parseStatement();
+ }
+ }
+
+ if (token.type !== Token.EOF) {
+ return parseStatement();
+ }
+ }
+
+ function parseSourceElements() {
+ var sourceElement, sourceElements = [], token, directive, firstRestricted;
+
+ while (index < length) {
+ token = lookahead();
+ if (token.type !== Token.StringLiteral) {
+ break;
+ }
+
+ sourceElement = parseSourceElement();
+ sourceElements.push(sourceElement);
+ if (sourceElement.expression.type !== Syntax.Literal) {
+ // this is not directive
+ break;
+ }
+ directive = sliceSource(token.range[0] + 1, token.range[1] - 1);
+ if (directive === 'use strict') {
+ strict = true;
+ if (firstRestricted) {
+ throwErrorTolerant(firstRestricted, Messages.StrictOctalLiteral);
+ }
+ } else {
+ if (!firstRestricted && token.octal) {
+ firstRestricted = token;
+ }
+ }
+ }
+
+ while (index < length) {
+ sourceElement = parseSourceElement();
+ if (typeof sourceElement === 'undefined') {
+ break;
+ }
+ sourceElements.push(sourceElement);
+ }
+ return sourceElements;
+ }
+
+ function parseProgram() {
+ var program;
+ strict = false;
+ program = {
+ type: Syntax.Program,
+ body: parseSourceElements()
+ };
+ return program;
+ }
+
+ // The following functions are needed only when the option to preserve
+ // the comments is active.
+
+ function addComment(type, value, start, end, loc) {
+ assert(typeof start === 'number', 'Comment must have valid position');
+
+ // Because the way the actual token is scanned, often the comments
+ // (if any) are skipped twice during the lexical analysis.
+ // Thus, we need to skip adding a comment if the comment array already
+ // handled it.
+ if (extra.comments.length > 0) {
+ if (extra.comments[extra.comments.length - 1].range[1] > start) {
+ return;
+ }
+ }
+
+ extra.comments.push({
+ type: type,
+ value: value,
+ range: [start, end],
+ loc: loc
+ });
+ }
+
+ function scanComment() {
+ var comment, ch, loc, start, blockComment, lineComment;
+
+ comment = '';
+ blockComment = false;
+ lineComment = false;
+
+ while (index < length) {
+ ch = source[index];
+
+ if (lineComment) {
+ ch = source[index++];
+ if (isLineTerminator(ch)) {
+ loc.end = {
+ line: lineNumber,
+ column: index - lineStart - 1
+ };
+ lineComment = false;
+ addComment('Line', comment, start, index - 1, loc);
+ if (ch === '\r' && source[index] === '\n') {
+ ++index;
+ }
+ ++lineNumber;
+ lineStart = index;
+ comment = '';
+ } else if (index >= length) {
+ lineComment = false;
+ comment += ch;
+ loc.end = {
+ line: lineNumber,
+ column: length - lineStart
+ };
+ addComment('Line', comment, start, length, loc);
+ } else {
+ comment += ch;
+ }
+ } else if (blockComment) {
+ if (isLineTerminator(ch)) {
+ if (ch === '\r' && source[index + 1] === '\n') {
+ ++index;
+ comment += '\r\n';
+ } else {
+ comment += ch;
+ }
+ ++lineNumber;
+ ++index;
+ lineStart = index;
+ if (index >= length) {
+ throwError({}, Messages.UnexpectedToken, 'ILLEGAL');
+ }
+ } else {
+ ch = source[index++];
+ if (index >= length) {
+ throwError({}, Messages.UnexpectedToken, 'ILLEGAL');
+ }
+ comment += ch;
+ if (ch === '*') {
+ ch = source[index];
+ if (ch === '/') {
+ comment = comment.substr(0, comment.length - 1);
+ blockComment = false;
+ ++index;
+ loc.end = {
+ line: lineNumber,
+ column: index - lineStart
+ };
+ addComment('Block', comment, start, index, loc);
+ comment = '';
+ }
+ }
+ }
+ } else if (ch === '/') {
+ ch = source[index + 1];
+ if (ch === '/') {
+ loc = {
+ start: {
+ line: lineNumber,
+ column: index - lineStart
+ }
+ };
+ start = index;
+ index += 2;
+ lineComment = true;
+ if (index >= length) {
+ loc.end = {
+ line: lineNumber,
+ column: index - lineStart
+ };
+ lineComment = false;
+ addComment('Line', comment, start, index, loc);
+ }
+ } else if (ch === '*') {
+ start = index;
+ index += 2;
+ blockComment = true;
+ loc = {
+ start: {
+ line: lineNumber,
+ column: index - lineStart - 2
+ }
+ };
+ if (index >= length) {
+ throwError({}, Messages.UnexpectedToken, 'ILLEGAL');
+ }
+ } else {
+ break;
+ }
+ } else if (isWhiteSpace(ch)) {
+ ++index;
+ } else if (isLineTerminator(ch)) {
+ ++index;
+ if (ch === '\r' && source[index] === '\n') {
+ ++index;
+ }
+ ++lineNumber;
+ lineStart = index;
+ } else {
+ break;
+ }
+ }
+ }
+
+ function filterCommentLocation() {
+ var i, entry, comment, comments = [];
+
+ for (i = 0; i < extra.comments.length; ++i) {
+ entry = extra.comments[i];
+ comment = {
+ type: entry.type,
+ value: entry.value
+ };
+ if (extra.range) {
+ comment.range = entry.range;
+ }
+ if (extra.loc) {
+ comment.loc = entry.loc;
+ }
+ comments.push(comment);
+ }
+
+ extra.comments = comments;
+ }
+
+ function collectToken() {
+ var start, loc, token, range, value;
+
+ skipComment();
+ start = index;
+ loc = {
+ start: {
+ line: lineNumber,
+ column: index - lineStart
+ }
+ };
+
+ token = extra.advance();
+ loc.end = {
+ line: lineNumber,
+ column: index - lineStart
+ };
+
+ if (token.type !== Token.EOF) {
+ range = [token.range[0], token.range[1]];
+ value = sliceSource(token.range[0], token.range[1]);
+ extra.tokens.push({
+ type: TokenName[token.type],
+ value: value,
+ range: range,
+ loc: loc
+ });
+ }
+
+ return token;
+ }
+
+ function collectRegex() {
+ var pos, loc, regex, token;
+
+ skipComment();
+
+ pos = index;
+ loc = {
+ start: {
+ line: lineNumber,
+ column: index - lineStart
+ }
+ };
+
+ regex = extra.scanRegExp();
+ loc.end = {
+ line: lineNumber,
+ column: index - lineStart
+ };
+
+ // Pop the previous token, which is likely '/' or '/='
+ if (extra.tokens.length > 0) {
+ token = extra.tokens[extra.tokens.length - 1];
+ if (token.range[0] === pos && token.type === 'Punctuator') {
+ if (token.value === '/' || token.value === '/=') {
+ extra.tokens.pop();
+ }
+ }
+ }
+
+ extra.tokens.push({
+ type: 'RegularExpression',
+ value: regex.literal,
+ range: [pos, index],
+ loc: loc
+ });
+
+ return regex;
+ }
+
+ function filterTokenLocation() {
+ var i, entry, token, tokens = [];
+
+ for (i = 0; i < extra.tokens.length; ++i) {
+ entry = extra.tokens[i];
+ token = {
+ type: entry.type,
+ value: entry.value
+ };
+ if (extra.range) {
+ token.range = entry.range;
+ }
+ if (extra.loc) {
+ token.loc = entry.loc;
+ }
+ tokens.push(token);
+ }
+
+ extra.tokens = tokens;
+ }
+
+ function createLiteral(token) {
+ return {
+ type: Syntax.Literal,
+ value: token.value
+ };
+ }
+
+ function createRawLiteral(token) {
+ return {
+ type: Syntax.Literal,
+ value: token.value,
+ raw: sliceSource(token.range[0], token.range[1])
+ };
+ }
+
+ function createLocationMarker() {
+ var marker = {};
+
+ marker.range = [index, index];
+ marker.loc = {
+ start: {
+ line: lineNumber,
+ column: index - lineStart
+ },
+ end: {
+ line: lineNumber,
+ column: index - lineStart
+ }
+ };
+
+ marker.end = function () {
+ this.range[1] = index;
+ this.loc.end.line = lineNumber;
+ this.loc.end.column = index - lineStart;
+ };
+
+ marker.applyGroup = function (node) {
+ if (extra.range) {
+ node.groupRange = [this.range[0], this.range[1]];
+ }
+ if (extra.loc) {
+ node.groupLoc = {
+ start: {
+ line: this.loc.start.line,
+ column: this.loc.start.column
+ },
+ end: {
+ line: this.loc.end.line,
+ column: this.loc.end.column
+ }
+ };
+ }
+ };
+
+ marker.apply = function (node) {
+ if (extra.range) {
+ node.range = [this.range[0], this.range[1]];
+ }
+ if (extra.loc) {
+ node.loc = {
+ start: {
+ line: this.loc.start.line,
+ column: this.loc.start.column
+ },
+ end: {
+ line: this.loc.end.line,
+ column: this.loc.end.column
+ }
+ };
+ }
+ };
+
+ return marker;
+ }
+
+ function trackGroupExpression() {
+ var marker, expr;
+
+ skipComment();
+ marker = createLocationMarker();
+ expect('(');
+
+ expr = parseExpression();
+
+ expect(')');
+
+ marker.end();
+ marker.applyGroup(expr);
+
+ return expr;
+ }
+
+ function trackLeftHandSideExpression() {
+ var marker, expr;
+
+ skipComment();
+ marker = createLocationMarker();
+
+ expr = matchKeyword('new') ? parseNewExpression() : parsePrimaryExpression();
+
+ while (match('.') || match('[')) {
+ if (match('[')) {
+ expr = {
+ type: Syntax.MemberExpression,
+ computed: true,
+ object: expr,
+ property: parseComputedMember()
+ };
+ marker.end();
+ marker.apply(expr);
+ } else {
+ expr = {
+ type: Syntax.MemberExpression,
+ computed: false,
+ object: expr,
+ property: parseNonComputedMember()
+ };
+ marker.end();
+ marker.apply(expr);
+ }
+ }
+
+ return expr;
+ }
+
+ function trackLeftHandSideExpressionAllowCall() {
+ var marker, expr;
+
+ skipComment();
+ marker = createLocationMarker();
+
+ expr = matchKeyword('new') ? parseNewExpression() : parsePrimaryExpression();
+
+ while (match('.') || match('[') || match('(')) {
+ if (match('(')) {
+ expr = {
+ type: Syntax.CallExpression,
+ callee: expr,
+ 'arguments': parseArguments()
+ };
+ marker.end();
+ marker.apply(expr);
+ } else if (match('[')) {
+ expr = {
+ type: Syntax.MemberExpression,
+ computed: true,
+ object: expr,
+ property: parseComputedMember()
+ };
+ marker.end();
+ marker.apply(expr);
+ } else {
+ expr = {
+ type: Syntax.MemberExpression,
+ computed: false,
+ object: expr,
+ property: parseNonComputedMember()
+ };
+ marker.end();
+ marker.apply(expr);
+ }
+ }
+
+ return expr;
+ }
+
+ function filterGroup(node) {
+ var n, i, entry;
+
+ n = (Object.prototype.toString.apply(node) === '[object Array]') ? [] : {};
+ for (i in node) {
+ if (node.hasOwnProperty(i) && i !== 'groupRange' && i !== 'groupLoc') {
+ entry = node[i];
+ if (entry === null || typeof entry !== 'object' || entry instanceof RegExp) {
+ n[i] = entry;
+ } else {
+ n[i] = filterGroup(entry);
+ }
+ }
+ }
+ return n;
+ }
+
+ function wrapTrackingFunction(range, loc) {
+
+ return function (parseFunction) {
+
+ function isBinary(node) {
+ return node.type === Syntax.LogicalExpression ||
+ node.type === Syntax.BinaryExpression;
+ }
+
+ function visit(node) {
+ var start, end;
+
+ if (isBinary(node.left)) {
+ visit(node.left);
+ }
+ if (isBinary(node.right)) {
+ visit(node.right);
+ }
+
+ if (range) {
+ if (node.left.groupRange || node.right.groupRange) {
+ start = node.left.groupRange ? node.left.groupRange[0] : node.left.range[0];
+ end = node.right.groupRange ? node.right.groupRange[1] : node.right.range[1];
+ node.range = [start, end];
+ } else if (typeof node.range === 'undefined') {
+ start = node.left.range[0];
+ end = node.right.range[1];
+ node.range = [start, end];
+ }
+ }
+ if (loc) {
+ if (node.left.groupLoc || node.right.groupLoc) {
+ start = node.left.groupLoc ? node.left.groupLoc.start : node.left.loc.start;
+ end = node.right.groupLoc ? node.right.groupLoc.end : node.right.loc.end;
+ node.loc = {
+ start: start,
+ end: end
+ };
+ } else if (typeof node.loc === 'undefined') {
+ node.loc = {
+ start: node.left.loc.start,
+ end: node.right.loc.end
+ };
+ }
+ }
+ }
+
+ return function () {
+ var marker, node;
+
+ skipComment();
+
+ marker = createLocationMarker();
+ node = parseFunction.apply(null, arguments);
+ marker.end();
+
+ if (range && typeof node.range === 'undefined') {
+ marker.apply(node);
+ }
+
+ if (loc && typeof node.loc === 'undefined') {
+ marker.apply(node);
+ }
+
+ if (isBinary(node)) {
+ visit(node);
+ }
+
+ return node;
+ };
+ };
+ }
+
+ function patch() {
+
+ var wrapTracking;
+
+ if (extra.comments) {
+ extra.skipComment = skipComment;
+ skipComment = scanComment;
+ }
+
+ if (extra.raw) {
+ extra.createLiteral = createLiteral;
+ createLiteral = createRawLiteral;
+ }
+
+ if (extra.range || extra.loc) {
+
+ extra.parseGroupExpression = parseGroupExpression;
+ extra.parseLeftHandSideExpression = parseLeftHandSideExpression;
+ extra.parseLeftHandSideExpressionAllowCall = parseLeftHandSideExpressionAllowCall;
+ parseGroupExpression = trackGroupExpression;
+ parseLeftHandSideExpression = trackLeftHandSideExpression;
+ parseLeftHandSideExpressionAllowCall = trackLeftHandSideExpressionAllowCall;
+
+ wrapTracking = wrapTrackingFunction(extra.range, extra.loc);
+
+ extra.parseAdditiveExpression = parseAdditiveExpression;
+ extra.parseAssignmentExpression = parseAssignmentExpression;
+ extra.parseBitwiseANDExpression = parseBitwiseANDExpression;
+ extra.parseBitwiseORExpression = parseBitwiseORExpression;
+ extra.parseBitwiseXORExpression = parseBitwiseXORExpression;
+ extra.parseBlock = parseBlock;
+ extra.parseFunctionSourceElements = parseFunctionSourceElements;
+ extra.parseCatchClause = parseCatchClause;
+ extra.parseComputedMember = parseComputedMember;
+ extra.parseConditionalExpression = parseConditionalExpression;
+ extra.parseConstLetDeclaration = parseConstLetDeclaration;
+ extra.parseEqualityExpression = parseEqualityExpression;
+ extra.parseExpression = parseExpression;
+ extra.parseForVariableDeclaration = parseForVariableDeclaration;
+ extra.parseFunctionDeclaration = parseFunctionDeclaration;
+ extra.parseFunctionExpression = parseFunctionExpression;
+ extra.parseLogicalANDExpression = parseLogicalANDExpression;
+ extra.parseLogicalORExpression = parseLogicalORExpression;
+ extra.parseMultiplicativeExpression = parseMultiplicativeExpression;
+ extra.parseNewExpression = parseNewExpression;
+ extra.parseNonComputedProperty = parseNonComputedProperty;
+ extra.parseObjectProperty = parseObjectProperty;
+ extra.parseObjectPropertyKey = parseObjectPropertyKey;
+ extra.parsePostfixExpression = parsePostfixExpression;
+ extra.parsePrimaryExpression = parsePrimaryExpression;
+ extra.parseProgram = parseProgram;
+ extra.parsePropertyFunction = parsePropertyFunction;
+ extra.parseRelationalExpression = parseRelationalExpression;
+ extra.parseStatement = parseStatement;
+ extra.parseShiftExpression = parseShiftExpression;
+ extra.parseSwitchCase = parseSwitchCase;
+ extra.parseUnaryExpression = parseUnaryExpression;
+ extra.parseVariableDeclaration = parseVariableDeclaration;
+ extra.parseVariableIdentifier = parseVariableIdentifier;
+
+ parseAdditiveExpression = wrapTracking(extra.parseAdditiveExpression);
+ parseAssignmentExpression = wrapTracking(extra.parseAssignmentExpression);
+ parseBitwiseANDExpression = wrapTracking(extra.parseBitwiseANDExpression);
+ parseBitwiseORExpression = wrapTracking(extra.parseBitwiseORExpression);
+ parseBitwiseXORExpression = wrapTracking(extra.parseBitwiseXORExpression);
+ parseBlock = wrapTracking(extra.parseBlock);
+ parseFunctionSourceElements = wrapTracking(extra.parseFunctionSourceElements);
+ parseCatchClause = wrapTracking(extra.parseCatchClause);
+ parseComputedMember = wrapTracking(extra.parseComputedMember);
+ parseConditionalExpression = wrapTracking(extra.parseConditionalExpression);
+ parseConstLetDeclaration = wrapTracking(extra.parseConstLetDeclaration);
+ parseEqualityExpression = wrapTracking(extra.parseEqualityExpression);
+ parseExpression = wrapTracking(extra.parseExpression);
+ parseForVariableDeclaration = wrapTracking(extra.parseForVariableDeclaration);
+ parseFunctionDeclaration = wrapTracking(extra.parseFunctionDeclaration);
+ parseFunctionExpression = wrapTracking(extra.parseFunctionExpression);
+ parseLeftHandSideExpression = wrapTracking(parseLeftHandSideExpression);
+ parseLogicalANDExpression = wrapTracking(extra.parseLogicalANDExpression);
+ parseLogicalORExpression = wrapTracking(extra.parseLogicalORExpression);
+ parseMultiplicativeExpression = wrapTracking(extra.parseMultiplicativeExpression);
+ parseNewExpression = wrapTracking(extra.parseNewExpression);
+ parseNonComputedProperty = wrapTracking(extra.parseNonComputedProperty);
+ parseObjectProperty = wrapTracking(extra.parseObjectProperty);
+ parseObjectPropertyKey = wrapTracking(extra.parseObjectPropertyKey);
+ parsePostfixExpression = wrapTracking(extra.parsePostfixExpression);
+ parsePrimaryExpression = wrapTracking(extra.parsePrimaryExpression);
+ parseProgram = wrapTracking(extra.parseProgram);
+ parsePropertyFunction = wrapTracking(extra.parsePropertyFunction);
+ parseRelationalExpression = wrapTracking(extra.parseRelationalExpression);
+ parseStatement = wrapTracking(extra.parseStatement);
+ parseShiftExpression = wrapTracking(extra.parseShiftExpression);
+ parseSwitchCase = wrapTracking(extra.parseSwitchCase);
+ parseUnaryExpression = wrapTracking(extra.parseUnaryExpression);
+ parseVariableDeclaration = wrapTracking(extra.parseVariableDeclaration);
+ parseVariableIdentifier = wrapTracking(extra.parseVariableIdentifier);
+ }
+
+ if (typeof extra.tokens !== 'undefined') {
+ extra.advance = advance;
+ extra.scanRegExp = scanRegExp;
+
+ advance = collectToken;
+ scanRegExp = collectRegex;
+ }
+ }
+
+ function unpatch() {
+ if (typeof extra.skipComment === 'function') {
+ skipComment = extra.skipComment;
+ }
+
+ if (extra.raw) {
+ createLiteral = extra.createLiteral;
+ }
+
+ if (extra.range || extra.loc) {
+ parseAdditiveExpression = extra.parseAdditiveExpression;
+ parseAssignmentExpression = extra.parseAssignmentExpression;
+ parseBitwiseANDExpression = extra.parseBitwiseANDExpression;
+ parseBitwiseORExpression = extra.parseBitwiseORExpression;
+ parseBitwiseXORExpression = extra.parseBitwiseXORExpression;
+ parseBlock = extra.parseBlock;
+ parseFunctionSourceElements = extra.parseFunctionSourceElements;
+ parseCatchClause = extra.parseCatchClause;
+ parseComputedMember = extra.parseComputedMember;
+ parseConditionalExpression = extra.parseConditionalExpression;
+ parseConstLetDeclaration = extra.parseConstLetDeclaration;
+ parseEqualityExpression = extra.parseEqualityExpression;
+ parseExpression = extra.parseExpression;
+ parseForVariableDeclaration = extra.parseForVariableDeclaration;
+ parseFunctionDeclaration = extra.parseFunctionDeclaration;
+ parseFunctionExpression = extra.parseFunctionExpression;
+ parseGroupExpression = extra.parseGroupExpression;
+ parseLeftHandSideExpression = extra.parseLeftHandSideExpression;
+ parseLeftHandSideExpressionAllowCall = extra.parseLeftHandSideExpressionAllowCall;
+ parseLogicalANDExpression = extra.parseLogicalANDExpression;
+ parseLogicalORExpression = extra.parseLogicalORExpression;
+ parseMultiplicativeExpression = extra.parseMultiplicativeExpression;
+ parseNewExpression = extra.parseNewExpression;
+ parseNonComputedProperty = extra.parseNonComputedProperty;
+ parseObjectProperty = extra.parseObjectProperty;
+ parseObjectPropertyKey = extra.parseObjectPropertyKey;
+ parsePrimaryExpression = extra.parsePrimaryExpression;
+ parsePostfixExpression = extra.parsePostfixExpression;
+ parseProgram = extra.parseProgram;
+ parsePropertyFunction = extra.parsePropertyFunction;
+ parseRelationalExpression = extra.parseRelationalExpression;
+ parseStatement = extra.parseStatement;
+ parseShiftExpression = extra.parseShiftExpression;
+ parseSwitchCase = extra.parseSwitchCase;
+ parseUnaryExpression = extra.parseUnaryExpression;
+ parseVariableDeclaration = extra.parseVariableDeclaration;
+ parseVariableIdentifier = extra.parseVariableIdentifier;
+ }
+
+ if (typeof extra.scanRegExp === 'function') {
+ advance = extra.advance;
+ scanRegExp = extra.scanRegExp;
+ }
+ }
+
+ function stringToArray(str) {
+ var length = str.length,
+ result = [],
+ i;
+ for (i = 0; i < length; ++i) {
+ result[i] = str.charAt(i);
+ }
+ return result;
+ }
+
+ function parse(code, options) {
+ var program, toString;
+
+ toString = String;
+ if (typeof code !== 'string' && !(code instanceof String)) {
+ code = toString(code);
+ }
+
+ source = code;
+ index = 0;
+ lineNumber = (source.length > 0) ? 1 : 0;
+ lineStart = 0;
+ length = source.length;
+ buffer = null;
+ state = {
+ allowIn: true,
+ labelSet: {},
+ inFunctionBody: false,
+ inIteration: false,
+ inSwitch: false
+ };
+
+ extra = {};
+ if (typeof options !== 'undefined') {
+ extra.range = (typeof options.range === 'boolean') && options.range;
+ extra.loc = (typeof options.loc === 'boolean') && options.loc;
+ extra.raw = (typeof options.raw === 'boolean') && options.raw;
+ if (typeof options.tokens === 'boolean' && options.tokens) {
+ extra.tokens = [];
+ }
+ if (typeof options.comment === 'boolean' && options.comment) {
+ extra.comments = [];
+ }
+ if (typeof options.tolerant === 'boolean' && options.tolerant) {
+ extra.errors = [];
+ }
+ }
+
+ if (length > 0) {
+ if (typeof source[0] === 'undefined') {
+ // Try first to convert to a string. This is good as fast path
+ // for old IE which understands string indexing for string
+ // literals only and not for string object.
+ if (code instanceof String) {
+ source = code.valueOf();
+ }
+
+ // Force accessing the characters via an array.
+ if (typeof source[0] === 'undefined') {
+ source = stringToArray(code);
+ }
+ }
+ }
+
+ patch();
+ try {
+ program = parseProgram();
+ if (typeof extra.comments !== 'undefined') {
+ filterCommentLocation();
+ program.comments = extra.comments;
+ }
+ if (typeof extra.tokens !== 'undefined') {
+ filterTokenLocation();
+ program.tokens = extra.tokens;
+ }
+ if (typeof extra.errors !== 'undefined') {
+ program.errors = extra.errors;
+ }
+ if (extra.range || extra.loc) {
+ program.body = filterGroup(program.body);
+ }
+ } catch (e) {
+ throw e;
+ } finally {
+ unpatch();
+ extra = {};
+ }
+
+ return program;
+ }
+
+ // Sync with package.json.
+ exports.version = '1.0.4';
+
+ exports.parse = parse;
+
+ // Deep copy.
+ exports.Syntax = (function () {
+ var name, types = {};
+
+ if (typeof Object.create === 'function') {
+ types = Object.create(null);
+ }
+
+ for (name in Syntax) {
+ if (Syntax.hasOwnProperty(name)) {
+ types[name] = Syntax[name];
+ }
+ }
+
+ if (typeof Object.freeze === 'function') {
+ Object.freeze(types);
+ }
+
+ return types;
+ }());
+
+}));
+/* vim: set sw=4 ts=4 et tw=80 : */
+/**
+ * @license Copyright (c) 2012-2014, The Dojo Foundation All Rights Reserved.
+ * Available via the MIT or new BSD license.
+ * see: http://github.com/jrburke/requirejs for details
+ */
+
+/*global define, Reflect */
+
+/*
+ * xpcshell has a smaller stack on linux and windows (1MB vs 9MB on mac),
+ * and the recursive nature of esprima can cause it to overflow pretty
+ * quickly. So favor it built in Reflect parser:
+ * https://developer.mozilla.org/en-US/docs/SpiderMonkey/Parser_API
+ */
+define('esprimaAdapter', ['./esprima', 'env'], function (esprima, env) {
+ if (env.get() === 'xpconnect' && typeof Reflect !== 'undefined') {
+ return Reflect;
+ } else {
+ return esprima;
+ }
+});
+define('uglifyjs/consolidator', ["require", "exports", "module", "./parse-js", "./process"], function(require, exports, module) {
+/**
+ * @preserve Copyright 2012 Robert Gust-Bardon <http://robert.gust-bardon.org/>.
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * * Redistributions of source code must retain the above
+ * copyright notice, this list of conditions and the following
+ * disclaimer.
+ *
+ * * Redistributions in binary form must reproduce the above
+ * copyright notice, this list of conditions and the following
+ * disclaimer in the documentation and/or other materials
+ * provided with the distribution.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDER "AS IS" AND ANY
+ * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
+ * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE
+ * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY,
+ * OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
+ * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
+ * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+ * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR
+ * TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF
+ * THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ * SUCH DAMAGE.
+ */
+
+/**
+ * @fileoverview Enhances <a href="https://github.com/mishoo/UglifyJS/"
+ * >UglifyJS</a> with consolidation of null, Boolean, and String values.
+ * <p>Also known as aliasing, this feature has been deprecated in <a href=
+ * "http://closure-compiler.googlecode.com/">the Closure Compiler</a> since its
+ * initial release, where it is unavailable from the <abbr title=
+ * "command line interface">CLI</a>. The Closure Compiler allows one to log and
+ * influence this process. In contrast, this implementation does not introduce
+ * any variable declarations in global code and derives String values from
+ * identifier names used as property accessors.</p>
+ * <p>Consolidating literals may worsen the data compression ratio when an <a
+ * href="http://tools.ietf.org/html/rfc2616#section-3.5">encoding
+ * transformation</a> is applied. For instance, <a href=
+ * "http://code.jquery.com/jquery-1.7.1.js">jQuery 1.7.1</a> takes 248235 bytes.
+ * Building it with <a href="https://github.com/mishoo/UglifyJS/tarball/v1.2.5">
+ * UglifyJS v1.2.5</a> results in 93647 bytes (37.73% of the original) which are
+ * then compressed to 33154 bytes (13.36% of the original) using <a href=
+ * "http://linux.die.net/man/1/gzip">gzip(1)</a>. Building it with the same
+ * version of UglifyJS 1.2.5 patched with the implementation of consolidation
+ * results in 80784 bytes (a decrease of 12863 bytes, i.e. 13.74%, in comparison
+ * to the aforementioned 93647 bytes) which are then compressed to 34013 bytes
+ * (an increase of 859 bytes, i.e. 2.59%, in comparison to the aforementioned
+ * 33154 bytes).</p>
+ * <p>Written in <a href="http://es5.github.com/#x4.2.2">the strict variant</a>
+ * of <a href="http://es5.github.com/">ECMA-262 5.1 Edition</a>. Encoded in <a
+ * href="http://tools.ietf.org/html/rfc3629">UTF-8</a>. Follows <a href=
+ * "http://google-styleguide.googlecode.com/svn-history/r76/trunk/javascriptguide.xml"
+ * >Revision 2.28 of the Google JavaScript Style Guide</a> (except for the
+ * discouraged use of the {@code function} tag and the {@code namespace} tag).
+ * 100% typed for the <a href=
+ * "http://closure-compiler.googlecode.com/files/compiler-20120123.tar.gz"
+ * >Closure Compiler Version 1741</a>.</p>
+ * <p>Should you find this software useful, please consider <a href=
+ * "https://paypal.com/cgi-bin/webscr?cmd=_s-xclick&hosted_button_id=JZLW72X8FD4WG"
+ * >a donation</a>.</p>
+ * @author follow.me@RGustBardon (Robert Gust-Bardon)
+ * @supported Tested with:
+ * <ul>
+ * <li><a href="http://nodejs.org/dist/v0.6.10/">Node v0.6.10</a>,</li>
+ * <li><a href="https://github.com/mishoo/UglifyJS/tarball/v1.2.5">UglifyJS
+ * v1.2.5</a>.</li>
+ * </ul>
+ */
+
+/*global console:false, exports:true, module:false, require:false */
+/*jshint sub:true */
+/**
+ * Consolidates null, Boolean, and String values found inside an <abbr title=
+ * "abstract syntax tree">AST</abbr>.
+ * @param {!TSyntacticCodeUnit} oAbstractSyntaxTree An array-like object
+ * representing an <abbr title="abstract syntax tree">AST</abbr>.
+ * @return {!TSyntacticCodeUnit} An array-like object representing an <abbr
+ * title="abstract syntax tree">AST</abbr> with its null, Boolean, and
+ * String values consolidated.
+ */
+// TODO(user) Consolidation of mathematical values found in numeric literals.
+// TODO(user) Unconsolidation.
+// TODO(user) Consolidation of ECMA-262 6th Edition programs.
+// TODO(user) Rewrite in ECMA-262 6th Edition.
+exports['ast_consolidate'] = function(oAbstractSyntaxTree) {
+ 'use strict';
+ /*jshint bitwise:true, curly:true, eqeqeq:true, forin:true, immed:true,
+ latedef:true, newcap:true, noarge:true, noempty:true, nonew:true,
+ onevar:true, plusplus:true, regexp:true, undef:true, strict:true,
+ sub:false, trailing:true */
+
+ var _,
+ /**
+ * A record consisting of data about one or more source elements.
+ * @constructor
+ * @nosideeffects
+ */
+ TSourceElementsData = function() {
+ /**
+ * The category of the elements.
+ * @type {number}
+ * @see ESourceElementCategories
+ */
+ this.nCategory = ESourceElementCategories.N_OTHER;
+ /**
+ * The number of occurrences (within the elements) of each primitive
+ * value that could be consolidated.
+ * @type {!Array.<!Object.<string, number>>}
+ */
+ this.aCount = [];
+ this.aCount[EPrimaryExpressionCategories.N_IDENTIFIER_NAMES] = {};
+ this.aCount[EPrimaryExpressionCategories.N_STRING_LITERALS] = {};
+ this.aCount[EPrimaryExpressionCategories.N_NULL_AND_BOOLEAN_LITERALS] =
+ {};
+ /**
+ * Identifier names found within the elements.
+ * @type {!Array.<string>}
+ */
+ this.aIdentifiers = [];
+ /**
+ * Prefixed representation Strings of each primitive value that could be
+ * consolidated within the elements.
+ * @type {!Array.<string>}
+ */
+ this.aPrimitiveValues = [];
+ },
+ /**
+ * A record consisting of data about a primitive value that could be
+ * consolidated.
+ * @constructor
+ * @nosideeffects
+ */
+ TPrimitiveValue = function() {
+ /**
+ * The difference in the number of terminal symbols between the original
+ * source text and the one with the primitive value consolidated. If the
+ * difference is positive, the primitive value is considered worthwhile.
+ * @type {number}
+ */
+ this.nSaving = 0;
+ /**
+ * An identifier name of the variable that will be declared and assigned
+ * the primitive value if the primitive value is consolidated.
+ * @type {string}
+ */
+ this.sName = '';
+ },
+ /**
+ * A record consisting of data on what to consolidate within the range of
+ * source elements that is currently being considered.
+ * @constructor
+ * @nosideeffects
+ */
+ TSolution = function() {
+ /**
+ * An object whose keys are prefixed representation Strings of each
+ * primitive value that could be consolidated within the elements and
+ * whose values are corresponding data about those primitive values.
+ * @type {!Object.<string, {nSaving: number, sName: string}>}
+ * @see TPrimitiveValue
+ */
+ this.oPrimitiveValues = {};
+ /**
+ * The difference in the number of terminal symbols between the original
+ * source text and the one with all the worthwhile primitive values
+ * consolidated.
+ * @type {number}
+ * @see TPrimitiveValue#nSaving
+ */
+ this.nSavings = 0;
+ },
+ /**
+ * The processor of <abbr title="abstract syntax tree">AST</abbr>s found
+ * in UglifyJS.
+ * @namespace
+ * @type {!TProcessor}
+ */
+ oProcessor = (/** @type {!TProcessor} */ require('./process')),
+ /**
+ * A record consisting of a number of constants that represent the
+ * difference in the number of terminal symbols between a source text with
+ * a modified syntactic code unit and the original one.
+ * @namespace
+ * @type {!Object.<string, number>}
+ */
+ oWeights = {
+ /**
+ * The difference in the number of punctuators required by the bracket
+ * notation and the dot notation.
+ * <p><code>'[]'.length - '.'.length</code></p>
+ * @const
+ * @type {number}
+ */
+ N_PROPERTY_ACCESSOR: 1,
+ /**
+ * The number of punctuators required by a variable declaration with an
+ * initialiser.
+ * <p><code>':'.length + ';'.length</code></p>
+ * @const
+ * @type {number}
+ */
+ N_VARIABLE_DECLARATION: 2,
+ /**
+ * The number of terminal symbols required to introduce a variable
+ * statement (excluding its variable declaration list).
+ * <p><code>'var '.length</code></p>
+ * @const
+ * @type {number}
+ */
+ N_VARIABLE_STATEMENT_AFFIXATION: 4,
+ /**
+ * The number of terminal symbols needed to enclose source elements
+ * within a function call with no argument values to a function with an
+ * empty parameter list.
+ * <p><code>'(function(){}());'.length</code></p>
+ * @const
+ * @type {number}
+ */
+ N_CLOSURE: 17
+ },
+ /**
+ * Categories of primary expressions from which primitive values that
+ * could be consolidated are derivable.
+ * @namespace
+ * @enum {number}
+ */
+ EPrimaryExpressionCategories = {
+ /**
+ * Identifier names used as property accessors.
+ * @type {number}
+ */
+ N_IDENTIFIER_NAMES: 0,
+ /**
+ * String literals.
+ * @type {number}
+ */
+ N_STRING_LITERALS: 1,
+ /**
+ * Null and Boolean literals.
+ * @type {number}
+ */
+ N_NULL_AND_BOOLEAN_LITERALS: 2
+ },
+ /**
+ * Prefixes of primitive values that could be consolidated.
+ * The String values of the prefixes must have same number of characters.
+ * The prefixes must not be used in any properties defined in any version
+ * of <a href=
+ * "http://www.ecma-international.org/publications/standards/Ecma-262.htm"
+ * >ECMA-262</a>.
+ * @namespace
+ * @enum {string}
+ */
+ EValuePrefixes = {
+ /**
+ * Identifies String values.
+ * @type {string}
+ */
+ S_STRING: '#S',
+ /**
+ * Identifies null and Boolean values.
+ * @type {string}
+ */
+ S_SYMBOLIC: '#O'
+ },
+ /**
+ * Categories of source elements in terms of their appropriateness of
+ * having their primitive values consolidated.
+ * @namespace
+ * @enum {number}
+ */
+ ESourceElementCategories = {
+ /**
+ * Identifies a source element that includes the <a href=
+ * "http://es5.github.com/#x12.10">{@code with}</a> statement.
+ * @type {number}
+ */
+ N_WITH: 0,
+ /**
+ * Identifies a source element that includes the <a href=
+ * "http://es5.github.com/#x15.1.2.1">{@code eval}</a> identifier name.
+ * @type {number}
+ */
+ N_EVAL: 1,
+ /**
+ * Identifies a source element that must be excluded from the process
+ * unless its whole scope is examined.
+ * @type {number}
+ */
+ N_EXCLUDABLE: 2,
+ /**
+ * Identifies source elements not posing any problems.
+ * @type {number}
+ */
+ N_OTHER: 3
+ },
+ /**
+ * The list of literals (other than the String ones) whose primitive
+ * values can be consolidated.
+ * @const
+ * @type {!Array.<string>}
+ */
+ A_OTHER_SUBSTITUTABLE_LITERALS = [
+ 'null', // The null literal.
+ 'false', // The Boolean literal {@code false}.
+ 'true' // The Boolean literal {@code true}.
+ ];
+
+ (/**
+ * Consolidates all worthwhile primitive values in a syntactic code unit.
+ * @param {!TSyntacticCodeUnit} oSyntacticCodeUnit An array-like object
+ * representing the branch of the abstract syntax tree representing the
+ * syntactic code unit along with its scope.
+ * @see TPrimitiveValue#nSaving
+ */
+ function fExamineSyntacticCodeUnit(oSyntacticCodeUnit) {
+ var _,
+ /**
+ * Indicates whether the syntactic code unit represents global code.
+ * @type {boolean}
+ */
+ bIsGlobal = 'toplevel' === oSyntacticCodeUnit[0],
+ /**
+ * Indicates whether the whole scope is being examined.
+ * @type {boolean}
+ */
+ bIsWhollyExaminable = !bIsGlobal,
+ /**
+ * An array-like object representing source elements that constitute a
+ * syntactic code unit.
+ * @type {!TSyntacticCodeUnit}
+ */
+ oSourceElements,
+ /**
+ * A record consisting of data about the source element that is
+ * currently being examined.
+ * @type {!TSourceElementsData}
+ */
+ oSourceElementData,
+ /**
+ * The scope of the syntactic code unit.
+ * @type {!TScope}
+ */
+ oScope,
+ /**
+ * An instance of an object that allows the traversal of an <abbr
+ * title="abstract syntax tree">AST</abbr>.
+ * @type {!TWalker}
+ */
+ oWalker,
+ /**
+ * An object encompassing collections of functions used during the
+ * traversal of an <abbr title="abstract syntax tree">AST</abbr>.
+ * @namespace
+ * @type {!Object.<string, !Object.<string, function(...[*])>>}
+ */
+ oWalkers = {
+ /**
+ * A collection of functions used during the surveyance of source
+ * elements.
+ * @namespace
+ * @type {!Object.<string, function(...[*])>}
+ */
+ oSurveySourceElement: {
+ /**#nocode+*/ // JsDoc Toolkit 2.4.0 hides some of the keys.
+ /**
+ * Classifies the source element as excludable if it does not
+ * contain a {@code with} statement or the {@code eval} identifier
+ * name. Adds the identifier of the function and its formal
+ * parameters to the list of identifier names found.
+ * @param {string} sIdentifier The identifier of the function.
+ * @param {!Array.<string>} aFormalParameterList Formal parameters.
+ * @param {!TSyntacticCodeUnit} oFunctionBody Function code.
+ */
+ 'defun': function(
+ sIdentifier,
+ aFormalParameterList,
+ oFunctionBody) {
+ fClassifyAsExcludable();
+ fAddIdentifier(sIdentifier);
+ aFormalParameterList.forEach(fAddIdentifier);
+ },
+ /**
+ * Increments the count of the number of occurrences of the String
+ * value that is equivalent to the sequence of terminal symbols
+ * that constitute the encountered identifier name.
+ * @param {!TSyntacticCodeUnit} oExpression The nonterminal
+ * MemberExpression.
+ * @param {string} sIdentifierName The identifier name used as the
+ * property accessor.
+ * @return {!Array} The encountered branch of an <abbr title=
+ * "abstract syntax tree">AST</abbr> with its nonterminal
+ * MemberExpression traversed.
+ */
+ 'dot': function(oExpression, sIdentifierName) {
+ fCountPrimaryExpression(
+ EPrimaryExpressionCategories.N_IDENTIFIER_NAMES,
+ EValuePrefixes.S_STRING + sIdentifierName);
+ return ['dot', oWalker.walk(oExpression), sIdentifierName];
+ },
+ /**
+ * Adds the optional identifier of the function and its formal
+ * parameters to the list of identifier names found.
+ * @param {?string} sIdentifier The optional identifier of the
+ * function.
+ * @param {!Array.<string>} aFormalParameterList Formal parameters.
+ * @param {!TSyntacticCodeUnit} oFunctionBody Function code.
+ */
+ 'function': function(
+ sIdentifier,
+ aFormalParameterList,
+ oFunctionBody) {
+ if ('string' === typeof sIdentifier) {
+ fAddIdentifier(sIdentifier);
+ }
+ aFormalParameterList.forEach(fAddIdentifier);
+ },
+ /**
+ * Either increments the count of the number of occurrences of the
+ * encountered null or Boolean value or classifies a source element
+ * as containing the {@code eval} identifier name.
+ * @param {string} sIdentifier The identifier encountered.
+ */
+ 'name': function(sIdentifier) {
+ if (-1 !== A_OTHER_SUBSTITUTABLE_LITERALS.indexOf(sIdentifier)) {
+ fCountPrimaryExpression(
+ EPrimaryExpressionCategories.N_NULL_AND_BOOLEAN_LITERALS,
+ EValuePrefixes.S_SYMBOLIC + sIdentifier);
+ } else {
+ if ('eval' === sIdentifier) {
+ oSourceElementData.nCategory =
+ ESourceElementCategories.N_EVAL;
+ }
+ fAddIdentifier(sIdentifier);
+ }
+ },
+ /**
+ * Classifies the source element as excludable if it does not
+ * contain a {@code with} statement or the {@code eval} identifier
+ * name.
+ * @param {TSyntacticCodeUnit} oExpression The expression whose
+ * value is to be returned.
+ */
+ 'return': function(oExpression) {
+ fClassifyAsExcludable();
+ },
+ /**
+ * Increments the count of the number of occurrences of the
+ * encountered String value.
+ * @param {string} sStringValue The String value of the string
+ * literal encountered.
+ */
+ 'string': function(sStringValue) {
+ if (sStringValue.length > 0) {
+ fCountPrimaryExpression(
+ EPrimaryExpressionCategories.N_STRING_LITERALS,
+ EValuePrefixes.S_STRING + sStringValue);
+ }
+ },
+ /**
+ * Adds the identifier reserved for an exception to the list of
+ * identifier names found.
+ * @param {!TSyntacticCodeUnit} oTry A block of code in which an
+ * exception can occur.
+ * @param {Array} aCatch The identifier reserved for an exception
+ * and a block of code to handle the exception.
+ * @param {TSyntacticCodeUnit} oFinally An optional block of code
+ * to be evaluated regardless of whether an exception occurs.
+ */
+ 'try': function(oTry, aCatch, oFinally) {
+ if (Array.isArray(aCatch)) {
+ fAddIdentifier(aCatch[0]);
+ }
+ },
+ /**
+ * Classifies the source element as excludable if it does not
+ * contain a {@code with} statement or the {@code eval} identifier
+ * name. Adds the identifier of each declared variable to the list
+ * of identifier names found.
+ * @param {!Array.<!Array>} aVariableDeclarationList Variable
+ * declarations.
+ */
+ 'var': function(aVariableDeclarationList) {
+ fClassifyAsExcludable();
+ aVariableDeclarationList.forEach(fAddVariable);
+ },
+ /**
+ * Classifies a source element as containing the {@code with}
+ * statement.
+ * @param {!TSyntacticCodeUnit} oExpression An expression whose
+ * value is to be converted to a value of type Object and
+ * become the binding object of a new object environment
+ * record of a new lexical environment in which the statement
+ * is to be executed.
+ * @param {!TSyntacticCodeUnit} oStatement The statement to be
+ * executed in the augmented lexical environment.
+ * @return {!Array} An empty array to stop the traversal.
+ */
+ 'with': function(oExpression, oStatement) {
+ oSourceElementData.nCategory = ESourceElementCategories.N_WITH;
+ return [];
+ }
+ /**#nocode-*/ // JsDoc Toolkit 2.4.0 hides some of the keys.
+ },
+ /**
+ * A collection of functions used while looking for nested functions.
+ * @namespace
+ * @type {!Object.<string, function(...[*])>}
+ */
+ oExamineFunctions: {
+ /**#nocode+*/ // JsDoc Toolkit 2.4.0 hides some of the keys.
+ /**
+ * Orders an examination of a nested function declaration.
+ * @this {!TSyntacticCodeUnit} An array-like object representing
+ * the branch of an <abbr title="abstract syntax tree"
+ * >AST</abbr> representing the syntactic code unit along with
+ * its scope.
+ * @return {!Array} An empty array to stop the traversal.
+ */
+ 'defun': function() {
+ fExamineSyntacticCodeUnit(this);
+ return [];
+ },
+ /**
+ * Orders an examination of a nested function expression.
+ * @this {!TSyntacticCodeUnit} An array-like object representing
+ * the branch of an <abbr title="abstract syntax tree"
+ * >AST</abbr> representing the syntactic code unit along with
+ * its scope.
+ * @return {!Array} An empty array to stop the traversal.
+ */
+ 'function': function() {
+ fExamineSyntacticCodeUnit(this);
+ return [];
+ }
+ /**#nocode-*/ // JsDoc Toolkit 2.4.0 hides some of the keys.
+ }
+ },
+ /**
+ * Records containing data about source elements.
+ * @type {Array.<TSourceElementsData>}
+ */
+ aSourceElementsData = [],
+ /**
+ * The index (in the source text order) of the source element
+ * immediately following a <a href="http://es5.github.com/#x14.1"
+ * >Directive Prologue</a>.
+ * @type {number}
+ */
+ nAfterDirectivePrologue = 0,
+ /**
+ * The index (in the source text order) of the source element that is
+ * currently being considered.
+ * @type {number}
+ */
+ nPosition,
+ /**
+ * The index (in the source text order) of the source element that is
+ * the last element of the range of source elements that is currently
+ * being considered.
+ * @type {(undefined|number)}
+ */
+ nTo,
+ /**
+ * Initiates the traversal of a source element.
+ * @param {!TWalker} oWalker An instance of an object that allows the
+ * traversal of an abstract syntax tree.
+ * @param {!TSyntacticCodeUnit} oSourceElement A source element from
+ * which the traversal should commence.
+ * @return {function(): !TSyntacticCodeUnit} A function that is able to
+ * initiate the traversal from a given source element.
+ */
+ cContext = function(oWalker, oSourceElement) {
+ /**
+ * @return {!TSyntacticCodeUnit} A function that is able to
+ * initiate the traversal from a given source element.
+ */
+ var fLambda = function() {
+ return oWalker.walk(oSourceElement);
+ };
+
+ return fLambda;
+ },
+ /**
+ * Classifies the source element as excludable if it does not
+ * contain a {@code with} statement or the {@code eval} identifier
+ * name.
+ */
+ fClassifyAsExcludable = function() {
+ if (oSourceElementData.nCategory ===
+ ESourceElementCategories.N_OTHER) {
+ oSourceElementData.nCategory =
+ ESourceElementCategories.N_EXCLUDABLE;
+ }
+ },
+ /**
+ * Adds an identifier to the list of identifier names found.
+ * @param {string} sIdentifier The identifier to be added.
+ */
+ fAddIdentifier = function(sIdentifier) {
+ if (-1 === oSourceElementData.aIdentifiers.indexOf(sIdentifier)) {
+ oSourceElementData.aIdentifiers.push(sIdentifier);
+ }
+ },
+ /**
+ * Adds the identifier of a variable to the list of identifier names
+ * found.
+ * @param {!Array} aVariableDeclaration A variable declaration.
+ */
+ fAddVariable = function(aVariableDeclaration) {
+ fAddIdentifier(/** @type {string} */ aVariableDeclaration[0]);
+ },
+ /**
+ * Increments the count of the number of occurrences of the prefixed
+ * String representation attributed to the primary expression.
+ * @param {number} nCategory The category of the primary expression.
+ * @param {string} sName The prefixed String representation attributed
+ * to the primary expression.
+ */
+ fCountPrimaryExpression = function(nCategory, sName) {
+ if (!oSourceElementData.aCount[nCategory].hasOwnProperty(sName)) {
+ oSourceElementData.aCount[nCategory][sName] = 0;
+ if (-1 === oSourceElementData.aPrimitiveValues.indexOf(sName)) {
+ oSourceElementData.aPrimitiveValues.push(sName);
+ }
+ }
+ oSourceElementData.aCount[nCategory][sName] += 1;
+ },
+ /**
+ * Consolidates all worthwhile primitive values in a range of source
+ * elements.
+ * @param {number} nFrom The index (in the source text order) of the
+ * source element that is the first element of the range.
+ * @param {number} nTo The index (in the source text order) of the
+ * source element that is the last element of the range.
+ * @param {boolean} bEnclose Indicates whether the range should be
+ * enclosed within a function call with no argument values to a
+ * function with an empty parameter list if any primitive values
+ * are consolidated.
+ * @see TPrimitiveValue#nSaving
+ */
+ fExamineSourceElements = function(nFrom, nTo, bEnclose) {
+ var _,
+ /**
+ * The index of the last mangled name.
+ * @type {number}
+ */
+ nIndex = oScope.cname,
+ /**
+ * The index of the source element that is currently being
+ * considered.
+ * @type {number}
+ */
+ nPosition,
+ /**
+ * A collection of functions used during the consolidation of
+ * primitive values and identifier names used as property
+ * accessors.
+ * @namespace
+ * @type {!Object.<string, function(...[*])>}
+ */
+ oWalkersTransformers = {
+ /**
+ * If the String value that is equivalent to the sequence of
+ * terminal symbols that constitute the encountered identifier
+ * name is worthwhile, a syntactic conversion from the dot
+ * notation to the bracket notation ensues with that sequence
+ * being substituted by an identifier name to which the value
+ * is assigned.
+ * Applies to property accessors that use the dot notation.
+ * @param {!TSyntacticCodeUnit} oExpression The nonterminal
+ * MemberExpression.
+ * @param {string} sIdentifierName The identifier name used as
+ * the property accessor.
+ * @return {!Array} A syntactic code unit that is equivalent to
+ * the one encountered.
+ * @see TPrimitiveValue#nSaving
+ */
+ 'dot': function(oExpression, sIdentifierName) {
+ /**
+ * The prefixed String value that is equivalent to the
+ * sequence of terminal symbols that constitute the
+ * encountered identifier name.
+ * @type {string}
+ */
+ var sPrefixed = EValuePrefixes.S_STRING + sIdentifierName;
+
+ return oSolutionBest.oPrimitiveValues.hasOwnProperty(
+ sPrefixed) &&
+ oSolutionBest.oPrimitiveValues[sPrefixed].nSaving > 0 ?
+ ['sub',
+ oWalker.walk(oExpression),
+ ['name',
+ oSolutionBest.oPrimitiveValues[sPrefixed].sName]] :
+ ['dot', oWalker.walk(oExpression), sIdentifierName];
+ },
+ /**
+ * If the encountered identifier is a null or Boolean literal
+ * and its value is worthwhile, the identifier is substituted
+ * by an identifier name to which that value is assigned.
+ * Applies to identifier names.
+ * @param {string} sIdentifier The identifier encountered.
+ * @return {!Array} A syntactic code unit that is equivalent to
+ * the one encountered.
+ * @see TPrimitiveValue#nSaving
+ */
+ 'name': function(sIdentifier) {
+ /**
+ * The prefixed representation String of the identifier.
+ * @type {string}
+ */
+ var sPrefixed = EValuePrefixes.S_SYMBOLIC + sIdentifier;
+
+ return [
+ 'name',
+ oSolutionBest.oPrimitiveValues.hasOwnProperty(sPrefixed) &&
+ oSolutionBest.oPrimitiveValues[sPrefixed].nSaving > 0 ?
+ oSolutionBest.oPrimitiveValues[sPrefixed].sName :
+ sIdentifier
+ ];
+ },
+ /**
+ * If the encountered String value is worthwhile, it is
+ * substituted by an identifier name to which that value is
+ * assigned.
+ * Applies to String values.
+ * @param {string} sStringValue The String value of the string
+ * literal encountered.
+ * @return {!Array} A syntactic code unit that is equivalent to
+ * the one encountered.
+ * @see TPrimitiveValue#nSaving
+ */
+ 'string': function(sStringValue) {
+ /**
+ * The prefixed representation String of the primitive value
+ * of the literal.
+ * @type {string}
+ */
+ var sPrefixed =
+ EValuePrefixes.S_STRING + sStringValue;
+
+ return oSolutionBest.oPrimitiveValues.hasOwnProperty(
+ sPrefixed) &&
+ oSolutionBest.oPrimitiveValues[sPrefixed].nSaving > 0 ?
+ ['name',
+ oSolutionBest.oPrimitiveValues[sPrefixed].sName] :
+ ['string', sStringValue];
+ }
+ },
+ /**
+ * Such data on what to consolidate within the range of source
+ * elements that is currently being considered that lead to the
+ * greatest known reduction of the number of the terminal symbols
+ * in comparison to the original source text.
+ * @type {!TSolution}
+ */
+ oSolutionBest = new TSolution(),
+ /**
+ * Data representing an ongoing attempt to find a better
+ * reduction of the number of the terminal symbols in comparison
+ * to the original source text than the best one that is
+ * currently known.
+ * @type {!TSolution}
+ * @see oSolutionBest
+ */
+ oSolutionCandidate = new TSolution(),
+ /**
+ * A record consisting of data about the range of source elements
+ * that is currently being examined.
+ * @type {!TSourceElementsData}
+ */
+ oSourceElementsData = new TSourceElementsData(),
+ /**
+ * Variable declarations for each primitive value that is to be
+ * consolidated within the elements.
+ * @type {!Array.<!Array>}
+ */
+ aVariableDeclarations = [],
+ /**
+ * Augments a list with a prefixed representation String.
+ * @param {!Array.<string>} aList A list that is to be augmented.
+ * @return {function(string)} A function that augments a list
+ * with a prefixed representation String.
+ */
+ cAugmentList = function(aList) {
+ /**
+ * @param {string} sPrefixed Prefixed representation String of
+ * a primitive value that could be consolidated within the
+ * elements.
+ */
+ var fLambda = function(sPrefixed) {
+ if (-1 === aList.indexOf(sPrefixed)) {
+ aList.push(sPrefixed);
+ }
+ };
+
+ return fLambda;
+ },
+ /**
+ * Adds the number of occurrences of a primitive value of a given
+ * category that could be consolidated in the source element with
+ * a given index to the count of occurrences of that primitive
+ * value within the range of source elements that is currently
+ * being considered.
+ * @param {number} nPosition The index (in the source text order)
+ * of a source element.
+ * @param {number} nCategory The category of the primary
+ * expression from which the primitive value is derived.
+ * @return {function(string)} A function that performs the
+ * addition.
+ * @see cAddOccurrencesInCategory
+ */
+ cAddOccurrences = function(nPosition, nCategory) {
+ /**
+ * @param {string} sPrefixed The prefixed representation String
+ * of a primitive value.
+ */
+ var fLambda = function(sPrefixed) {
+ if (!oSourceElementsData.aCount[nCategory].hasOwnProperty(
+ sPrefixed)) {
+ oSourceElementsData.aCount[nCategory][sPrefixed] = 0;
+ }
+ oSourceElementsData.aCount[nCategory][sPrefixed] +=
+ aSourceElementsData[nPosition].aCount[nCategory][
+ sPrefixed];
+ };
+
+ return fLambda;
+ },
+ /**
+ * Adds the number of occurrences of each primitive value of a
+ * given category that could be consolidated in the source
+ * element with a given index to the count of occurrences of that
+ * primitive values within the range of source elements that is
+ * currently being considered.
+ * @param {number} nPosition The index (in the source text order)
+ * of a source element.
+ * @return {function(number)} A function that performs the
+ * addition.
+ * @see fAddOccurrences
+ */
+ cAddOccurrencesInCategory = function(nPosition) {
+ /**
+ * @param {number} nCategory The category of the primary
+ * expression from which the primitive value is derived.
+ */
+ var fLambda = function(nCategory) {
+ Object.keys(
+ aSourceElementsData[nPosition].aCount[nCategory]
+ ).forEach(cAddOccurrences(nPosition, nCategory));
+ };
+
+ return fLambda;
+ },
+ /**
+ * Adds the number of occurrences of each primitive value that
+ * could be consolidated in the source element with a given index
+ * to the count of occurrences of that primitive values within
+ * the range of source elements that is currently being
+ * considered.
+ * @param {number} nPosition The index (in the source text order)
+ * of a source element.
+ */
+ fAddOccurrences = function(nPosition) {
+ Object.keys(aSourceElementsData[nPosition].aCount).forEach(
+ cAddOccurrencesInCategory(nPosition));
+ },
+ /**
+ * Creates a variable declaration for a primitive value if that
+ * primitive value is to be consolidated within the elements.
+ * @param {string} sPrefixed Prefixed representation String of a
+ * primitive value that could be consolidated within the
+ * elements.
+ * @see aVariableDeclarations
+ */
+ cAugmentVariableDeclarations = function(sPrefixed) {
+ if (oSolutionBest.oPrimitiveValues[sPrefixed].nSaving > 0) {
+ aVariableDeclarations.push([
+ oSolutionBest.oPrimitiveValues[sPrefixed].sName,
+ [0 === sPrefixed.indexOf(EValuePrefixes.S_SYMBOLIC) ?
+ 'name' : 'string',
+ sPrefixed.substring(EValuePrefixes.S_SYMBOLIC.length)]
+ ]);
+ }
+ },
+ /**
+ * Sorts primitive values with regard to the difference in the
+ * number of terminal symbols between the original source text
+ * and the one with those primitive values consolidated.
+ * @param {string} sPrefixed0 The prefixed representation String
+ * of the first of the two primitive values that are being
+ * compared.
+ * @param {string} sPrefixed1 The prefixed representation String
+ * of the second of the two primitive values that are being
+ * compared.
+ * @return {number}
+ * <dl>
+ * <dt>-1</dt>
+ * <dd>if the first primitive value must be placed before
+ * the other one,</dd>
+ * <dt>0</dt>
+ * <dd>if the first primitive value may be placed before
+ * the other one,</dd>
+ * <dt>1</dt>
+ * <dd>if the first primitive value must not be placed
+ * before the other one.</dd>
+ * </dl>
+ * @see TSolution.oPrimitiveValues
+ */
+ cSortPrimitiveValues = function(sPrefixed0, sPrefixed1) {
+ /**
+ * The difference between:
+ * <ol>
+ * <li>the difference in the number of terminal symbols
+ * between the original source text and the one with the
+ * first primitive value consolidated, and</li>
+ * <li>the difference in the number of terminal symbols
+ * between the original source text and the one with the
+ * second primitive value consolidated.</li>
+ * </ol>
+ * @type {number}
+ */
+ var nDifference =
+ oSolutionCandidate.oPrimitiveValues[sPrefixed0].nSaving -
+ oSolutionCandidate.oPrimitiveValues[sPrefixed1].nSaving;
+
+ return nDifference > 0 ? -1 : nDifference < 0 ? 1 : 0;
+ },
+ /**
+ * Assigns an identifier name to a primitive value and calculates
+ * whether instances of that primitive value are worth
+ * consolidating.
+ * @param {string} sPrefixed The prefixed representation String
+ * of a primitive value that is being evaluated.
+ */
+ fEvaluatePrimitiveValue = function(sPrefixed) {
+ var _,
+ /**
+ * The index of the last mangled name.
+ * @type {number}
+ */
+ nIndex,
+ /**
+ * The representation String of the primitive value that is
+ * being evaluated.
+ * @type {string}
+ */
+ sName =
+ sPrefixed.substring(EValuePrefixes.S_SYMBOLIC.length),
+ /**
+ * The number of source characters taken up by the
+ * representation String of the primitive value that is
+ * being evaluated.
+ * @type {number}
+ */
+ nLengthOriginal = sName.length,
+ /**
+ * The number of source characters taken up by the
+ * identifier name that could substitute the primitive
+ * value that is being evaluated.
+ * substituted.
+ * @type {number}
+ */
+ nLengthSubstitution,
+ /**
+ * The number of source characters taken up by by the
+ * representation String of the primitive value that is
+ * being evaluated when it is represented by a string
+ * literal.
+ * @type {number}
+ */
+ nLengthString = oProcessor.make_string(sName).length;
+
+ oSolutionCandidate.oPrimitiveValues[sPrefixed] =
+ new TPrimitiveValue();
+ do { // Find an identifier unused in this or any nested scope.
+ nIndex = oScope.cname;
+ oSolutionCandidate.oPrimitiveValues[sPrefixed].sName =
+ oScope.next_mangled();
+ } while (-1 !== oSourceElementsData.aIdentifiers.indexOf(
+ oSolutionCandidate.oPrimitiveValues[sPrefixed].sName));
+ nLengthSubstitution = oSolutionCandidate.oPrimitiveValues[
+ sPrefixed].sName.length;
+ if (0 === sPrefixed.indexOf(EValuePrefixes.S_SYMBOLIC)) {
+ // foo:null, or foo:null;
+ oSolutionCandidate.oPrimitiveValues[sPrefixed].nSaving -=
+ nLengthSubstitution + nLengthOriginal +
+ oWeights.N_VARIABLE_DECLARATION;
+ // null vs foo
+ oSolutionCandidate.oPrimitiveValues[sPrefixed].nSaving +=
+ oSourceElementsData.aCount[
+ EPrimaryExpressionCategories.
+ N_NULL_AND_BOOLEAN_LITERALS][sPrefixed] *
+ (nLengthOriginal - nLengthSubstitution);
+ } else {
+ // foo:'fromCharCode';
+ oSolutionCandidate.oPrimitiveValues[sPrefixed].nSaving -=
+ nLengthSubstitution + nLengthString +
+ oWeights.N_VARIABLE_DECLARATION;
+ // .fromCharCode vs [foo]
+ if (oSourceElementsData.aCount[
+ EPrimaryExpressionCategories.N_IDENTIFIER_NAMES
+ ].hasOwnProperty(sPrefixed)) {
+ oSolutionCandidate.oPrimitiveValues[sPrefixed].nSaving +=
+ oSourceElementsData.aCount[
+ EPrimaryExpressionCategories.N_IDENTIFIER_NAMES
+ ][sPrefixed] *
+ (nLengthOriginal - nLengthSubstitution -
+ oWeights.N_PROPERTY_ACCESSOR);
+ }
+ // 'fromCharCode' vs foo
+ if (oSourceElementsData.aCount[
+ EPrimaryExpressionCategories.N_STRING_LITERALS
+ ].hasOwnProperty(sPrefixed)) {
+ oSolutionCandidate.oPrimitiveValues[sPrefixed].nSaving +=
+ oSourceElementsData.aCount[
+ EPrimaryExpressionCategories.N_STRING_LITERALS
+ ][sPrefixed] *
+ (nLengthString - nLengthSubstitution);
+ }
+ }
+ if (oSolutionCandidate.oPrimitiveValues[sPrefixed].nSaving >
+ 0) {
+ oSolutionCandidate.nSavings +=
+ oSolutionCandidate.oPrimitiveValues[sPrefixed].nSaving;
+ } else {
+ oScope.cname = nIndex; // Free the identifier name.
+ }
+ },
+ /**
+ * Adds a variable declaration to an existing variable statement.
+ * @param {!Array} aVariableDeclaration A variable declaration
+ * with an initialiser.
+ */
+ cAddVariableDeclaration = function(aVariableDeclaration) {
+ (/** @type {!Array} */ oSourceElements[nFrom][1]).unshift(
+ aVariableDeclaration);
+ };
+
+ if (nFrom > nTo) {
+ return;
+ }
+ // If the range is a closure, reuse the closure.
+ if (nFrom === nTo &&
+ 'stat' === oSourceElements[nFrom][0] &&
+ 'call' === oSourceElements[nFrom][1][0] &&
+ 'function' === oSourceElements[nFrom][1][1][0]) {
+ fExamineSyntacticCodeUnit(oSourceElements[nFrom][1][1]);
+ return;
+ }
+ // Create a list of all derived primitive values within the range.
+ for (nPosition = nFrom; nPosition <= nTo; nPosition += 1) {
+ aSourceElementsData[nPosition].aPrimitiveValues.forEach(
+ cAugmentList(oSourceElementsData.aPrimitiveValues));
+ }
+ if (0 === oSourceElementsData.aPrimitiveValues.length) {
+ return;
+ }
+ for (nPosition = nFrom; nPosition <= nTo; nPosition += 1) {
+ // Add the number of occurrences to the total count.
+ fAddOccurrences(nPosition);
+ // Add identifiers of this or any nested scope to the list.
+ aSourceElementsData[nPosition].aIdentifiers.forEach(
+ cAugmentList(oSourceElementsData.aIdentifiers));
+ }
+ // Distribute identifier names among derived primitive values.
+ do { // If there was any progress, find a better distribution.
+ oSolutionBest = oSolutionCandidate;
+ if (Object.keys(oSolutionCandidate.oPrimitiveValues).length > 0) {
+ // Sort primitive values descending by their worthwhileness.
+ oSourceElementsData.aPrimitiveValues.sort(cSortPrimitiveValues);
+ }
+ oSolutionCandidate = new TSolution();
+ oSourceElementsData.aPrimitiveValues.forEach(
+ fEvaluatePrimitiveValue);
+ oScope.cname = nIndex;
+ } while (oSolutionCandidate.nSavings > oSolutionBest.nSavings);
+ // Take the necessity of adding a variable statement into account.
+ if ('var' !== oSourceElements[nFrom][0]) {
+ oSolutionBest.nSavings -= oWeights.N_VARIABLE_STATEMENT_AFFIXATION;
+ }
+ if (bEnclose) {
+ // Take the necessity of forming a closure into account.
+ oSolutionBest.nSavings -= oWeights.N_CLOSURE;
+ }
+ if (oSolutionBest.nSavings > 0) {
+ // Create variable declarations suitable for UglifyJS.
+ Object.keys(oSolutionBest.oPrimitiveValues).forEach(
+ cAugmentVariableDeclarations);
+ // Rewrite expressions that contain worthwhile primitive values.
+ for (nPosition = nFrom; nPosition <= nTo; nPosition += 1) {
+ oWalker = oProcessor.ast_walker();
+ oSourceElements[nPosition] =
+ oWalker.with_walkers(
+ oWalkersTransformers,
+ cContext(oWalker, oSourceElements[nPosition]));
+ }
+ if ('var' === oSourceElements[nFrom][0]) { // Reuse the statement.
+ (/** @type {!Array.<!Array>} */ aVariableDeclarations.reverse(
+ )).forEach(cAddVariableDeclaration);
+ } else { // Add a variable statement.
+ Array.prototype.splice.call(
+ oSourceElements,
+ nFrom,
+ 0,
+ ['var', aVariableDeclarations]);
+ nTo += 1;
+ }
+ if (bEnclose) {
+ // Add a closure.
+ Array.prototype.splice.call(
+ oSourceElements,
+ nFrom,
+ 0,
+ ['stat', ['call', ['function', null, [], []], []]]);
+ // Copy source elements into the closure.
+ for (nPosition = nTo + 1; nPosition > nFrom; nPosition -= 1) {
+ Array.prototype.unshift.call(
+ oSourceElements[nFrom][1][1][3],
+ oSourceElements[nPosition]);
+ }
+ // Remove source elements outside the closure.
+ Array.prototype.splice.call(
+ oSourceElements,
+ nFrom + 1,
+ nTo - nFrom + 1);
+ }
+ }
+ if (bEnclose) {
+ // Restore the availability of identifier names.
+ oScope.cname = nIndex;
+ }
+ };
+
+ oSourceElements = (/** @type {!TSyntacticCodeUnit} */
+ oSyntacticCodeUnit[bIsGlobal ? 1 : 3]);
+ if (0 === oSourceElements.length) {
+ return;
+ }
+ oScope = bIsGlobal ? oSyntacticCodeUnit.scope : oSourceElements.scope;
+ // Skip a Directive Prologue.
+ while (nAfterDirectivePrologue < oSourceElements.length &&
+ 'directive' === oSourceElements[nAfterDirectivePrologue][0]) {
+ nAfterDirectivePrologue += 1;
+ aSourceElementsData.push(null);
+ }
+ if (oSourceElements.length === nAfterDirectivePrologue) {
+ return;
+ }
+ for (nPosition = nAfterDirectivePrologue;
+ nPosition < oSourceElements.length;
+ nPosition += 1) {
+ oSourceElementData = new TSourceElementsData();
+ oWalker = oProcessor.ast_walker();
+ // Classify a source element.
+ // Find its derived primitive values and count their occurrences.
+ // Find all identifiers used (including nested scopes).
+ oWalker.with_walkers(
+ oWalkers.oSurveySourceElement,
+ cContext(oWalker, oSourceElements[nPosition]));
+ // Establish whether the scope is still wholly examinable.
+ bIsWhollyExaminable = bIsWhollyExaminable &&
+ ESourceElementCategories.N_WITH !== oSourceElementData.nCategory &&
+ ESourceElementCategories.N_EVAL !== oSourceElementData.nCategory;
+ aSourceElementsData.push(oSourceElementData);
+ }
+ if (bIsWhollyExaminable) { // Examine the whole scope.
+ fExamineSourceElements(
+ nAfterDirectivePrologue,
+ oSourceElements.length - 1,
+ false);
+ } else { // Examine unexcluded ranges of source elements.
+ for (nPosition = oSourceElements.length - 1;
+ nPosition >= nAfterDirectivePrologue;
+ nPosition -= 1) {
+ oSourceElementData = (/** @type {!TSourceElementsData} */
+ aSourceElementsData[nPosition]);
+ if (ESourceElementCategories.N_OTHER ===
+ oSourceElementData.nCategory) {
+ if ('undefined' === typeof nTo) {
+ nTo = nPosition; // Indicate the end of a range.
+ }
+ // Examine the range if it immediately follows a Directive Prologue.
+ if (nPosition === nAfterDirectivePrologue) {
+ fExamineSourceElements(nPosition, nTo, true);
+ }
+ } else {
+ if ('undefined' !== typeof nTo) {
+ // Examine the range that immediately follows this source element.
+ fExamineSourceElements(nPosition + 1, nTo, true);
+ nTo = void 0; // Obliterate the range.
+ }
+ // Examine nested functions.
+ oWalker = oProcessor.ast_walker();
+ oWalker.with_walkers(
+ oWalkers.oExamineFunctions,
+ cContext(oWalker, oSourceElements[nPosition]));
+ }
+ }
+ }
+ }(oAbstractSyntaxTree = oProcessor.ast_add_scope(oAbstractSyntaxTree)));
+ return oAbstractSyntaxTree;
+};
+/*jshint sub:false */
+
+/* Local Variables: */
+/* mode: js */
+/* coding: utf-8 */
+/* indent-tabs-mode: nil */
+/* tab-width: 2 */
+/* End: */
+/* vim: set ft=javascript fenc=utf-8 et ts=2 sts=2 sw=2: */
+/* :mode=javascript:noTabs=true:tabSize=2:indentSize=2:deepIndent=true: */
+});
+define('uglifyjs/parse-js', ["exports"], function(exports) {
+/***********************************************************************
+
+ A JavaScript tokenizer / parser / beautifier / compressor.
+
+ This version is suitable for Node.js. With minimal changes (the
+ exports stuff) it should work on any JS platform.
+
+ This file contains the tokenizer/parser. It is a port to JavaScript
+ of parse-js [1], a JavaScript parser library written in Common Lisp
+ by Marijn Haverbeke. Thank you Marijn!
+
+ [1] http://marijn.haverbeke.nl/parse-js/
+
+ Exported functions:
+
+ - tokenizer(code) -- returns a function. Call the returned
+ function to fetch the next token.
+
+ - parse(code) -- returns an AST of the given JavaScript code.
+
+ -------------------------------- (C) ---------------------------------
+
+ Author: Mihai Bazon
+ <mihai.bazon@gmail.com>
+ http://mihai.bazon.net/blog
+
+ Distributed under the BSD license:
+
+ Copyright 2010 (c) Mihai Bazon <mihai.bazon@gmail.com>
+ Based on parse-js (http://marijn.haverbeke.nl/parse-js/).
+
+ Redistribution and use in source and binary forms, with or without
+ modification, are permitted provided that the following conditions
+ are met:
+
+ * Redistributions of source code must retain the above
+ copyright notice, this list of conditions and the following
+ disclaimer.
+
+ * Redistributions in binary form must reproduce the above
+ copyright notice, this list of conditions and the following
+ disclaimer in the documentation and/or other materials
+ provided with the distribution.
+
+ THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDER “AS IS” AND ANY
+ EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
+ PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE
+ LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY,
+ OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
+ PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
+ PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+ THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR
+ TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF
+ THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ SUCH DAMAGE.
+
+ ***********************************************************************/
+
+/* -----[ Tokenizer (constants) ]----- */
+
+var KEYWORDS = array_to_hash([
+ "break",
+ "case",
+ "catch",
+ "const",
+ "continue",
+ "debugger",
+ "default",
+ "delete",
+ "do",
+ "else",
+ "finally",
+ "for",
+ "function",
+ "if",
+ "in",
+ "instanceof",
+ "new",
+ "return",
+ "switch",
+ "throw",
+ "try",
+ "typeof",
+ "var",
+ "void",
+ "while",
+ "with"
+]);
+
+var RESERVED_WORDS = array_to_hash([
+ "abstract",
+ "boolean",
+ "byte",
+ "char",
+ "class",
+ "double",
+ "enum",
+ "export",
+ "extends",
+ "final",
+ "float",
+ "goto",
+ "implements",
+ "import",
+ "int",
+ "interface",
+ "long",
+ "native",
+ "package",
+ "private",
+ "protected",
+ "public",
+ "short",
+ "static",
+ "super",
+ "synchronized",
+ "throws",
+ "transient",
+ "volatile"
+]);
+
+var KEYWORDS_BEFORE_EXPRESSION = array_to_hash([
+ "return",
+ "new",
+ "delete",
+ "throw",
+ "else",
+ "case"
+]);
+
+var KEYWORDS_ATOM = array_to_hash([
+ "false",
+ "null",
+ "true",
+ "undefined"
+]);
+
+var OPERATOR_CHARS = array_to_hash(characters("+-*&%=<>!?|~^"));
+
+var RE_HEX_NUMBER = /^0x[0-9a-f]+$/i;
+var RE_OCT_NUMBER = /^0[0-7]+$/;
+var RE_DEC_NUMBER = /^\d*\.?\d*(?:e[+-]?\d*(?:\d\.?|\.?\d)\d*)?$/i;
+
+var OPERATORS = array_to_hash([
+ "in",
+ "instanceof",
+ "typeof",
+ "new",
+ "void",
+ "delete",
+ "++",
+ "--",
+ "+",
+ "-",
+ "!",
+ "~",
+ "&",
+ "|",
+ "^",
+ "*",
+ "/",
+ "%",
+ ">>",
+ "<<",
+ ">>>",
+ "<",
+ ">",
+ "<=",
+ ">=",
+ "==",
+ "===",
+ "!=",
+ "!==",
+ "?",
+ "=",
+ "+=",
+ "-=",
+ "/=",
+ "*=",
+ "%=",
+ ">>=",
+ "<<=",
+ ">>>=",
+ "|=",
+ "^=",
+ "&=",
+ "&&",
+ "||"
+]);
+
+var WHITESPACE_CHARS = array_to_hash(characters(" \u00a0\n\r\t\f\u000b\u200b\u180e\u2000\u2001\u2002\u2003\u2004\u2005\u2006\u2007\u2008\u2009\u200a\u202f\u205f\u3000\uFEFF"));
+
+var PUNC_BEFORE_EXPRESSION = array_to_hash(characters("[{(,.;:"));
+
+var PUNC_CHARS = array_to_hash(characters("[]{}(),;:"));
+
+var REGEXP_MODIFIERS = array_to_hash(characters("gmsiy"));
+
+/* -----[ Tokenizer ]----- */
+
+var UNICODE = { // Unicode 6.1
+ letter: new RegExp("[\\u0041-\\u005A\\u0061-\\u007A\\u00AA\\u00B5\\u00BA\\u00C0-\\u00D6\\u00D8-\\u00F6\\u00F8-\\u02C1\\u02C6-\\u02D1\\u02E0-\\u02E4\\u02EC\\u02EE\\u0370-\\u0374\\u0376\\u0377\\u037A-\\u037D\\u0386\\u0388-\\u038A\\u038C\\u038E-\\u03A1\\u03A3-\\u03F5\\u03F7-\\u0481\\u048A-\\u0527\\u0531-\\u0556\\u0559\\u0561-\\u0587\\u05D0-\\u05EA\\u05F0-\\u05F2\\u0620-\\u064A\\u066E\\u066F\\u0671-\\u06D3\\u06D5\\u06E5\\u06E6\\u06EE\\u06EF\\u06FA-\\u06FC\\u06FF\\u0710\\u0712-\\u072F\\u074D-\\u07A5\\u07B1\\u07CA-\\u07EA\\u07F4\\u07F5\\u07FA\\u0800-\\u0815\\u081A\\u0824\\u0828\\u0840-\\u0858\\u08A0\\u08A2-\\u08AC\\u0904-\\u0939\\u093D\\u0950\\u0958-\\u0961\\u0971-\\u0977\\u0979-\\u097F\\u0985-\\u098C\\u098F\\u0990\\u0993-\\u09A8\\u09AA-\\u09B0\\u09B2\\u09B6-\\u09B9\\u09BD\\u09CE\\u09DC\\u09DD\\u09DF-\\u09E1\\u09F0\\u09F1\\u0A05-\\u0A0A\\u0A0F\\u0A10\\u0A13-\\u0A28\\u0A2A-\\u0A30\\u0A32\\u0A33\\u0A35\\u0A36\\u0A38\\u0A39\\u0A59-\\u0A5C\\u0A5E\\u0A72-\\u0A74\\u0A85-\\u0A8D\\u0A8F-\\u0A91\\u0A93-\\u0AA8\\u0AAA-\\u0AB0\\u0AB2\\u0AB3\\u0AB5-\\u0AB9\\u0ABD\\u0AD0\\u0AE0\\u0AE1\\u0B05-\\u0B0C\\u0B0F\\u0B10\\u0B13-\\u0B28\\u0B2A-\\u0B30\\u0B32\\u0B33\\u0B35-\\u0B39\\u0B3D\\u0B5C\\u0B5D\\u0B5F-\\u0B61\\u0B71\\u0B83\\u0B85-\\u0B8A\\u0B8E-\\u0B90\\u0B92-\\u0B95\\u0B99\\u0B9A\\u0B9C\\u0B9E\\u0B9F\\u0BA3\\u0BA4\\u0BA8-\\u0BAA\\u0BAE-\\u0BB9\\u0BD0\\u0C05-\\u0C0C\\u0C0E-\\u0C10\\u0C12-\\u0C28\\u0C2A-\\u0C33\\u0C35-\\u0C39\\u0C3D\\u0C58\\u0C59\\u0C60\\u0C61\\u0C85-\\u0C8C\\u0C8E-\\u0C90\\u0C92-\\u0CA8\\u0CAA-\\u0CB3\\u0CB5-\\u0CB9\\u0CBD\\u0CDE\\u0CE0\\u0CE1\\u0CF1\\u0CF2\\u0D05-\\u0D0C\\u0D0E-\\u0D10\\u0D12-\\u0D3A\\u0D3D\\u0D4E\\u0D60\\u0D61\\u0D7A-\\u0D7F\\u0D85-\\u0D96\\u0D9A-\\u0DB1\\u0DB3-\\u0DBB\\u0DBD\\u0DC0-\\u0DC6\\u0E01-\\u0E30\\u0E32\\u0E33\\u0E40-\\u0E46\\u0E81\\u0E82\\u0E84\\u0E87\\u0E88\\u0E8A\\u0E8D\\u0E94-\\u0E97\\u0E99-\\u0E9F\\u0EA1-\\u0EA3\\u0EA5\\u0EA7\\u0EAA\\u0EAB\\u0EAD-\\u0EB0\\u0EB2\\u0EB3\\u0EBD\\u0EC0-\\u0EC4\\u0EC6\\u0EDC-\\u0EDF\\u0F00\\u0F40-\\u0F47\\u0F49-\\u0F6C\\u0F88-\\u0F8C\\u1000-\\u102A\\u103F\\u1050-\\u1055\\u105A-\\u105D\\u1061\\u1065\\u1066\\u106E-\\u1070\\u1075-\\u1081\\u108E\\u10A0-\\u10C5\\u10C7\\u10CD\\u10D0-\\u10FA\\u10FC-\\u1248\\u124A-\\u124D\\u1250-\\u1256\\u1258\\u125A-\\u125D\\u1260-\\u1288\\u128A-\\u128D\\u1290-\\u12B0\\u12B2-\\u12B5\\u12B8-\\u12BE\\u12C0\\u12C2-\\u12C5\\u12C8-\\u12D6\\u12D8-\\u1310\\u1312-\\u1315\\u1318-\\u135A\\u1380-\\u138F\\u13A0-\\u13F4\\u1401-\\u166C\\u166F-\\u167F\\u1681-\\u169A\\u16A0-\\u16EA\\u16EE-\\u16F0\\u1700-\\u170C\\u170E-\\u1711\\u1720-\\u1731\\u1740-\\u1751\\u1760-\\u176C\\u176E-\\u1770\\u1780-\\u17B3\\u17D7\\u17DC\\u1820-\\u1877\\u1880-\\u18A8\\u18AA\\u18B0-\\u18F5\\u1900-\\u191C\\u1950-\\u196D\\u1970-\\u1974\\u1980-\\u19AB\\u19C1-\\u19C7\\u1A00-\\u1A16\\u1A20-\\u1A54\\u1AA7\\u1B05-\\u1B33\\u1B45-\\u1B4B\\u1B83-\\u1BA0\\u1BAE\\u1BAF\\u1BBA-\\u1BE5\\u1C00-\\u1C23\\u1C4D-\\u1C4F\\u1C5A-\\u1C7D\\u1CE9-\\u1CEC\\u1CEE-\\u1CF1\\u1CF5\\u1CF6\\u1D00-\\u1DBF\\u1E00-\\u1F15\\u1F18-\\u1F1D\\u1F20-\\u1F45\\u1F48-\\u1F4D\\u1F50-\\u1F57\\u1F59\\u1F5B\\u1F5D\\u1F5F-\\u1F7D\\u1F80-\\u1FB4\\u1FB6-\\u1FBC\\u1FBE\\u1FC2-\\u1FC4\\u1FC6-\\u1FCC\\u1FD0-\\u1FD3\\u1FD6-\\u1FDB\\u1FE0-\\u1FEC\\u1FF2-\\u1FF4\\u1FF6-\\u1FFC\\u2071\\u207F\\u2090-\\u209C\\u2102\\u2107\\u210A-\\u2113\\u2115\\u2119-\\u211D\\u2124\\u2126\\u2128\\u212A-\\u212D\\u212F-\\u2139\\u213C-\\u213F\\u2145-\\u2149\\u214E\\u2160-\\u2188\\u2C00-\\u2C2E\\u2C30-\\u2C5E\\u2C60-\\u2CE4\\u2CEB-\\u2CEE\\u2CF2\\u2CF3\\u2D00-\\u2D25\\u2D27\\u2D2D\\u2D30-\\u2D67\\u2D6F\\u2D80-\\u2D96\\u2DA0-\\u2DA6\\u2DA8-\\u2DAE\\u2DB0-\\u2DB6\\u2DB8-\\u2DBE\\u2DC0-\\u2DC6\\u2DC8-\\u2DCE\\u2DD0-\\u2DD6\\u2DD8-\\u2DDE\\u2E2F\\u3005-\\u3007\\u3021-\\u3029\\u3031-\\u3035\\u3038-\\u303C\\u3041-\\u3096\\u309D-\\u309F\\u30A1-\\u30FA\\u30FC-\\u30FF\\u3105-\\u312D\\u3131-\\u318E\\u31A0-\\u31BA\\u31F0-\\u31FF\\u3400-\\u4DB5\\u4E00-\\u9FCC\\uA000-\\uA48C\\uA4D0-\\uA4FD\\uA500-\\uA60C\\uA610-\\uA61F\\uA62A\\uA62B\\uA640-\\uA66E\\uA67F-\\uA697\\uA6A0-\\uA6EF\\uA717-\\uA71F\\uA722-\\uA788\\uA78B-\\uA78E\\uA790-\\uA793\\uA7A0-\\uA7AA\\uA7F8-\\uA801\\uA803-\\uA805\\uA807-\\uA80A\\uA80C-\\uA822\\uA840-\\uA873\\uA882-\\uA8B3\\uA8F2-\\uA8F7\\uA8FB\\uA90A-\\uA925\\uA930-\\uA946\\uA960-\\uA97C\\uA984-\\uA9B2\\uA9CF\\uAA00-\\uAA28\\uAA40-\\uAA42\\uAA44-\\uAA4B\\uAA60-\\uAA76\\uAA7A\\uAA80-\\uAAAF\\uAAB1\\uAAB5\\uAAB6\\uAAB9-\\uAABD\\uAAC0\\uAAC2\\uAADB-\\uAADD\\uAAE0-\\uAAEA\\uAAF2-\\uAAF4\\uAB01-\\uAB06\\uAB09-\\uAB0E\\uAB11-\\uAB16\\uAB20-\\uAB26\\uAB28-\\uAB2E\\uABC0-\\uABE2\\uAC00-\\uD7A3\\uD7B0-\\uD7C6\\uD7CB-\\uD7FB\\uF900-\\uFA6D\\uFA70-\\uFAD9\\uFB00-\\uFB06\\uFB13-\\uFB17\\uFB1D\\uFB1F-\\uFB28\\uFB2A-\\uFB36\\uFB38-\\uFB3C\\uFB3E\\uFB40\\uFB41\\uFB43\\uFB44\\uFB46-\\uFBB1\\uFBD3-\\uFD3D\\uFD50-\\uFD8F\\uFD92-\\uFDC7\\uFDF0-\\uFDFB\\uFE70-\\uFE74\\uFE76-\\uFEFC\\uFF21-\\uFF3A\\uFF41-\\uFF5A\\uFF66-\\uFFBE\\uFFC2-\\uFFC7\\uFFCA-\\uFFCF\\uFFD2-\\uFFD7\\uFFDA-\\uFFDC]"),
+ combining_mark: new RegExp("[\\u0300-\\u036F\\u0483-\\u0487\\u0591-\\u05BD\\u05BF\\u05C1\\u05C2\\u05C4\\u05C5\\u05C7\\u0610-\\u061A\\u064B-\\u065F\\u0670\\u06D6-\\u06DC\\u06DF-\\u06E4\\u06E7\\u06E8\\u06EA-\\u06ED\\u0711\\u0730-\\u074A\\u07A6-\\u07B0\\u07EB-\\u07F3\\u0816-\\u0819\\u081B-\\u0823\\u0825-\\u0827\\u0829-\\u082D\\u0859-\\u085B\\u08E4-\\u08FE\\u0900-\\u0903\\u093A-\\u093C\\u093E-\\u094F\\u0951-\\u0957\\u0962\\u0963\\u0981-\\u0983\\u09BC\\u09BE-\\u09C4\\u09C7\\u09C8\\u09CB-\\u09CD\\u09D7\\u09E2\\u09E3\\u0A01-\\u0A03\\u0A3C\\u0A3E-\\u0A42\\u0A47\\u0A48\\u0A4B-\\u0A4D\\u0A51\\u0A70\\u0A71\\u0A75\\u0A81-\\u0A83\\u0ABC\\u0ABE-\\u0AC5\\u0AC7-\\u0AC9\\u0ACB-\\u0ACD\\u0AE2\\u0AE3\\u0B01-\\u0B03\\u0B3C\\u0B3E-\\u0B44\\u0B47\\u0B48\\u0B4B-\\u0B4D\\u0B56\\u0B57\\u0B62\\u0B63\\u0B82\\u0BBE-\\u0BC2\\u0BC6-\\u0BC8\\u0BCA-\\u0BCD\\u0BD7\\u0C01-\\u0C03\\u0C3E-\\u0C44\\u0C46-\\u0C48\\u0C4A-\\u0C4D\\u0C55\\u0C56\\u0C62\\u0C63\\u0C82\\u0C83\\u0CBC\\u0CBE-\\u0CC4\\u0CC6-\\u0CC8\\u0CCA-\\u0CCD\\u0CD5\\u0CD6\\u0CE2\\u0CE3\\u0D02\\u0D03\\u0D3E-\\u0D44\\u0D46-\\u0D48\\u0D4A-\\u0D4D\\u0D57\\u0D62\\u0D63\\u0D82\\u0D83\\u0DCA\\u0DCF-\\u0DD4\\u0DD6\\u0DD8-\\u0DDF\\u0DF2\\u0DF3\\u0E31\\u0E34-\\u0E3A\\u0E47-\\u0E4E\\u0EB1\\u0EB4-\\u0EB9\\u0EBB\\u0EBC\\u0EC8-\\u0ECD\\u0F18\\u0F19\\u0F35\\u0F37\\u0F39\\u0F3E\\u0F3F\\u0F71-\\u0F84\\u0F86\\u0F87\\u0F8D-\\u0F97\\u0F99-\\u0FBC\\u0FC6\\u102B-\\u103E\\u1056-\\u1059\\u105E-\\u1060\\u1062-\\u1064\\u1067-\\u106D\\u1071-\\u1074\\u1082-\\u108D\\u108F\\u109A-\\u109D\\u135D-\\u135F\\u1712-\\u1714\\u1732-\\u1734\\u1752\\u1753\\u1772\\u1773\\u17B4-\\u17D3\\u17DD\\u180B-\\u180D\\u18A9\\u1920-\\u192B\\u1930-\\u193B\\u19B0-\\u19C0\\u19C8\\u19C9\\u1A17-\\u1A1B\\u1A55-\\u1A5E\\u1A60-\\u1A7C\\u1A7F\\u1B00-\\u1B04\\u1B34-\\u1B44\\u1B6B-\\u1B73\\u1B80-\\u1B82\\u1BA1-\\u1BAD\\u1BE6-\\u1BF3\\u1C24-\\u1C37\\u1CD0-\\u1CD2\\u1CD4-\\u1CE8\\u1CED\\u1CF2-\\u1CF4\\u1DC0-\\u1DE6\\u1DFC-\\u1DFF\\u20D0-\\u20DC\\u20E1\\u20E5-\\u20F0\\u2CEF-\\u2CF1\\u2D7F\\u2DE0-\\u2DFF\\u302A-\\u302F\\u3099\\u309A\\uA66F\\uA674-\\uA67D\\uA69F\\uA6F0\\uA6F1\\uA802\\uA806\\uA80B\\uA823-\\uA827\\uA880\\uA881\\uA8B4-\\uA8C4\\uA8E0-\\uA8F1\\uA926-\\uA92D\\uA947-\\uA953\\uA980-\\uA983\\uA9B3-\\uA9C0\\uAA29-\\uAA36\\uAA43\\uAA4C\\uAA4D\\uAA7B\\uAAB0\\uAAB2-\\uAAB4\\uAAB7\\uAAB8\\uAABE\\uAABF\\uAAC1\\uAAEB-\\uAAEF\\uAAF5\\uAAF6\\uABE3-\\uABEA\\uABEC\\uABED\\uFB1E\\uFE00-\\uFE0F\\uFE20-\\uFE26]"),
+ connector_punctuation: new RegExp("[\\u005F\\u203F\\u2040\\u2054\\uFE33\\uFE34\\uFE4D-\\uFE4F\\uFF3F]"),
+ digit: new RegExp("[\\u0030-\\u0039\\u0660-\\u0669\\u06F0-\\u06F9\\u07C0-\\u07C9\\u0966-\\u096F\\u09E6-\\u09EF\\u0A66-\\u0A6F\\u0AE6-\\u0AEF\\u0B66-\\u0B6F\\u0BE6-\\u0BEF\\u0C66-\\u0C6F\\u0CE6-\\u0CEF\\u0D66-\\u0D6F\\u0E50-\\u0E59\\u0ED0-\\u0ED9\\u0F20-\\u0F29\\u1040-\\u1049\\u1090-\\u1099\\u17E0-\\u17E9\\u1810-\\u1819\\u1946-\\u194F\\u19D0-\\u19D9\\u1A80-\\u1A89\\u1A90-\\u1A99\\u1B50-\\u1B59\\u1BB0-\\u1BB9\\u1C40-\\u1C49\\u1C50-\\u1C59\\uA620-\\uA629\\uA8D0-\\uA8D9\\uA900-\\uA909\\uA9D0-\\uA9D9\\uAA50-\\uAA59\\uABF0-\\uABF9\\uFF10-\\uFF19]")
+};
+
+function is_letter(ch) {
+ return UNICODE.letter.test(ch);
+};
+
+function is_digit(ch) {
+ ch = ch.charCodeAt(0);
+ return ch >= 48 && ch <= 57;
+};
+
+function is_unicode_digit(ch) {
+ return UNICODE.digit.test(ch);
+}
+
+function is_alphanumeric_char(ch) {
+ return is_digit(ch) || is_letter(ch);
+};
+
+function is_unicode_combining_mark(ch) {
+ return UNICODE.combining_mark.test(ch);
+};
+
+function is_unicode_connector_punctuation(ch) {
+ return UNICODE.connector_punctuation.test(ch);
+};
+
+function is_identifier_start(ch) {
+ return ch == "$" || ch == "_" || is_letter(ch);
+};
+
+function is_identifier_char(ch) {
+ return is_identifier_start(ch)
+ || is_unicode_combining_mark(ch)
+ || is_unicode_digit(ch)
+ || is_unicode_connector_punctuation(ch)
+ || ch == "\u200c" // zero-width non-joiner <ZWNJ>
+ || ch == "\u200d" // zero-width joiner <ZWJ> (in my ECMA-262 PDF, this is also 200c)
+ ;
+};
+
+function parse_js_number(num) {
+ if (RE_HEX_NUMBER.test(num)) {
+ return parseInt(num.substr(2), 16);
+ } else if (RE_OCT_NUMBER.test(num)) {
+ return parseInt(num.substr(1), 8);
+ } else if (RE_DEC_NUMBER.test(num)) {
+ return parseFloat(num);
+ }
+};
+
+function JS_Parse_Error(message, line, col, pos) {
+ this.message = message;
+ this.line = line + 1;
+ this.col = col + 1;
+ this.pos = pos + 1;
+ this.stack = new Error().stack;
+};
+
+JS_Parse_Error.prototype.toString = function() {
+ return this.message + " (line: " + this.line + ", col: " + this.col + ", pos: " + this.pos + ")" + "\n\n" + this.stack;
+};
+
+function js_error(message, line, col, pos) {
+ throw new JS_Parse_Error(message, line, col, pos);
+};
+
+function is_token(token, type, val) {
+ return token.type == type && (val == null || token.value == val);
+};
+
+var EX_EOF = {};
+
+function tokenizer($TEXT) {
+
+ var S = {
+ text : $TEXT.replace(/\r\n?|[\n\u2028\u2029]/g, "\n").replace(/^\uFEFF/, ''),
+ pos : 0,
+ tokpos : 0,
+ line : 0,
+ tokline : 0,
+ col : 0,
+ tokcol : 0,
+ newline_before : false,
+ regex_allowed : false,
+ comments_before : []
+ };
+
+ function peek() { return S.text.charAt(S.pos); };
+
+ function next(signal_eof, in_string) {
+ var ch = S.text.charAt(S.pos++);
+ if (signal_eof && !ch)
+ throw EX_EOF;
+ if (ch == "\n") {
+ S.newline_before = S.newline_before || !in_string;
+ ++S.line;
+ S.col = 0;
+ } else {
+ ++S.col;
+ }
+ return ch;
+ };
+
+ function eof() {
+ return !S.peek();
+ };
+
+ function find(what, signal_eof) {
+ var pos = S.text.indexOf(what, S.pos);
+ if (signal_eof && pos == -1) throw EX_EOF;
+ return pos;
+ };
+
+ function start_token() {
+ S.tokline = S.line;
+ S.tokcol = S.col;
+ S.tokpos = S.pos;
+ };
+
+ function token(type, value, is_comment) {
+ S.regex_allowed = ((type == "operator" && !HOP(UNARY_POSTFIX, value)) ||
+ (type == "keyword" && HOP(KEYWORDS_BEFORE_EXPRESSION, value)) ||
+ (type == "punc" && HOP(PUNC_BEFORE_EXPRESSION, value)));
+ var ret = {
+ type : type,
+ value : value,
+ line : S.tokline,
+ col : S.tokcol,
+ pos : S.tokpos,
+ endpos : S.pos,
+ nlb : S.newline_before
+ };
+ if (!is_comment) {
+ ret.comments_before = S.comments_before;
+ S.comments_before = [];
+ // make note of any newlines in the comments that came before
+ for (var i = 0, len = ret.comments_before.length; i < len; i++) {
+ ret.nlb = ret.nlb || ret.comments_before[i].nlb;
+ }
+ }
+ S.newline_before = false;
+ return ret;
+ };
+
+ function skip_whitespace() {
+ while (HOP(WHITESPACE_CHARS, peek()))
+ next();
+ };
+
+ function read_while(pred) {
+ var ret = "", ch = peek(), i = 0;
+ while (ch && pred(ch, i++)) {
+ ret += next();
+ ch = peek();
+ }
+ return ret;
+ };
+
+ function parse_error(err) {
+ js_error(err, S.tokline, S.tokcol, S.tokpos);
+ };
+
+ function read_num(prefix) {
+ var has_e = false, after_e = false, has_x = false, has_dot = prefix == ".";
+ var num = read_while(function(ch, i){
+ if (ch == "x" || ch == "X") {
+ if (has_x) return false;
+ return has_x = true;
+ }
+ if (!has_x && (ch == "E" || ch == "e")) {
+ if (has_e) return false;
+ return has_e = after_e = true;
+ }
+ if (ch == "-") {
+ if (after_e || (i == 0 && !prefix)) return true;
+ return false;
+ }
+ if (ch == "+") return after_e;
+ after_e = false;
+ if (ch == ".") {
+ if (!has_dot && !has_x && !has_e)
+ return has_dot = true;
+ return false;
+ }
+ return is_alphanumeric_char(ch);
+ });
+ if (prefix)
+ num = prefix + num;
+ var valid = parse_js_number(num);
+ if (!isNaN(valid)) {
+ return token("num", valid);
+ } else {
+ parse_error("Invalid syntax: " + num);
+ }
+ };
+
+ function read_escaped_char(in_string) {
+ var ch = next(true, in_string);
+ switch (ch) {
+ case "n" : return "\n";
+ case "r" : return "\r";
+ case "t" : return "\t";
+ case "b" : return "\b";
+ case "v" : return "\u000b";
+ case "f" : return "\f";
+ case "0" : return "\0";
+ case "x" : return String.fromCharCode(hex_bytes(2));
+ case "u" : return String.fromCharCode(hex_bytes(4));
+ case "\n": return "";
+ default : return ch;
+ }
+ };
+
+ function hex_bytes(n) {
+ var num = 0;
+ for (; n > 0; --n) {
+ var digit = parseInt(next(true), 16);
+ if (isNaN(digit))
+ parse_error("Invalid hex-character pattern in string");
+ num = (num << 4) | digit;
+ }
+ return num;
+ };
+
+ function read_string() {
+ return with_eof_error("Unterminated string constant", function(){
+ var quote = next(), ret = "";
+ for (;;) {
+ var ch = next(true);
+ if (ch == "\\") {
+ // read OctalEscapeSequence (XXX: deprecated if "strict mode")
+ // https://github.com/mishoo/UglifyJS/issues/178
+ var octal_len = 0, first = null;
+ ch = read_while(function(ch){
+ if (ch >= "0" && ch <= "7") {
+ if (!first) {
+ first = ch;
+ return ++octal_len;
+ }
+ else if (first <= "3" && octal_len <= 2) return ++octal_len;
+ else if (first >= "4" && octal_len <= 1) return ++octal_len;
+ }
+ return false;
+ });
+ if (octal_len > 0) ch = String.fromCharCode(parseInt(ch, 8));
+ else ch = read_escaped_char(true);
+ }
+ else if (ch == quote) break;
+ else if (ch == "\n") throw EX_EOF;
+ ret += ch;
+ }
+ return token("string", ret);
+ });
+ };
+
+ function read_line_comment() {
+ next();
+ var i = find("\n"), ret;
+ if (i == -1) {
+ ret = S.text.substr(S.pos);
+ S.pos = S.text.length;
+ } else {
+ ret = S.text.substring(S.pos, i);
+ S.pos = i;
+ }
+ return token("comment1", ret, true);
+ };
+
+ function read_multiline_comment() {
+ next();
+ return with_eof_error("Unterminated multiline comment", function(){
+ var i = find("*/", true),
+ text = S.text.substring(S.pos, i);
+ S.pos = i + 2;
+ S.line += text.split("\n").length - 1;
+ S.newline_before = S.newline_before || text.indexOf("\n") >= 0;
+
+ // https://github.com/mishoo/UglifyJS/issues/#issue/100
+ if (/^@cc_on/i.test(text)) {
+ warn("WARNING: at line " + S.line);
+ warn("*** Found \"conditional comment\": " + text);
+ warn("*** UglifyJS DISCARDS ALL COMMENTS. This means your code might no longer work properly in Internet Explorer.");
+ }
+
+ return token("comment2", text, true);
+ });
+ };
+
+ function read_name() {
+ var backslash = false, name = "", ch, escaped = false, hex;
+ while ((ch = peek()) != null) {
+ if (!backslash) {
+ if (ch == "\\") escaped = backslash = true, next();
+ else if (is_identifier_char(ch)) name += next();
+ else break;
+ }
+ else {
+ if (ch != "u") parse_error("Expecting UnicodeEscapeSequence -- uXXXX");
+ ch = read_escaped_char();
+ if (!is_identifier_char(ch)) parse_error("Unicode char: " + ch.charCodeAt(0) + " is not valid in identifier");
+ name += ch;
+ backslash = false;
+ }
+ }
+ if (HOP(KEYWORDS, name) && escaped) {
+ hex = name.charCodeAt(0).toString(16).toUpperCase();
+ name = "\\u" + "0000".substr(hex.length) + hex + name.slice(1);
+ }
+ return name;
+ };
+
+ function read_regexp(regexp) {
+ return with_eof_error("Unterminated regular expression", function(){
+ var prev_backslash = false, ch, in_class = false;
+ while ((ch = next(true))) if (prev_backslash) {
+ regexp += "\\" + ch;
+ prev_backslash = false;
+ } else if (ch == "[") {
+ in_class = true;
+ regexp += ch;
+ } else if (ch == "]" && in_class) {
+ in_class = false;
+ regexp += ch;
+ } else if (ch == "/" && !in_class) {
+ break;
+ } else if (ch == "\\") {
+ prev_backslash = true;
+ } else {
+ regexp += ch;
+ }
+ var mods = read_name();
+ return token("regexp", [ regexp, mods ]);
+ });
+ };
+
+ function read_operator(prefix) {
+ function grow(op) {
+ if (!peek()) return op;
+ var bigger = op + peek();
+ if (HOP(OPERATORS, bigger)) {
+ next();
+ return grow(bigger);
+ } else {
+ return op;
+ }
+ };
+ return token("operator", grow(prefix || next()));
+ };
+
+ function handle_slash() {
+ next();
+ var regex_allowed = S.regex_allowed;
+ switch (peek()) {
+ case "/":
+ S.comments_before.push(read_line_comment());
+ S.regex_allowed = regex_allowed;
+ return next_token();
+ case "*":
+ S.comments_before.push(read_multiline_comment());
+ S.regex_allowed = regex_allowed;
+ return next_token();
+ }
+ return S.regex_allowed ? read_regexp("") : read_operator("/");
+ };
+
+ function handle_dot() {
+ next();
+ return is_digit(peek())
+ ? read_num(".")
+ : token("punc", ".");
+ };
+
+ function read_word() {
+ var word = read_name();
+ return !HOP(KEYWORDS, word)
+ ? token("name", word)
+ : HOP(OPERATORS, word)
+ ? token("operator", word)
+ : HOP(KEYWORDS_ATOM, word)
+ ? token("atom", word)
+ : token("keyword", word);
+ };
+
+ function with_eof_error(eof_error, cont) {
+ try {
+ return cont();
+ } catch(ex) {
+ if (ex === EX_EOF) parse_error(eof_error);
+ else throw ex;
+ }
+ };
+
+ function next_token(force_regexp) {
+ if (force_regexp != null)
+ return read_regexp(force_regexp);
+ skip_whitespace();
+ start_token();
+ var ch = peek();
+ if (!ch) return token("eof");
+ if (is_digit(ch)) return read_num();
+ if (ch == '"' || ch == "'") return read_string();
+ if (HOP(PUNC_CHARS, ch)) return token("punc", next());
+ if (ch == ".") return handle_dot();
+ if (ch == "/") return handle_slash();
+ if (HOP(OPERATOR_CHARS, ch)) return read_operator();
+ if (ch == "\\" || is_identifier_start(ch)) return read_word();
+ parse_error("Unexpected character '" + ch + "'");
+ };
+
+ next_token.context = function(nc) {
+ if (nc) S = nc;
+ return S;
+ };
+
+ return next_token;
+
+};
+
+/* -----[ Parser (constants) ]----- */
+
+var UNARY_PREFIX = array_to_hash([
+ "typeof",
+ "void",
+ "delete",
+ "--",
+ "++",
+ "!",
+ "~",
+ "-",
+ "+"
+]);
+
+var UNARY_POSTFIX = array_to_hash([ "--", "++" ]);
+
+var ASSIGNMENT = (function(a, ret, i){
+ while (i < a.length) {
+ ret[a[i]] = a[i].substr(0, a[i].length - 1);
+ i++;
+ }
+ return ret;
+})(
+ ["+=", "-=", "/=", "*=", "%=", ">>=", "<<=", ">>>=", "|=", "^=", "&="],
+ { "=": true },
+ 0
+);
+
+var PRECEDENCE = (function(a, ret){
+ for (var i = 0, n = 1; i < a.length; ++i, ++n) {
+ var b = a[i];
+ for (var j = 0; j < b.length; ++j) {
+ ret[b[j]] = n;
+ }
+ }
+ return ret;
+})(
+ [
+ ["||"],
+ ["&&"],
+ ["|"],
+ ["^"],
+ ["&"],
+ ["==", "===", "!=", "!=="],
+ ["<", ">", "<=", ">=", "in", "instanceof"],
+ [">>", "<<", ">>>"],
+ ["+", "-"],
+ ["*", "/", "%"]
+ ],
+ {}
+);
+
+var STATEMENTS_WITH_LABELS = array_to_hash([ "for", "do", "while", "switch" ]);
+
+var ATOMIC_START_TOKEN = array_to_hash([ "atom", "num", "string", "regexp", "name" ]);
+
+/* -----[ Parser ]----- */
+
+function NodeWithToken(str, start, end) {
+ this.name = str;
+ this.start = start;
+ this.end = end;
+};
+
+NodeWithToken.prototype.toString = function() { return this.name; };
+
+function parse($TEXT, exigent_mode, embed_tokens) {
+
+ var S = {
+ input : typeof $TEXT == "string" ? tokenizer($TEXT, true) : $TEXT,
+ token : null,
+ prev : null,
+ peeked : null,
+ in_function : 0,
+ in_directives : true,
+ in_loop : 0,
+ labels : []
+ };
+
+ S.token = next();
+
+ function is(type, value) {
+ return is_token(S.token, type, value);
+ };
+
+ function peek() { return S.peeked || (S.peeked = S.input()); };
+
+ function next() {
+ S.prev = S.token;
+ if (S.peeked) {
+ S.token = S.peeked;
+ S.peeked = null;
+ } else {
+ S.token = S.input();
+ }
+ S.in_directives = S.in_directives && (
+ S.token.type == "string" || is("punc", ";")
+ );
+ return S.token;
+ };
+
+ function prev() {
+ return S.prev;
+ };
+
+ function croak(msg, line, col, pos) {
+ var ctx = S.input.context();
+ js_error(msg,
+ line != null ? line : ctx.tokline,
+ col != null ? col : ctx.tokcol,
+ pos != null ? pos : ctx.tokpos);
+ };
+
+ function token_error(token, msg) {
+ croak(msg, token.line, token.col);
+ };
+
+ function unexpected(token) {
+ if (token == null)
+ token = S.token;
+ token_error(token, "Unexpected token: " + token.type + " (" + token.value + ")");
+ };
+
+ function expect_token(type, val) {
+ if (is(type, val)) {
+ return next();
+ }
+ token_error(S.token, "Unexpected token " + S.token.type + ", expected " + type);
+ };
+
+ function expect(punc) { return expect_token("punc", punc); };
+
+ function can_insert_semicolon() {
+ return !exigent_mode && (
+ S.token.nlb || is("eof") || is("punc", "}")
+ );
+ };
+
+ function semicolon() {
+ if (is("punc", ";")) next();
+ else if (!can_insert_semicolon()) unexpected();
+ };
+
+ function as() {
+ return slice(arguments);
+ };
+
+ function parenthesised() {
+ expect("(");
+ var ex = expression();
+ expect(")");
+ return ex;
+ };
+
+ function add_tokens(str, start, end) {
+ return str instanceof NodeWithToken ? str : new NodeWithToken(str, start, end);
+ };
+
+ function maybe_embed_tokens(parser) {
+ if (embed_tokens) return function() {
+ var start = S.token;
+ var ast = parser.apply(this, arguments);
+ ast[0] = add_tokens(ast[0], start, prev());
+ return ast;
+ };
+ else return parser;
+ };
+
+ var statement = maybe_embed_tokens(function() {
+ if (is("operator", "/") || is("operator", "/=")) {
+ S.peeked = null;
+ S.token = S.input(S.token.value.substr(1)); // force regexp
+ }
+ switch (S.token.type) {
+ case "string":
+ var dir = S.in_directives, stat = simple_statement();
+ if (dir && stat[1][0] == "string" && !is("punc", ","))
+ return as("directive", stat[1][1]);
+ return stat;
+ case "num":
+ case "regexp":
+ case "operator":
+ case "atom":
+ return simple_statement();
+
+ case "name":
+ return is_token(peek(), "punc", ":")
+ ? labeled_statement(prog1(S.token.value, next, next))
+ : simple_statement();
+
+ case "punc":
+ switch (S.token.value) {
+ case "{":
+ return as("block", block_());
+ case "[":
+ case "(":
+ return simple_statement();
+ case ";":
+ next();
+ return as("block");
+ default:
+ unexpected();
+ }
+
+ case "keyword":
+ switch (prog1(S.token.value, next)) {
+ case "break":
+ return break_cont("break");
+
+ case "continue":
+ return break_cont("continue");
+
+ case "debugger":
+ semicolon();
+ return as("debugger");
+
+ case "do":
+ return (function(body){
+ expect_token("keyword", "while");
+ return as("do", prog1(parenthesised, semicolon), body);
+ })(in_loop(statement));
+
+ case "for":
+ return for_();
+
+ case "function":
+ return function_(true);
+
+ case "if":
+ return if_();
+
+ case "return":
+ if (S.in_function == 0)
+ croak("'return' outside of function");
+ return as("return",
+ is("punc", ";")
+ ? (next(), null)
+ : can_insert_semicolon()
+ ? null
+ : prog1(expression, semicolon));
+
+ case "switch":
+ return as("switch", parenthesised(), switch_block_());
+
+ case "throw":
+ if (S.token.nlb)
+ croak("Illegal newline after 'throw'");
+ return as("throw", prog1(expression, semicolon));
+
+ case "try":
+ return try_();
+
+ case "var":
+ return prog1(var_, semicolon);
+
+ case "const":
+ return prog1(const_, semicolon);
+
+ case "while":
+ return as("while", parenthesised(), in_loop(statement));
+
+ case "with":
+ return as("with", parenthesised(), statement());
+
+ default:
+ unexpected();
+ }
+ }
+ });
+
+ function labeled_statement(label) {
+ S.labels.push(label);
+ var start = S.token, stat = statement();
+ if (exigent_mode && !HOP(STATEMENTS_WITH_LABELS, stat[0]))
+ unexpected(start);
+ S.labels.pop();
+ return as("label", label, stat);
+ };
+
+ function simple_statement() {
+ return as("stat", prog1(expression, semicolon));
+ };
+
+ function break_cont(type) {
+ var name;
+ if (!can_insert_semicolon()) {
+ name = is("name") ? S.token.value : null;
+ }
+ if (name != null) {
+ next();
+ if (!member(name, S.labels))
+ croak("Label " + name + " without matching loop or statement");
+ }
+ else if (S.in_loop == 0)
+ croak(type + " not inside a loop or switch");
+ semicolon();
+ return as(type, name);
+ };
+
+ function for_() {
+ expect("(");
+ var init = null;
+ if (!is("punc", ";")) {
+ init = is("keyword", "var")
+ ? (next(), var_(true))
+ : expression(true, true);
+ if (is("operator", "in")) {
+ if (init[0] == "var" && init[1].length > 1)
+ croak("Only one variable declaration allowed in for..in loop");
+ return for_in(init);
+ }
+ }
+ return regular_for(init);
+ };
+
+ function regular_for(init) {
+ expect(";");
+ var test = is("punc", ";") ? null : expression();
+ expect(";");
+ var step = is("punc", ")") ? null : expression();
+ expect(")");
+ return as("for", init, test, step, in_loop(statement));
+ };
+
+ function for_in(init) {
+ var lhs = init[0] == "var" ? as("name", init[1][0]) : init;
+ next();
+ var obj = expression();
+ expect(")");
+ return as("for-in", init, lhs, obj, in_loop(statement));
+ };
+
+ var function_ = function(in_statement) {
+ var name = is("name") ? prog1(S.token.value, next) : null;
+ if (in_statement && !name)
+ unexpected();
+ expect("(");
+ return as(in_statement ? "defun" : "function",
+ name,
+ // arguments
+ (function(first, a){
+ while (!is("punc", ")")) {
+ if (first) first = false; else expect(",");
+ if (!is("name")) unexpected();
+ a.push(S.token.value);
+ next();
+ }
+ next();
+ return a;
+ })(true, []),
+ // body
+ (function(){
+ ++S.in_function;
+ var loop = S.in_loop;
+ S.in_directives = true;
+ S.in_loop = 0;
+ var a = block_();
+ --S.in_function;
+ S.in_loop = loop;
+ return a;
+ })());
+ };
+
+ function if_() {
+ var cond = parenthesised(), body = statement(), belse;
+ if (is("keyword", "else")) {
+ next();
+ belse = statement();
+ }
+ return as("if", cond, body, belse);
+ };
+
+ function block_() {
+ expect("{");
+ var a = [];
+ while (!is("punc", "}")) {
+ if (is("eof")) unexpected();
+ a.push(statement());
+ }
+ next();
+ return a;
+ };
+
+ var switch_block_ = curry(in_loop, function(){
+ expect("{");
+ var a = [], cur = null;
+ while (!is("punc", "}")) {
+ if (is("eof")) unexpected();
+ if (is("keyword", "case")) {
+ next();
+ cur = [];
+ a.push([ expression(), cur ]);
+ expect(":");
+ }
+ else if (is("keyword", "default")) {
+ next();
+ expect(":");
+ cur = [];
+ a.push([ null, cur ]);
+ }
+ else {
+ if (!cur) unexpected();
+ cur.push(statement());
+ }
+ }
+ next();
+ return a;
+ });
+
+ function try_() {
+ var body = block_(), bcatch, bfinally;
+ if (is("keyword", "catch")) {
+ next();
+ expect("(");
+ if (!is("name"))
+ croak("Name expected");
+ var name = S.token.value;
+ next();
+ expect(")");
+ bcatch = [ name, block_() ];
+ }
+ if (is("keyword", "finally")) {
+ next();
+ bfinally = block_();
+ }
+ if (!bcatch && !bfinally)
+ croak("Missing catch/finally blocks");
+ return as("try", body, bcatch, bfinally);
+ };
+
+ function vardefs(no_in) {
+ var a = [];
+ for (;;) {
+ if (!is("name"))
+ unexpected();
+ var name = S.token.value;
+ next();
+ if (is("operator", "=")) {
+ next();
+ a.push([ name, expression(false, no_in) ]);
+ } else {
+ a.push([ name ]);
+ }
+ if (!is("punc", ","))
+ break;
+ next();
+ }
+ return a;
+ };
+
+ function var_(no_in) {
+ return as("var", vardefs(no_in));
+ };
+
+ function const_() {
+ return as("const", vardefs());
+ };
+
+ function new_() {
+ var newexp = expr_atom(false), args;
+ if (is("punc", "(")) {
+ next();
+ args = expr_list(")");
+ } else {
+ args = [];
+ }
+ return subscripts(as("new", newexp, args), true);
+ };
+
+ var expr_atom = maybe_embed_tokens(function(allow_calls) {
+ if (is("operator", "new")) {
+ next();
+ return new_();
+ }
+ if (is("punc")) {
+ switch (S.token.value) {
+ case "(":
+ next();
+ return subscripts(prog1(expression, curry(expect, ")")), allow_calls);
+ case "[":
+ next();
+ return subscripts(array_(), allow_calls);
+ case "{":
+ next();
+ return subscripts(object_(), allow_calls);
+ }
+ unexpected();
+ }
+ if (is("keyword", "function")) {
+ next();
+ return subscripts(function_(false), allow_calls);
+ }
+ if (HOP(ATOMIC_START_TOKEN, S.token.type)) {
+ var atom = S.token.type == "regexp"
+ ? as("regexp", S.token.value[0], S.token.value[1])
+ : as(S.token.type, S.token.value);
+ return subscripts(prog1(atom, next), allow_calls);
+ }
+ unexpected();
+ });
+
+ function expr_list(closing, allow_trailing_comma, allow_empty) {
+ var first = true, a = [];
+ while (!is("punc", closing)) {
+ if (first) first = false; else expect(",");
+ if (allow_trailing_comma && is("punc", closing)) break;
+ if (is("punc", ",") && allow_empty) {
+ a.push([ "atom", "undefined" ]);
+ } else {
+ a.push(expression(false));
+ }
+ }
+ next();
+ return a;
+ };
+
+ function array_() {
+ return as("array", expr_list("]", !exigent_mode, true));
+ };
+
+ function object_() {
+ var first = true, a = [];
+ while (!is("punc", "}")) {
+ if (first) first = false; else expect(",");
+ if (!exigent_mode && is("punc", "}"))
+ // allow trailing comma
+ break;
+ var type = S.token.type;
+ var name = as_property_name();
+ if (type == "name" && (name == "get" || name == "set") && !is("punc", ":")) {
+ a.push([ as_name(), function_(false), name ]);
+ } else {
+ expect(":");
+ a.push([ name, expression(false) ]);
+ }
+ }
+ next();
+ return as("object", a);
+ };
+
+ function as_property_name() {
+ switch (S.token.type) {
+ case "num":
+ case "string":
+ return prog1(S.token.value, next);
+ }
+ return as_name();
+ };
+
+ function as_name() {
+ switch (S.token.type) {
+ case "name":
+ case "operator":
+ case "keyword":
+ case "atom":
+ return prog1(S.token.value, next);
+ default:
+ unexpected();
+ }
+ };
+
+ function subscripts(expr, allow_calls) {
+ if (is("punc", ".")) {
+ next();
+ return subscripts(as("dot", expr, as_name()), allow_calls);
+ }
+ if (is("punc", "[")) {
+ next();
+ return subscripts(as("sub", expr, prog1(expression, curry(expect, "]"))), allow_calls);
+ }
+ if (allow_calls && is("punc", "(")) {
+ next();
+ return subscripts(as("call", expr, expr_list(")")), true);
+ }
+ return expr;
+ };
+
+ function maybe_unary(allow_calls) {
+ if (is("operator") && HOP(UNARY_PREFIX, S.token.value)) {
+ return make_unary("unary-prefix",
+ prog1(S.token.value, next),
+ maybe_unary(allow_calls));
+ }
+ var val = expr_atom(allow_calls);
+ while (is("operator") && HOP(UNARY_POSTFIX, S.token.value) && !S.token.nlb) {
+ val = make_unary("unary-postfix", S.token.value, val);
+ next();
+ }
+ return val;
+ };
+
+ function make_unary(tag, op, expr) {
+ if ((op == "++" || op == "--") && !is_assignable(expr))
+ croak("Invalid use of " + op + " operator");
+ return as(tag, op, expr);
+ };
+
+ function expr_op(left, min_prec, no_in) {
+ var op = is("operator") ? S.token.value : null;
+ if (op && op == "in" && no_in) op = null;
+ var prec = op != null ? PRECEDENCE[op] : null;
+ if (prec != null && prec > min_prec) {
+ next();
+ var right = expr_op(maybe_unary(true), prec, no_in);
+ return expr_op(as("binary", op, left, right), min_prec, no_in);
+ }
+ return left;
+ };
+
+ function expr_ops(no_in) {
+ return expr_op(maybe_unary(true), 0, no_in);
+ };
+
+ function maybe_conditional(no_in) {
+ var expr = expr_ops(no_in);
+ if (is("operator", "?")) {
+ next();
+ var yes = expression(false);
+ expect(":");
+ return as("conditional", expr, yes, expression(false, no_in));
+ }
+ return expr;
+ };
+
+ function is_assignable(expr) {
+ if (!exigent_mode) return true;
+ switch (expr[0]+"") {
+ case "dot":
+ case "sub":
+ case "new":
+ case "call":
+ return true;
+ case "name":
+ return expr[1] != "this";
+ }
+ };
+
+ function maybe_assign(no_in) {
+ var left = maybe_conditional(no_in), val = S.token.value;
+ if (is("operator") && HOP(ASSIGNMENT, val)) {
+ if (is_assignable(left)) {
+ next();
+ return as("assign", ASSIGNMENT[val], left, maybe_assign(no_in));
+ }
+ croak("Invalid assignment");
+ }
+ return left;
+ };
+
+ var expression = maybe_embed_tokens(function(commas, no_in) {
+ if (arguments.length == 0)
+ commas = true;
+ var expr = maybe_assign(no_in);
+ if (commas && is("punc", ",")) {
+ next();
+ return as("seq", expr, expression(true, no_in));
+ }
+ return expr;
+ });
+
+ function in_loop(cont) {
+ try {
+ ++S.in_loop;
+ return cont();
+ } finally {
+ --S.in_loop;
+ }
+ };
+
+ return as("toplevel", (function(a){
+ while (!is("eof"))
+ a.push(statement());
+ return a;
+ })([]));
+
+};
+
+/* -----[ Utilities ]----- */
+
+function curry(f) {
+ var args = slice(arguments, 1);
+ return function() { return f.apply(this, args.concat(slice(arguments))); };
+};
+
+function prog1(ret) {
+ if (ret instanceof Function)
+ ret = ret();
+ for (var i = 1, n = arguments.length; --n > 0; ++i)
+ arguments[i]();
+ return ret;
+};
+
+function array_to_hash(a) {
+ var ret = {};
+ for (var i = 0; i < a.length; ++i)
+ ret[a[i]] = true;
+ return ret;
+};
+
+function slice(a, start) {
+ return Array.prototype.slice.call(a, start || 0);
+};
+
+function characters(str) {
+ return str.split("");
+};
+
+function member(name, array) {
+ for (var i = array.length; --i >= 0;)
+ if (array[i] == name)
+ return true;
+ return false;
+};
+
+function HOP(obj, prop) {
+ return Object.prototype.hasOwnProperty.call(obj, prop);
+};
+
+var warn = function() {};
+
+/* -----[ Exports ]----- */
+
+exports.tokenizer = tokenizer;
+exports.parse = parse;
+exports.slice = slice;
+exports.curry = curry;
+exports.member = member;
+exports.array_to_hash = array_to_hash;
+exports.PRECEDENCE = PRECEDENCE;
+exports.KEYWORDS_ATOM = KEYWORDS_ATOM;
+exports.RESERVED_WORDS = RESERVED_WORDS;
+exports.KEYWORDS = KEYWORDS;
+exports.ATOMIC_START_TOKEN = ATOMIC_START_TOKEN;
+exports.OPERATORS = OPERATORS;
+exports.is_alphanumeric_char = is_alphanumeric_char;
+exports.is_identifier_start = is_identifier_start;
+exports.is_identifier_char = is_identifier_char;
+exports.set_logger = function(logger) {
+ warn = logger;
+};
+
+// Local variables:
+// js-indent-level: 4
+// End:
+});define('uglifyjs/squeeze-more', ["require", "exports", "module", "./parse-js", "./squeeze-more"], function(require, exports, module) {
+var jsp = require("./parse-js"),
+ pro = require("./process"),
+ slice = jsp.slice,
+ member = jsp.member,
+ curry = jsp.curry,
+ MAP = pro.MAP,
+ PRECEDENCE = jsp.PRECEDENCE,
+ OPERATORS = jsp.OPERATORS;
+
+function ast_squeeze_more(ast) {
+ var w = pro.ast_walker(), walk = w.walk, scope;
+ function with_scope(s, cont) {
+ var save = scope, ret;
+ scope = s;
+ ret = cont();
+ scope = save;
+ return ret;
+ };
+ function _lambda(name, args, body) {
+ return [ this[0], name, args, with_scope(body.scope, curry(MAP, body, walk)) ];
+ };
+ return w.with_walkers({
+ "toplevel": function(body) {
+ return [ this[0], with_scope(this.scope, curry(MAP, body, walk)) ];
+ },
+ "function": _lambda,
+ "defun": _lambda,
+ "new": function(ctor, args) {
+ if (ctor[0] == "name") {
+ if (ctor[1] == "Array" && !scope.has("Array")) {
+ if (args.length != 1) {
+ return [ "array", args ];
+ } else {
+ return walk([ "call", [ "name", "Array" ], args ]);
+ }
+ } else if (ctor[1] == "Object" && !scope.has("Object")) {
+ if (!args.length) {
+ return [ "object", [] ];
+ } else {
+ return walk([ "call", [ "name", "Object" ], args ]);
+ }
+ } else if ((ctor[1] == "RegExp" || ctor[1] == "Function" || ctor[1] == "Error") && !scope.has(ctor[1])) {
+ return walk([ "call", [ "name", ctor[1] ], args]);
+ }
+ }
+ },
+ "call": function(expr, args) {
+ if (expr[0] == "dot" && expr[1][0] == "string" && args.length == 1
+ && (args[0][1] > 0 && expr[2] == "substring" || expr[2] == "substr")) {
+ return [ "call", [ "dot", expr[1], "slice"], args];
+ }
+ if (expr[0] == "dot" && expr[2] == "toString" && args.length == 0) {
+ // foo.toString() ==> foo+""
+ if (expr[1][0] == "string") return expr[1];
+ return [ "binary", "+", expr[1], [ "string", "" ]];
+ }
+ if (expr[0] == "name") {
+ if (expr[1] == "Array" && args.length != 1 && !scope.has("Array")) {
+ return [ "array", args ];
+ }
+ if (expr[1] == "Object" && !args.length && !scope.has("Object")) {
+ return [ "object", [] ];
+ }
+ if (expr[1] == "String" && !scope.has("String")) {
+ return [ "binary", "+", args[0], [ "string", "" ]];
+ }
+ }
+ }
+ }, function() {
+ return walk(pro.ast_add_scope(ast));
+ });
+};
+
+exports.ast_squeeze_more = ast_squeeze_more;
+
+// Local variables:
+// js-indent-level: 4
+// End:
+});
+define('uglifyjs/process', ["require", "exports", "module", "./parse-js", "./squeeze-more"], function(require, exports, module) {
+/***********************************************************************
+
+ A JavaScript tokenizer / parser / beautifier / compressor.
+
+ This version is suitable for Node.js. With minimal changes (the
+ exports stuff) it should work on any JS platform.
+
+ This file implements some AST processors. They work on data built
+ by parse-js.
+
+ Exported functions:
+
+ - ast_mangle(ast, options) -- mangles the variable/function names
+ in the AST. Returns an AST.
+
+ - ast_squeeze(ast) -- employs various optimizations to make the
+ final generated code even smaller. Returns an AST.
+
+ - gen_code(ast, options) -- generates JS code from the AST. Pass
+ true (or an object, see the code for some options) as second
+ argument to get "pretty" (indented) code.
+
+ -------------------------------- (C) ---------------------------------
+
+ Author: Mihai Bazon
+ <mihai.bazon@gmail.com>
+ http://mihai.bazon.net/blog
+
+ Distributed under the BSD license:
+
+ Copyright 2010 (c) Mihai Bazon <mihai.bazon@gmail.com>
+
+ Redistribution and use in source and binary forms, with or without
+ modification, are permitted provided that the following conditions
+ are met:
+
+ * Redistributions of source code must retain the above
+ copyright notice, this list of conditions and the following
+ disclaimer.
+
+ * Redistributions in binary form must reproduce the above
+ copyright notice, this list of conditions and the following
+ disclaimer in the documentation and/or other materials
+ provided with the distribution.
+
+ THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDER “AS IS” AND ANY
+ EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
+ PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE
+ LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY,
+ OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
+ PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
+ PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+ THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR
+ TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF
+ THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ SUCH DAMAGE.
+
+ ***********************************************************************/
+
+var jsp = require("./parse-js"),
+ curry = jsp.curry,
+ slice = jsp.slice,
+ member = jsp.member,
+ is_identifier_char = jsp.is_identifier_char,
+ PRECEDENCE = jsp.PRECEDENCE,
+ OPERATORS = jsp.OPERATORS;
+
+/* -----[ helper for AST traversal ]----- */
+
+function ast_walker() {
+ function _vardefs(defs) {
+ return [ this[0], MAP(defs, function(def){
+ var a = [ def[0] ];
+ if (def.length > 1)
+ a[1] = walk(def[1]);
+ return a;
+ }) ];
+ };
+ function _block(statements) {
+ var out = [ this[0] ];
+ if (statements != null)
+ out.push(MAP(statements, walk));
+ return out;
+ };
+ var walkers = {
+ "string": function(str) {
+ return [ this[0], str ];
+ },
+ "num": function(num) {
+ return [ this[0], num ];
+ },
+ "name": function(name) {
+ return [ this[0], name ];
+ },
+ "toplevel": function(statements) {
+ return [ this[0], MAP(statements, walk) ];
+ },
+ "block": _block,
+ "splice": _block,
+ "var": _vardefs,
+ "const": _vardefs,
+ "try": function(t, c, f) {
+ return [
+ this[0],
+ MAP(t, walk),
+ c != null ? [ c[0], MAP(c[1], walk) ] : null,
+ f != null ? MAP(f, walk) : null
+ ];
+ },
+ "throw": function(expr) {
+ return [ this[0], walk(expr) ];
+ },
+ "new": function(ctor, args) {
+ return [ this[0], walk(ctor), MAP(args, walk) ];
+ },
+ "switch": function(expr, body) {
+ return [ this[0], walk(expr), MAP(body, function(branch){
+ return [ branch[0] ? walk(branch[0]) : null,
+ MAP(branch[1], walk) ];
+ }) ];
+ },
+ "break": function(label) {
+ return [ this[0], label ];
+ },
+ "continue": function(label) {
+ return [ this[0], label ];
+ },
+ "conditional": function(cond, t, e) {
+ return [ this[0], walk(cond), walk(t), walk(e) ];
+ },
+ "assign": function(op, lvalue, rvalue) {
+ return [ this[0], op, walk(lvalue), walk(rvalue) ];
+ },
+ "dot": function(expr) {
+ return [ this[0], walk(expr) ].concat(slice(arguments, 1));
+ },
+ "call": function(expr, args) {
+ return [ this[0], walk(expr), MAP(args, walk) ];
+ },
+ "function": function(name, args, body) {
+ return [ this[0], name, args.slice(), MAP(body, walk) ];
+ },
+ "debugger": function() {
+ return [ this[0] ];
+ },
+ "defun": function(name, args, body) {
+ return [ this[0], name, args.slice(), MAP(body, walk) ];
+ },
+ "if": function(conditional, t, e) {
+ return [ this[0], walk(conditional), walk(t), walk(e) ];
+ },
+ "for": function(init, cond, step, block) {
+ return [ this[0], walk(init), walk(cond), walk(step), walk(block) ];
+ },
+ "for-in": function(vvar, key, hash, block) {
+ return [ this[0], walk(vvar), walk(key), walk(hash), walk(block) ];
+ },
+ "while": function(cond, block) {
+ return [ this[0], walk(cond), walk(block) ];
+ },
+ "do": function(cond, block) {
+ return [ this[0], walk(cond), walk(block) ];
+ },
+ "return": function(expr) {
+ return [ this[0], walk(expr) ];
+ },
+ "binary": function(op, left, right) {
+ return [ this[0], op, walk(left), walk(right) ];
+ },
+ "unary-prefix": function(op, expr) {
+ return [ this[0], op, walk(expr) ];
+ },
+ "unary-postfix": function(op, expr) {
+ return [ this[0], op, walk(expr) ];
+ },
+ "sub": function(expr, subscript) {
+ return [ this[0], walk(expr), walk(subscript) ];
+ },
+ "object": function(props) {
+ return [ this[0], MAP(props, function(p){
+ return p.length == 2
+ ? [ p[0], walk(p[1]) ]
+ : [ p[0], walk(p[1]), p[2] ]; // get/set-ter
+ }) ];
+ },
+ "regexp": function(rx, mods) {
+ return [ this[0], rx, mods ];
+ },
+ "array": function(elements) {
+ return [ this[0], MAP(elements, walk) ];
+ },
+ "stat": function(stat) {
+ return [ this[0], walk(stat) ];
+ },
+ "seq": function() {
+ return [ this[0] ].concat(MAP(slice(arguments), walk));
+ },
+ "label": function(name, block) {
+ return [ this[0], name, walk(block) ];
+ },
+ "with": function(expr, block) {
+ return [ this[0], walk(expr), walk(block) ];
+ },
+ "atom": function(name) {
+ return [ this[0], name ];
+ },
+ "directive": function(dir) {
+ return [ this[0], dir ];
+ }
+ };
+
+ var user = {};
+ var stack = [];
+ function walk(ast) {
+ if (ast == null)
+ return null;
+ try {
+ stack.push(ast);
+ var type = ast[0];
+ var gen = user[type];
+ if (gen) {
+ var ret = gen.apply(ast, ast.slice(1));
+ if (ret != null)
+ return ret;
+ }
+ gen = walkers[type];
+ return gen.apply(ast, ast.slice(1));
+ } finally {
+ stack.pop();
+ }
+ };
+
+ function dive(ast) {
+ if (ast == null)
+ return null;
+ try {
+ stack.push(ast);
+ return walkers[ast[0]].apply(ast, ast.slice(1));
+ } finally {
+ stack.pop();
+ }
+ };
+
+ function with_walkers(walkers, cont){
+ var save = {}, i;
+ for (i in walkers) if (HOP(walkers, i)) {
+ save[i] = user[i];
+ user[i] = walkers[i];
+ }
+ var ret = cont();
+ for (i in save) if (HOP(save, i)) {
+ if (!save[i]) delete user[i];
+ else user[i] = save[i];
+ }
+ return ret;
+ };
+
+ return {
+ walk: walk,
+ dive: dive,
+ with_walkers: with_walkers,
+ parent: function() {
+ return stack[stack.length - 2]; // last one is current node
+ },
+ stack: function() {
+ return stack;
+ }
+ };
+};
+
+/* -----[ Scope and mangling ]----- */
+
+function Scope(parent) {
+ this.names = {}; // names defined in this scope
+ this.mangled = {}; // mangled names (orig.name => mangled)
+ this.rev_mangled = {}; // reverse lookup (mangled => orig.name)
+ this.cname = -1; // current mangled name
+ this.refs = {}; // names referenced from this scope
+ this.uses_with = false; // will become TRUE if with() is detected in this or any subscopes
+ this.uses_eval = false; // will become TRUE if eval() is detected in this or any subscopes
+ this.directives = []; // directives activated from this scope
+ this.parent = parent; // parent scope
+ this.children = []; // sub-scopes
+ if (parent) {
+ this.level = parent.level + 1;
+ parent.children.push(this);
+ } else {
+ this.level = 0;
+ }
+};
+
+function base54_digits() {
+ if (typeof DIGITS_OVERRIDE_FOR_TESTING != "undefined")
+ return DIGITS_OVERRIDE_FOR_TESTING;
+ else
+ return "etnrisouaflchpdvmgybwESxTNCkLAOM_DPHBjFIqRUzWXV$JKQGYZ0516372984";
+}
+
+var base54 = (function(){
+ var DIGITS = base54_digits();
+ return function(num) {
+ var ret = "", base = 54;
+ do {
+ ret += DIGITS.charAt(num % base);
+ num = Math.floor(num / base);
+ base = 64;
+ } while (num > 0);
+ return ret;
+ };
+})();
+
+Scope.prototype = {
+ has: function(name) {
+ for (var s = this; s; s = s.parent)
+ if (HOP(s.names, name))
+ return s;
+ },
+ has_mangled: function(mname) {
+ for (var s = this; s; s = s.parent)
+ if (HOP(s.rev_mangled, mname))
+ return s;
+ },
+ toJSON: function() {
+ return {
+ names: this.names,
+ uses_eval: this.uses_eval,
+ uses_with: this.uses_with
+ };
+ },
+
+ next_mangled: function() {
+ // we must be careful that the new mangled name:
+ //
+ // 1. doesn't shadow a mangled name from a parent
+ // scope, unless we don't reference the original
+ // name from this scope OR from any sub-scopes!
+ // This will get slow.
+ //
+ // 2. doesn't shadow an original name from a parent
+ // scope, in the event that the name is not mangled
+ // in the parent scope and we reference that name
+ // here OR IN ANY SUBSCOPES!
+ //
+ // 3. doesn't shadow a name that is referenced but not
+ // defined (possibly global defined elsewhere).
+ for (;;) {
+ var m = base54(++this.cname), prior;
+
+ // case 1.
+ prior = this.has_mangled(m);
+ if (prior && this.refs[prior.rev_mangled[m]] === prior)
+ continue;
+
+ // case 2.
+ prior = this.has(m);
+ if (prior && prior !== this && this.refs[m] === prior && !prior.has_mangled(m))
+ continue;
+
+ // case 3.
+ if (HOP(this.refs, m) && this.refs[m] == null)
+ continue;
+
+ // I got "do" once. :-/
+ if (!is_identifier(m))
+ continue;
+
+ return m;
+ }
+ },
+ set_mangle: function(name, m) {
+ this.rev_mangled[m] = name;
+ return this.mangled[name] = m;
+ },
+ get_mangled: function(name, newMangle) {
+ if (this.uses_eval || this.uses_with) return name; // no mangle if eval or with is in use
+ var s = this.has(name);
+ if (!s) return name; // not in visible scope, no mangle
+ if (HOP(s.mangled, name)) return s.mangled[name]; // already mangled in this scope
+ if (!newMangle) return name; // not found and no mangling requested
+ return s.set_mangle(name, s.next_mangled());
+ },
+ references: function(name) {
+ return name && !this.parent || this.uses_with || this.uses_eval || this.refs[name];
+ },
+ define: function(name, type) {
+ if (name != null) {
+ if (type == "var" || !HOP(this.names, name))
+ this.names[name] = type || "var";
+ return name;
+ }
+ },
+ active_directive: function(dir) {
+ return member(dir, this.directives) || this.parent && this.parent.active_directive(dir);
+ }
+};
+
+function ast_add_scope(ast) {
+
+ var current_scope = null;
+ var w = ast_walker(), walk = w.walk;
+ var having_eval = [];
+
+ function with_new_scope(cont) {
+ current_scope = new Scope(current_scope);
+ current_scope.labels = new Scope();
+ var ret = current_scope.body = cont();
+ ret.scope = current_scope;
+ current_scope = current_scope.parent;
+ return ret;
+ };
+
+ function define(name, type) {
+ return current_scope.define(name, type);
+ };
+
+ function reference(name) {
+ current_scope.refs[name] = true;
+ };
+
+ function _lambda(name, args, body) {
+ var is_defun = this[0] == "defun";
+ return [ this[0], is_defun ? define(name, "defun") : name, args, with_new_scope(function(){
+ if (!is_defun) define(name, "lambda");
+ MAP(args, function(name){ define(name, "arg") });
+ return MAP(body, walk);
+ })];
+ };
+
+ function _vardefs(type) {
+ return function(defs) {
+ MAP(defs, function(d){
+ define(d[0], type);
+ if (d[1]) reference(d[0]);
+ });
+ };
+ };
+
+ function _breacont(label) {
+ if (label)
+ current_scope.labels.refs[label] = true;
+ };
+
+ return with_new_scope(function(){
+ // process AST
+ var ret = w.with_walkers({
+ "function": _lambda,
+ "defun": _lambda,
+ "label": function(name, stat) { current_scope.labels.define(name) },
+ "break": _breacont,
+ "continue": _breacont,
+ "with": function(expr, block) {
+ for (var s = current_scope; s; s = s.parent)
+ s.uses_with = true;
+ },
+ "var": _vardefs("var"),
+ "const": _vardefs("const"),
+ "try": function(t, c, f) {
+ if (c != null) return [
+ this[0],
+ MAP(t, walk),
+ [ define(c[0], "catch"), MAP(c[1], walk) ],
+ f != null ? MAP(f, walk) : null
+ ];
+ },
+ "name": function(name) {
+ if (name == "eval")
+ having_eval.push(current_scope);
+ reference(name);
+ }
+ }, function(){
+ return walk(ast);
+ });
+
+ // the reason why we need an additional pass here is
+ // that names can be used prior to their definition.
+
+ // scopes where eval was detected and their parents
+ // are marked with uses_eval, unless they define the
+ // "eval" name.
+ MAP(having_eval, function(scope){
+ if (!scope.has("eval")) while (scope) {
+ scope.uses_eval = true;
+ scope = scope.parent;
+ }
+ });
+
+ // for referenced names it might be useful to know
+ // their origin scope. current_scope here is the
+ // toplevel one.
+ function fixrefs(scope, i) {
+ // do children first; order shouldn't matter
+ for (i = scope.children.length; --i >= 0;)
+ fixrefs(scope.children[i]);
+ for (i in scope.refs) if (HOP(scope.refs, i)) {
+ // find origin scope and propagate the reference to origin
+ for (var origin = scope.has(i), s = scope; s; s = s.parent) {
+ s.refs[i] = origin;
+ if (s === origin) break;
+ }
+ }
+ };
+ fixrefs(current_scope);
+
+ return ret;
+ });
+
+};
+
+/* -----[ mangle names ]----- */
+
+function ast_mangle(ast, options) {
+ var w = ast_walker(), walk = w.walk, scope;
+ options = defaults(options, {
+ mangle : true,
+ toplevel : false,
+ defines : null,
+ except : null,
+ no_functions : false
+ });
+
+ function get_mangled(name, newMangle) {
+ if (!options.mangle) return name;
+ if (!options.toplevel && !scope.parent) return name; // don't mangle toplevel
+ if (options.except && member(name, options.except))
+ return name;
+ if (options.no_functions && HOP(scope.names, name) &&
+ (scope.names[name] == 'defun' || scope.names[name] == 'lambda'))
+ return name;
+ return scope.get_mangled(name, newMangle);
+ };
+
+ function get_define(name) {
+ if (options.defines) {
+ // we always lookup a defined symbol for the current scope FIRST, so declared
+ // vars trump a DEFINE symbol, but if no such var is found, then match a DEFINE value
+ if (!scope.has(name)) {
+ if (HOP(options.defines, name)) {
+ return options.defines[name];
+ }
+ }
+ return null;
+ }
+ };
+
+ function _lambda(name, args, body) {
+ if (!options.no_functions && options.mangle) {
+ var is_defun = this[0] == "defun", extra;
+ if (name) {
+ if (is_defun) name = get_mangled(name);
+ else if (body.scope.references(name)) {
+ extra = {};
+ if (!(scope.uses_eval || scope.uses_with))
+ name = extra[name] = scope.next_mangled();
+ else
+ extra[name] = name;
+ }
+ else name = null;
+ }
+ }
+ body = with_scope(body.scope, function(){
+ args = MAP(args, function(name){ return get_mangled(name) });
+ return MAP(body, walk);
+ }, extra);
+ return [ this[0], name, args, body ];
+ };
+
+ function with_scope(s, cont, extra) {
+ var _scope = scope;
+ scope = s;
+ if (extra) for (var i in extra) if (HOP(extra, i)) {
+ s.set_mangle(i, extra[i]);
+ }
+ for (var i in s.names) if (HOP(s.names, i)) {
+ get_mangled(i, true);
+ }
+ var ret = cont();
+ ret.scope = s;
+ scope = _scope;
+ return ret;
+ };
+
+ function _vardefs(defs) {
+ return [ this[0], MAP(defs, function(d){
+ return [ get_mangled(d[0]), walk(d[1]) ];
+ }) ];
+ };
+
+ function _breacont(label) {
+ if (label) return [ this[0], scope.labels.get_mangled(label) ];
+ };
+
+ return w.with_walkers({
+ "function": _lambda,
+ "defun": function() {
+ // move function declarations to the top when
+ // they are not in some block.
+ var ast = _lambda.apply(this, arguments);
+ switch (w.parent()[0]) {
+ case "toplevel":
+ case "function":
+ case "defun":
+ return MAP.at_top(ast);
+ }
+ return ast;
+ },
+ "label": function(label, stat) {
+ if (scope.labels.refs[label]) return [
+ this[0],
+ scope.labels.get_mangled(label, true),
+ walk(stat)
+ ];
+ return walk(stat);
+ },
+ "break": _breacont,
+ "continue": _breacont,
+ "var": _vardefs,
+ "const": _vardefs,
+ "name": function(name) {
+ return get_define(name) || [ this[0], get_mangled(name) ];
+ },
+ "try": function(t, c, f) {
+ return [ this[0],
+ MAP(t, walk),
+ c != null ? [ get_mangled(c[0]), MAP(c[1], walk) ] : null,
+ f != null ? MAP(f, walk) : null ];
+ },
+ "toplevel": function(body) {
+ var self = this;
+ return with_scope(self.scope, function(){
+ return [ self[0], MAP(body, walk) ];
+ });
+ },
+ "directive": function() {
+ return MAP.at_top(this);
+ }
+ }, function() {
+ return walk(ast_add_scope(ast));
+ });
+};
+
+/* -----[
+ - compress foo["bar"] into foo.bar,
+ - remove block brackets {} where possible
+ - join consecutive var declarations
+ - various optimizations for IFs:
+ - if (cond) foo(); else bar(); ==> cond?foo():bar();
+ - if (cond) foo(); ==> cond&&foo();
+ - if (foo) return bar(); else return baz(); ==> return foo?bar():baz(); // also for throw
+ - if (foo) return bar(); else something(); ==> {if(foo)return bar();something()}
+ ]----- */
+
+var warn = function(){};
+
+function best_of(ast1, ast2) {
+ return gen_code(ast1).length > gen_code(ast2[0] == "stat" ? ast2[1] : ast2).length ? ast2 : ast1;
+};
+
+function last_stat(b) {
+ if (b[0] == "block" && b[1] && b[1].length > 0)
+ return b[1][b[1].length - 1];
+ return b;
+}
+
+function aborts(t) {
+ if (t) switch (last_stat(t)[0]) {
+ case "return":
+ case "break":
+ case "continue":
+ case "throw":
+ return true;
+ }
+};
+
+function boolean_expr(expr) {
+ return ( (expr[0] == "unary-prefix"
+ && member(expr[1], [ "!", "delete" ])) ||
+
+ (expr[0] == "binary"
+ && member(expr[1], [ "in", "instanceof", "==", "!=", "===", "!==", "<", "<=", ">=", ">" ])) ||
+
+ (expr[0] == "binary"
+ && member(expr[1], [ "&&", "||" ])
+ && boolean_expr(expr[2])
+ && boolean_expr(expr[3])) ||
+
+ (expr[0] == "conditional"
+ && boolean_expr(expr[2])
+ && boolean_expr(expr[3])) ||
+
+ (expr[0] == "assign"
+ && expr[1] === true
+ && boolean_expr(expr[3])) ||
+
+ (expr[0] == "seq"
+ && boolean_expr(expr[expr.length - 1]))
+ );
+};
+
+function empty(b) {
+ return !b || (b[0] == "block" && (!b[1] || b[1].length == 0));
+};
+
+function is_string(node) {
+ return (node[0] == "string" ||
+ node[0] == "unary-prefix" && node[1] == "typeof" ||
+ node[0] == "binary" && node[1] == "+" &&
+ (is_string(node[2]) || is_string(node[3])));
+};
+
+var when_constant = (function(){
+
+ var $NOT_CONSTANT = {};
+
+ // this can only evaluate constant expressions. If it finds anything
+ // not constant, it throws $NOT_CONSTANT.
+ function evaluate(expr) {
+ switch (expr[0]) {
+ case "string":
+ case "num":
+ return expr[1];
+ case "name":
+ case "atom":
+ switch (expr[1]) {
+ case "true": return true;
+ case "false": return false;
+ case "null": return null;
+ }
+ break;
+ case "unary-prefix":
+ switch (expr[1]) {
+ case "!": return !evaluate(expr[2]);
+ case "typeof": return typeof evaluate(expr[2]);
+ case "~": return ~evaluate(expr[2]);
+ case "-": return -evaluate(expr[2]);
+ case "+": return +evaluate(expr[2]);
+ }
+ break;
+ case "binary":
+ var left = expr[2], right = expr[3];
+ switch (expr[1]) {
+ case "&&" : return evaluate(left) && evaluate(right);
+ case "||" : return evaluate(left) || evaluate(right);
+ case "|" : return evaluate(left) | evaluate(right);
+ case "&" : return evaluate(left) & evaluate(right);
+ case "^" : return evaluate(left) ^ evaluate(right);
+ case "+" : return evaluate(left) + evaluate(right);
+ case "*" : return evaluate(left) * evaluate(right);
+ case "/" : return evaluate(left) / evaluate(right);
+ case "%" : return evaluate(left) % evaluate(right);
+ case "-" : return evaluate(left) - evaluate(right);
+ case "<<" : return evaluate(left) << evaluate(right);
+ case ">>" : return evaluate(left) >> evaluate(right);
+ case ">>>" : return evaluate(left) >>> evaluate(right);
+ case "==" : return evaluate(left) == evaluate(right);
+ case "===" : return evaluate(left) === evaluate(right);
+ case "!=" : return evaluate(left) != evaluate(right);
+ case "!==" : return evaluate(left) !== evaluate(right);
+ case "<" : return evaluate(left) < evaluate(right);
+ case "<=" : return evaluate(left) <= evaluate(right);
+ case ">" : return evaluate(left) > evaluate(right);
+ case ">=" : return evaluate(left) >= evaluate(right);
+ case "in" : return evaluate(left) in evaluate(right);
+ case "instanceof" : return evaluate(left) instanceof evaluate(right);
+ }
+ }
+ throw $NOT_CONSTANT;
+ };
+
+ return function(expr, yes, no) {
+ try {
+ var val = evaluate(expr), ast;
+ switch (typeof val) {
+ case "string": ast = [ "string", val ]; break;
+ case "number": ast = [ "num", val ]; break;
+ case "boolean": ast = [ "name", String(val) ]; break;
+ default:
+ if (val === null) { ast = [ "atom", "null" ]; break; }
+ throw new Error("Can't handle constant of type: " + (typeof val));
+ }
+ return yes.call(expr, ast, val);
+ } catch(ex) {
+ if (ex === $NOT_CONSTANT) {
+ if (expr[0] == "binary"
+ && (expr[1] == "===" || expr[1] == "!==")
+ && ((is_string(expr[2]) && is_string(expr[3]))
+ || (boolean_expr(expr[2]) && boolean_expr(expr[3])))) {
+ expr[1] = expr[1].substr(0, 2);
+ }
+ else if (no && expr[0] == "binary"
+ && (expr[1] == "||" || expr[1] == "&&")) {
+ // the whole expression is not constant but the lval may be...
+ try {
+ var lval = evaluate(expr[2]);
+ expr = ((expr[1] == "&&" && (lval ? expr[3] : lval)) ||
+ (expr[1] == "||" && (lval ? lval : expr[3])) ||
+ expr);
+ } catch(ex2) {
+ // IGNORE... lval is not constant
+ }
+ }
+ return no ? no.call(expr, expr) : null;
+ }
+ else throw ex;
+ }
+ };
+
+})();
+
+function warn_unreachable(ast) {
+ if (!empty(ast))
+ warn("Dropping unreachable code: " + gen_code(ast, true));
+};
+
+function prepare_ifs(ast) {
+ var w = ast_walker(), walk = w.walk;
+ // In this first pass, we rewrite ifs which abort with no else with an
+ // if-else. For example:
+ //
+ // if (x) {
+ // blah();
+ // return y;
+ // }
+ // foobar();
+ //
+ // is rewritten into:
+ //
+ // if (x) {
+ // blah();
+ // return y;
+ // } else {
+ // foobar();
+ // }
+ function redo_if(statements) {
+ statements = MAP(statements, walk);
+
+ for (var i = 0; i < statements.length; ++i) {
+ var fi = statements[i];
+ if (fi[0] != "if") continue;
+
+ if (fi[3]) continue;
+
+ var t = fi[2];
+ if (!aborts(t)) continue;
+
+ var conditional = walk(fi[1]);
+
+ var e_body = redo_if(statements.slice(i + 1));
+ var e = e_body.length == 1 ? e_body[0] : [ "block", e_body ];
+
+ return statements.slice(0, i).concat([ [
+ fi[0], // "if"
+ conditional, // conditional
+ t, // then
+ e // else
+ ] ]);
+ }
+
+ return statements;
+ };
+
+ function redo_if_lambda(name, args, body) {
+ body = redo_if(body);
+ return [ this[0], name, args, body ];
+ };
+
+ function redo_if_block(statements) {
+ return [ this[0], statements != null ? redo_if(statements) : null ];
+ };
+
+ return w.with_walkers({
+ "defun": redo_if_lambda,
+ "function": redo_if_lambda,
+ "block": redo_if_block,
+ "splice": redo_if_block,
+ "toplevel": function(statements) {
+ return [ this[0], redo_if(statements) ];
+ },
+ "try": function(t, c, f) {
+ return [
+ this[0],
+ redo_if(t),
+ c != null ? [ c[0], redo_if(c[1]) ] : null,
+ f != null ? redo_if(f) : null
+ ];
+ }
+ }, function() {
+ return walk(ast);
+ });
+};
+
+function for_side_effects(ast, handler) {
+ var w = ast_walker(), walk = w.walk;
+ var $stop = {}, $restart = {};
+ function stop() { throw $stop };
+ function restart() { throw $restart };
+ function found(){ return handler.call(this, this, w, stop, restart) };
+ function unary(op) {
+ if (op == "++" || op == "--")
+ return found.apply(this, arguments);
+ };
+ function binary(op) {
+ if (op == "&&" || op == "||")
+ return found.apply(this, arguments);
+ };
+ return w.with_walkers({
+ "try": found,
+ "throw": found,
+ "return": found,
+ "new": found,
+ "switch": found,
+ "break": found,
+ "continue": found,
+ "assign": found,
+ "call": found,
+ "if": found,
+ "for": found,
+ "for-in": found,
+ "while": found,
+ "do": found,
+ "return": found,
+ "unary-prefix": unary,
+ "unary-postfix": unary,
+ "conditional": found,
+ "binary": binary,
+ "defun": found
+ }, function(){
+ while (true) try {
+ walk(ast);
+ break;
+ } catch(ex) {
+ if (ex === $stop) break;
+ if (ex === $restart) continue;
+ throw ex;
+ }
+ });
+};
+
+function ast_lift_variables(ast) {
+ var w = ast_walker(), walk = w.walk, scope;
+ function do_body(body, env) {
+ var _scope = scope;
+ scope = env;
+ body = MAP(body, walk);
+ var hash = {}, names = MAP(env.names, function(type, name){
+ if (type != "var") return MAP.skip;
+ if (!env.references(name)) return MAP.skip;
+ hash[name] = true;
+ return [ name ];
+ });
+ if (names.length > 0) {
+ // looking for assignments to any of these variables.
+ // we can save considerable space by moving the definitions
+ // in the var declaration.
+ for_side_effects([ "block", body ], function(ast, walker, stop, restart) {
+ if (ast[0] == "assign"
+ && ast[1] === true
+ && ast[2][0] == "name"
+ && HOP(hash, ast[2][1])) {
+ // insert the definition into the var declaration
+ for (var i = names.length; --i >= 0;) {
+ if (names[i][0] == ast[2][1]) {
+ if (names[i][1]) // this name already defined, we must stop
+ stop();
+ names[i][1] = ast[3]; // definition
+ names.push(names.splice(i, 1)[0]);
+ break;
+ }
+ }
+ // remove this assignment from the AST.
+ var p = walker.parent();
+ if (p[0] == "seq") {
+ var a = p[2];
+ a.unshift(0, p.length);
+ p.splice.apply(p, a);
+ }
+ else if (p[0] == "stat") {
+ p.splice(0, p.length, "block"); // empty statement
+ }
+ else {
+ stop();
+ }
+ restart();
+ }
+ stop();
+ });
+ body.unshift([ "var", names ]);
+ }
+ scope = _scope;
+ return body;
+ };
+ function _vardefs(defs) {
+ var ret = null;
+ for (var i = defs.length; --i >= 0;) {
+ var d = defs[i];
+ if (!d[1]) continue;
+ d = [ "assign", true, [ "name", d[0] ], d[1] ];
+ if (ret == null) ret = d;
+ else ret = [ "seq", d, ret ];
+ }
+ if (ret == null && w.parent()[0] != "for") {
+ if (w.parent()[0] == "for-in")
+ return [ "name", defs[0][0] ];
+ return MAP.skip;
+ }
+ return [ "stat", ret ];
+ };
+ function _toplevel(body) {
+ return [ this[0], do_body(body, this.scope) ];
+ };
+ return w.with_walkers({
+ "function": function(name, args, body){
+ for (var i = args.length; --i >= 0 && !body.scope.references(args[i]);)
+ args.pop();
+ if (!body.scope.references(name)) name = null;
+ return [ this[0], name, args, do_body(body, body.scope) ];
+ },
+ "defun": function(name, args, body){
+ if (!scope.references(name)) return MAP.skip;
+ for (var i = args.length; --i >= 0 && !body.scope.references(args[i]);)
+ args.pop();
+ return [ this[0], name, args, do_body(body, body.scope) ];
+ },
+ "var": _vardefs,
+ "toplevel": _toplevel
+ }, function(){
+ return walk(ast_add_scope(ast));
+ });
+};
+
+function ast_squeeze(ast, options) {
+ ast = squeeze_1(ast, options);
+ ast = squeeze_2(ast, options);
+ return ast;
+};
+
+function squeeze_1(ast, options) {
+ options = defaults(options, {
+ make_seqs : true,
+ dead_code : true,
+ no_warnings : false,
+ keep_comps : true,
+ unsafe : false
+ });
+
+ var w = ast_walker(), walk = w.walk, scope;
+
+ function negate(c) {
+ var not_c = [ "unary-prefix", "!", c ];
+ switch (c[0]) {
+ case "unary-prefix":
+ return c[1] == "!" && boolean_expr(c[2]) ? c[2] : not_c;
+ case "seq":
+ c = slice(c);
+ c[c.length - 1] = negate(c[c.length - 1]);
+ return c;
+ case "conditional":
+ return best_of(not_c, [ "conditional", c[1], negate(c[2]), negate(c[3]) ]);
+ case "binary":
+ var op = c[1], left = c[2], right = c[3];
+ if (!options.keep_comps) switch (op) {
+ case "<=" : return [ "binary", ">", left, right ];
+ case "<" : return [ "binary", ">=", left, right ];
+ case ">=" : return [ "binary", "<", left, right ];
+ case ">" : return [ "binary", "<=", left, right ];
+ }
+ switch (op) {
+ case "==" : return [ "binary", "!=", left, right ];
+ case "!=" : return [ "binary", "==", left, right ];
+ case "===" : return [ "binary", "!==", left, right ];
+ case "!==" : return [ "binary", "===", left, right ];
+ case "&&" : return best_of(not_c, [ "binary", "||", negate(left), negate(right) ]);
+ case "||" : return best_of(not_c, [ "binary", "&&", negate(left), negate(right) ]);
+ }
+ break;
+ }
+ return not_c;
+ };
+
+ function make_conditional(c, t, e) {
+ var make_real_conditional = function() {
+ if (c[0] == "unary-prefix" && c[1] == "!") {
+ return e ? [ "conditional", c[2], e, t ] : [ "binary", "||", c[2], t ];
+ } else {
+ return e ? best_of(
+ [ "conditional", c, t, e ],
+ [ "conditional", negate(c), e, t ]
+ ) : [ "binary", "&&", c, t ];
+ }
+ };
+ // shortcut the conditional if the expression has a constant value
+ return when_constant(c, function(ast, val){
+ warn_unreachable(val ? e : t);
+ return (val ? t : e);
+ }, make_real_conditional);
+ };
+
+ function rmblock(block) {
+ if (block != null && block[0] == "block" && block[1]) {
+ if (block[1].length == 1)
+ block = block[1][0];
+ else if (block[1].length == 0)
+ block = [ "block" ];
+ }
+ return block;
+ };
+
+ function _lambda(name, args, body) {
+ return [ this[0], name, args, tighten(body, "lambda") ];
+ };
+
+ // this function does a few things:
+ // 1. discard useless blocks
+ // 2. join consecutive var declarations
+ // 3. remove obviously dead code
+ // 4. transform consecutive statements using the comma operator
+ // 5. if block_type == "lambda" and it detects constructs like if(foo) return ... - rewrite like if (!foo) { ... }
+ function tighten(statements, block_type) {
+ statements = MAP(statements, walk);
+
+ statements = statements.reduce(function(a, stat){
+ if (stat[0] == "block") {
+ if (stat[1]) {
+ a.push.apply(a, stat[1]);
+ }
+ } else {
+ a.push(stat);
+ }
+ return a;
+ }, []);
+
+ statements = (function(a, prev){
+ statements.forEach(function(cur){
+ if (prev && ((cur[0] == "var" && prev[0] == "var") ||
+ (cur[0] == "const" && prev[0] == "const"))) {
+ prev[1] = prev[1].concat(cur[1]);
+ } else {
+ a.push(cur);
+ prev = cur;
+ }
+ });
+ return a;
+ })([]);
+
+ if (options.dead_code) statements = (function(a, has_quit){
+ statements.forEach(function(st){
+ if (has_quit) {
+ if (st[0] == "function" || st[0] == "defun") {
+ a.push(st);
+ }
+ else if (st[0] == "var" || st[0] == "const") {
+ if (!options.no_warnings)
+ warn("Variables declared in unreachable code");
+ st[1] = MAP(st[1], function(def){
+ if (def[1] && !options.no_warnings)
+ warn_unreachable([ "assign", true, [ "name", def[0] ], def[1] ]);
+ return [ def[0] ];
+ });
+ a.push(st);
+ }
+ else if (!options.no_warnings)
+ warn_unreachable(st);
+ }
+ else {
+ a.push(st);
+ if (member(st[0], [ "return", "throw", "break", "continue" ]))
+ has_quit = true;
+ }
+ });
+ return a;
+ })([]);
+
+ if (options.make_seqs) statements = (function(a, prev) {
+ statements.forEach(function(cur){
+ if (prev && prev[0] == "stat" && cur[0] == "stat") {
+ prev[1] = [ "seq", prev[1], cur[1] ];
+ } else {
+ a.push(cur);
+ prev = cur;
+ }
+ });
+ if (a.length >= 2
+ && a[a.length-2][0] == "stat"
+ && (a[a.length-1][0] == "return" || a[a.length-1][0] == "throw")
+ && a[a.length-1][1])
+ {
+ a.splice(a.length - 2, 2,
+ [ a[a.length-1][0],
+ [ "seq", a[a.length-2][1], a[a.length-1][1] ]]);
+ }
+ return a;
+ })([]);
+
+ // this increases jQuery by 1K. Probably not such a good idea after all..
+ // part of this is done in prepare_ifs anyway.
+ // if (block_type == "lambda") statements = (function(i, a, stat){
+ // while (i < statements.length) {
+ // stat = statements[i++];
+ // if (stat[0] == "if" && !stat[3]) {
+ // if (stat[2][0] == "return" && stat[2][1] == null) {
+ // a.push(make_if(negate(stat[1]), [ "block", statements.slice(i) ]));
+ // break;
+ // }
+ // var last = last_stat(stat[2]);
+ // if (last[0] == "return" && last[1] == null) {
+ // a.push(make_if(stat[1], [ "block", stat[2][1].slice(0, -1) ], [ "block", statements.slice(i) ]));
+ // break;
+ // }
+ // }
+ // a.push(stat);
+ // }
+ // return a;
+ // })(0, []);
+
+ return statements;
+ };
+
+ function make_if(c, t, e) {
+ return when_constant(c, function(ast, val){
+ if (val) {
+ t = walk(t);
+ warn_unreachable(e);
+ return t || [ "block" ];
+ } else {
+ e = walk(e);
+ warn_unreachable(t);
+ return e || [ "block" ];
+ }
+ }, function() {
+ return make_real_if(c, t, e);
+ });
+ };
+
+ function abort_else(c, t, e) {
+ var ret = [ [ "if", negate(c), e ] ];
+ if (t[0] == "block") {
+ if (t[1]) ret = ret.concat(t[1]);
+ } else {
+ ret.push(t);
+ }
+ return walk([ "block", ret ]);
+ };
+
+ function make_real_if(c, t, e) {
+ c = walk(c);
+ t = walk(t);
+ e = walk(e);
+
+ if (empty(e) && empty(t))
+ return [ "stat", c ];
+
+ if (empty(t)) {
+ c = negate(c);
+ t = e;
+ e = null;
+ } else if (empty(e)) {
+ e = null;
+ } else {
+ // if we have both else and then, maybe it makes sense to switch them?
+ (function(){
+ var a = gen_code(c);
+ var n = negate(c);
+ var b = gen_code(n);
+ if (b.length < a.length) {
+ var tmp = t;
+ t = e;
+ e = tmp;
+ c = n;
+ }
+ })();
+ }
+ var ret = [ "if", c, t, e ];
+ if (t[0] == "if" && empty(t[3]) && empty(e)) {
+ ret = best_of(ret, walk([ "if", [ "binary", "&&", c, t[1] ], t[2] ]));
+ }
+ else if (t[0] == "stat") {
+ if (e) {
+ if (e[0] == "stat")
+ ret = best_of(ret, [ "stat", make_conditional(c, t[1], e[1]) ]);
+ else if (aborts(e))
+ ret = abort_else(c, t, e);
+ }
+ else {
+ ret = best_of(ret, [ "stat", make_conditional(c, t[1]) ]);
+ }
+ }
+ else if (e && t[0] == e[0] && (t[0] == "return" || t[0] == "throw") && t[1] && e[1]) {
+ ret = best_of(ret, [ t[0], make_conditional(c, t[1], e[1] ) ]);
+ }
+ else if (e && aborts(t)) {
+ ret = [ [ "if", c, t ] ];
+ if (e[0] == "block") {
+ if (e[1]) ret = ret.concat(e[1]);
+ }
+ else {
+ ret.push(e);
+ }
+ ret = walk([ "block", ret ]);
+ }
+ else if (t && aborts(e)) {
+ ret = abort_else(c, t, e);
+ }
+ return ret;
+ };
+
+ function _do_while(cond, body) {
+ return when_constant(cond, function(cond, val){
+ if (!val) {
+ warn_unreachable(body);
+ return [ "block" ];
+ } else {
+ return [ "for", null, null, null, walk(body) ];
+ }
+ });
+ };
+
+ return w.with_walkers({
+ "sub": function(expr, subscript) {
+ if (subscript[0] == "string") {
+ var name = subscript[1];
+ if (is_identifier(name))
+ return [ "dot", walk(expr), name ];
+ else if (/^[1-9][0-9]*$/.test(name) || name === "0")
+ return [ "sub", walk(expr), [ "num", parseInt(name, 10) ] ];
+ }
+ },
+ "if": make_if,
+ "toplevel": function(body) {
+ return [ "toplevel", tighten(body) ];
+ },
+ "switch": function(expr, body) {
+ var last = body.length - 1;
+ return [ "switch", walk(expr), MAP(body, function(branch, i){
+ var block = tighten(branch[1]);
+ if (i == last && block.length > 0) {
+ var node = block[block.length - 1];
+ if (node[0] == "break" && !node[1])
+ block.pop();
+ }
+ return [ branch[0] ? walk(branch[0]) : null, block ];
+ }) ];
+ },
+ "function": _lambda,
+ "defun": _lambda,
+ "block": function(body) {
+ if (body) return rmblock([ "block", tighten(body) ]);
+ },
+ "binary": function(op, left, right) {
+ return when_constant([ "binary", op, walk(left), walk(right) ], function yes(c){
+ return best_of(walk(c), this);
+ }, function no() {
+ return function(){
+ if(op != "==" && op != "!=") return;
+ var l = walk(left), r = walk(right);
+ if(l && l[0] == "unary-prefix" && l[1] == "!" && l[2][0] == "num")
+ left = ['num', +!l[2][1]];
+ else if (r && r[0] == "unary-prefix" && r[1] == "!" && r[2][0] == "num")
+ right = ['num', +!r[2][1]];
+ return ["binary", op, left, right];
+ }() || this;
+ });
+ },
+ "conditional": function(c, t, e) {
+ return make_conditional(walk(c), walk(t), walk(e));
+ },
+ "try": function(t, c, f) {
+ return [
+ "try",
+ tighten(t),
+ c != null ? [ c[0], tighten(c[1]) ] : null,
+ f != null ? tighten(f) : null
+ ];
+ },
+ "unary-prefix": function(op, expr) {
+ expr = walk(expr);
+ var ret = [ "unary-prefix", op, expr ];
+ if (op == "!")
+ ret = best_of(ret, negate(expr));
+ return when_constant(ret, function(ast, val){
+ return walk(ast); // it's either true or false, so minifies to !0 or !1
+ }, function() { return ret });
+ },
+ "name": function(name) {
+ switch (name) {
+ case "true": return [ "unary-prefix", "!", [ "num", 0 ]];
+ case "false": return [ "unary-prefix", "!", [ "num", 1 ]];
+ }
+ },
+ "while": _do_while,
+ "assign": function(op, lvalue, rvalue) {
+ lvalue = walk(lvalue);
+ rvalue = walk(rvalue);
+ var okOps = [ '+', '-', '/', '*', '%', '>>', '<<', '>>>', '|', '^', '&' ];
+ if (op === true && lvalue[0] === "name" && rvalue[0] === "binary" &&
+ ~okOps.indexOf(rvalue[1]) && rvalue[2][0] === "name" &&
+ rvalue[2][1] === lvalue[1]) {
+ return [ this[0], rvalue[1], lvalue, rvalue[3] ]
+ }
+ return [ this[0], op, lvalue, rvalue ];
+ },
+ "call": function(expr, args) {
+ expr = walk(expr);
+ if (options.unsafe && expr[0] == "dot" && expr[1][0] == "string" && expr[2] == "toString") {
+ return expr[1];
+ }
+ return [ this[0], expr, MAP(args, walk) ];
+ },
+ "num": function (num) {
+ if (!isFinite(num))
+ return [ "binary", "/", num === 1 / 0
+ ? [ "num", 1 ] : num === -1 / 0
+ ? [ "unary-prefix", "-", [ "num", 1 ] ]
+ : [ "num", 0 ], [ "num", 0 ] ];
+
+ return [ this[0], num ];
+ }
+ }, function() {
+ return walk(prepare_ifs(walk(prepare_ifs(ast))));
+ });
+};
+
+function squeeze_2(ast, options) {
+ var w = ast_walker(), walk = w.walk, scope;
+ function with_scope(s, cont) {
+ var save = scope, ret;
+ scope = s;
+ ret = cont();
+ scope = save;
+ return ret;
+ };
+ function lambda(name, args, body) {
+ return [ this[0], name, args, with_scope(body.scope, curry(MAP, body, walk)) ];
+ };
+ return w.with_walkers({
+ "directive": function(dir) {
+ if (scope.active_directive(dir))
+ return [ "block" ];
+ scope.directives.push(dir);
+ },
+ "toplevel": function(body) {
+ return [ this[0], with_scope(this.scope, curry(MAP, body, walk)) ];
+ },
+ "function": lambda,
+ "defun": lambda
+ }, function(){
+ return walk(ast_add_scope(ast));
+ });
+};
+
+/* -----[ re-generate code from the AST ]----- */
+
+var DOT_CALL_NO_PARENS = jsp.array_to_hash([
+ "name",
+ "array",
+ "object",
+ "string",
+ "dot",
+ "sub",
+ "call",
+ "regexp",
+ "defun"
+]);
+
+function make_string(str, ascii_only) {
+ var dq = 0, sq = 0;
+ str = str.replace(/[\\\b\f\n\r\t\x22\x27\u2028\u2029\0]/g, function(s){
+ switch (s) {
+ case "\\": return "\\\\";
+ case "\b": return "\\b";
+ case "\f": return "\\f";
+ case "\n": return "\\n";
+ case "\r": return "\\r";
+ case "\u2028": return "\\u2028";
+ case "\u2029": return "\\u2029";
+ case '"': ++dq; return '"';
+ case "'": ++sq; return "'";
+ case "\0": return "\\0";
+ }
+ return s;
+ });
+ if (ascii_only) str = to_ascii(str);
+ if (dq > sq) return "'" + str.replace(/\x27/g, "\\'") + "'";
+ else return '"' + str.replace(/\x22/g, '\\"') + '"';
+};
+
+function to_ascii(str) {
+ return str.replace(/[\u0080-\uffff]/g, function(ch) {
+ var code = ch.charCodeAt(0).toString(16);
+ while (code.length < 4) code = "0" + code;
+ return "\\u" + code;
+ });
+};
+
+var SPLICE_NEEDS_BRACKETS = jsp.array_to_hash([ "if", "while", "do", "for", "for-in", "with" ]);
+
+function gen_code(ast, options) {
+ options = defaults(options, {
+ indent_start : 0,
+ indent_level : 4,
+ quote_keys : false,
+ space_colon : false,
+ beautify : false,
+ ascii_only : false,
+ inline_script: false
+ });
+ var beautify = !!options.beautify;
+ var indentation = 0,
+ newline = beautify ? "\n" : "",
+ space = beautify ? " " : "";
+
+ function encode_string(str) {
+ var ret = make_string(str, options.ascii_only);
+ if (options.inline_script)
+ ret = ret.replace(/<\x2fscript([>\/\t\n\f\r ])/gi, "<\\/script$1");
+ return ret;
+ };
+
+ function make_name(name) {
+ name = name.toString();
+ if (options.ascii_only)
+ name = to_ascii(name);
+ return name;
+ };
+
+ function indent(line) {
+ if (line == null)
+ line = "";
+ if (beautify)
+ line = repeat_string(" ", options.indent_start + indentation * options.indent_level) + line;
+ return line;
+ };
+
+ function with_indent(cont, incr) {
+ if (incr == null) incr = 1;
+ indentation += incr;
+ try { return cont.apply(null, slice(arguments, 1)); }
+ finally { indentation -= incr; }
+ };
+
+ function last_char(str) {
+ str = str.toString();
+ return str.charAt(str.length - 1);
+ };
+
+ function first_char(str) {
+ return str.toString().charAt(0);
+ };
+
+ function add_spaces(a) {
+ if (beautify)
+ return a.join(" ");
+ var b = [];
+ for (var i = 0; i < a.length; ++i) {
+ var next = a[i + 1];
+ b.push(a[i]);
+ if (next &&
+ ((is_identifier_char(last_char(a[i])) && (is_identifier_char(first_char(next))
+ || first_char(next) == "\\")) ||
+ (/[\+\-]$/.test(a[i].toString()) && /^[\+\-]/.test(next.toString()) ||
+ last_char(a[i]) == "/" && first_char(next) == "/"))) {
+ b.push(" ");
+ }
+ }
+ return b.join("");
+ };
+
+ function add_commas(a) {
+ return a.join("," + space);
+ };
+
+ function parenthesize(expr) {
+ var gen = make(expr);
+ for (var i = 1; i < arguments.length; ++i) {
+ var el = arguments[i];
+ if ((el instanceof Function && el(expr)) || expr[0] == el)
+ return "(" + gen + ")";
+ }
+ return gen;
+ };
+
+ function best_of(a) {
+ if (a.length == 1) {
+ return a[0];
+ }
+ if (a.length == 2) {
+ var b = a[1];
+ a = a[0];
+ return a.length <= b.length ? a : b;
+ }
+ return best_of([ a[0], best_of(a.slice(1)) ]);
+ };
+
+ function needs_parens(expr) {
+ if (expr[0] == "function" || expr[0] == "object") {
+ // dot/call on a literal function requires the
+ // function literal itself to be parenthesized
+ // only if it's the first "thing" in a
+ // statement. This means that the parent is
+ // "stat", but it could also be a "seq" and
+ // we're the first in this "seq" and the
+ // parent is "stat", and so on. Messy stuff,
+ // but it worths the trouble.
+ var a = slice(w.stack()), self = a.pop(), p = a.pop();
+ while (p) {
+ if (p[0] == "stat") return true;
+ if (((p[0] == "seq" || p[0] == "call" || p[0] == "dot" || p[0] == "sub" || p[0] == "conditional") && p[1] === self) ||
+ ((p[0] == "binary" || p[0] == "assign" || p[0] == "unary-postfix") && p[2] === self)) {
+ self = p;
+ p = a.pop();
+ } else {
+ return false;
+ }
+ }
+ }
+ return !HOP(DOT_CALL_NO_PARENS, expr[0]);
+ };
+
+ function make_num(num) {
+ var str = num.toString(10), a = [ str.replace(/^0\./, ".").replace('e+', 'e') ], m;
+ if (Math.floor(num) === num) {
+ if (num >= 0) {
+ a.push("0x" + num.toString(16).toLowerCase(), // probably pointless
+ "0" + num.toString(8)); // same.
+ } else {
+ a.push("-0x" + (-num).toString(16).toLowerCase(), // probably pointless
+ "-0" + (-num).toString(8)); // same.
+ }
+ if ((m = /^(.*?)(0+)$/.exec(num))) {
+ a.push(m[1] + "e" + m[2].length);
+ }
+ } else if ((m = /^0?\.(0+)(.*)$/.exec(num))) {
+ a.push(m[2] + "e-" + (m[1].length + m[2].length),
+ str.substr(str.indexOf(".")));
+ }
+ return best_of(a);
+ };
+
+ var w = ast_walker();
+ var make = w.walk;
+ return w.with_walkers({
+ "string": encode_string,
+ "num": make_num,
+ "name": make_name,
+ "debugger": function(){ return "debugger;" },
+ "toplevel": function(statements) {
+ return make_block_statements(statements)
+ .join(newline + newline);
+ },
+ "splice": function(statements) {
+ var parent = w.parent();
+ if (HOP(SPLICE_NEEDS_BRACKETS, parent)) {
+ // we need block brackets in this case
+ return make_block.apply(this, arguments);
+ } else {
+ return MAP(make_block_statements(statements, true),
+ function(line, i) {
+ // the first line is already indented
+ return i > 0 ? indent(line) : line;
+ }).join(newline);
+ }
+ },
+ "block": make_block,
+ "var": function(defs) {
+ return "var " + add_commas(MAP(defs, make_1vardef)) + ";";
+ },
+ "const": function(defs) {
+ return "const " + add_commas(MAP(defs, make_1vardef)) + ";";
+ },
+ "try": function(tr, ca, fi) {
+ var out = [ "try", make_block(tr) ];
+ if (ca) out.push("catch", "(" + ca[0] + ")", make_block(ca[1]));
+ if (fi) out.push("finally", make_block(fi));
+ return add_spaces(out);
+ },
+ "throw": function(expr) {
+ return add_spaces([ "throw", make(expr) ]) + ";";
+ },
+ "new": function(ctor, args) {
+ args = args.length > 0 ? "(" + add_commas(MAP(args, function(expr){
+ return parenthesize(expr, "seq");
+ })) + ")" : "";
+ return add_spaces([ "new", parenthesize(ctor, "seq", "binary", "conditional", "assign", function(expr){
+ var w = ast_walker(), has_call = {};
+ try {
+ w.with_walkers({
+ "call": function() { throw has_call },
+ "function": function() { return this }
+ }, function(){
+ w.walk(expr);
+ });
+ } catch(ex) {
+ if (ex === has_call)
+ return true;
+ throw ex;
+ }
+ }) + args ]);
+ },
+ "switch": function(expr, body) {
+ return add_spaces([ "switch", "(" + make(expr) + ")", make_switch_block(body) ]);
+ },
+ "break": function(label) {
+ var out = "break";
+ if (label != null)
+ out += " " + make_name(label);
+ return out + ";";
+ },
+ "continue": function(label) {
+ var out = "continue";
+ if (label != null)
+ out += " " + make_name(label);
+ return out + ";";
+ },
+ "conditional": function(co, th, el) {
+ return add_spaces([ parenthesize(co, "assign", "seq", "conditional"), "?",
+ parenthesize(th, "seq"), ":",
+ parenthesize(el, "seq") ]);
+ },
+ "assign": function(op, lvalue, rvalue) {
+ if (op && op !== true) op += "=";
+ else op = "=";
+ return add_spaces([ make(lvalue), op, parenthesize(rvalue, "seq") ]);
+ },
+ "dot": function(expr) {
+ var out = make(expr), i = 1;
+ if (expr[0] == "num") {
+ if (!/[a-f.]/i.test(out))
+ out += ".";
+ } else if (expr[0] != "function" && needs_parens(expr))
+ out = "(" + out + ")";
+ while (i < arguments.length)
+ out += "." + make_name(arguments[i++]);
+ return out;
+ },
+ "call": function(func, args) {
+ var f = make(func);
+ if (f.charAt(0) != "(" && needs_parens(func))
+ f = "(" + f + ")";
+ return f + "(" + add_commas(MAP(args, function(expr){
+ return parenthesize(expr, "seq");
+ })) + ")";
+ },
+ "function": make_function,
+ "defun": make_function,
+ "if": function(co, th, el) {
+ var out = [ "if", "(" + make(co) + ")", el ? make_then(th) : make(th) ];
+ if (el) {
+ out.push("else", make(el));
+ }
+ return add_spaces(out);
+ },
+ "for": function(init, cond, step, block) {
+ var out = [ "for" ];
+ init = (init != null ? make(init) : "").replace(/;*\s*$/, ";" + space);
+ cond = (cond != null ? make(cond) : "").replace(/;*\s*$/, ";" + space);
+ step = (step != null ? make(step) : "").replace(/;*\s*$/, "");
+ var args = init + cond + step;
+ if (args == "; ; ") args = ";;";
+ out.push("(" + args + ")", make(block));
+ return add_spaces(out);
+ },
+ "for-in": function(vvar, key, hash, block) {
+ return add_spaces([ "for", "(" +
+ (vvar ? make(vvar).replace(/;+$/, "") : make(key)),
+ "in",
+ make(hash) + ")", make(block) ]);
+ },
+ "while": function(condition, block) {
+ return add_spaces([ "while", "(" + make(condition) + ")", make(block) ]);
+ },
+ "do": function(condition, block) {
+ return add_spaces([ "do", make(block), "while", "(" + make(condition) + ")" ]) + ";";
+ },
+ "return": function(expr) {
+ var out = [ "return" ];
+ if (expr != null) out.push(make(expr));
+ return add_spaces(out) + ";";
+ },
+ "binary": function(operator, lvalue, rvalue) {
+ var left = make(lvalue), right = make(rvalue);
+ // XXX: I'm pretty sure other cases will bite here.
+ // we need to be smarter.
+ // adding parens all the time is the safest bet.
+ if (member(lvalue[0], [ "assign", "conditional", "seq" ]) ||
+ lvalue[0] == "binary" && PRECEDENCE[operator] > PRECEDENCE[lvalue[1]] ||
+ lvalue[0] == "function" && needs_parens(this)) {
+ left = "(" + left + ")";
+ }
+ if (member(rvalue[0], [ "assign", "conditional", "seq" ]) ||
+ rvalue[0] == "binary" && PRECEDENCE[operator] >= PRECEDENCE[rvalue[1]] &&
+ !(rvalue[1] == operator && member(operator, [ "&&", "||", "*" ]))) {
+ right = "(" + right + ")";
+ }
+ else if (!beautify && options.inline_script && (operator == "<" || operator == "<<")
+ && rvalue[0] == "regexp" && /^script/i.test(rvalue[1])) {
+ right = " " + right;
+ }
+ return add_spaces([ left, operator, right ]);
+ },
+ "unary-prefix": function(operator, expr) {
+ var val = make(expr);
+ if (!(expr[0] == "num" || (expr[0] == "unary-prefix" && !HOP(OPERATORS, operator + expr[1])) || !needs_parens(expr)))
+ val = "(" + val + ")";
+ return operator + (jsp.is_alphanumeric_char(operator.charAt(0)) ? " " : "") + val;
+ },
+ "unary-postfix": function(operator, expr) {
+ var val = make(expr);
+ if (!(expr[0] == "num" || (expr[0] == "unary-postfix" && !HOP(OPERATORS, operator + expr[1])) || !needs_parens(expr)))
+ val = "(" + val + ")";
+ return val + operator;
+ },
+ "sub": function(expr, subscript) {
+ var hash = make(expr);
+ if (needs_parens(expr))
+ hash = "(" + hash + ")";
+ return hash + "[" + make(subscript) + "]";
+ },
+ "object": function(props) {
+ var obj_needs_parens = needs_parens(this);
+ if (props.length == 0)
+ return obj_needs_parens ? "({})" : "{}";
+ var out = "{" + newline + with_indent(function(){
+ return MAP(props, function(p){
+ if (p.length == 3) {
+ // getter/setter. The name is in p[0], the arg.list in p[1][2], the
+ // body in p[1][3] and type ("get" / "set") in p[2].
+ return indent(make_function(p[0], p[1][2], p[1][3], p[2], true));
+ }
+ var key = p[0], val = parenthesize(p[1], "seq");
+ if (options.quote_keys) {
+ key = encode_string(key);
+ } else if ((typeof key == "number" || !beautify && +key + "" == key)
+ && parseFloat(key) >= 0) {
+ key = make_num(+key);
+ } else if (!is_identifier(key)) {
+ key = encode_string(key);
+ }
+ return indent(add_spaces(beautify && options.space_colon
+ ? [ key, ":", val ]
+ : [ key + ":", val ]));
+ }).join("," + newline);
+ }) + newline + indent("}");
+ return obj_needs_parens ? "(" + out + ")" : out;
+ },
+ "regexp": function(rx, mods) {
+ if (options.ascii_only) rx = to_ascii(rx);
+ return "/" + rx + "/" + mods;
+ },
+ "array": function(elements) {
+ if (elements.length == 0) return "[]";
+ return add_spaces([ "[", add_commas(MAP(elements, function(el, i){
+ if (!beautify && el[0] == "atom" && el[1] == "undefined") return i === elements.length - 1 ? "," : "";
+ return parenthesize(el, "seq");
+ })), "]" ]);
+ },
+ "stat": function(stmt) {
+ return stmt != null
+ ? make(stmt).replace(/;*\s*$/, ";")
+ : ";";
+ },
+ "seq": function() {
+ return add_commas(MAP(slice(arguments), make));
+ },
+ "label": function(name, block) {
+ return add_spaces([ make_name(name), ":", make(block) ]);
+ },
+ "with": function(expr, block) {
+ return add_spaces([ "with", "(" + make(expr) + ")", make(block) ]);
+ },
+ "atom": function(name) {
+ return make_name(name);
+ },
+ "directive": function(dir) {
+ return make_string(dir) + ";";
+ }
+ }, function(){ return make(ast) });
+
+ // The squeezer replaces "block"-s that contain only a single
+ // statement with the statement itself; technically, the AST
+ // is correct, but this can create problems when we output an
+ // IF having an ELSE clause where the THEN clause ends in an
+ // IF *without* an ELSE block (then the outer ELSE would refer
+ // to the inner IF). This function checks for this case and
+ // adds the block brackets if needed.
+ function make_then(th) {
+ if (th == null) return ";";
+ if (th[0] == "do") {
+ // https://github.com/mishoo/UglifyJS/issues/#issue/57
+ // IE croaks with "syntax error" on code like this:
+ // if (foo) do ... while(cond); else ...
+ // we need block brackets around do/while
+ return make_block([ th ]);
+ }
+ var b = th;
+ while (true) {
+ var type = b[0];
+ if (type == "if") {
+ if (!b[3])
+ // no else, we must add the block
+ return make([ "block", [ th ]]);
+ b = b[3];
+ }
+ else if (type == "while" || type == "do") b = b[2];
+ else if (type == "for" || type == "for-in") b = b[4];
+ else break;
+ }
+ return make(th);
+ };
+
+ function make_function(name, args, body, keyword, no_parens) {
+ var out = keyword || "function";
+ if (name) {
+ out += " " + make_name(name);
+ }
+ out += "(" + add_commas(MAP(args, make_name)) + ")";
+ out = add_spaces([ out, make_block(body) ]);
+ return (!no_parens && needs_parens(this)) ? "(" + out + ")" : out;
+ };
+
+ function must_has_semicolon(node) {
+ switch (node[0]) {
+ case "with":
+ case "while":
+ return empty(node[2]) || must_has_semicolon(node[2]);
+ case "for":
+ case "for-in":
+ return empty(node[4]) || must_has_semicolon(node[4]);
+ case "if":
+ if (empty(node[2]) && !node[3]) return true; // `if' with empty `then' and no `else'
+ if (node[3]) {
+ if (empty(node[3])) return true; // `else' present but empty
+ return must_has_semicolon(node[3]); // dive into the `else' branch
+ }
+ return must_has_semicolon(node[2]); // dive into the `then' branch
+ case "directive":
+ return true;
+ }
+ };
+
+ function make_block_statements(statements, noindent) {
+ for (var a = [], last = statements.length - 1, i = 0; i <= last; ++i) {
+ var stat = statements[i];
+ var code = make(stat);
+ if (code != ";") {
+ if (!beautify && i == last && !must_has_semicolon(stat)) {
+ code = code.replace(/;+\s*$/, "");
+ }
+ a.push(code);
+ }
+ }
+ return noindent ? a : MAP(a, indent);
+ };
+
+ function make_switch_block(body) {
+ var n = body.length;
+ if (n == 0) return "{}";
+ return "{" + newline + MAP(body, function(branch, i){
+ var has_body = branch[1].length > 0, code = with_indent(function(){
+ return indent(branch[0]
+ ? add_spaces([ "case", make(branch[0]) + ":" ])
+ : "default:");
+ }, 0.5) + (has_body ? newline + with_indent(function(){
+ return make_block_statements(branch[1]).join(newline);
+ }) : "");
+ if (!beautify && has_body && i < n - 1)
+ code += ";";
+ return code;
+ }).join(newline) + newline + indent("}");
+ };
+
+ function make_block(statements) {
+ if (!statements) return ";";
+ if (statements.length == 0) return "{}";
+ return "{" + newline + with_indent(function(){
+ return make_block_statements(statements).join(newline);
+ }) + newline + indent("}");
+ };
+
+ function make_1vardef(def) {
+ var name = def[0], val = def[1];
+ if (val != null)
+ name = add_spaces([ make_name(name), "=", parenthesize(val, "seq") ]);
+ return name;
+ };
+
+};
+
+function split_lines(code, max_line_length) {
+ var splits = [ 0 ];
+ jsp.parse(function(){
+ var next_token = jsp.tokenizer(code);
+ var last_split = 0;
+ var prev_token;
+ function current_length(tok) {
+ return tok.pos - last_split;
+ };
+ function split_here(tok) {
+ last_split = tok.pos;
+ splits.push(last_split);
+ };
+ function custom(){
+ var tok = next_token.apply(this, arguments);
+ out: {
+ if (prev_token) {
+ if (prev_token.type == "keyword") break out;
+ }
+ if (current_length(tok) > max_line_length) {
+ switch (tok.type) {
+ case "keyword":
+ case "atom":
+ case "name":
+ case "punc":
+ split_here(tok);
+ break out;
+ }
+ }
+ }
+ prev_token = tok;
+ return tok;
+ };
+ custom.context = function() {
+ return next_token.context.apply(this, arguments);
+ };
+ return custom;
+ }());
+ return splits.map(function(pos, i){
+ return code.substring(pos, splits[i + 1] || code.length);
+ }).join("\n");
+};
+
+/* -----[ Utilities ]----- */
+
+function repeat_string(str, i) {
+ if (i <= 0) return "";
+ if (i == 1) return str;
+ var d = repeat_string(str, i >> 1);
+ d += d;
+ if (i & 1) d += str;
+ return d;
+};
+
+function defaults(args, defs) {
+ var ret = {};
+ if (args === true)
+ args = {};
+ for (var i in defs) if (HOP(defs, i)) {
+ ret[i] = (args && HOP(args, i)) ? args[i] : defs[i];
+ }
+ return ret;
+};
+
+function is_identifier(name) {
+ return /^[a-z_$][a-z0-9_$]*$/i.test(name)
+ && name != "this"
+ && !HOP(jsp.KEYWORDS_ATOM, name)
+ && !HOP(jsp.RESERVED_WORDS, name)
+ && !HOP(jsp.KEYWORDS, name);
+};
+
+function HOP(obj, prop) {
+ return Object.prototype.hasOwnProperty.call(obj, prop);
+};
+
+// some utilities
+
+var MAP;
+
+(function(){
+ MAP = function(a, f, o) {
+ var ret = [], top = [], i;
+ function doit() {
+ var val = f.call(o, a[i], i);
+ if (val instanceof AtTop) {
+ val = val.v;
+ if (val instanceof Splice) {
+ top.push.apply(top, val.v);
+ } else {
+ top.push(val);
+ }
+ }
+ else if (val != skip) {
+ if (val instanceof Splice) {
+ ret.push.apply(ret, val.v);
+ } else {
+ ret.push(val);
+ }
+ }
+ };
+ if (a instanceof Array) for (i = 0; i < a.length; ++i) doit();
+ else for (i in a) if (HOP(a, i)) doit();
+ return top.concat(ret);
+ };
+ MAP.at_top = function(val) { return new AtTop(val) };
+ MAP.splice = function(val) { return new Splice(val) };
+ var skip = MAP.skip = {};
+ function AtTop(val) { this.v = val };
+ function Splice(val) { this.v = val };
+})();
+
+/* -----[ Exports ]----- */
+
+exports.ast_walker = ast_walker;
+exports.ast_mangle = ast_mangle;
+exports.ast_squeeze = ast_squeeze;
+exports.ast_lift_variables = ast_lift_variables;
+exports.gen_code = gen_code;
+exports.ast_add_scope = ast_add_scope;
+exports.set_logger = function(logger) { warn = logger };
+exports.make_string = make_string;
+exports.split_lines = split_lines;
+exports.MAP = MAP;
+
+// keep this last!
+exports.ast_squeeze_more = require("./squeeze-more").ast_squeeze_more;
+
+// Local variables:
+// js-indent-level: 4
+// End:
+});
+define('uglifyjs/index', ["require", "exports", "module", "./parse-js", "./process", "./consolidator"], function(require, exports, module) {
+//convienence function(src, [options]);
+function uglify(orig_code, options){
+ options || (options = {});
+ var jsp = uglify.parser;
+ var pro = uglify.uglify;
+
+ var ast = jsp.parse(orig_code, options.strict_semicolons); // parse code and get the initial AST
+ ast = pro.ast_mangle(ast, options.mangle_options); // get a new AST with mangled names
+ ast = pro.ast_squeeze(ast, options.squeeze_options); // get an AST with compression optimizations
+ var final_code = pro.gen_code(ast, options.gen_options); // compressed code here
+ return final_code;
+};
+
+uglify.parser = require("./parse-js");
+uglify.uglify = require("./process");
+uglify.consolidator = require("./consolidator");
+
+module.exports = uglify
+});/* -*- Mode: js; js-indent-level: 2; -*- */
+/*
+ * Copyright 2011 Mozilla Foundation and contributors
+ * Licensed under the New BSD license. See LICENSE or:
+ * http://opensource.org/licenses/BSD-3-Clause
+ */
+
+define('source-map/array-set', function (require, exports, module) {
+
+ var util = require('./util');
+
+ /**
+ * A data structure which is a combination of an array and a set. Adding a new
+ * member is O(1), testing for membership is O(1), and finding the index of an
+ * element is O(1). Removing elements from the set is not supported. Only
+ * strings are supported for membership.
+ */
+ function ArraySet() {
+ this._array = [];
+ this._set = {};
+ }
+
+ /**
+ * Static method for creating ArraySet instances from an existing array.
+ */
+ ArraySet.fromArray = function ArraySet_fromArray(aArray, aAllowDuplicates) {
+ var set = new ArraySet();
+ for (var i = 0, len = aArray.length; i < len; i++) {
+ set.add(aArray[i], aAllowDuplicates);
+ }
+ return set;
+ };
+
+ /**
+ * Add the given string to this set.
+ *
+ * @param String aStr
+ */
+ ArraySet.prototype.add = function ArraySet_add(aStr, aAllowDuplicates) {
+ var isDuplicate = this.has(aStr);
+ var idx = this._array.length;
+ if (!isDuplicate || aAllowDuplicates) {
+ this._array.push(aStr);
+ }
+ if (!isDuplicate) {
+ this._set[util.toSetString(aStr)] = idx;
+ }
+ };
+
+ /**
+ * Is the given string a member of this set?
+ *
+ * @param String aStr
+ */
+ ArraySet.prototype.has = function ArraySet_has(aStr) {
+ return Object.prototype.hasOwnProperty.call(this._set,
+ util.toSetString(aStr));
+ };
+
+ /**
+ * What is the index of the given string in the array?
+ *
+ * @param String aStr
+ */
+ ArraySet.prototype.indexOf = function ArraySet_indexOf(aStr) {
+ if (this.has(aStr)) {
+ return this._set[util.toSetString(aStr)];
+ }
+ throw new Error('"' + aStr + '" is not in the set.');
+ };
+
+ /**
+ * What is the element at the given index?
+ *
+ * @param Number aIdx
+ */
+ ArraySet.prototype.at = function ArraySet_at(aIdx) {
+ if (aIdx >= 0 && aIdx < this._array.length) {
+ return this._array[aIdx];
+ }
+ throw new Error('No element indexed by ' + aIdx);
+ };
+
+ /**
+ * Returns the array representation of this set (which has the proper indices
+ * indicated by indexOf). Note that this is a copy of the internal array used
+ * for storing the members so that no one can mess with internal state.
+ */
+ ArraySet.prototype.toArray = function ArraySet_toArray() {
+ return this._array.slice();
+ };
+
+ exports.ArraySet = ArraySet;
+
+});
+/* -*- Mode: js; js-indent-level: 2; -*- */
+/*
+ * Copyright 2011 Mozilla Foundation and contributors
+ * Licensed under the New BSD license. See LICENSE or:
+ * http://opensource.org/licenses/BSD-3-Clause
+ *
+ * Based on the Base 64 VLQ implementation in Closure Compiler:
+ * https://code.google.com/p/closure-compiler/source/browse/trunk/src/com/google/debugging/sourcemap/Base64VLQ.java
+ *
+ * Copyright 2011 The Closure Compiler Authors. All rights reserved.
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are
+ * met:
+ *
+ * * Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * * Redistributions in binary form must reproduce the above
+ * copyright notice, this list of conditions and the following
+ * disclaimer in the documentation and/or other materials provided
+ * with the distribution.
+ * * Neither the name of Google Inc. nor the names of its
+ * contributors may be used to endorse or promote products derived
+ * from this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+ * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+ * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
+ * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+ * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
+ * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+ * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+ * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+ * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+define('source-map/base64-vlq', function (require, exports, module) {
+
+ var base64 = require('./base64');
+
+ // A single base 64 digit can contain 6 bits of data. For the base 64 variable
+ // length quantities we use in the source map spec, the first bit is the sign,
+ // the next four bits are the actual value, and the 6th bit is the
+ // continuation bit. The continuation bit tells us whether there are more
+ // digits in this value following this digit.
+ //
+ // Continuation
+ // | Sign
+ // | |
+ // V V
+ // 101011
+
+ var VLQ_BASE_SHIFT = 5;
+
+ // binary: 100000
+ var VLQ_BASE = 1 << VLQ_BASE_SHIFT;
+
+ // binary: 011111
+ var VLQ_BASE_MASK = VLQ_BASE - 1;
+
+ // binary: 100000
+ var VLQ_CONTINUATION_BIT = VLQ_BASE;
+
+ /**
+ * Converts from a two-complement value to a value where the sign bit is
+ * is placed in the least significant bit. For example, as decimals:
+ * 1 becomes 2 (10 binary), -1 becomes 3 (11 binary)
+ * 2 becomes 4 (100 binary), -2 becomes 5 (101 binary)
+ */
+ function toVLQSigned(aValue) {
+ return aValue < 0
+ ? ((-aValue) << 1) + 1
+ : (aValue << 1) + 0;
+ }
+
+ /**
+ * Converts to a two-complement value from a value where the sign bit is
+ * is placed in the least significant bit. For example, as decimals:
+ * 2 (10 binary) becomes 1, 3 (11 binary) becomes -1
+ * 4 (100 binary) becomes 2, 5 (101 binary) becomes -2
+ */
+ function fromVLQSigned(aValue) {
+ var isNegative = (aValue & 1) === 1;
+ var shifted = aValue >> 1;
+ return isNegative
+ ? -shifted
+ : shifted;
+ }
+
+ /**
+ * Returns the base 64 VLQ encoded value.
+ */
+ exports.encode = function base64VLQ_encode(aValue) {
+ var encoded = "";
+ var digit;
+
+ var vlq = toVLQSigned(aValue);
+
+ do {
+ digit = vlq & VLQ_BASE_MASK;
+ vlq >>>= VLQ_BASE_SHIFT;
+ if (vlq > 0) {
+ // There are still more digits in this value, so we must make sure the
+ // continuation bit is marked.
+ digit |= VLQ_CONTINUATION_BIT;
+ }
+ encoded += base64.encode(digit);
+ } while (vlq > 0);
+
+ return encoded;
+ };
+
+ /**
+ * Decodes the next base 64 VLQ value from the given string and returns the
+ * value and the rest of the string.
+ */
+ exports.decode = function base64VLQ_decode(aStr) {
+ var i = 0;
+ var strLen = aStr.length;
+ var result = 0;
+ var shift = 0;
+ var continuation, digit;
+
+ do {
+ if (i >= strLen) {
+ throw new Error("Expected more digits in base 64 VLQ value.");
+ }
+ digit = base64.decode(aStr.charAt(i++));
+ continuation = !!(digit & VLQ_CONTINUATION_BIT);
+ digit &= VLQ_BASE_MASK;
+ result = result + (digit << shift);
+ shift += VLQ_BASE_SHIFT;
+ } while (continuation);
+
+ return {
+ value: fromVLQSigned(result),
+ rest: aStr.slice(i)
+ };
+ };
+
+});
+/* -*- Mode: js; js-indent-level: 2; -*- */
+/*
+ * Copyright 2011 Mozilla Foundation and contributors
+ * Licensed under the New BSD license. See LICENSE or:
+ * http://opensource.org/licenses/BSD-3-Clause
+ */
+
+define('source-map/base64', function (require, exports, module) {
+
+ var charToIntMap = {};
+ var intToCharMap = {};
+
+ 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'
+ .split('')
+ .forEach(function (ch, index) {
+ charToIntMap[ch] = index;
+ intToCharMap[index] = ch;
+ });
+
+ /**
+ * Encode an integer in the range of 0 to 63 to a single base 64 digit.
+ */
+ exports.encode = function base64_encode(aNumber) {
+ if (aNumber in intToCharMap) {
+ return intToCharMap[aNumber];
+ }
+ throw new TypeError("Must be between 0 and 63: " + aNumber);
+ };
+
+ /**
+ * Decode a single base 64 digit to an integer.
+ */
+ exports.decode = function base64_decode(aChar) {
+ if (aChar in charToIntMap) {
+ return charToIntMap[aChar];
+ }
+ throw new TypeError("Not a valid base 64 digit: " + aChar);
+ };
+
+});
+/* -*- Mode: js; js-indent-level: 2; -*- */
+/*
+ * Copyright 2011 Mozilla Foundation and contributors
+ * Licensed under the New BSD license. See LICENSE or:
+ * http://opensource.org/licenses/BSD-3-Clause
+ */
+
+define('source-map/binary-search', function (require, exports, module) {
+
+ /**
+ * Recursive implementation of binary search.
+ *
+ * @param aLow Indices here and lower do not contain the needle.
+ * @param aHigh Indices here and higher do not contain the needle.
+ * @param aNeedle The element being searched for.
+ * @param aHaystack The non-empty array being searched.
+ * @param aCompare Function which takes two elements and returns -1, 0, or 1.
+ */
+ function recursiveSearch(aLow, aHigh, aNeedle, aHaystack, aCompare) {
+ // This function terminates when one of the following is true:
+ //
+ // 1. We find the exact element we are looking for.
+ //
+ // 2. We did not find the exact element, but we can return the next
+ // closest element that is less than that element.
+ //
+ // 3. We did not find the exact element, and there is no next-closest
+ // element which is less than the one we are searching for, so we
+ // return null.
+ var mid = Math.floor((aHigh - aLow) / 2) + aLow;
+ var cmp = aCompare(aNeedle, aHaystack[mid], true);
+ if (cmp === 0) {
+ // Found the element we are looking for.
+ return aHaystack[mid];
+ }
+ else if (cmp > 0) {
+ // aHaystack[mid] is greater than our needle.
+ if (aHigh - mid > 1) {
+ // The element is in the upper half.
+ return recursiveSearch(mid, aHigh, aNeedle, aHaystack, aCompare);
+ }
+ // We did not find an exact match, return the next closest one
+ // (termination case 2).
+ return aHaystack[mid];
+ }
+ else {
+ // aHaystack[mid] is less than our needle.
+ if (mid - aLow > 1) {
+ // The element is in the lower half.
+ return recursiveSearch(aLow, mid, aNeedle, aHaystack, aCompare);
+ }
+ // The exact needle element was not found in this haystack. Determine if
+ // we are in termination case (2) or (3) and return the appropriate thing.
+ return aLow < 0
+ ? null
+ : aHaystack[aLow];
+ }
+ }
+
+ /**
+ * This is an implementation of binary search which will always try and return
+ * the next lowest value checked if there is no exact hit. This is because
+ * mappings between original and generated line/col pairs are single points,
+ * and there is an implicit region between each of them, so a miss just means
+ * that you aren't on the very start of a region.
+ *
+ * @param aNeedle The element you are looking for.
+ * @param aHaystack The array that is being searched.
+ * @param aCompare A function which takes the needle and an element in the
+ * array and returns -1, 0, or 1 depending on whether the needle is less
+ * than, equal to, or greater than the element, respectively.
+ */
+ exports.search = function search(aNeedle, aHaystack, aCompare) {
+ return aHaystack.length > 0
+ ? recursiveSearch(-1, aHaystack.length, aNeedle, aHaystack, aCompare)
+ : null;
+ };
+
+});
+/* -*- Mode: js; js-indent-level: 2; -*- */
+/*
+ * Copyright 2011 Mozilla Foundation and contributors
+ * Licensed under the New BSD license. See LICENSE or:
+ * http://opensource.org/licenses/BSD-3-Clause
+ */
+
+define('source-map/source-map-consumer', function (require, exports, module) {
+
+ var util = require('./util');
+ var binarySearch = require('./binary-search');
+ var ArraySet = require('./array-set').ArraySet;
+ var base64VLQ = require('./base64-vlq');
+
+ /**
+ * A SourceMapConsumer instance represents a parsed source map which we can
+ * query for information about the original file positions by giving it a file
+ * position in the generated source.
+ *
+ * The only parameter is the raw source map (either as a JSON string, or
+ * already parsed to an object). According to the spec, source maps have the
+ * following attributes:
+ *
+ * - version: Which version of the source map spec this map is following.
+ * - sources: An array of URLs to the original source files.
+ * - names: An array of identifiers which can be referrenced by individual mappings.
+ * - sourceRoot: Optional. The URL root from which all sources are relative.
+ * - sourcesContent: Optional. An array of contents of the original source files.
+ * - mappings: A string of base64 VLQs which contain the actual mappings.
+ * - file: The generated file this source map is associated with.
+ *
+ * Here is an example source map, taken from the source map spec[0]:
+ *
+ * {
+ * version : 3,
+ * file: "out.js",
+ * sourceRoot : "",
+ * sources: ["foo.js", "bar.js"],
+ * names: ["src", "maps", "are", "fun"],
+ * mappings: "AA,AB;;ABCDE;"
+ * }
+ *
+ * [0]: https://docs.google.com/document/d/1U1RGAehQwRypUTovF1KRlpiOFze0b-_2gc6fAH0KY0k/edit?pli=1#
+ */
+ function SourceMapConsumer(aSourceMap) {
+ var sourceMap = aSourceMap;
+ if (typeof aSourceMap === 'string') {
+ sourceMap = JSON.parse(aSourceMap.replace(/^\)\]\}'/, ''));
+ }
+
+ var version = util.getArg(sourceMap, 'version');
+ var sources = util.getArg(sourceMap, 'sources');
+ // Sass 3.3 leaves out the 'names' array, so we deviate from the spec (which
+ // requires the array) to play nice here.
+ var names = util.getArg(sourceMap, 'names', []);
+ var sourceRoot = util.getArg(sourceMap, 'sourceRoot', null);
+ var sourcesContent = util.getArg(sourceMap, 'sourcesContent', null);
+ var mappings = util.getArg(sourceMap, 'mappings');
+ var file = util.getArg(sourceMap, 'file', null);
+
+ // Once again, Sass deviates from the spec and supplies the version as a
+ // string rather than a number, so we use loose equality checking here.
+ if (version != this._version) {
+ throw new Error('Unsupported version: ' + version);
+ }
+
+ // Pass `true` below to allow duplicate names and sources. While source maps
+ // are intended to be compressed and deduplicated, the TypeScript compiler
+ // sometimes generates source maps with duplicates in them. See Github issue
+ // #72 and bugzil.la/889492.
+ this._names = ArraySet.fromArray(names, true);
+ this._sources = ArraySet.fromArray(sources, true);
+
+ this.sourceRoot = sourceRoot;
+ this.sourcesContent = sourcesContent;
+ this._mappings = mappings;
+ this.file = file;
+ }
+
+ /**
+ * Create a SourceMapConsumer from a SourceMapGenerator.
+ *
+ * @param SourceMapGenerator aSourceMap
+ * The source map that will be consumed.
+ * @returns SourceMapConsumer
+ */
+ SourceMapConsumer.fromSourceMap =
+ function SourceMapConsumer_fromSourceMap(aSourceMap) {
+ var smc = Object.create(SourceMapConsumer.prototype);
+
+ smc._names = ArraySet.fromArray(aSourceMap._names.toArray(), true);
+ smc._sources = ArraySet.fromArray(aSourceMap._sources.toArray(), true);
+ smc.sourceRoot = aSourceMap._sourceRoot;
+ smc.sourcesContent = aSourceMap._generateSourcesContent(smc._sources.toArray(),
+ smc.sourceRoot);
+ smc.file = aSourceMap._file;
+
+ smc.__generatedMappings = aSourceMap._mappings.slice()
+ .sort(util.compareByGeneratedPositions);
+ smc.__originalMappings = aSourceMap._mappings.slice()
+ .sort(util.compareByOriginalPositions);
+
+ return smc;
+ };
+
+ /**
+ * The version of the source mapping spec that we are consuming.
+ */
+ SourceMapConsumer.prototype._version = 3;
+
+ /**
+ * The list of original sources.
+ */
+ Object.defineProperty(SourceMapConsumer.prototype, 'sources', {
+ get: function () {
+ return this._sources.toArray().map(function (s) {
+ return this.sourceRoot ? util.join(this.sourceRoot, s) : s;
+ }, this);
+ }
+ });
+
+ // `__generatedMappings` and `__originalMappings` are arrays that hold the
+ // parsed mapping coordinates from the source map's "mappings" attribute. They
+ // are lazily instantiated, accessed via the `_generatedMappings` and
+ // `_originalMappings` getters respectively, and we only parse the mappings
+ // and create these arrays once queried for a source location. We jump through
+ // these hoops because there can be many thousands of mappings, and parsing
+ // them is expensive, so we only want to do it if we must.
+ //
+ // Each object in the arrays is of the form:
+ //
+ // {
+ // generatedLine: The line number in the generated code,
+ // generatedColumn: The column number in the generated code,
+ // source: The path to the original source file that generated this
+ // chunk of code,
+ // originalLine: The line number in the original source that
+ // corresponds to this chunk of generated code,
+ // originalColumn: The column number in the original source that
+ // corresponds to this chunk of generated code,
+ // name: The name of the original symbol which generated this chunk of
+ // code.
+ // }
+ //
+ // All properties except for `generatedLine` and `generatedColumn` can be
+ // `null`.
+ //
+ // `_generatedMappings` is ordered by the generated positions.
+ //
+ // `_originalMappings` is ordered by the original positions.
+
+ SourceMapConsumer.prototype.__generatedMappings = null;
+ Object.defineProperty(SourceMapConsumer.prototype, '_generatedMappings', {
+ get: function () {
+ if (!this.__generatedMappings) {
+ this.__generatedMappings = [];
+ this.__originalMappings = [];
+ this._parseMappings(this._mappings, this.sourceRoot);
+ }
+
+ return this.__generatedMappings;
+ }
+ });
+
+ SourceMapConsumer.prototype.__originalMappings = null;
+ Object.defineProperty(SourceMapConsumer.prototype, '_originalMappings', {
+ get: function () {
+ if (!this.__originalMappings) {
+ this.__generatedMappings = [];
+ this.__originalMappings = [];
+ this._parseMappings(this._mappings, this.sourceRoot);
+ }
+
+ return this.__originalMappings;
+ }
+ });
+
+ /**
+ * Parse the mappings in a string in to a data structure which we can easily
+ * query (the ordered arrays in the `this.__generatedMappings` and
+ * `this.__originalMappings` properties).
+ */
+ SourceMapConsumer.prototype._parseMappings =
+ function SourceMapConsumer_parseMappings(aStr, aSourceRoot) {
+ var generatedLine = 1;
+ var previousGeneratedColumn = 0;
+ var previousOriginalLine = 0;
+ var previousOriginalColumn = 0;
+ var previousSource = 0;
+ var previousName = 0;
+ var mappingSeparator = /^[,;]/;
+ var str = aStr;
+ var mapping;
+ var temp;
+
+ while (str.length > 0) {
+ if (str.charAt(0) === ';') {
+ generatedLine++;
+ str = str.slice(1);
+ previousGeneratedColumn = 0;
+ }
+ else if (str.charAt(0) === ',') {
+ str = str.slice(1);
+ }
+ else {
+ mapping = {};
+ mapping.generatedLine = generatedLine;
+
+ // Generated column.
+ temp = base64VLQ.decode(str);
+ mapping.generatedColumn = previousGeneratedColumn + temp.value;
+ previousGeneratedColumn = mapping.generatedColumn;
+ str = temp.rest;
+
+ if (str.length > 0 && !mappingSeparator.test(str.charAt(0))) {
+ // Original source.
+ temp = base64VLQ.decode(str);
+ mapping.source = this._sources.at(previousSource + temp.value);
+ previousSource += temp.value;
+ str = temp.rest;
+ if (str.length === 0 || mappingSeparator.test(str.charAt(0))) {
+ throw new Error('Found a source, but no line and column');
+ }
+
+ // Original line.
+ temp = base64VLQ.decode(str);
+ mapping.originalLine = previousOriginalLine + temp.value;
+ previousOriginalLine = mapping.originalLine;
+ // Lines are stored 0-based
+ mapping.originalLine += 1;
+ str = temp.rest;
+ if (str.length === 0 || mappingSeparator.test(str.charAt(0))) {
+ throw new Error('Found a source and line, but no column');
+ }
+
+ // Original column.
+ temp = base64VLQ.decode(str);
+ mapping.originalColumn = previousOriginalColumn + temp.value;
+ previousOriginalColumn = mapping.originalColumn;
+ str = temp.rest;
+
+ if (str.length > 0 && !mappingSeparator.test(str.charAt(0))) {
+ // Original name.
+ temp = base64VLQ.decode(str);
+ mapping.name = this._names.at(previousName + temp.value);
+ previousName += temp.value;
+ str = temp.rest;
+ }
+ }
+
+ this.__generatedMappings.push(mapping);
+ if (typeof mapping.originalLine === 'number') {
+ this.__originalMappings.push(mapping);
+ }
+ }
+ }
+
+ this.__generatedMappings.sort(util.compareByGeneratedPositions);
+ this.__originalMappings.sort(util.compareByOriginalPositions);
+ };
+
+ /**
+ * Find the mapping that best matches the hypothetical "needle" mapping that
+ * we are searching for in the given "haystack" of mappings.
+ */
+ SourceMapConsumer.prototype._findMapping =
+ function SourceMapConsumer_findMapping(aNeedle, aMappings, aLineName,
+ aColumnName, aComparator) {
+ // To return the position we are searching for, we must first find the
+ // mapping for the given position and then return the opposite position it
+ // points to. Because the mappings are sorted, we can use binary search to
+ // find the best mapping.
+
+ if (aNeedle[aLineName] <= 0) {
+ throw new TypeError('Line must be greater than or equal to 1, got '
+ + aNeedle[aLineName]);
+ }
+ if (aNeedle[aColumnName] < 0) {
+ throw new TypeError('Column must be greater than or equal to 0, got '
+ + aNeedle[aColumnName]);
+ }
+
+ return binarySearch.search(aNeedle, aMappings, aComparator);
+ };
+
+ /**
+ * Returns the original source, line, and column information for the generated
+ * source's line and column positions provided. The only argument is an object
+ * with the following properties:
+ *
+ * - line: The line number in the generated source.
+ * - column: The column number in the generated source.
+ *
+ * and an object is returned with the following properties:
+ *
+ * - source: The original source file, or null.
+ * - line: The line number in the original source, or null.
+ * - column: The column number in the original source, or null.
+ * - name: The original identifier, or null.
+ */
+ SourceMapConsumer.prototype.originalPositionFor =
+ function SourceMapConsumer_originalPositionFor(aArgs) {
+ var needle = {
+ generatedLine: util.getArg(aArgs, 'line'),
+ generatedColumn: util.getArg(aArgs, 'column')
+ };
+
+ var mapping = this._findMapping(needle,
+ this._generatedMappings,
+ "generatedLine",
+ "generatedColumn",
+ util.compareByGeneratedPositions);
+
+ if (mapping) {
+ var source = util.getArg(mapping, 'source', null);
+ if (source && this.sourceRoot) {
+ source = util.join(this.sourceRoot, source);
+ }
+ return {
+ source: source,
+ line: util.getArg(mapping, 'originalLine', null),
+ column: util.getArg(mapping, 'originalColumn', null),
+ name: util.getArg(mapping, 'name', null)
+ };
+ }
+
+ return {
+ source: null,
+ line: null,
+ column: null,
+ name: null
+ };
+ };
+
+ /**
+ * Returns the original source content. The only argument is the url of the
+ * original source file. Returns null if no original source content is
+ * availible.
+ */
+ SourceMapConsumer.prototype.sourceContentFor =
+ function SourceMapConsumer_sourceContentFor(aSource) {
+ if (!this.sourcesContent) {
+ return null;
+ }
+
+ if (this.sourceRoot) {
+ aSource = util.relative(this.sourceRoot, aSource);
+ }
+
+ if (this._sources.has(aSource)) {
+ return this.sourcesContent[this._sources.indexOf(aSource)];
+ }
+
+ var url;
+ if (this.sourceRoot
+ && (url = util.urlParse(this.sourceRoot))) {
+ // XXX: file:// URIs and absolute paths lead to unexpected behavior for
+ // many users. We can help them out when they expect file:// URIs to
+ // behave like it would if they were running a local HTTP server. See
+ // https://bugzilla.mozilla.org/show_bug.cgi?id=885597.
+ var fileUriAbsPath = aSource.replace(/^file:\/\//, "");
+ if (url.scheme == "file"
+ && this._sources.has(fileUriAbsPath)) {
+ return this.sourcesContent[this._sources.indexOf(fileUriAbsPath)]
+ }
+
+ if ((!url.path || url.path == "/")
+ && this._sources.has("/" + aSource)) {
+ return this.sourcesContent[this._sources.indexOf("/" + aSource)];
+ }
+ }
+
+ throw new Error('"' + aSource + '" is not in the SourceMap.');
+ };
+
+ /**
+ * Returns the generated line and column information for the original source,
+ * line, and column positions provided. The only argument is an object with
+ * the following properties:
+ *
+ * - source: The filename of the original source.
+ * - line: The line number in the original source.
+ * - column: The column number in the original source.
+ *
+ * and an object is returned with the following properties:
+ *
+ * - line: The line number in the generated source, or null.
+ * - column: The column number in the generated source, or null.
+ */
+ SourceMapConsumer.prototype.generatedPositionFor =
+ function SourceMapConsumer_generatedPositionFor(aArgs) {
+ var needle = {
+ source: util.getArg(aArgs, 'source'),
+ originalLine: util.getArg(aArgs, 'line'),
+ originalColumn: util.getArg(aArgs, 'column')
+ };
+
+ if (this.sourceRoot) {
+ needle.source = util.relative(this.sourceRoot, needle.source);
+ }
+
+ var mapping = this._findMapping(needle,
+ this._originalMappings,
+ "originalLine",
+ "originalColumn",
+ util.compareByOriginalPositions);
+
+ if (mapping) {
+ return {
+ line: util.getArg(mapping, 'generatedLine', null),
+ column: util.getArg(mapping, 'generatedColumn', null)
+ };
+ }
+
+ return {
+ line: null,
+ column: null
+ };
+ };
+
+ SourceMapConsumer.GENERATED_ORDER = 1;
+ SourceMapConsumer.ORIGINAL_ORDER = 2;
+
+ /**
+ * Iterate over each mapping between an original source/line/column and a
+ * generated line/column in this source map.
+ *
+ * @param Function aCallback
+ * The function that is called with each mapping.
+ * @param Object aContext
+ * Optional. If specified, this object will be the value of `this` every
+ * time that `aCallback` is called.
+ * @param aOrder
+ * Either `SourceMapConsumer.GENERATED_ORDER` or
+ * `SourceMapConsumer.ORIGINAL_ORDER`. Specifies whether you want to
+ * iterate over the mappings sorted by the generated file's line/column
+ * order or the original's source/line/column order, respectively. Defaults to
+ * `SourceMapConsumer.GENERATED_ORDER`.
+ */
+ SourceMapConsumer.prototype.eachMapping =
+ function SourceMapConsumer_eachMapping(aCallback, aContext, aOrder) {
+ var context = aContext || null;
+ var order = aOrder || SourceMapConsumer.GENERATED_ORDER;
+
+ var mappings;
+ switch (order) {
+ case SourceMapConsumer.GENERATED_ORDER:
+ mappings = this._generatedMappings;
+ break;
+ case SourceMapConsumer.ORIGINAL_ORDER:
+ mappings = this._originalMappings;
+ break;
+ default:
+ throw new Error("Unknown order of iteration.");
+ }
+
+ var sourceRoot = this.sourceRoot;
+ mappings.map(function (mapping) {
+ var source = mapping.source;
+ if (source && sourceRoot) {
+ source = util.join(sourceRoot, source);
+ }
+ return {
+ source: source,
+ generatedLine: mapping.generatedLine,
+ generatedColumn: mapping.generatedColumn,
+ originalLine: mapping.originalLine,
+ originalColumn: mapping.originalColumn,
+ name: mapping.name
+ };
+ }).forEach(aCallback, context);
+ };
+
+ exports.SourceMapConsumer = SourceMapConsumer;
+
+});
+/* -*- Mode: js; js-indent-level: 2; -*- */
+/*
+ * Copyright 2011 Mozilla Foundation and contributors
+ * Licensed under the New BSD license. See LICENSE or:
+ * http://opensource.org/licenses/BSD-3-Clause
+ */
+
+define('source-map/source-map-generator', function (require, exports, module) {
+
+ var base64VLQ = require('./base64-vlq');
+ var util = require('./util');
+ var ArraySet = require('./array-set').ArraySet;
+
+ /**
+ * An instance of the SourceMapGenerator represents a source map which is
+ * being built incrementally. To create a new one, you must pass an object
+ * with the following properties:
+ *
+ * - file: The filename of the generated source.
+ * - sourceRoot: An optional root for all URLs in this source map.
+ */
+ function SourceMapGenerator(aArgs) {
+ this._file = util.getArg(aArgs, 'file');
+ this._sourceRoot = util.getArg(aArgs, 'sourceRoot', null);
+ this._sources = new ArraySet();
+ this._names = new ArraySet();
+ this._mappings = [];
+ this._sourcesContents = null;
+ }
+
+ SourceMapGenerator.prototype._version = 3;
+
+ /**
+ * Creates a new SourceMapGenerator based on a SourceMapConsumer
+ *
+ * @param aSourceMapConsumer The SourceMap.
+ */
+ SourceMapGenerator.fromSourceMap =
+ function SourceMapGenerator_fromSourceMap(aSourceMapConsumer) {
+ var sourceRoot = aSourceMapConsumer.sourceRoot;
+ var generator = new SourceMapGenerator({
+ file: aSourceMapConsumer.file,
+ sourceRoot: sourceRoot
+ });
+ aSourceMapConsumer.eachMapping(function (mapping) {
+ var newMapping = {
+ generated: {
+ line: mapping.generatedLine,
+ column: mapping.generatedColumn
+ }
+ };
+
+ if (mapping.source) {
+ newMapping.source = mapping.source;
+ if (sourceRoot) {
+ newMapping.source = util.relative(sourceRoot, newMapping.source);
+ }
+
+ newMapping.original = {
+ line: mapping.originalLine,
+ column: mapping.originalColumn
+ };
+
+ if (mapping.name) {
+ newMapping.name = mapping.name;
+ }
+ }
+
+ generator.addMapping(newMapping);
+ });
+ aSourceMapConsumer.sources.forEach(function (sourceFile) {
+ var content = aSourceMapConsumer.sourceContentFor(sourceFile);
+ if (content) {
+ generator.setSourceContent(sourceFile, content);
+ }
+ });
+ return generator;
+ };
+
+ /**
+ * Add a single mapping from original source line and column to the generated
+ * source's line and column for this source map being created. The mapping
+ * object should have the following properties:
+ *
+ * - generated: An object with the generated line and column positions.
+ * - original: An object with the original line and column positions.
+ * - source: The original source file (relative to the sourceRoot).
+ * - name: An optional original token name for this mapping.
+ */
+ SourceMapGenerator.prototype.addMapping =
+ function SourceMapGenerator_addMapping(aArgs) {
+ var generated = util.getArg(aArgs, 'generated');
+ var original = util.getArg(aArgs, 'original', null);
+ var source = util.getArg(aArgs, 'source', null);
+ var name = util.getArg(aArgs, 'name', null);
+
+ this._validateMapping(generated, original, source, name);
+
+ if (source && !this._sources.has(source)) {
+ this._sources.add(source);
+ }
+
+ if (name && !this._names.has(name)) {
+ this._names.add(name);
+ }
+
+ this._mappings.push({
+ generatedLine: generated.line,
+ generatedColumn: generated.column,
+ originalLine: original != null && original.line,
+ originalColumn: original != null && original.column,
+ source: source,
+ name: name
+ });
+ };
+
+ /**
+ * Set the source content for a source file.
+ */
+ SourceMapGenerator.prototype.setSourceContent =
+ function SourceMapGenerator_setSourceContent(aSourceFile, aSourceContent) {
+ var source = aSourceFile;
+ if (this._sourceRoot) {
+ source = util.relative(this._sourceRoot, source);
+ }
+
+ if (aSourceContent !== null) {
+ // Add the source content to the _sourcesContents map.
+ // Create a new _sourcesContents map if the property is null.
+ if (!this._sourcesContents) {
+ this._sourcesContents = {};
+ }
+ this._sourcesContents[util.toSetString(source)] = aSourceContent;
+ } else {
+ // Remove the source file from the _sourcesContents map.
+ // If the _sourcesContents map is empty, set the property to null.
+ delete this._sourcesContents[util.toSetString(source)];
+ if (Object.keys(this._sourcesContents).length === 0) {
+ this._sourcesContents = null;
+ }
+ }
+ };
+
+ /**
+ * Applies the mappings of a sub-source-map for a specific source file to the
+ * source map being generated. Each mapping to the supplied source file is
+ * rewritten using the supplied source map. Note: The resolution for the
+ * resulting mappings is the minimium of this map and the supplied map.
+ *
+ * @param aSourceMapConsumer The source map to be applied.
+ * @param aSourceFile Optional. The filename of the source file.
+ * If omitted, SourceMapConsumer's file property will be used.
+ */
+ SourceMapGenerator.prototype.applySourceMap =
+ function SourceMapGenerator_applySourceMap(aSourceMapConsumer, aSourceFile) {
+ // If aSourceFile is omitted, we will use the file property of the SourceMap
+ if (!aSourceFile) {
+ aSourceFile = aSourceMapConsumer.file;
+ }
+ var sourceRoot = this._sourceRoot;
+ // Make "aSourceFile" relative if an absolute Url is passed.
+ if (sourceRoot) {
+ aSourceFile = util.relative(sourceRoot, aSourceFile);
+ }
+ // Applying the SourceMap can add and remove items from the sources and
+ // the names array.
+ var newSources = new ArraySet();
+ var newNames = new ArraySet();
+
+ // Find mappings for the "aSourceFile"
+ this._mappings.forEach(function (mapping) {
+ if (mapping.source === aSourceFile && mapping.originalLine) {
+ // Check if it can be mapped by the source map, then update the mapping.
+ var original = aSourceMapConsumer.originalPositionFor({
+ line: mapping.originalLine,
+ column: mapping.originalColumn
+ });
+ if (original.source !== null) {
+ // Copy mapping
+ if (sourceRoot) {
+ mapping.source = util.relative(sourceRoot, original.source);
+ } else {
+ mapping.source = original.source;
+ }
+ mapping.originalLine = original.line;
+ mapping.originalColumn = original.column;
+ if (original.name !== null && mapping.name !== null) {
+ // Only use the identifier name if it's an identifier
+ // in both SourceMaps
+ mapping.name = original.name;
+ }
+ }
+ }
+
+ var source = mapping.source;
+ if (source && !newSources.has(source)) {
+ newSources.add(source);
+ }
+
+ var name = mapping.name;
+ if (name && !newNames.has(name)) {
+ newNames.add(name);
+ }
+
+ }, this);
+ this._sources = newSources;
+ this._names = newNames;
+
+ // Copy sourcesContents of applied map.
+ aSourceMapConsumer.sources.forEach(function (sourceFile) {
+ var content = aSourceMapConsumer.sourceContentFor(sourceFile);
+ if (content) {
+ if (sourceRoot) {
+ sourceFile = util.relative(sourceRoot, sourceFile);
+ }
+ this.setSourceContent(sourceFile, content);
+ }
+ }, this);
+ };
+
+ /**
+ * A mapping can have one of the three levels of data:
+ *
+ * 1. Just the generated position.
+ * 2. The Generated position, original position, and original source.
+ * 3. Generated and original position, original source, as well as a name
+ * token.
+ *
+ * To maintain consistency, we validate that any new mapping being added falls
+ * in to one of these categories.
+ */
+ SourceMapGenerator.prototype._validateMapping =
+ function SourceMapGenerator_validateMapping(aGenerated, aOriginal, aSource,
+ aName) {
+ if (aGenerated && 'line' in aGenerated && 'column' in aGenerated
+ && aGenerated.line > 0 && aGenerated.column >= 0
+ && !aOriginal && !aSource && !aName) {
+ // Case 1.
+ return;
+ }
+ else if (aGenerated && 'line' in aGenerated && 'column' in aGenerated
+ && aOriginal && 'line' in aOriginal && 'column' in aOriginal
+ && aGenerated.line > 0 && aGenerated.column >= 0
+ && aOriginal.line > 0 && aOriginal.column >= 0
+ && aSource) {
+ // Cases 2 and 3.
+ return;
+ }
+ else {
+ throw new Error('Invalid mapping: ' + JSON.stringify({
+ generated: aGenerated,
+ source: aSource,
+ original: aOriginal,
+ name: aName
+ }));
+ }
+ };
+
+ /**
+ * Serialize the accumulated mappings in to the stream of base 64 VLQs
+ * specified by the source map format.
+ */
+ SourceMapGenerator.prototype._serializeMappings =
+ function SourceMapGenerator_serializeMappings() {
+ var previousGeneratedColumn = 0;
+ var previousGeneratedLine = 1;
+ var previousOriginalColumn = 0;
+ var previousOriginalLine = 0;
+ var previousName = 0;
+ var previousSource = 0;
+ var result = '';
+ var mapping;
+
+ // The mappings must be guaranteed to be in sorted order before we start
+ // serializing them or else the generated line numbers (which are defined
+ // via the ';' separators) will be all messed up. Note: it might be more
+ // performant to maintain the sorting as we insert them, rather than as we
+ // serialize them, but the big O is the same either way.
+ this._mappings.sort(util.compareByGeneratedPositions);
+
+ for (var i = 0, len = this._mappings.length; i < len; i++) {
+ mapping = this._mappings[i];
+
+ if (mapping.generatedLine !== previousGeneratedLine) {
+ previousGeneratedColumn = 0;
+ while (mapping.generatedLine !== previousGeneratedLine) {
+ result += ';';
+ previousGeneratedLine++;
+ }
+ }
+ else {
+ if (i > 0) {
+ if (!util.compareByGeneratedPositions(mapping, this._mappings[i - 1])) {
+ continue;
+ }
+ result += ',';
+ }
+ }
+
+ result += base64VLQ.encode(mapping.generatedColumn
+ - previousGeneratedColumn);
+ previousGeneratedColumn = mapping.generatedColumn;
+
+ if (mapping.source) {
+ result += base64VLQ.encode(this._sources.indexOf(mapping.source)
+ - previousSource);
+ previousSource = this._sources.indexOf(mapping.source);
+
+ // lines are stored 0-based in SourceMap spec version 3
+ result += base64VLQ.encode(mapping.originalLine - 1
+ - previousOriginalLine);
+ previousOriginalLine = mapping.originalLine - 1;
+
+ result += base64VLQ.encode(mapping.originalColumn
+ - previousOriginalColumn);
+ previousOriginalColumn = mapping.originalColumn;
+
+ if (mapping.name) {
+ result += base64VLQ.encode(this._names.indexOf(mapping.name)
+ - previousName);
+ previousName = this._names.indexOf(mapping.name);
+ }
+ }
+ }
+
+ return result;
+ };
+
+ SourceMapGenerator.prototype._generateSourcesContent =
+ function SourceMapGenerator_generateSourcesContent(aSources, aSourceRoot) {
+ return aSources.map(function (source) {
+ if (!this._sourcesContents) {
+ return null;
+ }
+ if (aSourceRoot) {
+ source = util.relative(aSourceRoot, source);
+ }
+ var key = util.toSetString(source);
+ return Object.prototype.hasOwnProperty.call(this._sourcesContents,
+ key)
+ ? this._sourcesContents[key]
+ : null;
+ }, this);
+ };
+
+ /**
+ * Externalize the source map.
+ */
+ SourceMapGenerator.prototype.toJSON =
+ function SourceMapGenerator_toJSON() {
+ var map = {
+ version: this._version,
+ file: this._file,
+ sources: this._sources.toArray(),
+ names: this._names.toArray(),
+ mappings: this._serializeMappings()
+ };
+ if (this._sourceRoot) {
+ map.sourceRoot = this._sourceRoot;
+ }
+ if (this._sourcesContents) {
+ map.sourcesContent = this._generateSourcesContent(map.sources, map.sourceRoot);
+ }
+
+ return map;
+ };
+
+ /**
+ * Render the source map being generated to a string.
+ */
+ SourceMapGenerator.prototype.toString =
+ function SourceMapGenerator_toString() {
+ return JSON.stringify(this);
+ };
+
+ exports.SourceMapGenerator = SourceMapGenerator;
+
+});
+/* -*- Mode: js; js-indent-level: 2; -*- */
+/*
+ * Copyright 2011 Mozilla Foundation and contributors
+ * Licensed under the New BSD license. See LICENSE or:
+ * http://opensource.org/licenses/BSD-3-Clause
+ */
+
+define('source-map/source-node', function (require, exports, module) {
+
+ var SourceMapGenerator = require('./source-map-generator').SourceMapGenerator;
+ var util = require('./util');
+
+ /**
+ * SourceNodes provide a way to abstract over interpolating/concatenating
+ * snippets of generated JavaScript source code while maintaining the line and
+ * column information associated with the original source code.
+ *
+ * @param aLine The original line number.
+ * @param aColumn The original column number.
+ * @param aSource The original source's filename.
+ * @param aChunks Optional. An array of strings which are snippets of
+ * generated JS, or other SourceNodes.
+ * @param aName The original identifier.
+ */
+ function SourceNode(aLine, aColumn, aSource, aChunks, aName) {
+ this.children = [];
+ this.sourceContents = {};
+ this.line = aLine === undefined ? null : aLine;
+ this.column = aColumn === undefined ? null : aColumn;
+ this.source = aSource === undefined ? null : aSource;
+ this.name = aName === undefined ? null : aName;
+ if (aChunks != null) this.add(aChunks);
+ }
+
+ /**
+ * Creates a SourceNode from generated code and a SourceMapConsumer.
+ *
+ * @param aGeneratedCode The generated code
+ * @param aSourceMapConsumer The SourceMap for the generated code
+ */
+ SourceNode.fromStringWithSourceMap =
+ function SourceNode_fromStringWithSourceMap(aGeneratedCode, aSourceMapConsumer) {
+ // The SourceNode we want to fill with the generated code
+ // and the SourceMap
+ var node = new SourceNode();
+
+ // The generated code
+ // Processed fragments are removed from this array.
+ var remainingLines = aGeneratedCode.split('\n');
+
+ // We need to remember the position of "remainingLines"
+ var lastGeneratedLine = 1, lastGeneratedColumn = 0;
+
+ // The generate SourceNodes we need a code range.
+ // To extract it current and last mapping is used.
+ // Here we store the last mapping.
+ var lastMapping = null;
+
+ aSourceMapConsumer.eachMapping(function (mapping) {
+ if (lastMapping === null) {
+ // We add the generated code until the first mapping
+ // to the SourceNode without any mapping.
+ // Each line is added as separate string.
+ while (lastGeneratedLine < mapping.generatedLine) {
+ node.add(remainingLines.shift() + "\n");
+ lastGeneratedLine++;
+ }
+ if (lastGeneratedColumn < mapping.generatedColumn) {
+ var nextLine = remainingLines[0];
+ node.add(nextLine.substr(0, mapping.generatedColumn));
+ remainingLines[0] = nextLine.substr(mapping.generatedColumn);
+ lastGeneratedColumn = mapping.generatedColumn;
+ }
+ } else {
+ // We add the code from "lastMapping" to "mapping":
+ // First check if there is a new line in between.
+ if (lastGeneratedLine < mapping.generatedLine) {
+ var code = "";
+ // Associate full lines with "lastMapping"
+ do {
+ code += remainingLines.shift() + "\n";
+ lastGeneratedLine++;
+ lastGeneratedColumn = 0;
+ } while (lastGeneratedLine < mapping.generatedLine);
+ // When we reached the correct line, we add code until we
+ // reach the correct column too.
+ if (lastGeneratedColumn < mapping.generatedColumn) {
+ var nextLine = remainingLines[0];
+ code += nextLine.substr(0, mapping.generatedColumn);
+ remainingLines[0] = nextLine.substr(mapping.generatedColumn);
+ lastGeneratedColumn = mapping.generatedColumn;
+ }
+ // Create the SourceNode.
+ addMappingWithCode(lastMapping, code);
+ } else {
+ // There is no new line in between.
+ // Associate the code between "lastGeneratedColumn" and
+ // "mapping.generatedColumn" with "lastMapping"
+ var nextLine = remainingLines[0];
+ var code = nextLine.substr(0, mapping.generatedColumn -
+ lastGeneratedColumn);
+ remainingLines[0] = nextLine.substr(mapping.generatedColumn -
+ lastGeneratedColumn);
+ lastGeneratedColumn = mapping.generatedColumn;
+ addMappingWithCode(lastMapping, code);
+ }
+ }
+ lastMapping = mapping;
+ }, this);
+ // We have processed all mappings.
+ // Associate the remaining code in the current line with "lastMapping"
+ // and add the remaining lines without any mapping
+ addMappingWithCode(lastMapping, remainingLines.join("\n"));
+
+ // Copy sourcesContent into SourceNode
+ aSourceMapConsumer.sources.forEach(function (sourceFile) {
+ var content = aSourceMapConsumer.sourceContentFor(sourceFile);
+ if (content) {
+ node.setSourceContent(sourceFile, content);
+ }
+ });
+
+ return node;
+
+ function addMappingWithCode(mapping, code) {
+ if (mapping === null || mapping.source === undefined) {
+ node.add(code);
+ } else {
+ node.add(new SourceNode(mapping.originalLine,
+ mapping.originalColumn,
+ mapping.source,
+ code,
+ mapping.name));
+ }
+ }
+ };
+
+ /**
+ * Add a chunk of generated JS to this source node.
+ *
+ * @param aChunk A string snippet of generated JS code, another instance of
+ * SourceNode, or an array where each member is one of those things.
+ */
+ SourceNode.prototype.add = function SourceNode_add(aChunk) {
+ if (Array.isArray(aChunk)) {
+ aChunk.forEach(function (chunk) {
+ this.add(chunk);
+ }, this);
+ }
+ else if (aChunk instanceof SourceNode || typeof aChunk === "string") {
+ if (aChunk) {
+ this.children.push(aChunk);
+ }
+ }
+ else {
+ throw new TypeError(
+ "Expected a SourceNode, string, or an array of SourceNodes and strings. Got " + aChunk
+ );
+ }
+ return this;
+ };
+
+ /**
+ * Add a chunk of generated JS to the beginning of this source node.
+ *
+ * @param aChunk A string snippet of generated JS code, another instance of
+ * SourceNode, or an array where each member is one of those things.
+ */
+ SourceNode.prototype.prepend = function SourceNode_prepend(aChunk) {
+ if (Array.isArray(aChunk)) {
+ for (var i = aChunk.length-1; i >= 0; i--) {
+ this.prepend(aChunk[i]);
+ }
+ }
+ else if (aChunk instanceof SourceNode || typeof aChunk === "string") {
+ this.children.unshift(aChunk);
+ }
+ else {
+ throw new TypeError(
+ "Expected a SourceNode, string, or an array of SourceNodes and strings. Got " + aChunk
+ );
+ }
+ return this;
+ };
+
+ /**
+ * Walk over the tree of JS snippets in this node and its children. The
+ * walking function is called once for each snippet of JS and is passed that
+ * snippet and the its original associated source's line/column location.
+ *
+ * @param aFn The traversal function.
+ */
+ SourceNode.prototype.walk = function SourceNode_walk(aFn) {
+ var chunk;
+ for (var i = 0, len = this.children.length; i < len; i++) {
+ chunk = this.children[i];
+ if (chunk instanceof SourceNode) {
+ chunk.walk(aFn);
+ }
+ else {
+ if (chunk !== '') {
+ aFn(chunk, { source: this.source,
+ line: this.line,
+ column: this.column,
+ name: this.name });
+ }
+ }
+ }
+ };
+
+ /**
+ * Like `String.prototype.join` except for SourceNodes. Inserts `aStr` between
+ * each of `this.children`.
+ *
+ * @param aSep The separator.
+ */
+ SourceNode.prototype.join = function SourceNode_join(aSep) {
+ var newChildren;
+ var i;
+ var len = this.children.length;
+ if (len > 0) {
+ newChildren = [];
+ for (i = 0; i < len-1; i++) {
+ newChildren.push(this.children[i]);
+ newChildren.push(aSep);
+ }
+ newChildren.push(this.children[i]);
+ this.children = newChildren;
+ }
+ return this;
+ };
+
+ /**
+ * Call String.prototype.replace on the very right-most source snippet. Useful
+ * for trimming whitespace from the end of a source node, etc.
+ *
+ * @param aPattern The pattern to replace.
+ * @param aReplacement The thing to replace the pattern with.
+ */
+ SourceNode.prototype.replaceRight = function SourceNode_replaceRight(aPattern, aReplacement) {
+ var lastChild = this.children[this.children.length - 1];
+ if (lastChild instanceof SourceNode) {
+ lastChild.replaceRight(aPattern, aReplacement);
+ }
+ else if (typeof lastChild === 'string') {
+ this.children[this.children.length - 1] = lastChild.replace(aPattern, aReplacement);
+ }
+ else {
+ this.children.push(''.replace(aPattern, aReplacement));
+ }
+ return this;
+ };
+
+ /**
+ * Set the source content for a source file. This will be added to the SourceMapGenerator
+ * in the sourcesContent field.
+ *
+ * @param aSourceFile The filename of the source file
+ * @param aSourceContent The content of the source file
+ */
+ SourceNode.prototype.setSourceContent =
+ function SourceNode_setSourceContent(aSourceFile, aSourceContent) {
+ this.sourceContents[util.toSetString(aSourceFile)] = aSourceContent;
+ };
+
+ /**
+ * Walk over the tree of SourceNodes. The walking function is called for each
+ * source file content and is passed the filename and source content.
+ *
+ * @param aFn The traversal function.
+ */
+ SourceNode.prototype.walkSourceContents =
+ function SourceNode_walkSourceContents(aFn) {
+ for (var i = 0, len = this.children.length; i < len; i++) {
+ if (this.children[i] instanceof SourceNode) {
+ this.children[i].walkSourceContents(aFn);
+ }
+ }
+
+ var sources = Object.keys(this.sourceContents);
+ for (var i = 0, len = sources.length; i < len; i++) {
+ aFn(util.fromSetString(sources[i]), this.sourceContents[sources[i]]);
+ }
+ };
+
+ /**
+ * Return the string representation of this source node. Walks over the tree
+ * and concatenates all the various snippets together to one string.
+ */
+ SourceNode.prototype.toString = function SourceNode_toString() {
+ var str = "";
+ this.walk(function (chunk) {
+ str += chunk;
+ });
+ return str;
+ };
+
+ /**
+ * Returns the string representation of this source node along with a source
+ * map.
+ */
+ SourceNode.prototype.toStringWithSourceMap = function SourceNode_toStringWithSourceMap(aArgs) {
+ var generated = {
+ code: "",
+ line: 1,
+ column: 0
+ };
+ var map = new SourceMapGenerator(aArgs);
+ var sourceMappingActive = false;
+ var lastOriginalSource = null;
+ var lastOriginalLine = null;
+ var lastOriginalColumn = null;
+ var lastOriginalName = null;
+ this.walk(function (chunk, original) {
+ generated.code += chunk;
+ if (original.source !== null
+ && original.line !== null
+ && original.column !== null) {
+ if(lastOriginalSource !== original.source
+ || lastOriginalLine !== original.line
+ || lastOriginalColumn !== original.column
+ || lastOriginalName !== original.name) {
+ map.addMapping({
+ source: original.source,
+ original: {
+ line: original.line,
+ column: original.column
+ },
+ generated: {
+ line: generated.line,
+ column: generated.column
+ },
+ name: original.name
+ });
+ }
+ lastOriginalSource = original.source;
+ lastOriginalLine = original.line;
+ lastOriginalColumn = original.column;
+ lastOriginalName = original.name;
+ sourceMappingActive = true;
+ } else if (sourceMappingActive) {
+ map.addMapping({
+ generated: {
+ line: generated.line,
+ column: generated.column
+ }
+ });
+ lastOriginalSource = null;
+ sourceMappingActive = false;
+ }
+ chunk.split('').forEach(function (ch) {
+ if (ch === '\n') {
+ generated.line++;
+ generated.column = 0;
+ } else {
+ generated.column++;
+ }
+ });
+ });
+ this.walkSourceContents(function (sourceFile, sourceContent) {
+ map.setSourceContent(sourceFile, sourceContent);
+ });
+
+ return { code: generated.code, map: map };
+ };
+
+ exports.SourceNode = SourceNode;
+
+});
+/* -*- Mode: js; js-indent-level: 2; -*- */
+/*
+ * Copyright 2011 Mozilla Foundation and contributors
+ * Licensed under the New BSD license. See LICENSE or:
+ * http://opensource.org/licenses/BSD-3-Clause
+ */
+
+define('source-map/util', function (require, exports, module) {
+
+ /**
+ * This is a helper function for getting values from parameter/options
+ * objects.
+ *
+ * @param args The object we are extracting values from
+ * @param name The name of the property we are getting.
+ * @param defaultValue An optional value to return if the property is missing
+ * from the object. If this is not specified and the property is missing, an
+ * error will be thrown.
+ */
+ function getArg(aArgs, aName, aDefaultValue) {
+ if (aName in aArgs) {
+ return aArgs[aName];
+ } else if (arguments.length === 3) {
+ return aDefaultValue;
+ } else {
+ throw new Error('"' + aName + '" is a required argument.');
+ }
+ }
+ exports.getArg = getArg;
+
+ var urlRegexp = /([\w+\-.]+):\/\/((\w+:\w+)@)?([\w.]+)?(:(\d+))?(\S+)?/;
+ var dataUrlRegexp = /^data:.+\,.+/;
+
+ function urlParse(aUrl) {
+ var match = aUrl.match(urlRegexp);
+ if (!match) {
+ return null;
+ }
+ return {
+ scheme: match[1],
+ auth: match[3],
+ host: match[4],
+ port: match[6],
+ path: match[7]
+ };
+ }
+ exports.urlParse = urlParse;
+
+ function urlGenerate(aParsedUrl) {
+ var url = aParsedUrl.scheme + "://";
+ if (aParsedUrl.auth) {
+ url += aParsedUrl.auth + "@"
+ }
+ if (aParsedUrl.host) {
+ url += aParsedUrl.host;
+ }
+ if (aParsedUrl.port) {
+ url += ":" + aParsedUrl.port
+ }
+ if (aParsedUrl.path) {
+ url += aParsedUrl.path;
+ }
+ return url;
+ }
+ exports.urlGenerate = urlGenerate;
+
+ function join(aRoot, aPath) {
+ var url;
+
+ if (aPath.match(urlRegexp) || aPath.match(dataUrlRegexp)) {
+ return aPath;
+ }
+
+ if (aPath.charAt(0) === '/' && (url = urlParse(aRoot))) {
+ url.path = aPath;
+ return urlGenerate(url);
+ }
+
+ return aRoot.replace(/\/$/, '') + '/' + aPath;
+ }
+ exports.join = join;
+
+ /**
+ * Because behavior goes wacky when you set `__proto__` on objects, we
+ * have to prefix all the strings in our set with an arbitrary character.
+ *
+ * See https://github.com/mozilla/source-map/pull/31 and
+ * https://github.com/mozilla/source-map/issues/30
+ *
+ * @param String aStr
+ */
+ function toSetString(aStr) {
+ return '$' + aStr;
+ }
+ exports.toSetString = toSetString;
+
+ function fromSetString(aStr) {
+ return aStr.substr(1);
+ }
+ exports.fromSetString = fromSetString;
+
+ function relative(aRoot, aPath) {
+ aRoot = aRoot.replace(/\/$/, '');
+
+ var url = urlParse(aRoot);
+ if (aPath.charAt(0) == "/" && url && url.path == "/") {
+ return aPath.slice(1);
+ }
+
+ return aPath.indexOf(aRoot + '/') === 0
+ ? aPath.substr(aRoot.length + 1)
+ : aPath;
+ }
+ exports.relative = relative;
+
+ function strcmp(aStr1, aStr2) {
+ var s1 = aStr1 || "";
+ var s2 = aStr2 || "";
+ return (s1 > s2) - (s1 < s2);
+ }
+
+ /**
+ * Comparator between two mappings where the original positions are compared.
+ *
+ * Optionally pass in `true` as `onlyCompareGenerated` to consider two
+ * mappings with the same original source/line/column, but different generated
+ * line and column the same. Useful when searching for a mapping with a
+ * stubbed out mapping.
+ */
+ function compareByOriginalPositions(mappingA, mappingB, onlyCompareOriginal) {
+ var cmp;
+
+ cmp = strcmp(mappingA.source, mappingB.source);
+ if (cmp) {
+ return cmp;
+ }
+
+ cmp = mappingA.originalLine - mappingB.originalLine;
+ if (cmp) {
+ return cmp;
+ }
+
+ cmp = mappingA.originalColumn - mappingB.originalColumn;
+ if (cmp || onlyCompareOriginal) {
+ return cmp;
+ }
+
+ cmp = strcmp(mappingA.name, mappingB.name);
+ if (cmp) {
+ return cmp;
+ }
+
+ cmp = mappingA.generatedLine - mappingB.generatedLine;
+ if (cmp) {
+ return cmp;
+ }
+
+ return mappingA.generatedColumn - mappingB.generatedColumn;
+ };
+ exports.compareByOriginalPositions = compareByOriginalPositions;
+
+ /**
+ * Comparator between two mappings where the generated positions are
+ * compared.
+ *
+ * Optionally pass in `true` as `onlyCompareGenerated` to consider two
+ * mappings with the same generated line and column, but different
+ * source/name/original line and column the same. Useful when searching for a
+ * mapping with a stubbed out mapping.
+ */
+ function compareByGeneratedPositions(mappingA, mappingB, onlyCompareGenerated) {
+ var cmp;
+
+ cmp = mappingA.generatedLine - mappingB.generatedLine;
+ if (cmp) {
+ return cmp;
+ }
+
+ cmp = mappingA.generatedColumn - mappingB.generatedColumn;
+ if (cmp || onlyCompareGenerated) {
+ return cmp;
+ }
+
+ cmp = strcmp(mappingA.source, mappingB.source);
+ if (cmp) {
+ return cmp;
+ }
+
+ cmp = mappingA.originalLine - mappingB.originalLine;
+ if (cmp) {
+ return cmp;
+ }
+
+ cmp = mappingA.originalColumn - mappingB.originalColumn;
+ if (cmp) {
+ return cmp;
+ }
+
+ return strcmp(mappingA.name, mappingB.name);
+ };
+ exports.compareByGeneratedPositions = compareByGeneratedPositions;
+
+});
+define('source-map', function (require, exports, module) {
+
+/*
+ * Copyright 2009-2011 Mozilla Foundation and contributors
+ * Licensed under the New BSD license. See LICENSE.txt or:
+ * http://opensource.org/licenses/BSD-3-Clause
+ */
+exports.SourceMapGenerator = require('./source-map/source-map-generator').SourceMapGenerator;
+exports.SourceMapConsumer = require('./source-map/source-map-consumer').SourceMapConsumer;
+exports.SourceNode = require('./source-map/source-node').SourceNode;
+
+});
+
+//Distributed under the BSD license:
+//Copyright 2012 (c) Mihai Bazon <mihai.bazon@gmail.com>
+define('uglifyjs2', ['exports', 'source-map', 'logger', 'env!env/file'], function (exports, MOZ_SourceMap, logger, rjsFile) {
+
+/***********************************************************************
+
+ A JavaScript tokenizer / parser / beautifier / compressor.
+ https://github.com/mishoo/UglifyJS2
+
+ -------------------------------- (C) ---------------------------------
+
+ Author: Mihai Bazon
+ <mihai.bazon@gmail.com>
+ http://mihai.bazon.net/blog
+
+ Distributed under the BSD license:
+
+ Copyright 2012 (c) Mihai Bazon <mihai.bazon@gmail.com>
+
+ Redistribution and use in source and binary forms, with or without
+ modification, are permitted provided that the following conditions
+ are met:
+
+ * Redistributions of source code must retain the above
+ copyright notice, this list of conditions and the following
+ disclaimer.
+
+ * Redistributions in binary form must reproduce the above
+ copyright notice, this list of conditions and the following
+ disclaimer in the documentation and/or other materials
+ provided with the distribution.
+
+ THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDER “AS IS” AND ANY
+ EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
+ PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE
+ LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY,
+ OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
+ PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
+ PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+ THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR
+ TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF
+ THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ SUCH DAMAGE.
+
+ ***********************************************************************/
+
+"use strict";
+
+function array_to_hash(a) {
+ var ret = Object.create(null);
+ for (var i = 0; i < a.length; ++i)
+ ret[a[i]] = true;
+ return ret;
+};
+
+function slice(a, start) {
+ return Array.prototype.slice.call(a, start || 0);
+};
+
+function characters(str) {
+ return str.split("");
+};
+
+function member(name, array) {
+ for (var i = array.length; --i >= 0;)
+ if (array[i] == name)
+ return true;
+ return false;
+};
+
+function find_if(func, array) {
+ for (var i = 0, n = array.length; i < n; ++i) {
+ if (func(array[i]))
+ return array[i];
+ }
+};
+
+function repeat_string(str, i) {
+ if (i <= 0) return "";
+ if (i == 1) return str;
+ var d = repeat_string(str, i >> 1);
+ d += d;
+ if (i & 1) d += str;
+ return d;
+};
+
+function DefaultsError(msg, defs) {
+ Error.call(this, msg);
+ this.msg = msg;
+ this.defs = defs;
+};
+DefaultsError.prototype = Object.create(Error.prototype);
+DefaultsError.prototype.constructor = DefaultsError;
+
+DefaultsError.croak = function(msg, defs) {
+ throw new DefaultsError(msg, defs);
+};
+
+function defaults(args, defs, croak) {
+ if (args === true)
+ args = {};
+ var ret = args || {};
+ if (croak) for (var i in ret) if (ret.hasOwnProperty(i) && !defs.hasOwnProperty(i))
+ DefaultsError.croak("`" + i + "` is not a supported option", defs);
+ for (var i in defs) if (defs.hasOwnProperty(i)) {
+ ret[i] = (args && args.hasOwnProperty(i)) ? args[i] : defs[i];
+ }
+ return ret;
+};
+
+function merge(obj, ext) {
+ for (var i in ext) if (ext.hasOwnProperty(i)) {
+ obj[i] = ext[i];
+ }
+ return obj;
+};
+
+function noop() {};
+
+var MAP = (function(){
+ function MAP(a, f, backwards) {
+ var ret = [], top = [], i;
+ function doit() {
+ var val = f(a[i], i);
+ var is_last = val instanceof Last;
+ if (is_last) val = val.v;
+ if (val instanceof AtTop) {
+ val = val.v;
+ if (val instanceof Splice) {
+ top.push.apply(top, backwards ? val.v.slice().reverse() : val.v);
+ } else {
+ top.push(val);
+ }
+ }
+ else if (val !== skip) {
+ if (val instanceof Splice) {
+ ret.push.apply(ret, backwards ? val.v.slice().reverse() : val.v);
+ } else {
+ ret.push(val);
+ }
+ }
+ return is_last;
+ };
+ if (a instanceof Array) {
+ if (backwards) {
+ for (i = a.length; --i >= 0;) if (doit()) break;
+ ret.reverse();
+ top.reverse();
+ } else {
+ for (i = 0; i < a.length; ++i) if (doit()) break;
+ }
+ }
+ else {
+ for (i in a) if (a.hasOwnProperty(i)) if (doit()) break;
+ }
+ return top.concat(ret);
+ };
+ MAP.at_top = function(val) { return new AtTop(val) };
+ MAP.splice = function(val) { return new Splice(val) };
+ MAP.last = function(val) { return new Last(val) };
+ var skip = MAP.skip = {};
+ function AtTop(val) { this.v = val };
+ function Splice(val) { this.v = val };
+ function Last(val) { this.v = val };
+ return MAP;
+})();
+
+function push_uniq(array, el) {
+ if (array.indexOf(el) < 0)
+ array.push(el);
+};
+
+function string_template(text, props) {
+ return text.replace(/\{(.+?)\}/g, function(str, p){
+ return props[p];
+ });
+};
+
+function remove(array, el) {
+ for (var i = array.length; --i >= 0;) {
+ if (array[i] === el) array.splice(i, 1);
+ }
+};
+
+function mergeSort(array, cmp) {
+ if (array.length < 2) return array.slice();
+ function merge(a, b) {
+ var r = [], ai = 0, bi = 0, i = 0;
+ while (ai < a.length && bi < b.length) {
+ cmp(a[ai], b[bi]) <= 0
+ ? r[i++] = a[ai++]
+ : r[i++] = b[bi++];
+ }
+ if (ai < a.length) r.push.apply(r, a.slice(ai));
+ if (bi < b.length) r.push.apply(r, b.slice(bi));
+ return r;
+ };
+ function _ms(a) {
+ if (a.length <= 1)
+ return a;
+ var m = Math.floor(a.length / 2), left = a.slice(0, m), right = a.slice(m);
+ left = _ms(left);
+ right = _ms(right);
+ return merge(left, right);
+ };
+ return _ms(array);
+};
+
+function set_difference(a, b) {
+ return a.filter(function(el){
+ return b.indexOf(el) < 0;
+ });
+};
+
+function set_intersection(a, b) {
+ return a.filter(function(el){
+ return b.indexOf(el) >= 0;
+ });
+};
+
+// this function is taken from Acorn [1], written by Marijn Haverbeke
+// [1] https://github.com/marijnh/acorn
+function makePredicate(words) {
+ if (!(words instanceof Array)) words = words.split(" ");
+ var f = "", cats = [];
+ out: for (var i = 0; i < words.length; ++i) {
+ for (var j = 0; j < cats.length; ++j)
+ if (cats[j][0].length == words[i].length) {
+ cats[j].push(words[i]);
+ continue out;
+ }
+ cats.push([words[i]]);
+ }
+ function compareTo(arr) {
+ if (arr.length == 1) return f += "return str === " + JSON.stringify(arr[0]) + ";";
+ f += "switch(str){";
+ for (var i = 0; i < arr.length; ++i) f += "case " + JSON.stringify(arr[i]) + ":";
+ f += "return true}return false;";
+ }
+ // When there are more than three length categories, an outer
+ // switch first dispatches on the lengths, to save on comparisons.
+ if (cats.length > 3) {
+ cats.sort(function(a, b) {return b.length - a.length;});
+ f += "switch(str.length){";
+ for (var i = 0; i < cats.length; ++i) {
+ var cat = cats[i];
+ f += "case " + cat[0].length + ":";
+ compareTo(cat);
+ }
+ f += "}";
+ // Otherwise, simply generate a flat `switch` statement.
+ } else {
+ compareTo(words);
+ }
+ return new Function("str", f);
+};
+
+function all(array, predicate) {
+ for (var i = array.length; --i >= 0;)
+ if (!predicate(array[i]))
+ return false;
+ return true;
+};
+
+function Dictionary() {
+ this._values = Object.create(null);
+ this._size = 0;
+};
+Dictionary.prototype = {
+ set: function(key, val) {
+ if (!this.has(key)) ++this._size;
+ this._values["$" + key] = val;
+ return this;
+ },
+ add: function(key, val) {
+ if (this.has(key)) {
+ this.get(key).push(val);
+ } else {
+ this.set(key, [ val ]);
+ }
+ return this;
+ },
+ get: function(key) { return this._values["$" + key] },
+ del: function(key) {
+ if (this.has(key)) {
+ --this._size;
+ delete this._values["$" + key];
+ }
+ return this;
+ },
+ has: function(key) { return ("$" + key) in this._values },
+ each: function(f) {
+ for (var i in this._values)
+ f(this._values[i], i.substr(1));
+ },
+ size: function() {
+ return this._size;
+ },
+ map: function(f) {
+ var ret = [];
+ for (var i in this._values)
+ ret.push(f(this._values[i], i.substr(1)));
+ return ret;
+ }
+};
+
+/***********************************************************************
+
+ A JavaScript tokenizer / parser / beautifier / compressor.
+ https://github.com/mishoo/UglifyJS2
+
+ -------------------------------- (C) ---------------------------------
+
+ Author: Mihai Bazon
+ <mihai.bazon@gmail.com>
+ http://mihai.bazon.net/blog
+
+ Distributed under the BSD license:
+
+ Copyright 2012 (c) Mihai Bazon <mihai.bazon@gmail.com>
+
+ Redistribution and use in source and binary forms, with or without
+ modification, are permitted provided that the following conditions
+ are met:
+
+ * Redistributions of source code must retain the above
+ copyright notice, this list of conditions and the following
+ disclaimer.
+
+ * Redistributions in binary form must reproduce the above
+ copyright notice, this list of conditions and the following
+ disclaimer in the documentation and/or other materials
+ provided with the distribution.
+
+ THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDER “AS IS” AND ANY
+ EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
+ PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE
+ LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY,
+ OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
+ PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
+ PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+ THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR
+ TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF
+ THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ SUCH DAMAGE.
+
+ ***********************************************************************/
+
+"use strict";
+
+function DEFNODE(type, props, methods, base) {
+ if (arguments.length < 4) base = AST_Node;
+ if (!props) props = [];
+ else props = props.split(/\s+/);
+ var self_props = props;
+ if (base && base.PROPS)
+ props = props.concat(base.PROPS);
+ var code = "return function AST_" + type + "(props){ if (props) { ";
+ for (var i = props.length; --i >= 0;) {
+ code += "this." + props[i] + " = props." + props[i] + ";";
+ }
+ var proto = base && new base;
+ if (proto && proto.initialize || (methods && methods.initialize))
+ code += "this.initialize();";
+ code += "}}";
+ var ctor = new Function(code)();
+ if (proto) {
+ ctor.prototype = proto;
+ ctor.BASE = base;
+ }
+ if (base) base.SUBCLASSES.push(ctor);
+ ctor.prototype.CTOR = ctor;
+ ctor.PROPS = props || null;
+ ctor.SELF_PROPS = self_props;
+ ctor.SUBCLASSES = [];
+ if (type) {
+ ctor.prototype.TYPE = ctor.TYPE = type;
+ }
+ if (methods) for (i in methods) if (methods.hasOwnProperty(i)) {
+ if (/^\$/.test(i)) {
+ ctor[i.substr(1)] = methods[i];
+ } else {
+ ctor.prototype[i] = methods[i];
+ }
+ }
+ ctor.DEFMETHOD = function(name, method) {
+ this.prototype[name] = method;
+ };
+ return ctor;
+};
+
+var AST_Token = DEFNODE("Token", "type value line col pos endpos nlb comments_before file", {
+}, null);
+
+var AST_Node = DEFNODE("Node", "start end", {
+ clone: function() {
+ return new this.CTOR(this);
+ },
+ $documentation: "Base class of all AST nodes",
+ $propdoc: {
+ start: "[AST_Token] The first token of this node",
+ end: "[AST_Token] The last token of this node"
+ },
+ _walk: function(visitor) {
+ return visitor._visit(this);
+ },
+ walk: function(visitor) {
+ return this._walk(visitor); // not sure the indirection will be any help
+ }
+}, null);
+
+AST_Node.warn_function = null;
+AST_Node.warn = function(txt, props) {
+ if (AST_Node.warn_function)
+ AST_Node.warn_function(string_template(txt, props));
+};
+
+/* -----[ statements ]----- */
+
+var AST_Statement = DEFNODE("Statement", null, {
+ $documentation: "Base class of all statements",
+});
+
+var AST_Debugger = DEFNODE("Debugger", null, {
+ $documentation: "Represents a debugger statement",
+}, AST_Statement);
+
+var AST_Directive = DEFNODE("Directive", "value scope", {
+ $documentation: "Represents a directive, like \"use strict\";",
+ $propdoc: {
+ value: "[string] The value of this directive as a plain string (it's not an AST_String!)",
+ scope: "[AST_Scope/S] The scope that this directive affects"
+ },
+}, AST_Statement);
+
+var AST_SimpleStatement = DEFNODE("SimpleStatement", "body", {
+ $documentation: "A statement consisting of an expression, i.e. a = 1 + 2",
+ $propdoc: {
+ body: "[AST_Node] an expression node (should not be instanceof AST_Statement)"
+ },
+ _walk: function(visitor) {
+ return visitor._visit(this, function(){
+ this.body._walk(visitor);
+ });
+ }
+}, AST_Statement);
+
+function walk_body(node, visitor) {
+ if (node.body instanceof AST_Statement) {
+ node.body._walk(visitor);
+ }
+ else node.body.forEach(function(stat){
+ stat._walk(visitor);
+ });
+};
+
+var AST_Block = DEFNODE("Block", "body", {
+ $documentation: "A body of statements (usually bracketed)",
+ $propdoc: {
+ body: "[AST_Statement*] an array of statements"
+ },
+ _walk: function(visitor) {
+ return visitor._visit(this, function(){
+ walk_body(this, visitor);
+ });
+ }
+}, AST_Statement);
+
+var AST_BlockStatement = DEFNODE("BlockStatement", null, {
+ $documentation: "A block statement",
+}, AST_Block);
+
+var AST_EmptyStatement = DEFNODE("EmptyStatement", null, {
+ $documentation: "The empty statement (empty block or simply a semicolon)",
+ _walk: function(visitor) {
+ return visitor._visit(this);
+ }
+}, AST_Statement);
+
+var AST_StatementWithBody = DEFNODE("StatementWithBody", "body", {
+ $documentation: "Base class for all statements that contain one nested body: `For`, `ForIn`, `Do`, `While`, `With`",
+ $propdoc: {
+ body: "[AST_Statement] the body; this should always be present, even if it's an AST_EmptyStatement"
+ },
+ _walk: function(visitor) {
+ return visitor._visit(this, function(){
+ this.body._walk(visitor);
+ });
+ }
+}, AST_Statement);
+
+var AST_LabeledStatement = DEFNODE("LabeledStatement", "label", {
+ $documentation: "Statement with a label",
+ $propdoc: {
+ label: "[AST_Label] a label definition"
+ },
+ _walk: function(visitor) {
+ return visitor._visit(this, function(){
+ this.label._walk(visitor);
+ this.body._walk(visitor);
+ });
+ }
+}, AST_StatementWithBody);
+
+var AST_IterationStatement = DEFNODE("IterationStatement", null, {
+ $documentation: "Internal class. All loops inherit from it."
+}, AST_StatementWithBody);
+
+var AST_DWLoop = DEFNODE("DWLoop", "condition", {
+ $documentation: "Base class for do/while statements",
+ $propdoc: {
+ condition: "[AST_Node] the loop condition. Should not be instanceof AST_Statement"
+ },
+ _walk: function(visitor) {
+ return visitor._visit(this, function(){
+ this.condition._walk(visitor);
+ this.body._walk(visitor);
+ });
+ }
+}, AST_IterationStatement);
+
+var AST_Do = DEFNODE("Do", null, {
+ $documentation: "A `do` statement",
+}, AST_DWLoop);
+
+var AST_While = DEFNODE("While", null, {
+ $documentation: "A `while` statement",
+}, AST_DWLoop);
+
+var AST_For = DEFNODE("For", "init condition step", {
+ $documentation: "A `for` statement",
+ $propdoc: {
+ init: "[AST_Node?] the `for` initialization code, or null if empty",
+ condition: "[AST_Node?] the `for` termination clause, or null if empty",
+ step: "[AST_Node?] the `for` update clause, or null if empty"
+ },
+ _walk: function(visitor) {
+ return visitor._visit(this, function(){
+ if (this.init) this.init._walk(visitor);
+ if (this.condition) this.condition._walk(visitor);
+ if (this.step) this.step._walk(visitor);
+ this.body._walk(visitor);
+ });
+ }
+}, AST_IterationStatement);
+
+var AST_ForIn = DEFNODE("ForIn", "init name object", {
+ $documentation: "A `for ... in` statement",
+ $propdoc: {
+ init: "[AST_Node] the `for/in` initialization code",
+ name: "[AST_SymbolRef?] the loop variable, only if `init` is AST_Var",
+ object: "[AST_Node] the object that we're looping through"
+ },
+ _walk: function(visitor) {
+ return visitor._visit(this, function(){
+ this.init._walk(visitor);
+ this.object._walk(visitor);
+ this.body._walk(visitor);
+ });
+ }
+}, AST_IterationStatement);
+
+var AST_With = DEFNODE("With", "expression", {
+ $documentation: "A `with` statement",
+ $propdoc: {
+ expression: "[AST_Node] the `with` expression"
+ },
+ _walk: function(visitor) {
+ return visitor._visit(this, function(){
+ this.expression._walk(visitor);
+ this.body._walk(visitor);
+ });
+ }
+}, AST_StatementWithBody);
+
+/* -----[ scope and functions ]----- */
+
+var AST_Scope = DEFNODE("Scope", "directives variables functions uses_with uses_eval parent_scope enclosed cname", {
+ $documentation: "Base class for all statements introducing a lexical scope",
+ $propdoc: {
+ directives: "[string*/S] an array of directives declared in this scope",
+ variables: "[Object/S] a map of name -> SymbolDef for all variables/functions defined in this scope",
+ functions: "[Object/S] like `variables`, but only lists function declarations",
+ uses_with: "[boolean/S] tells whether this scope uses the `with` statement",
+ uses_eval: "[boolean/S] tells whether this scope contains a direct call to the global `eval`",
+ parent_scope: "[AST_Scope?/S] link to the parent scope",
+ enclosed: "[SymbolDef*/S] a list of all symbol definitions that are accessed from this scope or any subscopes",
+ cname: "[integer/S] current index for mangling variables (used internally by the mangler)",
+ },
+}, AST_Block);
+
+var AST_Toplevel = DEFNODE("Toplevel", "globals", {
+ $documentation: "The toplevel scope",
+ $propdoc: {
+ globals: "[Object/S] a map of name -> SymbolDef for all undeclared names",
+ },
+ wrap_enclose: function(arg_parameter_pairs) {
+ var self = this;
+ var args = [];
+ var parameters = [];
+
+ arg_parameter_pairs.forEach(function(pair) {
+ var split = pair.split(":");
+
+ args.push(split[0]);
+ parameters.push(split[1]);
+ });
+
+ var wrapped_tl = "(function(" + parameters.join(",") + "){ '$ORIG'; })(" + args.join(",") + ")";
+ wrapped_tl = parse(wrapped_tl);
+ wrapped_tl = wrapped_tl.transform(new TreeTransformer(function before(node){
+ if (node instanceof AST_Directive && node.value == "$ORIG") {
+ return MAP.splice(self.body);
+ }
+ }));
+ return wrapped_tl;
+ },
+ wrap_commonjs: function(name, export_all) {
+ var self = this;
+ var to_export = [];
+ if (export_all) {
+ self.figure_out_scope();
+ self.walk(new TreeWalker(function(node){
+ if (node instanceof AST_SymbolDeclaration && node.definition().global) {
+ if (!find_if(function(n){ return n.name == node.name }, to_export))
+ to_export.push(node);
+ }
+ }));
+ }
+ var wrapped_tl = "(function(exports, global){ global['" + name + "'] = exports; '$ORIG'; '$EXPORTS'; }({}, (function(){return this}())))";
+ wrapped_tl = parse(wrapped_tl);
+ wrapped_tl = wrapped_tl.transform(new TreeTransformer(function before(node){
+ if (node instanceof AST_SimpleStatement) {
+ node = node.body;
+ if (node instanceof AST_String) switch (node.getValue()) {
+ case "$ORIG":
+ return MAP.splice(self.body);
+ case "$EXPORTS":
+ var body = [];
+ to_export.forEach(function(sym){
+ body.push(new AST_SimpleStatement({
+ body: new AST_Assign({
+ left: new AST_Sub({
+ expression: new AST_SymbolRef({ name: "exports" }),
+ property: new AST_String({ value: sym.name }),
+ }),
+ operator: "=",
+ right: new AST_SymbolRef(sym),
+ }),
+ }));
+ });
+ return MAP.splice(body);
+ }
+ }
+ }));
+ return wrapped_tl;
+ }
+}, AST_Scope);
+
+var AST_Lambda = DEFNODE("Lambda", "name argnames uses_arguments", {
+ $documentation: "Base class for functions",
+ $propdoc: {
+ name: "[AST_SymbolDeclaration?] the name of this function",
+ argnames: "[AST_SymbolFunarg*] array of function arguments",
+ uses_arguments: "[boolean/S] tells whether this function accesses the arguments array"
+ },
+ _walk: function(visitor) {
+ return visitor._visit(this, function(){
+ if (this.name) this.name._walk(visitor);
+ this.argnames.forEach(function(arg){
+ arg._walk(visitor);
+ });
+ walk_body(this, visitor);
+ });
+ }
+}, AST_Scope);
+
+var AST_Accessor = DEFNODE("Accessor", null, {
+ $documentation: "A setter/getter function. The `name` property is always null."
+}, AST_Lambda);
+
+var AST_Function = DEFNODE("Function", null, {
+ $documentation: "A function expression"
+}, AST_Lambda);
+
+var AST_Defun = DEFNODE("Defun", null, {
+ $documentation: "A function definition"
+}, AST_Lambda);
+
+/* -----[ JUMPS ]----- */
+
+var AST_Jump = DEFNODE("Jump", null, {
+ $documentation: "Base class for “jumps” (for now that's `return`, `throw`, `break` and `continue`)"
+}, AST_Statement);
+
+var AST_Exit = DEFNODE("Exit", "value", {
+ $documentation: "Base class for “exits” (`return` and `throw`)",
+ $propdoc: {
+ value: "[AST_Node?] the value returned or thrown by this statement; could be null for AST_Return"
+ },
+ _walk: function(visitor) {
+ return visitor._visit(this, this.value && function(){
+ this.value._walk(visitor);
+ });
+ }
+}, AST_Jump);
+
+var AST_Return = DEFNODE("Return", null, {
+ $documentation: "A `return` statement"
+}, AST_Exit);
+
+var AST_Throw = DEFNODE("Throw", null, {
+ $documentation: "A `throw` statement"
+}, AST_Exit);
+
+var AST_LoopControl = DEFNODE("LoopControl", "label", {
+ $documentation: "Base class for loop control statements (`break` and `continue`)",
+ $propdoc: {
+ label: "[AST_LabelRef?] the label, or null if none",
+ },
+ _walk: function(visitor) {
+ return visitor._visit(this, this.label && function(){
+ this.label._walk(visitor);
+ });
+ }
+}, AST_Jump);
+
+var AST_Break = DEFNODE("Break", null, {
+ $documentation: "A `break` statement"
+}, AST_LoopControl);
+
+var AST_Continue = DEFNODE("Continue", null, {
+ $documentation: "A `continue` statement"
+}, AST_LoopControl);
+
+/* -----[ IF ]----- */
+
+var AST_If = DEFNODE("If", "condition alternative", {
+ $documentation: "A `if` statement",
+ $propdoc: {
+ condition: "[AST_Node] the `if` condition",
+ alternative: "[AST_Statement?] the `else` part, or null if not present"
+ },
+ _walk: function(visitor) {
+ return visitor._visit(this, function(){
+ this.condition._walk(visitor);
+ this.body._walk(visitor);
+ if (this.alternative) this.alternative._walk(visitor);
+ });
+ }
+}, AST_StatementWithBody);
+
+/* -----[ SWITCH ]----- */
+
+var AST_Switch = DEFNODE("Switch", "expression", {
+ $documentation: "A `switch` statement",
+ $propdoc: {
+ expression: "[AST_Node] the `switch` “discriminant”"
+ },
+ _walk: function(visitor) {
+ return visitor._visit(this, function(){
+ this.expression._walk(visitor);
+ walk_body(this, visitor);
+ });
+ }
+}, AST_Block);
+
+var AST_SwitchBranch = DEFNODE("SwitchBranch", null, {
+ $documentation: "Base class for `switch` branches",
+}, AST_Block);
+
+var AST_Default = DEFNODE("Default", null, {
+ $documentation: "A `default` switch branch",
+}, AST_SwitchBranch);
+
+var AST_Case = DEFNODE("Case", "expression", {
+ $documentation: "A `case` switch branch",
+ $propdoc: {
+ expression: "[AST_Node] the `case` expression"
+ },
+ _walk: function(visitor) {
+ return visitor._visit(this, function(){
+ this.expression._walk(visitor);
+ walk_body(this, visitor);
+ });
+ }
+}, AST_SwitchBranch);
+
+/* -----[ EXCEPTIONS ]----- */
+
+var AST_Try = DEFNODE("Try", "bcatch bfinally", {
+ $documentation: "A `try` statement",
+ $propdoc: {
+ bcatch: "[AST_Catch?] the catch block, or null if not present",
+ bfinally: "[AST_Finally?] the finally block, or null if not present"
+ },
+ _walk: function(visitor) {
+ return visitor._visit(this, function(){
+ walk_body(this, visitor);
+ if (this.bcatch) this.bcatch._walk(visitor);
+ if (this.bfinally) this.bfinally._walk(visitor);
+ });
+ }
+}, AST_Block);
+
+var AST_Catch = DEFNODE("Catch", "argname", {
+ $documentation: "A `catch` node; only makes sense as part of a `try` statement",
+ $propdoc: {
+ argname: "[AST_SymbolCatch] symbol for the exception"
+ },
+ _walk: function(visitor) {
+ return visitor._visit(this, function(){
+ this.argname._walk(visitor);
+ walk_body(this, visitor);
+ });
+ }
+}, AST_Block);
+
+var AST_Finally = DEFNODE("Finally", null, {
+ $documentation: "A `finally` node; only makes sense as part of a `try` statement"
+}, AST_Block);
+
+/* -----[ VAR/CONST ]----- */
+
+var AST_Definitions = DEFNODE("Definitions", "definitions", {
+ $documentation: "Base class for `var` or `const` nodes (variable declarations/initializations)",
+ $propdoc: {
+ definitions: "[AST_VarDef*] array of variable definitions"
+ },
+ _walk: function(visitor) {
+ return visitor._visit(this, function(){
+ this.definitions.forEach(function(def){
+ def._walk(visitor);
+ });
+ });
+ }
+}, AST_Statement);
+
+var AST_Var = DEFNODE("Var", null, {
+ $documentation: "A `var` statement"
+}, AST_Definitions);
+
+var AST_Const = DEFNODE("Const", null, {
+ $documentation: "A `const` statement"
+}, AST_Definitions);
+
+var AST_VarDef = DEFNODE("VarDef", "name value", {
+ $documentation: "A variable declaration; only appears in a AST_Definitions node",
+ $propdoc: {
+ name: "[AST_SymbolVar|AST_SymbolConst] name of the variable",
+ value: "[AST_Node?] initializer, or null of there's no initializer"
+ },
+ _walk: function(visitor) {
+ return visitor._visit(this, function(){
+ this.name._walk(visitor);
+ if (this.value) this.value._walk(visitor);
+ });
+ }
+});
+
+/* -----[ OTHER ]----- */
+
+var AST_Call = DEFNODE("Call", "expression args", {
+ $documentation: "A function call expression",
+ $propdoc: {
+ expression: "[AST_Node] expression to invoke as function",
+ args: "[AST_Node*] array of arguments"
+ },
+ _walk: function(visitor) {
+ return visitor._visit(this, function(){
+ this.expression._walk(visitor);
+ this.args.forEach(function(arg){
+ arg._walk(visitor);
+ });
+ });
+ }
+});
+
+var AST_New = DEFNODE("New", null, {
+ $documentation: "An object instantiation. Derives from a function call since it has exactly the same properties"
+}, AST_Call);
+
+var AST_Seq = DEFNODE("Seq", "car cdr", {
+ $documentation: "A sequence expression (two comma-separated expressions)",
+ $propdoc: {
+ car: "[AST_Node] first element in sequence",
+ cdr: "[AST_Node] second element in sequence"
+ },
+ $cons: function(x, y) {
+ var seq = new AST_Seq(x);
+ seq.car = x;
+ seq.cdr = y;
+ return seq;
+ },
+ $from_array: function(array) {
+ if (array.length == 0) return null;
+ if (array.length == 1) return array[0].clone();
+ var list = null;
+ for (var i = array.length; --i >= 0;) {
+ list = AST_Seq.cons(array[i], list);
+ }
+ var p = list;
+ while (p) {
+ if (p.cdr && !p.cdr.cdr) {
+ p.cdr = p.cdr.car;
+ break;
+ }
+ p = p.cdr;
+ }
+ return list;
+ },
+ to_array: function() {
+ var p = this, a = [];
+ while (p) {
+ a.push(p.car);
+ if (p.cdr && !(p.cdr instanceof AST_Seq)) {
+ a.push(p.cdr);
+ break;
+ }
+ p = p.cdr;
+ }
+ return a;
+ },
+ add: function(node) {
+ var p = this;
+ while (p) {
+ if (!(p.cdr instanceof AST_Seq)) {
+ var cell = AST_Seq.cons(p.cdr, node);
+ return p.cdr = cell;
+ }
+ p = p.cdr;
+ }
+ },
+ _walk: function(visitor) {
+ return visitor._visit(this, function(){
+ this.car._walk(visitor);
+ if (this.cdr) this.cdr._walk(visitor);
+ });
+ }
+});
+
+var AST_PropAccess = DEFNODE("PropAccess", "expression property", {
+ $documentation: "Base class for property access expressions, i.e. `a.foo` or `a[\"foo\"]`",
+ $propdoc: {
+ expression: "[AST_Node] the “container” expression",
+ property: "[AST_Node|string] the property to access. For AST_Dot this is always a plain string, while for AST_Sub it's an arbitrary AST_Node"
+ }
+});
+
+var AST_Dot = DEFNODE("Dot", null, {
+ $documentation: "A dotted property access expression",
+ _walk: function(visitor) {
+ return visitor._visit(this, function(){
+ this.expression._walk(visitor);
+ });
+ }
+}, AST_PropAccess);
+
+var AST_Sub = DEFNODE("Sub", null, {
+ $documentation: "Index-style property access, i.e. `a[\"foo\"]`",
+ _walk: function(visitor) {
+ return visitor._visit(this, function(){
+ this.expression._walk(visitor);
+ this.property._walk(visitor);
+ });
+ }
+}, AST_PropAccess);
+
+var AST_Unary = DEFNODE("Unary", "operator expression", {
+ $documentation: "Base class for unary expressions",
+ $propdoc: {
+ operator: "[string] the operator",
+ expression: "[AST_Node] expression that this unary operator applies to"
+ },
+ _walk: function(visitor) {
+ return visitor._visit(this, function(){
+ this.expression._walk(visitor);
+ });
+ }
+});
+
+var AST_UnaryPrefix = DEFNODE("UnaryPrefix", null, {
+ $documentation: "Unary prefix expression, i.e. `typeof i` or `++i`"
+}, AST_Unary);
+
+var AST_UnaryPostfix = DEFNODE("UnaryPostfix", null, {
+ $documentation: "Unary postfix expression, i.e. `i++`"
+}, AST_Unary);
+
+var AST_Binary = DEFNODE("Binary", "left operator right", {
+ $documentation: "Binary expression, i.e. `a + b`",
+ $propdoc: {
+ left: "[AST_Node] left-hand side expression",
+ operator: "[string] the operator",
+ right: "[AST_Node] right-hand side expression"
+ },
+ _walk: function(visitor) {
+ return visitor._visit(this, function(){
+ this.left._walk(visitor);
+ this.right._walk(visitor);
+ });
+ }
+});
+
+var AST_Conditional = DEFNODE("Conditional", "condition consequent alternative", {
+ $documentation: "Conditional expression using the ternary operator, i.e. `a ? b : c`",
+ $propdoc: {
+ condition: "[AST_Node]",
+ consequent: "[AST_Node]",
+ alternative: "[AST_Node]"
+ },
+ _walk: function(visitor) {
+ return visitor._visit(this, function(){
+ this.condition._walk(visitor);
+ this.consequent._walk(visitor);
+ this.alternative._walk(visitor);
+ });
+ }
+});
+
+var AST_Assign = DEFNODE("Assign", null, {
+ $documentation: "An assignment expression — `a = b + 5`",
+}, AST_Binary);
+
+/* -----[ LITERALS ]----- */
+
+var AST_Array = DEFNODE("Array", "elements", {
+ $documentation: "An array literal",
+ $propdoc: {
+ elements: "[AST_Node*] array of elements"
+ },
+ _walk: function(visitor) {
+ return visitor._visit(this, function(){
+ this.elements.forEach(function(el){
+ el._walk(visitor);
+ });
+ });
+ }
+});
+
+var AST_Object = DEFNODE("Object", "properties", {
+ $documentation: "An object literal",
+ $propdoc: {
+ properties: "[AST_ObjectProperty*] array of properties"
+ },
+ _walk: function(visitor) {
+ return visitor._visit(this, function(){
+ this.properties.forEach(function(prop){
+ prop._walk(visitor);
+ });
+ });
+ }
+});
+
+var AST_ObjectProperty = DEFNODE("ObjectProperty", "key value", {
+ $documentation: "Base class for literal object properties",
+ $propdoc: {
+ key: "[string] the property name converted to a string for ObjectKeyVal. For setters and getters this is an arbitrary AST_Node.",
+ value: "[AST_Node] property value. For setters and getters this is an AST_Function."
+ },
+ _walk: function(visitor) {
+ return visitor._visit(this, function(){
+ this.value._walk(visitor);
+ });
+ }
+});
+
+var AST_ObjectKeyVal = DEFNODE("ObjectKeyVal", null, {
+ $documentation: "A key: value object property",
+}, AST_ObjectProperty);
+
+var AST_ObjectSetter = DEFNODE("ObjectSetter", null, {
+ $documentation: "An object setter property",
+}, AST_ObjectProperty);
+
+var AST_ObjectGetter = DEFNODE("ObjectGetter", null, {
+ $documentation: "An object getter property",
+}, AST_ObjectProperty);
+
+var AST_Symbol = DEFNODE("Symbol", "scope name thedef", {
+ $propdoc: {
+ name: "[string] name of this symbol",
+ scope: "[AST_Scope/S] the current scope (not necessarily the definition scope)",
+ thedef: "[SymbolDef/S] the definition of this symbol"
+ },
+ $documentation: "Base class for all symbols",
+});
+
+var AST_SymbolAccessor = DEFNODE("SymbolAccessor", null, {
+ $documentation: "The name of a property accessor (setter/getter function)"
+}, AST_Symbol);
+
+var AST_SymbolDeclaration = DEFNODE("SymbolDeclaration", "init", {
+ $documentation: "A declaration symbol (symbol in var/const, function name or argument, symbol in catch)",
+ $propdoc: {
+ init: "[AST_Node*/S] array of initializers for this declaration."
+ }
+}, AST_Symbol);
+
+var AST_SymbolVar = DEFNODE("SymbolVar", null, {
+ $documentation: "Symbol defining a variable",
+}, AST_SymbolDeclaration);
+
+var AST_SymbolConst = DEFNODE("SymbolConst", null, {
+ $documentation: "A constant declaration"
+}, AST_SymbolDeclaration);
+
+var AST_SymbolFunarg = DEFNODE("SymbolFunarg", null, {
+ $documentation: "Symbol naming a function argument",
+}, AST_SymbolVar);
+
+var AST_SymbolDefun = DEFNODE("SymbolDefun", null, {
+ $documentation: "Symbol defining a function",
+}, AST_SymbolDeclaration);
+
+var AST_SymbolLambda = DEFNODE("SymbolLambda", null, {
+ $documentation: "Symbol naming a function expression",
+}, AST_SymbolDeclaration);
+
+var AST_SymbolCatch = DEFNODE("SymbolCatch", null, {
+ $documentation: "Symbol naming the exception in catch",
+}, AST_SymbolDeclaration);
+
+var AST_Label = DEFNODE("Label", "references", {
+ $documentation: "Symbol naming a label (declaration)",
+ $propdoc: {
+ references: "[AST_LoopControl*] a list of nodes referring to this label"
+ },
+ initialize: function() {
+ this.references = [];
+ this.thedef = this;
+ }
+}, AST_Symbol);
+
+var AST_SymbolRef = DEFNODE("SymbolRef", null, {
+ $documentation: "Reference to some symbol (not definition/declaration)",
+}, AST_Symbol);
+
+var AST_LabelRef = DEFNODE("LabelRef", null, {
+ $documentation: "Reference to a label symbol",
+}, AST_Symbol);
+
+var AST_This = DEFNODE("This", null, {
+ $documentation: "The `this` symbol",
+}, AST_Symbol);
+
+var AST_Constant = DEFNODE("Constant", null, {
+ $documentation: "Base class for all constants",
+ getValue: function() {
+ return this.value;
+ }
+});
+
+var AST_String = DEFNODE("String", "value", {
+ $documentation: "A string literal",
+ $propdoc: {
+ value: "[string] the contents of this string"
+ }
+}, AST_Constant);
+
+var AST_Number = DEFNODE("Number", "value", {
+ $documentation: "A number literal",
+ $propdoc: {
+ value: "[number] the numeric value"
+ }
+}, AST_Constant);
+
+var AST_RegExp = DEFNODE("RegExp", "value", {
+ $documentation: "A regexp literal",
+ $propdoc: {
+ value: "[RegExp] the actual regexp"
+ }
+}, AST_Constant);
+
+var AST_Atom = DEFNODE("Atom", null, {
+ $documentation: "Base class for atoms",
+}, AST_Constant);
+
+var AST_Null = DEFNODE("Null", null, {
+ $documentation: "The `null` atom",
+ value: null
+}, AST_Atom);
+
+var AST_NaN = DEFNODE("NaN", null, {
+ $documentation: "The impossible value",
+ value: 0/0
+}, AST_Atom);
+
+var AST_Undefined = DEFNODE("Undefined", null, {
+ $documentation: "The `undefined` value",
+ value: (function(){}())
+}, AST_Atom);
+
+var AST_Hole = DEFNODE("Hole", null, {
+ $documentation: "A hole in an array",
+ value: (function(){}())
+}, AST_Atom);
+
+var AST_Infinity = DEFNODE("Infinity", null, {
+ $documentation: "The `Infinity` value",
+ value: 1/0
+}, AST_Atom);
+
+var AST_Boolean = DEFNODE("Boolean", null, {
+ $documentation: "Base class for booleans",
+}, AST_Atom);
+
+var AST_False = DEFNODE("False", null, {
+ $documentation: "The `false` atom",
+ value: false
+}, AST_Boolean);
+
+var AST_True = DEFNODE("True", null, {
+ $documentation: "The `true` atom",
+ value: true
+}, AST_Boolean);
+
+/* -----[ TreeWalker ]----- */
+
+function TreeWalker(callback) {
+ this.visit = callback;
+ this.stack = [];
+};
+TreeWalker.prototype = {
+ _visit: function(node, descend) {
+ this.stack.push(node);
+ var ret = this.visit(node, descend ? function(){
+ descend.call(node);
+ } : noop);
+ if (!ret && descend) {
+ descend.call(node);
+ }
+ this.stack.pop();
+ return ret;
+ },
+ parent: function(n) {
+ return this.stack[this.stack.length - 2 - (n || 0)];
+ },
+ push: function (node) {
+ this.stack.push(node);
+ },
+ pop: function() {
+ return this.stack.pop();
+ },
+ self: function() {
+ return this.stack[this.stack.length - 1];
+ },
+ find_parent: function(type) {
+ var stack = this.stack;
+ for (var i = stack.length; --i >= 0;) {
+ var x = stack[i];
+ if (x instanceof type) return x;
+ }
+ },
+ has_directive: function(type) {
+ return this.find_parent(AST_Scope).has_directive(type);
+ },
+ in_boolean_context: function() {
+ var stack = this.stack;
+ var i = stack.length, self = stack[--i];
+ while (i > 0) {
+ var p = stack[--i];
+ if ((p instanceof AST_If && p.condition === self) ||
+ (p instanceof AST_Conditional && p.condition === self) ||
+ (p instanceof AST_DWLoop && p.condition === self) ||
+ (p instanceof AST_For && p.condition === self) ||
+ (p instanceof AST_UnaryPrefix && p.operator == "!" && p.expression === self))
+ {
+ return true;
+ }
+ if (!(p instanceof AST_Binary && (p.operator == "&&" || p.operator == "||")))
+ return false;
+ self = p;
+ }
+ },
+ loopcontrol_target: function(label) {
+ var stack = this.stack;
+ if (label) for (var i = stack.length; --i >= 0;) {
+ var x = stack[i];
+ if (x instanceof AST_LabeledStatement && x.label.name == label.name) {
+ return x.body;
+ }
+ } else for (var i = stack.length; --i >= 0;) {
+ var x = stack[i];
+ if (x instanceof AST_Switch || x instanceof AST_IterationStatement)
+ return x;
+ }
+ }
+};
+
+/***********************************************************************
+
+ A JavaScript tokenizer / parser / beautifier / compressor.
+ https://github.com/mishoo/UglifyJS2
+
+ -------------------------------- (C) ---------------------------------
+
+ Author: Mihai Bazon
+ <mihai.bazon@gmail.com>
+ http://mihai.bazon.net/blog
+
+ Distributed under the BSD license:
+
+ Copyright 2012 (c) Mihai Bazon <mihai.bazon@gmail.com>
+ Parser based on parse-js (http://marijn.haverbeke.nl/parse-js/).
+
+ Redistribution and use in source and binary forms, with or without
+ modification, are permitted provided that the following conditions
+ are met:
+
+ * Redistributions of source code must retain the above
+ copyright notice, this list of conditions and the following
+ disclaimer.
+
+ * Redistributions in binary form must reproduce the above
+ copyright notice, this list of conditions and the following
+ disclaimer in the documentation and/or other materials
+ provided with the distribution.
+
+ THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDER “AS IS” AND ANY
+ EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
+ PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE
+ LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY,
+ OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
+ PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
+ PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+ THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR
+ TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF
+ THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ SUCH DAMAGE.
+
+ ***********************************************************************/
+
+"use strict";
+
+var KEYWORDS = 'break case catch const continue debugger default delete do else finally for function if in instanceof new return switch throw try typeof var void while with';
+var KEYWORDS_ATOM = 'false null true';
+var RESERVED_WORDS = 'abstract boolean byte char class double enum export extends final float goto implements import int interface long native package private protected public short static super synchronized this throws transient volatile yield'
+ + " " + KEYWORDS_ATOM + " " + KEYWORDS;
+var KEYWORDS_BEFORE_EXPRESSION = 'return new delete throw else case';
+
+KEYWORDS = makePredicate(KEYWORDS);
+RESERVED_WORDS = makePredicate(RESERVED_WORDS);
+KEYWORDS_BEFORE_EXPRESSION = makePredicate(KEYWORDS_BEFORE_EXPRESSION);
+KEYWORDS_ATOM = makePredicate(KEYWORDS_ATOM);
+
+var OPERATOR_CHARS = makePredicate(characters("+-*&%=<>!?|~^"));
+
+var RE_HEX_NUMBER = /^0x[0-9a-f]+$/i;
+var RE_OCT_NUMBER = /^0[0-7]+$/;
+var RE_DEC_NUMBER = /^\d*\.?\d*(?:e[+-]?\d*(?:\d\.?|\.?\d)\d*)?$/i;
+
+var OPERATORS = makePredicate([
+ "in",
+ "instanceof",
+ "typeof",
+ "new",
+ "void",
+ "delete",
+ "++",
+ "--",
+ "+",
+ "-",
+ "!",
+ "~",
+ "&",
+ "|",
+ "^",
+ "*",
+ "/",
+ "%",
+ ">>",
+ "<<",
+ ">>>",
+ "<",
+ ">",
+ "<=",
+ ">=",
+ "==",
+ "===",
+ "!=",
+ "!==",
+ "?",
+ "=",
+ "+=",
+ "-=",
+ "/=",
+ "*=",
+ "%=",
+ ">>=",
+ "<<=",
+ ">>>=",
+ "|=",
+ "^=",
+ "&=",
+ "&&",
+ "||"
+]);
+
+var WHITESPACE_CHARS = makePredicate(characters(" \u00a0\n\r\t\f\u000b\u200b\u180e\u2000\u2001\u2002\u2003\u2004\u2005\u2006\u2007\u2008\u2009\u200a\u202f\u205f\u3000"));
+
+var PUNC_BEFORE_EXPRESSION = makePredicate(characters("[{(,.;:"));
+
+var PUNC_CHARS = makePredicate(characters("[]{}(),;:"));
+
+var REGEXP_MODIFIERS = makePredicate(characters("gmsiy"));
+
+/* -----[ Tokenizer ]----- */
+
+// regexps adapted from http://xregexp.com/plugins/#unicode
+var UNICODE = {
+ letter: new RegExp("[\\u0041-\\u005A\\u0061-\\u007A\\u00AA\\u00B5\\u00BA\\u00C0-\\u00D6\\u00D8-\\u00F6\\u00F8-\\u02C1\\u02C6-\\u02D1\\u02E0-\\u02E4\\u02EC\\u02EE\\u0370-\\u0374\\u0376\\u0377\\u037A-\\u037D\\u0386\\u0388-\\u038A\\u038C\\u038E-\\u03A1\\u03A3-\\u03F5\\u03F7-\\u0481\\u048A-\\u0523\\u0531-\\u0556\\u0559\\u0561-\\u0587\\u05D0-\\u05EA\\u05F0-\\u05F2\\u0621-\\u064A\\u066E\\u066F\\u0671-\\u06D3\\u06D5\\u06E5\\u06E6\\u06EE\\u06EF\\u06FA-\\u06FC\\u06FF\\u0710\\u0712-\\u072F\\u074D-\\u07A5\\u07B1\\u07CA-\\u07EA\\u07F4\\u07F5\\u07FA\\u0904-\\u0939\\u093D\\u0950\\u0958-\\u0961\\u0971\\u0972\\u097B-\\u097F\\u0985-\\u098C\\u098F\\u0990\\u0993-\\u09A8\\u09AA-\\u09B0\\u09B2\\u09B6-\\u09B9\\u09BD\\u09CE\\u09DC\\u09DD\\u09DF-\\u09E1\\u09F0\\u09F1\\u0A05-\\u0A0A\\u0A0F\\u0A10\\u0A13-\\u0A28\\u0A2A-\\u0A30\\u0A32\\u0A33\\u0A35\\u0A36\\u0A38\\u0A39\\u0A59-\\u0A5C\\u0A5E\\u0A72-\\u0A74\\u0A85-\\u0A8D\\u0A8F-\\u0A91\\u0A93-\\u0AA8\\u0AAA-\\u0AB0\\u0AB2\\u0AB3\\u0AB5-\\u0AB9\\u0ABD\\u0AD0\\u0AE0\\u0AE1\\u0B05-\\u0B0C\\u0B0F\\u0B10\\u0B13-\\u0B28\\u0B2A-\\u0B30\\u0B32\\u0B33\\u0B35-\\u0B39\\u0B3D\\u0B5C\\u0B5D\\u0B5F-\\u0B61\\u0B71\\u0B83\\u0B85-\\u0B8A\\u0B8E-\\u0B90\\u0B92-\\u0B95\\u0B99\\u0B9A\\u0B9C\\u0B9E\\u0B9F\\u0BA3\\u0BA4\\u0BA8-\\u0BAA\\u0BAE-\\u0BB9\\u0BD0\\u0C05-\\u0C0C\\u0C0E-\\u0C10\\u0C12-\\u0C28\\u0C2A-\\u0C33\\u0C35-\\u0C39\\u0C3D\\u0C58\\u0C59\\u0C60\\u0C61\\u0C85-\\u0C8C\\u0C8E-\\u0C90\\u0C92-\\u0CA8\\u0CAA-\\u0CB3\\u0CB5-\\u0CB9\\u0CBD\\u0CDE\\u0CE0\\u0CE1\\u0D05-\\u0D0C\\u0D0E-\\u0D10\\u0D12-\\u0D28\\u0D2A-\\u0D39\\u0D3D\\u0D60\\u0D61\\u0D7A-\\u0D7F\\u0D85-\\u0D96\\u0D9A-\\u0DB1\\u0DB3-\\u0DBB\\u0DBD\\u0DC0-\\u0DC6\\u0E01-\\u0E30\\u0E32\\u0E33\\u0E40-\\u0E46\\u0E81\\u0E82\\u0E84\\u0E87\\u0E88\\u0E8A\\u0E8D\\u0E94-\\u0E97\\u0E99-\\u0E9F\\u0EA1-\\u0EA3\\u0EA5\\u0EA7\\u0EAA\\u0EAB\\u0EAD-\\u0EB0\\u0EB2\\u0EB3\\u0EBD\\u0EC0-\\u0EC4\\u0EC6\\u0EDC\\u0EDD\\u0F00\\u0F40-\\u0F47\\u0F49-\\u0F6C\\u0F88-\\u0F8B\\u1000-\\u102A\\u103F\\u1050-\\u1055\\u105A-\\u105D\\u1061\\u1065\\u1066\\u106E-\\u1070\\u1075-\\u1081\\u108E\\u10A0-\\u10C5\\u10D0-\\u10FA\\u10FC\\u1100-\\u1159\\u115F-\\u11A2\\u11A8-\\u11F9\\u1200-\\u1248\\u124A-\\u124D\\u1250-\\u1256\\u1258\\u125A-\\u125D\\u1260-\\u1288\\u128A-\\u128D\\u1290-\\u12B0\\u12B2-\\u12B5\\u12B8-\\u12BE\\u12C0\\u12C2-\\u12C5\\u12C8-\\u12D6\\u12D8-\\u1310\\u1312-\\u1315\\u1318-\\u135A\\u1380-\\u138F\\u13A0-\\u13F4\\u1401-\\u166C\\u166F-\\u1676\\u1681-\\u169A\\u16A0-\\u16EA\\u1700-\\u170C\\u170E-\\u1711\\u1720-\\u1731\\u1740-\\u1751\\u1760-\\u176C\\u176E-\\u1770\\u1780-\\u17B3\\u17D7\\u17DC\\u1820-\\u1877\\u1880-\\u18A8\\u18AA\\u1900-\\u191C\\u1950-\\u196D\\u1970-\\u1974\\u1980-\\u19A9\\u19C1-\\u19C7\\u1A00-\\u1A16\\u1B05-\\u1B33\\u1B45-\\u1B4B\\u1B83-\\u1BA0\\u1BAE\\u1BAF\\u1C00-\\u1C23\\u1C4D-\\u1C4F\\u1C5A-\\u1C7D\\u1D00-\\u1DBF\\u1E00-\\u1F15\\u1F18-\\u1F1D\\u1F20-\\u1F45\\u1F48-\\u1F4D\\u1F50-\\u1F57\\u1F59\\u1F5B\\u1F5D\\u1F5F-\\u1F7D\\u1F80-\\u1FB4\\u1FB6-\\u1FBC\\u1FBE\\u1FC2-\\u1FC4\\u1FC6-\\u1FCC\\u1FD0-\\u1FD3\\u1FD6-\\u1FDB\\u1FE0-\\u1FEC\\u1FF2-\\u1FF4\\u1FF6-\\u1FFC\\u2071\\u207F\\u2090-\\u2094\\u2102\\u2107\\u210A-\\u2113\\u2115\\u2119-\\u211D\\u2124\\u2126\\u2128\\u212A-\\u212D\\u212F-\\u2139\\u213C-\\u213F\\u2145-\\u2149\\u214E\\u2183\\u2184\\u2C00-\\u2C2E\\u2C30-\\u2C5E\\u2C60-\\u2C6F\\u2C71-\\u2C7D\\u2C80-\\u2CE4\\u2D00-\\u2D25\\u2D30-\\u2D65\\u2D6F\\u2D80-\\u2D96\\u2DA0-\\u2DA6\\u2DA8-\\u2DAE\\u2DB0-\\u2DB6\\u2DB8-\\u2DBE\\u2DC0-\\u2DC6\\u2DC8-\\u2DCE\\u2DD0-\\u2DD6\\u2DD8-\\u2DDE\\u2E2F\\u3005\\u3006\\u3031-\\u3035\\u303B\\u303C\\u3041-\\u3096\\u309D-\\u309F\\u30A1-\\u30FA\\u30FC-\\u30FF\\u3105-\\u312D\\u3131-\\u318E\\u31A0-\\u31B7\\u31F0-\\u31FF\\u3400\\u4DB5\\u4E00\\u9FC3\\uA000-\\uA48C\\uA500-\\uA60C\\uA610-\\uA61F\\uA62A\\uA62B\\uA640-\\uA65F\\uA662-\\uA66E\\uA67F-\\uA697\\uA717-\\uA71F\\uA722-\\uA788\\uA78B\\uA78C\\uA7FB-\\uA801\\uA803-\\uA805\\uA807-\\uA80A\\uA80C-\\uA822\\uA840-\\uA873\\uA882-\\uA8B3\\uA90A-\\uA925\\uA930-\\uA946\\uAA00-\\uAA28\\uAA40-\\uAA42\\uAA44-\\uAA4B\\uAC00\\uD7A3\\uF900-\\uFA2D\\uFA30-\\uFA6A\\uFA70-\\uFAD9\\uFB00-\\uFB06\\uFB13-\\uFB17\\uFB1D\\uFB1F-\\uFB28\\uFB2A-\\uFB36\\uFB38-\\uFB3C\\uFB3E\\uFB40\\uFB41\\uFB43\\uFB44\\uFB46-\\uFBB1\\uFBD3-\\uFD3D\\uFD50-\\uFD8F\\uFD92-\\uFDC7\\uFDF0-\\uFDFB\\uFE70-\\uFE74\\uFE76-\\uFEFC\\uFF21-\\uFF3A\\uFF41-\\uFF5A\\uFF66-\\uFFBE\\uFFC2-\\uFFC7\\uFFCA-\\uFFCF\\uFFD2-\\uFFD7\\uFFDA-\\uFFDC]"),
+ non_spacing_mark: new RegExp("[\\u0300-\\u036F\\u0483-\\u0487\\u0591-\\u05BD\\u05BF\\u05C1\\u05C2\\u05C4\\u05C5\\u05C7\\u0610-\\u061A\\u064B-\\u065E\\u0670\\u06D6-\\u06DC\\u06DF-\\u06E4\\u06E7\\u06E8\\u06EA-\\u06ED\\u0711\\u0730-\\u074A\\u07A6-\\u07B0\\u07EB-\\u07F3\\u0816-\\u0819\\u081B-\\u0823\\u0825-\\u0827\\u0829-\\u082D\\u0900-\\u0902\\u093C\\u0941-\\u0948\\u094D\\u0951-\\u0955\\u0962\\u0963\\u0981\\u09BC\\u09C1-\\u09C4\\u09CD\\u09E2\\u09E3\\u0A01\\u0A02\\u0A3C\\u0A41\\u0A42\\u0A47\\u0A48\\u0A4B-\\u0A4D\\u0A51\\u0A70\\u0A71\\u0A75\\u0A81\\u0A82\\u0ABC\\u0AC1-\\u0AC5\\u0AC7\\u0AC8\\u0ACD\\u0AE2\\u0AE3\\u0B01\\u0B3C\\u0B3F\\u0B41-\\u0B44\\u0B4D\\u0B56\\u0B62\\u0B63\\u0B82\\u0BC0\\u0BCD\\u0C3E-\\u0C40\\u0C46-\\u0C48\\u0C4A-\\u0C4D\\u0C55\\u0C56\\u0C62\\u0C63\\u0CBC\\u0CBF\\u0CC6\\u0CCC\\u0CCD\\u0CE2\\u0CE3\\u0D41-\\u0D44\\u0D4D\\u0D62\\u0D63\\u0DCA\\u0DD2-\\u0DD4\\u0DD6\\u0E31\\u0E34-\\u0E3A\\u0E47-\\u0E4E\\u0EB1\\u0EB4-\\u0EB9\\u0EBB\\u0EBC\\u0EC8-\\u0ECD\\u0F18\\u0F19\\u0F35\\u0F37\\u0F39\\u0F71-\\u0F7E\\u0F80-\\u0F84\\u0F86\\u0F87\\u0F90-\\u0F97\\u0F99-\\u0FBC\\u0FC6\\u102D-\\u1030\\u1032-\\u1037\\u1039\\u103A\\u103D\\u103E\\u1058\\u1059\\u105E-\\u1060\\u1071-\\u1074\\u1082\\u1085\\u1086\\u108D\\u109D\\u135F\\u1712-\\u1714\\u1732-\\u1734\\u1752\\u1753\\u1772\\u1773\\u17B7-\\u17BD\\u17C6\\u17C9-\\u17D3\\u17DD\\u180B-\\u180D\\u18A9\\u1920-\\u1922\\u1927\\u1928\\u1932\\u1939-\\u193B\\u1A17\\u1A18\\u1A56\\u1A58-\\u1A5E\\u1A60\\u1A62\\u1A65-\\u1A6C\\u1A73-\\u1A7C\\u1A7F\\u1B00-\\u1B03\\u1B34\\u1B36-\\u1B3A\\u1B3C\\u1B42\\u1B6B-\\u1B73\\u1B80\\u1B81\\u1BA2-\\u1BA5\\u1BA8\\u1BA9\\u1C2C-\\u1C33\\u1C36\\u1C37\\u1CD0-\\u1CD2\\u1CD4-\\u1CE0\\u1CE2-\\u1CE8\\u1CED\\u1DC0-\\u1DE6\\u1DFD-\\u1DFF\\u20D0-\\u20DC\\u20E1\\u20E5-\\u20F0\\u2CEF-\\u2CF1\\u2DE0-\\u2DFF\\u302A-\\u302F\\u3099\\u309A\\uA66F\\uA67C\\uA67D\\uA6F0\\uA6F1\\uA802\\uA806\\uA80B\\uA825\\uA826\\uA8C4\\uA8E0-\\uA8F1\\uA926-\\uA92D\\uA947-\\uA951\\uA980-\\uA982\\uA9B3\\uA9B6-\\uA9B9\\uA9BC\\uAA29-\\uAA2E\\uAA31\\uAA32\\uAA35\\uAA36\\uAA43\\uAA4C\\uAAB0\\uAAB2-\\uAAB4\\uAAB7\\uAAB8\\uAABE\\uAABF\\uAAC1\\uABE5\\uABE8\\uABED\\uFB1E\\uFE00-\\uFE0F\\uFE20-\\uFE26]"),
+ space_combining_mark: new RegExp("[\\u0903\\u093E-\\u0940\\u0949-\\u094C\\u094E\\u0982\\u0983\\u09BE-\\u09C0\\u09C7\\u09C8\\u09CB\\u09CC\\u09D7\\u0A03\\u0A3E-\\u0A40\\u0A83\\u0ABE-\\u0AC0\\u0AC9\\u0ACB\\u0ACC\\u0B02\\u0B03\\u0B3E\\u0B40\\u0B47\\u0B48\\u0B4B\\u0B4C\\u0B57\\u0BBE\\u0BBF\\u0BC1\\u0BC2\\u0BC6-\\u0BC8\\u0BCA-\\u0BCC\\u0BD7\\u0C01-\\u0C03\\u0C41-\\u0C44\\u0C82\\u0C83\\u0CBE\\u0CC0-\\u0CC4\\u0CC7\\u0CC8\\u0CCA\\u0CCB\\u0CD5\\u0CD6\\u0D02\\u0D03\\u0D3E-\\u0D40\\u0D46-\\u0D48\\u0D4A-\\u0D4C\\u0D57\\u0D82\\u0D83\\u0DCF-\\u0DD1\\u0DD8-\\u0DDF\\u0DF2\\u0DF3\\u0F3E\\u0F3F\\u0F7F\\u102B\\u102C\\u1031\\u1038\\u103B\\u103C\\u1056\\u1057\\u1062-\\u1064\\u1067-\\u106D\\u1083\\u1084\\u1087-\\u108C\\u108F\\u109A-\\u109C\\u17B6\\u17BE-\\u17C5\\u17C7\\u17C8\\u1923-\\u1926\\u1929-\\u192B\\u1930\\u1931\\u1933-\\u1938\\u19B0-\\u19C0\\u19C8\\u19C9\\u1A19-\\u1A1B\\u1A55\\u1A57\\u1A61\\u1A63\\u1A64\\u1A6D-\\u1A72\\u1B04\\u1B35\\u1B3B\\u1B3D-\\u1B41\\u1B43\\u1B44\\u1B82\\u1BA1\\u1BA6\\u1BA7\\u1BAA\\u1C24-\\u1C2B\\u1C34\\u1C35\\u1CE1\\u1CF2\\uA823\\uA824\\uA827\\uA880\\uA881\\uA8B4-\\uA8C3\\uA952\\uA953\\uA983\\uA9B4\\uA9B5\\uA9BA\\uA9BB\\uA9BD-\\uA9C0\\uAA2F\\uAA30\\uAA33\\uAA34\\uAA4D\\uAA7B\\uABE3\\uABE4\\uABE6\\uABE7\\uABE9\\uABEA\\uABEC]"),
+ connector_punctuation: new RegExp("[\\u005F\\u203F\\u2040\\u2054\\uFE33\\uFE34\\uFE4D-\\uFE4F\\uFF3F]")
+};
+
+function is_letter(code) {
+ return (code >= 97 && code <= 122)
+ || (code >= 65 && code <= 90)
+ || (code >= 0xaa && UNICODE.letter.test(String.fromCharCode(code)));
+};
+
+function is_digit(code) {
+ return code >= 48 && code <= 57; //XXX: find out if "UnicodeDigit" means something else than 0..9
+};
+
+function is_alphanumeric_char(code) {
+ return is_digit(code) || is_letter(code);
+};
+
+function is_unicode_combining_mark(ch) {
+ return UNICODE.non_spacing_mark.test(ch) || UNICODE.space_combining_mark.test(ch);
+};
+
+function is_unicode_connector_punctuation(ch) {
+ return UNICODE.connector_punctuation.test(ch);
+};
+
+function is_identifier(name) {
+ return !RESERVED_WORDS(name) && /^[a-z_$][a-z0-9_$]*$/i.test(name);
+};
+
+function is_identifier_start(code) {
+ return code == 36 || code == 95 || is_letter(code);
+};
+
+function is_identifier_char(ch) {
+ var code = ch.charCodeAt(0);
+ return is_identifier_start(code)
+ || is_digit(code)
+ || code == 8204 // \u200c: zero-width non-joiner <ZWNJ>
+ || code == 8205 // \u200d: zero-width joiner <ZWJ> (in my ECMA-262 PDF, this is also 200c)
+ || is_unicode_combining_mark(ch)
+ || is_unicode_connector_punctuation(ch)
+ ;
+};
+
+function is_identifier_string(str){
+ var i = str.length;
+ if (i == 0) return false;
+ if (!is_identifier_start(str.charCodeAt(0))) return false;
+ while (--i >= 0) {
+ if (!is_identifier_char(str.charAt(i)))
+ return false;
+ }
+ return true;
+};
+
+function parse_js_number(num) {
+ if (RE_HEX_NUMBER.test(num)) {
+ return parseInt(num.substr(2), 16);
+ } else if (RE_OCT_NUMBER.test(num)) {
+ return parseInt(num.substr(1), 8);
+ } else if (RE_DEC_NUMBER.test(num)) {
+ return parseFloat(num);
+ }
+};
+
+function JS_Parse_Error(message, line, col, pos) {
+ this.message = message;
+ this.line = line;
+ this.col = col;
+ this.pos = pos;
+ this.stack = new Error().stack;
+};
+
+JS_Parse_Error.prototype.toString = function() {
+ return this.message + " (line: " + this.line + ", col: " + this.col + ", pos: " + this.pos + ")" + "\n\n" + this.stack;
+};
+
+function js_error(message, filename, line, col, pos) {
+ throw new JS_Parse_Error(message, line, col, pos);
+};
+
+function is_token(token, type, val) {
+ return token.type == type && (val == null || token.value == val);
+};
+
+var EX_EOF = {};
+
+function tokenizer($TEXT, filename, html5_comments) {
+
+ var S = {
+ text : $TEXT.replace(/\r\n?|[\n\u2028\u2029]/g, "\n").replace(/\uFEFF/g, ''),
+ filename : filename,
+ pos : 0,
+ tokpos : 0,
+ line : 1,
+ tokline : 0,
+ col : 0,
+ tokcol : 0,
+ newline_before : false,
+ regex_allowed : false,
+ comments_before : []
+ };
+
+ function peek() { return S.text.charAt(S.pos); };
+
+ function next(signal_eof, in_string) {
+ var ch = S.text.charAt(S.pos++);
+ if (signal_eof && !ch)
+ throw EX_EOF;
+ if (ch == "\n") {
+ S.newline_before = S.newline_before || !in_string;
+ ++S.line;
+ S.col = 0;
+ } else {
+ ++S.col;
+ }
+ return ch;
+ };
+
+ function forward(i) {
+ while (i-- > 0) next();
+ };
+
+ function looking_at(str) {
+ return S.text.substr(S.pos, str.length) == str;
+ };
+
+ function find(what, signal_eof) {
+ var pos = S.text.indexOf(what, S.pos);
+ if (signal_eof && pos == -1) throw EX_EOF;
+ return pos;
+ };
+
+ function start_token() {
+ S.tokline = S.line;
+ S.tokcol = S.col;
+ S.tokpos = S.pos;
+ };
+
+ var prev_was_dot = false;
+ function token(type, value, is_comment) {
+ S.regex_allowed = ((type == "operator" && !UNARY_POSTFIX(value)) ||
+ (type == "keyword" && KEYWORDS_BEFORE_EXPRESSION(value)) ||
+ (type == "punc" && PUNC_BEFORE_EXPRESSION(value)));
+ prev_was_dot = (type == "punc" && value == ".");
+ var ret = {
+ type : type,
+ value : value,
+ line : S.tokline,
+ col : S.tokcol,
+ pos : S.tokpos,
+ endpos : S.pos,
+ nlb : S.newline_before,
+ file : filename
+ };
+ if (!is_comment) {
+ ret.comments_before = S.comments_before;
+ S.comments_before = [];
+ // make note of any newlines in the comments that came before
+ for (var i = 0, len = ret.comments_before.length; i < len; i++) {
+ ret.nlb = ret.nlb || ret.comments_before[i].nlb;
+ }
+ }
+ S.newline_before = false;
+ return new AST_Token(ret);
+ };
+
+ function skip_whitespace() {
+ while (WHITESPACE_CHARS(peek()))
+ next();
+ };
+
+ function read_while(pred) {
+ var ret = "", ch, i = 0;
+ while ((ch = peek()) && pred(ch, i++))
+ ret += next();
+ return ret;
+ };
+
+ function parse_error(err) {
+ js_error(err, filename, S.tokline, S.tokcol, S.tokpos);
+ };
+
+ function read_num(prefix) {
+ var has_e = false, after_e = false, has_x = false, has_dot = prefix == ".";
+ var num = read_while(function(ch, i){
+ var code = ch.charCodeAt(0);
+ switch (code) {
+ case 120: case 88: // xX
+ return has_x ? false : (has_x = true);
+ case 101: case 69: // eE
+ return has_x ? true : has_e ? false : (has_e = after_e = true);
+ case 45: // -
+ return after_e || (i == 0 && !prefix);
+ case 43: // +
+ return after_e;
+ case (after_e = false, 46): // .
+ return (!has_dot && !has_x && !has_e) ? (has_dot = true) : false;
+ }
+ return is_alphanumeric_char(code);
+ });
+ if (prefix) num = prefix + num;
+ var valid = parse_js_number(num);
+ if (!isNaN(valid)) {
+ return token("num", valid);
+ } else {
+ parse_error("Invalid syntax: " + num);
+ }
+ };
+
+ function read_escaped_char(in_string) {
+ var ch = next(true, in_string);
+ switch (ch.charCodeAt(0)) {
+ case 110 : return "\n";
+ case 114 : return "\r";
+ case 116 : return "\t";
+ case 98 : return "\b";
+ case 118 : return "\u000b"; // \v
+ case 102 : return "\f";
+ case 48 : return "\0";
+ case 120 : return String.fromCharCode(hex_bytes(2)); // \x
+ case 117 : return String.fromCharCode(hex_bytes(4)); // \u
+ case 10 : return ""; // newline
+ default : return ch;
+ }
+ };
+
+ function hex_bytes(n) {
+ var num = 0;
+ for (; n > 0; --n) {
+ var digit = parseInt(next(true), 16);
+ if (isNaN(digit))
+ parse_error("Invalid hex-character pattern in string");
+ num = (num << 4) | digit;
+ }
+ return num;
+ };
+
+ var read_string = with_eof_error("Unterminated string constant", function(){
+ var quote = next(), ret = "";
+ for (;;) {
+ var ch = next(true);
+ if (ch == "\\") {
+ // read OctalEscapeSequence (XXX: deprecated if "strict mode")
+ // https://github.com/mishoo/UglifyJS/issues/178
+ var octal_len = 0, first = null;
+ ch = read_while(function(ch){
+ if (ch >= "0" && ch <= "7") {
+ if (!first) {
+ first = ch;
+ return ++octal_len;
+ }
+ else if (first <= "3" && octal_len <= 2) return ++octal_len;
+ else if (first >= "4" && octal_len <= 1) return ++octal_len;
+ }
+ return false;
+ });
+ if (octal_len > 0) ch = String.fromCharCode(parseInt(ch, 8));
+ else ch = read_escaped_char(true);
+ }
+ else if (ch == quote) break;
+ ret += ch;
+ }
+ return token("string", ret);
+ });
+
+ function skip_line_comment(type) {
+ var regex_allowed = S.regex_allowed;
+ var i = find("\n"), ret;
+ if (i == -1) {
+ ret = S.text.substr(S.pos);
+ S.pos = S.text.length;
+ } else {
+ ret = S.text.substring(S.pos, i);
+ S.pos = i;
+ }
+ S.comments_before.push(token(type, ret, true));
+ S.regex_allowed = regex_allowed;
+ return next_token();
+ };
+
+ var skip_multiline_comment = with_eof_error("Unterminated multiline comment", function(){
+ var regex_allowed = S.regex_allowed;
+ var i = find("*/", true);
+ var text = S.text.substring(S.pos, i);
+ var a = text.split("\n"), n = a.length;
+ // update stream position
+ S.pos = i + 2;
+ S.line += n - 1;
+ if (n > 1) S.col = a[n - 1].length;
+ else S.col += a[n - 1].length;
+ S.col += 2;
+ var nlb = S.newline_before = S.newline_before || text.indexOf("\n") >= 0;
+ S.comments_before.push(token("comment2", text, true));
+ S.regex_allowed = regex_allowed;
+ S.newline_before = nlb;
+ return next_token();
+ });
+
+ function read_name() {
+ var backslash = false, name = "", ch, escaped = false, hex;
+ while ((ch = peek()) != null) {
+ if (!backslash) {
+ if (ch == "\\") escaped = backslash = true, next();
+ else if (is_identifier_char(ch)) name += next();
+ else break;
+ }
+ else {
+ if (ch != "u") parse_error("Expecting UnicodeEscapeSequence -- uXXXX");
+ ch = read_escaped_char();
+ if (!is_identifier_char(ch)) parse_error("Unicode char: " + ch.charCodeAt(0) + " is not valid in identifier");
+ name += ch;
+ backslash = false;
+ }
+ }
+ if (KEYWORDS(name) && escaped) {
+ hex = name.charCodeAt(0).toString(16).toUpperCase();
+ name = "\\u" + "0000".substr(hex.length) + hex + name.slice(1);
+ }
+ return name;
+ };
+
+ var read_regexp = with_eof_error("Unterminated regular expression", function(regexp){
+ var prev_backslash = false, ch, in_class = false;
+ while ((ch = next(true))) if (prev_backslash) {
+ regexp += "\\" + ch;
+ prev_backslash = false;
+ } else if (ch == "[") {
+ in_class = true;
+ regexp += ch;
+ } else if (ch == "]" && in_class) {
+ in_class = false;
+ regexp += ch;
+ } else if (ch == "/" && !in_class) {
+ break;
+ } else if (ch == "\\") {
+ prev_backslash = true;
+ } else {
+ regexp += ch;
+ }
+ var mods = read_name();
+ return token("regexp", new RegExp(regexp, mods));
+ });
+
+ function read_operator(prefix) {
+ function grow(op) {
+ if (!peek()) return op;
+ var bigger = op + peek();
+ if (OPERATORS(bigger)) {
+ next();
+ return grow(bigger);
+ } else {
+ return op;
+ }
+ };
+ return token("operator", grow(prefix || next()));
+ };
+
+ function handle_slash() {
+ next();
+ switch (peek()) {
+ case "/":
+ next();
+ return skip_line_comment("comment1");
+ case "*":
+ next();
+ return skip_multiline_comment();
+ }
+ return S.regex_allowed ? read_regexp("") : read_operator("/");
+ };
+
+ function handle_dot() {
+ next();
+ return is_digit(peek().charCodeAt(0))
+ ? read_num(".")
+ : token("punc", ".");
+ };
+
+ function read_word() {
+ var word = read_name();
+ if (prev_was_dot) return token("name", word);
+ return KEYWORDS_ATOM(word) ? token("atom", word)
+ : !KEYWORDS(word) ? token("name", word)
+ : OPERATORS(word) ? token("operator", word)
+ : token("keyword", word);
+ };
+
+ function with_eof_error(eof_error, cont) {
+ return function(x) {
+ try {
+ return cont(x);
+ } catch(ex) {
+ if (ex === EX_EOF) parse_error(eof_error);
+ else throw ex;
+ }
+ };
+ };
+
+ function next_token(force_regexp) {
+ if (force_regexp != null)
+ return read_regexp(force_regexp);
+ skip_whitespace();
+ start_token();
+ if (html5_comments) {
+ if (looking_at("<!--")) {
+ forward(4);
+ return skip_line_comment("comment3");
+ }
+ if (looking_at("-->") && S.newline_before) {
+ forward(3);
+ return skip_line_comment("comment4");
+ }
+ }
+ var ch = peek();
+ if (!ch) return token("eof");
+ var code = ch.charCodeAt(0);
+ switch (code) {
+ case 34: case 39: return read_string();
+ case 46: return handle_dot();
+ case 47: return handle_slash();
+ }
+ if (is_digit(code)) return read_num();
+ if (PUNC_CHARS(ch)) return token("punc", next());
+ if (OPERATOR_CHARS(ch)) return read_operator();
+ if (code == 92 || is_identifier_start(code)) return read_word();
+ parse_error("Unexpected character '" + ch + "'");
+ };
+
+ next_token.context = function(nc) {
+ if (nc) S = nc;
+ return S;
+ };
+
+ return next_token;
+
+};
+
+/* -----[ Parser (constants) ]----- */
+
+var UNARY_PREFIX = makePredicate([
+ "typeof",
+ "void",
+ "delete",
+ "--",
+ "++",
+ "!",
+ "~",
+ "-",
+ "+"
+]);
+
+var UNARY_POSTFIX = makePredicate([ "--", "++" ]);
+
+var ASSIGNMENT = makePredicate([ "=", "+=", "-=", "/=", "*=", "%=", ">>=", "<<=", ">>>=", "|=", "^=", "&=" ]);
+
+var PRECEDENCE = (function(a, ret){
+ for (var i = 0; i < a.length; ++i) {
+ var b = a[i];
+ for (var j = 0; j < b.length; ++j) {
+ ret[b[j]] = i + 1;
+ }
+ }
+ return ret;
+})(
+ [
+ ["||"],
+ ["&&"],
+ ["|"],
+ ["^"],
+ ["&"],
+ ["==", "===", "!=", "!=="],
+ ["<", ">", "<=", ">=", "in", "instanceof"],
+ [">>", "<<", ">>>"],
+ ["+", "-"],
+ ["*", "/", "%"]
+ ],
+ {}
+);
+
+var STATEMENTS_WITH_LABELS = array_to_hash([ "for", "do", "while", "switch" ]);
+
+var ATOMIC_START_TOKEN = array_to_hash([ "atom", "num", "string", "regexp", "name" ]);
+
+/* -----[ Parser ]----- */
+
+function parse($TEXT, options) {
+
+ options = defaults(options, {
+ strict : false,
+ filename : null,
+ toplevel : null,
+ expression : false,
+ html5_comments : true,
+ });
+
+ var S = {
+ input : (typeof $TEXT == "string"
+ ? tokenizer($TEXT, options.filename,
+ options.html5_comments)
+ : $TEXT),
+ token : null,
+ prev : null,
+ peeked : null,
+ in_function : 0,
+ in_directives : true,
+ in_loop : 0,
+ labels : []
+ };
+
+ S.token = next();
+
+ function is(type, value) {
+ return is_token(S.token, type, value);
+ };
+
+ function peek() { return S.peeked || (S.peeked = S.input()); };
+
+ function next() {
+ S.prev = S.token;
+ if (S.peeked) {
+ S.token = S.peeked;
+ S.peeked = null;
+ } else {
+ S.token = S.input();
+ }
+ S.in_directives = S.in_directives && (
+ S.token.type == "string" || is("punc", ";")
+ );
+ return S.token;
+ };
+
+ function prev() {
+ return S.prev;
+ };
+
+ function croak(msg, line, col, pos) {
+ var ctx = S.input.context();
+ js_error(msg,
+ ctx.filename,
+ line != null ? line : ctx.tokline,
+ col != null ? col : ctx.tokcol,
+ pos != null ? pos : ctx.tokpos);
+ };
+
+ function token_error(token, msg) {
+ croak(msg, token.line, token.col);
+ };
+
+ function unexpected(token) {
+ if (token == null)
+ token = S.token;
+ token_error(token, "Unexpected token: " + token.type + " (" + token.value + ")");
+ };
+
+ function expect_token(type, val) {
+ if (is(type, val)) {
+ return next();
+ }
+ token_error(S.token, "Unexpected token " + S.token.type + " «" + S.token.value + "»" + ", expected " + type + " «" + val + "»");
+ };
+
+ function expect(punc) { return expect_token("punc", punc); };
+
+ function can_insert_semicolon() {
+ return !options.strict && (
+ S.token.nlb || is("eof") || is("punc", "}")
+ );
+ };
+
+ function semicolon() {
+ if (is("punc", ";")) next();
+ else if (!can_insert_semicolon()) unexpected();
+ };
+
+ function parenthesised() {
+ expect("(");
+ var exp = expression(true);
+ expect(")");
+ return exp;
+ };
+
+ function embed_tokens(parser) {
+ return function() {
+ var start = S.token;
+ var expr = parser();
+ var end = prev();
+ expr.start = start;
+ expr.end = end;
+ return expr;
+ };
+ };
+
+ function handle_regexp() {
+ if (is("operator", "/") || is("operator", "/=")) {
+ S.peeked = null;
+ S.token = S.input(S.token.value.substr(1)); // force regexp
+ }
+ };
+
+ var statement = embed_tokens(function() {
+ var tmp;
+ handle_regexp();
+ switch (S.token.type) {
+ case "string":
+ var dir = S.in_directives, stat = simple_statement();
+ // XXXv2: decide how to fix directives
+ if (dir && stat.body instanceof AST_String && !is("punc", ","))
+ return new AST_Directive({ value: stat.body.value });
+ return stat;
+ case "num":
+ case "regexp":
+ case "operator":
+ case "atom":
+ return simple_statement();
+
+ case "name":
+ return is_token(peek(), "punc", ":")
+ ? labeled_statement()
+ : simple_statement();
+
+ case "punc":
+ switch (S.token.value) {
+ case "{":
+ return new AST_BlockStatement({
+ start : S.token,
+ body : block_(),
+ end : prev()
+ });
+ case "[":
+ case "(":
+ return simple_statement();
+ case ";":
+ next();
+ return new AST_EmptyStatement();
+ default:
+ unexpected();
+ }
+
+ case "keyword":
+ switch (tmp = S.token.value, next(), tmp) {
+ case "break":
+ return break_cont(AST_Break);
+
+ case "continue":
+ return break_cont(AST_Continue);
+
+ case "debugger":
+ semicolon();
+ return new AST_Debugger();
+
+ case "do":
+ return new AST_Do({
+ body : in_loop(statement),
+ condition : (expect_token("keyword", "while"), tmp = parenthesised(), semicolon(), tmp)
+ });
+
+ case "while":
+ return new AST_While({
+ condition : parenthesised(),
+ body : in_loop(statement)
+ });
+
+ case "for":
+ return for_();
+
+ case "function":
+ return function_(AST_Defun);
+
+ case "if":
+ return if_();
+
+ case "return":
+ if (S.in_function == 0)
+ croak("'return' outside of function");
+ return new AST_Return({
+ value: ( is("punc", ";")
+ ? (next(), null)
+ : can_insert_semicolon()
+ ? null
+ : (tmp = expression(true), semicolon(), tmp) )
+ });
+
+ case "switch":
+ return new AST_Switch({
+ expression : parenthesised(),
+ body : in_loop(switch_body_)
+ });
+
+ case "throw":
+ if (S.token.nlb)
+ croak("Illegal newline after 'throw'");
+ return new AST_Throw({
+ value: (tmp = expression(true), semicolon(), tmp)
+ });
+
+ case "try":
+ return try_();
+
+ case "var":
+ return tmp = var_(), semicolon(), tmp;
+
+ case "const":
+ return tmp = const_(), semicolon(), tmp;
+
+ case "with":
+ return new AST_With({
+ expression : parenthesised(),
+ body : statement()
+ });
+
+ default:
+ unexpected();
+ }
+ }
+ });
+
+ function labeled_statement() {
+ var label = as_symbol(AST_Label);
+ if (find_if(function(l){ return l.name == label.name }, S.labels)) {
+ // ECMA-262, 12.12: An ECMAScript program is considered
+ // syntactically incorrect if it contains a
+ // LabelledStatement that is enclosed by a
+ // LabelledStatement with the same Identifier as label.
+ croak("Label " + label.name + " defined twice");
+ }
+ expect(":");
+ S.labels.push(label);
+ var stat = statement();
+ S.labels.pop();
+ if (!(stat instanceof AST_IterationStatement)) {
+ // check for `continue` that refers to this label.
+ // those should be reported as syntax errors.
+ // https://github.com/mishoo/UglifyJS2/issues/287
+ label.references.forEach(function(ref){
+ if (ref instanceof AST_Continue) {
+ ref = ref.label.start;
+ croak("Continue label `" + label.name + "` refers to non-IterationStatement.",
+ ref.line, ref.col, ref.pos);
+ }
+ });
+ }
+ return new AST_LabeledStatement({ body: stat, label: label });
+ };
+
+ function simple_statement(tmp) {
+ return new AST_SimpleStatement({ body: (tmp = expression(true), semicolon(), tmp) });
+ };
+
+ function break_cont(type) {
+ var label = null, ldef;
+ if (!can_insert_semicolon()) {
+ label = as_symbol(AST_LabelRef, true);
+ }
+ if (label != null) {
+ ldef = find_if(function(l){ return l.name == label.name }, S.labels);
+ if (!ldef)
+ croak("Undefined label " + label.name);
+ label.thedef = ldef;
+ }
+ else if (S.in_loop == 0)
+ croak(type.TYPE + " not inside a loop or switch");
+ semicolon();
+ var stat = new type({ label: label });
+ if (ldef) ldef.references.push(stat);
+ return stat;
+ };
+
+ function for_() {
+ expect("(");
+ var init = null;
+ if (!is("punc", ";")) {
+ init = is("keyword", "var")
+ ? (next(), var_(true))
+ : expression(true, true);
+ if (is("operator", "in")) {
+ if (init instanceof AST_Var && init.definitions.length > 1)
+ croak("Only one variable declaration allowed in for..in loop");
+ next();
+ return for_in(init);
+ }
+ }
+ return regular_for(init);
+ };
+
+ function regular_for(init) {
+ expect(";");
+ var test = is("punc", ";") ? null : expression(true);
+ expect(";");
+ var step = is("punc", ")") ? null : expression(true);
+ expect(")");
+ return new AST_For({
+ init : init,
+ condition : test,
+ step : step,
+ body : in_loop(statement)
+ });
+ };
+
+ function for_in(init) {
+ var lhs = init instanceof AST_Var ? init.definitions[0].name : null;
+ var obj = expression(true);
+ expect(")");
+ return new AST_ForIn({
+ init : init,
+ name : lhs,
+ object : obj,
+ body : in_loop(statement)
+ });
+ };
+
+ var function_ = function(ctor) {
+ var in_statement = ctor === AST_Defun;
+ var name = is("name") ? as_symbol(in_statement ? AST_SymbolDefun : AST_SymbolLambda) : null;
+ if (in_statement && !name)
+ unexpected();
+ expect("(");
+ return new ctor({
+ name: name,
+ argnames: (function(first, a){
+ while (!is("punc", ")")) {
+ if (first) first = false; else expect(",");
+ a.push(as_symbol(AST_SymbolFunarg));
+ }
+ next();
+ return a;
+ })(true, []),
+ body: (function(loop, labels){
+ ++S.in_function;
+ S.in_directives = true;
+ S.in_loop = 0;
+ S.labels = [];
+ var a = block_();
+ --S.in_function;
+ S.in_loop = loop;
+ S.labels = labels;
+ return a;
+ })(S.in_loop, S.labels)
+ });
+ };
+
+ function if_() {
+ var cond = parenthesised(), body = statement(), belse = null;
+ if (is("keyword", "else")) {
+ next();
+ belse = statement();
+ }
+ return new AST_If({
+ condition : cond,
+ body : body,
+ alternative : belse
+ });
+ };
+
+ function block_() {
+ expect("{");
+ var a = [];
+ while (!is("punc", "}")) {
+ if (is("eof")) unexpected();
+ a.push(statement());
+ }
+ next();
+ return a;
+ };
+
+ function switch_body_() {
+ expect("{");
+ var a = [], cur = null, branch = null, tmp;
+ while (!is("punc", "}")) {
+ if (is("eof")) unexpected();
+ if (is("keyword", "case")) {
+ if (branch) branch.end = prev();
+ cur = [];
+ branch = new AST_Case({
+ start : (tmp = S.token, next(), tmp),
+ expression : expression(true),
+ body : cur
+ });
+ a.push(branch);
+ expect(":");
+ }
+ else if (is("keyword", "default")) {
+ if (branch) branch.end = prev();
+ cur = [];
+ branch = new AST_Default({
+ start : (tmp = S.token, next(), expect(":"), tmp),
+ body : cur
+ });
+ a.push(branch);
+ }
+ else {
+ if (!cur) unexpected();
+ cur.push(statement());
+ }
+ }
+ if (branch) branch.end = prev();
+ next();
+ return a;
+ };
+
+ function try_() {
+ var body = block_(), bcatch = null, bfinally = null;
+ if (is("keyword", "catch")) {
+ var start = S.token;
+ next();
+ expect("(");
+ var name = as_symbol(AST_SymbolCatch);
+ expect(")");
+ bcatch = new AST_Catch({
+ start : start,
+ argname : name,
+ body : block_(),
+ end : prev()
+ });
+ }
+ if (is("keyword", "finally")) {
+ var start = S.token;
+ next();
+ bfinally = new AST_Finally({
+ start : start,
+ body : block_(),
+ end : prev()
+ });
+ }
+ if (!bcatch && !bfinally)
+ croak("Missing catch/finally blocks");
+ return new AST_Try({
+ body : body,
+ bcatch : bcatch,
+ bfinally : bfinally
+ });
+ };
+
+ function vardefs(no_in, in_const) {
+ var a = [];
+ for (;;) {
+ a.push(new AST_VarDef({
+ start : S.token,
+ name : as_symbol(in_const ? AST_SymbolConst : AST_SymbolVar),
+ value : is("operator", "=") ? (next(), expression(false, no_in)) : null,
+ end : prev()
+ }));
+ if (!is("punc", ","))
+ break;
+ next();
+ }
+ return a;
+ };
+
+ var var_ = function(no_in) {
+ return new AST_Var({
+ start : prev(),
+ definitions : vardefs(no_in, false),
+ end : prev()
+ });
+ };
+
+ var const_ = function() {
+ return new AST_Const({
+ start : prev(),
+ definitions : vardefs(false, true),
+ end : prev()
+ });
+ };
+
+ var new_ = function() {
+ var start = S.token;
+ expect_token("operator", "new");
+ var newexp = expr_atom(false), args;
+ if (is("punc", "(")) {
+ next();
+ args = expr_list(")");
+ } else {
+ args = [];
+ }
+ return subscripts(new AST_New({
+ start : start,
+ expression : newexp,
+ args : args,
+ end : prev()
+ }), true);
+ };
+
+ function as_atom_node() {
+ var tok = S.token, ret;
+ switch (tok.type) {
+ case "name":
+ case "keyword":
+ ret = _make_symbol(AST_SymbolRef);
+ break;
+ case "num":
+ ret = new AST_Number({ start: tok, end: tok, value: tok.value });
+ break;
+ case "string":
+ ret = new AST_String({ start: tok, end: tok, value: tok.value });
+ break;
+ case "regexp":
+ ret = new AST_RegExp({ start: tok, end: tok, value: tok.value });
+ break;
+ case "atom":
+ switch (tok.value) {
+ case "false":
+ ret = new AST_False({ start: tok, end: tok });
+ break;
+ case "true":
+ ret = new AST_True({ start: tok, end: tok });
+ break;
+ case "null":
+ ret = new AST_Null({ start: tok, end: tok });
+ break;
+ }
+ break;
+ }
+ next();
+ return ret;
+ };
+
+ var expr_atom = function(allow_calls) {
+ if (is("operator", "new")) {
+ return new_();
+ }
+ var start = S.token;
+ if (is("punc")) {
+ switch (start.value) {
+ case "(":
+ next();
+ var ex = expression(true);
+ ex.start = start;
+ ex.end = S.token;
+ expect(")");
+ return subscripts(ex, allow_calls);
+ case "[":
+ return subscripts(array_(), allow_calls);
+ case "{":
+ return subscripts(object_(), allow_calls);
+ }
+ unexpected();
+ }
+ if (is("keyword", "function")) {
+ next();
+ var func = function_(AST_Function);
+ func.start = start;
+ func.end = prev();
+ return subscripts(func, allow_calls);
+ }
+ if (ATOMIC_START_TOKEN[S.token.type]) {
+ return subscripts(as_atom_node(), allow_calls);
+ }
+ unexpected();
+ };
+
+ function expr_list(closing, allow_trailing_comma, allow_empty) {
+ var first = true, a = [];
+ while (!is("punc", closing)) {
+ if (first) first = false; else expect(",");
+ if (allow_trailing_comma && is("punc", closing)) break;
+ if (is("punc", ",") && allow_empty) {
+ a.push(new AST_Hole({ start: S.token, end: S.token }));
+ } else {
+ a.push(expression(false));
+ }
+ }
+ next();
+ return a;
+ };
+
+ var array_ = embed_tokens(function() {
+ expect("[");
+ return new AST_Array({
+ elements: expr_list("]", !options.strict, true)
+ });
+ });
+
+ var object_ = embed_tokens(function() {
+ expect("{");
+ var first = true, a = [];
+ while (!is("punc", "}")) {
+ if (first) first = false; else expect(",");
+ if (!options.strict && is("punc", "}"))
+ // allow trailing comma
+ break;
+ var start = S.token;
+ var type = start.type;
+ var name = as_property_name();
+ if (type == "name" && !is("punc", ":")) {
+ if (name == "get") {
+ a.push(new AST_ObjectGetter({
+ start : start,
+ key : as_atom_node(),
+ value : function_(AST_Accessor),
+ end : prev()
+ }));
+ continue;
+ }
+ if (name == "set") {
+ a.push(new AST_ObjectSetter({
+ start : start,
+ key : as_atom_node(),
+ value : function_(AST_Accessor),
+ end : prev()
+ }));
+ continue;
+ }
+ }
+ expect(":");
+ a.push(new AST_ObjectKeyVal({
+ start : start,
+ key : name,
+ value : expression(false),
+ end : prev()
+ }));
+ }
+ next();
+ return new AST_Object({ properties: a });
+ });
+
+ function as_property_name() {
+ var tmp = S.token;
+ next();
+ switch (tmp.type) {
+ case "num":
+ case "string":
+ case "name":
+ case "operator":
+ case "keyword":
+ case "atom":
+ return tmp.value;
+ default:
+ unexpected();
+ }
+ };
+
+ function as_name() {
+ var tmp = S.token;
+ next();
+ switch (tmp.type) {
+ case "name":
+ case "operator":
+ case "keyword":
+ case "atom":
+ return tmp.value;
+ default:
+ unexpected();
+ }
+ };
+
+ function _make_symbol(type) {
+ var name = S.token.value;
+ return new (name == "this" ? AST_This : type)({
+ name : String(name),
+ start : S.token,
+ end : S.token
+ });
+ };
+
+ function as_symbol(type, noerror) {
+ if (!is("name")) {
+ if (!noerror) croak("Name expected");
+ return null;
+ }
+ var sym = _make_symbol(type);
+ next();
+ return sym;
+ };
+
+ var subscripts = function(expr, allow_calls) {
+ var start = expr.start;
+ if (is("punc", ".")) {
+ next();
+ return subscripts(new AST_Dot({
+ start : start,
+ expression : expr,
+ property : as_name(),
+ end : prev()
+ }), allow_calls);
+ }
+ if (is("punc", "[")) {
+ next();
+ var prop = expression(true);
+ expect("]");
+ return subscripts(new AST_Sub({
+ start : start,
+ expression : expr,
+ property : prop,
+ end : prev()
+ }), allow_calls);
+ }
+ if (allow_calls && is("punc", "(")) {
+ next();
+ return subscripts(new AST_Call({
+ start : start,
+ expression : expr,
+ args : expr_list(")"),
+ end : prev()
+ }), true);
+ }
+ return expr;
+ };
+
+ var maybe_unary = function(allow_calls) {
+ var start = S.token;
+ if (is("operator") && UNARY_PREFIX(start.value)) {
+ next();
+ handle_regexp();
+ var ex = make_unary(AST_UnaryPrefix, start.value, maybe_unary(allow_calls));
+ ex.start = start;
+ ex.end = prev();
+ return ex;
+ }
+ var val = expr_atom(allow_calls);
+ while (is("operator") && UNARY_POSTFIX(S.token.value) && !S.token.nlb) {
+ val = make_unary(AST_UnaryPostfix, S.token.value, val);
+ val.start = start;
+ val.end = S.token;
+ next();
+ }
+ return val;
+ };
+
+ function make_unary(ctor, op, expr) {
+ if ((op == "++" || op == "--") && !is_assignable(expr))
+ croak("Invalid use of " + op + " operator");
+ return new ctor({ operator: op, expression: expr });
+ };
+
+ var expr_op = function(left, min_prec, no_in) {
+ var op = is("operator") ? S.token.value : null;
+ if (op == "in" && no_in) op = null;
+ var prec = op != null ? PRECEDENCE[op] : null;
+ if (prec != null && prec > min_prec) {
+ next();
+ var right = expr_op(maybe_unary(true), prec, no_in);
+ return expr_op(new AST_Binary({
+ start : left.start,
+ left : left,
+ operator : op,
+ right : right,
+ end : right.end
+ }), min_prec, no_in);
+ }
+ return left;
+ };
+
+ function expr_ops(no_in) {
+ return expr_op(maybe_unary(true), 0, no_in);
+ };
+
+ var maybe_conditional = function(no_in) {
+ var start = S.token;
+ var expr = expr_ops(no_in);
+ if (is("operator", "?")) {
+ next();
+ var yes = expression(false);
+ expect(":");
+ return new AST_Conditional({
+ start : start,
+ condition : expr,
+ consequent : yes,
+ alternative : expression(false, no_in),
+ end : prev()
+ });
+ }
+ return expr;
+ };
+
+ function is_assignable(expr) {
+ if (!options.strict) return true;
+ if (expr instanceof AST_This) return false;
+ return (expr instanceof AST_PropAccess || expr instanceof AST_Symbol);
+ };
+
+ var maybe_assign = function(no_in) {
+ var start = S.token;
+ var left = maybe_conditional(no_in), val = S.token.value;
+ if (is("operator") && ASSIGNMENT(val)) {
+ if (is_assignable(left)) {
+ next();
+ return new AST_Assign({
+ start : start,
+ left : left,
+ operator : val,
+ right : maybe_assign(no_in),
+ end : prev()
+ });
+ }
+ croak("Invalid assignment");
+ }
+ return left;
+ };
+
+ var expression = function(commas, no_in) {
+ var start = S.token;
+ var expr = maybe_assign(no_in);
+ if (commas && is("punc", ",")) {
+ next();
+ return new AST_Seq({
+ start : start,
+ car : expr,
+ cdr : expression(true, no_in),
+ end : peek()
+ });
+ }
+ return expr;
+ };
+
+ function in_loop(cont) {
+ ++S.in_loop;
+ var ret = cont();
+ --S.in_loop;
+ return ret;
+ };
+
+ if (options.expression) {
+ return expression(true);
+ }
+
+ return (function(){
+ var start = S.token;
+ var body = [];
+ while (!is("eof"))
+ body.push(statement());
+ var end = prev();
+ var toplevel = options.toplevel;
+ if (toplevel) {
+ toplevel.body = toplevel.body.concat(body);
+ toplevel.end = end;
+ } else {
+ toplevel = new AST_Toplevel({ start: start, body: body, end: end });
+ }
+ return toplevel;
+ })();
+
+};
+
+/***********************************************************************
+
+ A JavaScript tokenizer / parser / beautifier / compressor.
+ https://github.com/mishoo/UglifyJS2
+
+ -------------------------------- (C) ---------------------------------
+
+ Author: Mihai Bazon
+ <mihai.bazon@gmail.com>
+ http://mihai.bazon.net/blog
+
+ Distributed under the BSD license:
+
+ Copyright 2012 (c) Mihai Bazon <mihai.bazon@gmail.com>
+
+ Redistribution and use in source and binary forms, with or without
+ modification, are permitted provided that the following conditions
+ are met:
+
+ * Redistributions of source code must retain the above
+ copyright notice, this list of conditions and the following
+ disclaimer.
+
+ * Redistributions in binary form must reproduce the above
+ copyright notice, this list of conditions and the following
+ disclaimer in the documentation and/or other materials
+ provided with the distribution.
+
+ THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDER “AS IS” AND ANY
+ EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
+ PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE
+ LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY,
+ OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
+ PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
+ PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+ THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR
+ TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF
+ THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ SUCH DAMAGE.
+
+ ***********************************************************************/
+
+"use strict";
+
+// Tree transformer helpers.
+
+function TreeTransformer(before, after) {
+ TreeWalker.call(this);
+ this.before = before;
+ this.after = after;
+}
+TreeTransformer.prototype = new TreeWalker;
+
+(function(undefined){
+
+ function _(node, descend) {
+ node.DEFMETHOD("transform", function(tw, in_list){
+ var x, y;
+ tw.push(this);
+ if (tw.before) x = tw.before(this, descend, in_list);
+ if (x === undefined) {
+ if (!tw.after) {
+ x = this;
+ descend(x, tw);
+ } else {
+ tw.stack[tw.stack.length - 1] = x = this.clone();
+ descend(x, tw);
+ y = tw.after(x, in_list);
+ if (y !== undefined) x = y;
+ }
+ }
+ tw.pop();
+ return x;
+ });
+ };
+
+ function do_list(list, tw) {
+ return MAP(list, function(node){
+ return node.transform(tw, true);
+ });
+ };
+
+ _(AST_Node, noop);
+
+ _(AST_LabeledStatement, function(self, tw){
+ self.label = self.label.transform(tw);
+ self.body = self.body.transform(tw);
+ });
+
+ _(AST_SimpleStatement, function(self, tw){
+ self.body = self.body.transform(tw);
+ });
+
+ _(AST_Block, function(self, tw){
+ self.body = do_list(self.body, tw);
+ });
+
+ _(AST_DWLoop, function(self, tw){
+ self.condition = self.condition.transform(tw);
+ self.body = self.body.transform(tw);
+ });
+
+ _(AST_For, function(self, tw){
+ if (self.init) self.init = self.init.transform(tw);
+ if (self.condition) self.condition = self.condition.transform(tw);
+ if (self.step) self.step = self.step.transform(tw);
+ self.body = self.body.transform(tw);
+ });
+
+ _(AST_ForIn, function(self, tw){
+ self.init = self.init.transform(tw);
+ self.object = self.object.transform(tw);
+ self.body = self.body.transform(tw);
+ });
+
+ _(AST_With, function(self, tw){
+ self.expression = self.expression.transform(tw);
+ self.body = self.body.transform(tw);
+ });
+
+ _(AST_Exit, function(self, tw){
+ if (self.value) self.value = self.value.transform(tw);
+ });
+
+ _(AST_LoopControl, function(self, tw){
+ if (self.label) self.label = self.label.transform(tw);
+ });
+
+ _(AST_If, function(self, tw){
+ self.condition = self.condition.transform(tw);
+ self.body = self.body.transform(tw);
+ if (self.alternative) self.alternative = self.alternative.transform(tw);
+ });
+
+ _(AST_Switch, function(self, tw){
+ self.expression = self.expression.transform(tw);
+ self.body = do_list(self.body, tw);
+ });
+
+ _(AST_Case, function(self, tw){
+ self.expression = self.expression.transform(tw);
+ self.body = do_list(self.body, tw);
+ });
+
+ _(AST_Try, function(self, tw){
+ self.body = do_list(self.body, tw);
+ if (self.bcatch) self.bcatch = self.bcatch.transform(tw);
+ if (self.bfinally) self.bfinally = self.bfinally.transform(tw);
+ });
+
+ _(AST_Catch, function(self, tw){
+ self.argname = self.argname.transform(tw);
+ self.body = do_list(self.body, tw);
+ });
+
+ _(AST_Definitions, function(self, tw){
+ self.definitions = do_list(self.definitions, tw);
+ });
+
+ _(AST_VarDef, function(self, tw){
+ self.name = self.name.transform(tw);
+ if (self.value) self.value = self.value.transform(tw);
+ });
+
+ _(AST_Lambda, function(self, tw){
+ if (self.name) self.name = self.name.transform(tw);
+ self.argnames = do_list(self.argnames, tw);
+ self.body = do_list(self.body, tw);
+ });
+
+ _(AST_Call, function(self, tw){
+ self.expression = self.expression.transform(tw);
+ self.args = do_list(self.args, tw);
+ });
+
+ _(AST_Seq, function(self, tw){
+ self.car = self.car.transform(tw);
+ self.cdr = self.cdr.transform(tw);
+ });
+
+ _(AST_Dot, function(self, tw){
+ self.expression = self.expression.transform(tw);
+ });
+
+ _(AST_Sub, function(self, tw){
+ self.expression = self.expression.transform(tw);
+ self.property = self.property.transform(tw);
+ });
+
+ _(AST_Unary, function(self, tw){
+ self.expression = self.expression.transform(tw);
+ });
+
+ _(AST_Binary, function(self, tw){
+ self.left = self.left.transform(tw);
+ self.right = self.right.transform(tw);
+ });
+
+ _(AST_Conditional, function(self, tw){
+ self.condition = self.condition.transform(tw);
+ self.consequent = self.consequent.transform(tw);
+ self.alternative = self.alternative.transform(tw);
+ });
+
+ _(AST_Array, function(self, tw){
+ self.elements = do_list(self.elements, tw);
+ });
+
+ _(AST_Object, function(self, tw){
+ self.properties = do_list(self.properties, tw);
+ });
+
+ _(AST_ObjectProperty, function(self, tw){
+ self.value = self.value.transform(tw);
+ });
+
+})();
+
+/***********************************************************************
+
+ A JavaScript tokenizer / parser / beautifier / compressor.
+ https://github.com/mishoo/UglifyJS2
+
+ -------------------------------- (C) ---------------------------------
+
+ Author: Mihai Bazon
+ <mihai.bazon@gmail.com>
+ http://mihai.bazon.net/blog
+
+ Distributed under the BSD license:
+
+ Copyright 2012 (c) Mihai Bazon <mihai.bazon@gmail.com>
+
+ Redistribution and use in source and binary forms, with or without
+ modification, are permitted provided that the following conditions
+ are met:
+
+ * Redistributions of source code must retain the above
+ copyright notice, this list of conditions and the following
+ disclaimer.
+
+ * Redistributions in binary form must reproduce the above
+ copyright notice, this list of conditions and the following
+ disclaimer in the documentation and/or other materials
+ provided with the distribution.
+
+ THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDER “AS IS” AND ANY
+ EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
+ PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE
+ LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY,
+ OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
+ PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
+ PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+ THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR
+ TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF
+ THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ SUCH DAMAGE.
+
+ ***********************************************************************/
+
+"use strict";
+
+function SymbolDef(scope, index, orig) {
+ this.name = orig.name;
+ this.orig = [ orig ];
+ this.scope = scope;
+ this.references = [];
+ this.global = false;
+ this.mangled_name = null;
+ this.undeclared = false;
+ this.constant = false;
+ this.index = index;
+};
+
+SymbolDef.prototype = {
+ unmangleable: function(options) {
+ return (this.global && !(options && options.toplevel))
+ || this.undeclared
+ || (!(options && options.eval) && (this.scope.uses_eval || this.scope.uses_with));
+ },
+ mangle: function(options) {
+ if (!this.mangled_name && !this.unmangleable(options)) {
+ var s = this.scope;
+ if (!options.screw_ie8 && this.orig[0] instanceof AST_SymbolLambda)
+ s = s.parent_scope;
+ this.mangled_name = s.next_mangled(options, this);
+ }
+ }
+};
+
+AST_Toplevel.DEFMETHOD("figure_out_scope", function(options){
+ options = defaults(options, {
+ screw_ie8: false
+ });
+
+ // pass 1: setup scope chaining and handle definitions
+ var self = this;
+ var scope = self.parent_scope = null;
+ var defun = null;
+ var nesting = 0;
+ var tw = new TreeWalker(function(node, descend){
+ if (options.screw_ie8 && node instanceof AST_Catch) {
+ var save_scope = scope;
+ scope = new AST_Scope(node);
+ scope.init_scope_vars(nesting);
+ scope.parent_scope = save_scope;
+ descend();
+ scope = save_scope;
+ return true;
+ }
+ if (node instanceof AST_Scope) {
+ node.init_scope_vars(nesting);
+ var save_scope = node.parent_scope = scope;
+ var save_defun = defun;
+ defun = scope = node;
+ ++nesting; descend(); --nesting;
+ scope = save_scope;
+ defun = save_defun;
+ return true; // don't descend again in TreeWalker
+ }
+ if (node instanceof AST_Directive) {
+ node.scope = scope;
+ push_uniq(scope.directives, node.value);
+ return true;
+ }
+ if (node instanceof AST_With) {
+ for (var s = scope; s; s = s.parent_scope)
+ s.uses_with = true;
+ return;
+ }
+ if (node instanceof AST_Symbol) {
+ node.scope = scope;
+ }
+ if (node instanceof AST_SymbolLambda) {
+ defun.def_function(node);
+ }
+ else if (node instanceof AST_SymbolDefun) {
+ // Careful here, the scope where this should be defined is
+ // the parent scope. The reason is that we enter a new
+ // scope when we encounter the AST_Defun node (which is
+ // instanceof AST_Scope) but we get to the symbol a bit
+ // later.
+ (node.scope = defun.parent_scope).def_function(node);
+ }
+ else if (node instanceof AST_SymbolVar
+ || node instanceof AST_SymbolConst) {
+ var def = defun.def_variable(node);
+ def.constant = node instanceof AST_SymbolConst;
+ def.init = tw.parent().value;
+ }
+ else if (node instanceof AST_SymbolCatch) {
+ (options.screw_ie8 ? scope : defun)
+ .def_variable(node);
+ }
+ });
+ self.walk(tw);
+
+ // pass 2: find back references and eval
+ var func = null;
+ var globals = self.globals = new Dictionary();
+ var tw = new TreeWalker(function(node, descend){
+ if (node instanceof AST_Lambda) {
+ var prev_func = func;
+ func = node;
+ descend();
+ func = prev_func;
+ return true;
+ }
+ if (node instanceof AST_SymbolRef) {
+ var name = node.name;
+ var sym = node.scope.find_variable(name);
+ if (!sym) {
+ var g;
+ if (globals.has(name)) {
+ g = globals.get(name);
+ } else {
+ g = new SymbolDef(self, globals.size(), node);
+ g.undeclared = true;
+ g.global = true;
+ globals.set(name, g);
+ }
+ node.thedef = g;
+ if (name == "eval" && tw.parent() instanceof AST_Call) {
+ for (var s = node.scope; s && !s.uses_eval; s = s.parent_scope)
+ s.uses_eval = true;
+ }
+ if (func && name == "arguments") {
+ func.uses_arguments = true;
+ }
+ } else {
+ node.thedef = sym;
+ }
+ node.reference();
+ return true;
+ }
+ });
+ self.walk(tw);
+});
+
+AST_Scope.DEFMETHOD("init_scope_vars", function(nesting){
+ this.directives = []; // contains the directives defined in this scope, i.e. "use strict"
+ this.variables = new Dictionary(); // map name to AST_SymbolVar (variables defined in this scope; includes functions)
+ this.functions = new Dictionary(); // map name to AST_SymbolDefun (functions defined in this scope)
+ this.uses_with = false; // will be set to true if this or some nested scope uses the `with` statement
+ this.uses_eval = false; // will be set to true if this or nested scope uses the global `eval`
+ this.parent_scope = null; // the parent scope
+ this.enclosed = []; // a list of variables from this or outer scope(s) that are referenced from this or inner scopes
+ this.cname = -1; // the current index for mangling functions/variables
+ this.nesting = nesting; // the nesting level of this scope (0 means toplevel)
+});
+
+AST_Scope.DEFMETHOD("strict", function(){
+ return this.has_directive("use strict");
+});
+
+AST_Lambda.DEFMETHOD("init_scope_vars", function(){
+ AST_Scope.prototype.init_scope_vars.apply(this, arguments);
+ this.uses_arguments = false;
+});
+
+AST_SymbolRef.DEFMETHOD("reference", function() {
+ var def = this.definition();
+ def.references.push(this);
+ var s = this.scope;
+ while (s) {
+ push_uniq(s.enclosed, def);
+ if (s === def.scope) break;
+ s = s.parent_scope;
+ }
+ this.frame = this.scope.nesting - def.scope.nesting;
+});
+
+AST_Scope.DEFMETHOD("find_variable", function(name){
+ if (name instanceof AST_Symbol) name = name.name;
+ return this.variables.get(name)
+ || (this.parent_scope && this.parent_scope.find_variable(name));
+});
+
+AST_Scope.DEFMETHOD("has_directive", function(value){
+ return this.parent_scope && this.parent_scope.has_directive(value)
+ || (this.directives.indexOf(value) >= 0 ? this : null);
+});
+
+AST_Scope.DEFMETHOD("def_function", function(symbol){
+ this.functions.set(symbol.name, this.def_variable(symbol));
+});
+
+AST_Scope.DEFMETHOD("def_variable", function(symbol){
+ var def;
+ if (!this.variables.has(symbol.name)) {
+ def = new SymbolDef(this, this.variables.size(), symbol);
+ this.variables.set(symbol.name, def);
+ def.global = !this.parent_scope;
+ } else {
+ def = this.variables.get(symbol.name);
+ def.orig.push(symbol);
+ }
+ return symbol.thedef = def;
+});
+
+AST_Scope.DEFMETHOD("next_mangled", function(options){
+ var ext = this.enclosed;
+ out: while (true) {
+ var m = base54(++this.cname);
+ if (!is_identifier(m)) continue; // skip over "do"
+
+ // https://github.com/mishoo/UglifyJS2/issues/242 -- do not
+ // shadow a name excepted from mangling.
+ if (options.except.indexOf(m) >= 0) continue;
+
+ // we must ensure that the mangled name does not shadow a name
+ // from some parent scope that is referenced in this or in
+ // inner scopes.
+ for (var i = ext.length; --i >= 0;) {
+ var sym = ext[i];
+ var name = sym.mangled_name || (sym.unmangleable(options) && sym.name);
+ if (m == name) continue out;
+ }
+ return m;
+ }
+});
+
+AST_Function.DEFMETHOD("next_mangled", function(options, def){
+ // #179, #326
+ // in Safari strict mode, something like (function x(x){...}) is a syntax error;
+ // a function expression's argument cannot shadow the function expression's name
+
+ var tricky_def = def.orig[0] instanceof AST_SymbolFunarg && this.name && this.name.definition();
+ while (true) {
+ var name = AST_Lambda.prototype.next_mangled.call(this, options, def);
+ if (!(tricky_def && tricky_def.mangled_name == name))
+ return name;
+ }
+});
+
+AST_Scope.DEFMETHOD("references", function(sym){
+ if (sym instanceof AST_Symbol) sym = sym.definition();
+ return this.enclosed.indexOf(sym) < 0 ? null : sym;
+});
+
+AST_Symbol.DEFMETHOD("unmangleable", function(options){
+ return this.definition().unmangleable(options);
+});
+
+// property accessors are not mangleable
+AST_SymbolAccessor.DEFMETHOD("unmangleable", function(){
+ return true;
+});
+
+// labels are always mangleable
+AST_Label.DEFMETHOD("unmangleable", function(){
+ return false;
+});
+
+AST_Symbol.DEFMETHOD("unreferenced", function(){
+ return this.definition().references.length == 0
+ && !(this.scope.uses_eval || this.scope.uses_with);
+});
+
+AST_Symbol.DEFMETHOD("undeclared", function(){
+ return this.definition().undeclared;
+});
+
+AST_LabelRef.DEFMETHOD("undeclared", function(){
+ return false;
+});
+
+AST_Label.DEFMETHOD("undeclared", function(){
+ return false;
+});
+
+AST_Symbol.DEFMETHOD("definition", function(){
+ return this.thedef;
+});
+
+AST_Symbol.DEFMETHOD("global", function(){
+ return this.definition().global;
+});
+
+AST_Toplevel.DEFMETHOD("_default_mangler_options", function(options){
+ return defaults(options, {
+ except : [],
+ eval : false,
+ sort : false,
+ toplevel : false,
+ screw_ie8 : false
+ });
+});
+
+AST_Toplevel.DEFMETHOD("mangle_names", function(options){
+ options = this._default_mangler_options(options);
+ // We only need to mangle declaration nodes. Special logic wired
+ // into the code generator will display the mangled name if it's
+ // present (and for AST_SymbolRef-s it'll use the mangled name of
+ // the AST_SymbolDeclaration that it points to).
+ var lname = -1;
+ var to_mangle = [];
+ var tw = new TreeWalker(function(node, descend){
+ if (node instanceof AST_LabeledStatement) {
+ // lname is incremented when we get to the AST_Label
+ var save_nesting = lname;
+ descend();
+ lname = save_nesting;
+ return true; // don't descend again in TreeWalker
+ }
+ if (node instanceof AST_Scope) {
+ var p = tw.parent(), a = [];
+ node.variables.each(function(symbol){
+ if (options.except.indexOf(symbol.name) < 0) {
+ a.push(symbol);
+ }
+ });
+ if (options.sort) a.sort(function(a, b){
+ return b.references.length - a.references.length;
+ });
+ to_mangle.push.apply(to_mangle, a);
+ return;
+ }
+ if (node instanceof AST_Label) {
+ var name;
+ do name = base54(++lname); while (!is_identifier(name));
+ node.mangled_name = name;
+ return true;
+ }
+ });
+ this.walk(tw);
+ to_mangle.forEach(function(def){ def.mangle(options) });
+});
+
+AST_Toplevel.DEFMETHOD("compute_char_frequency", function(options){
+ options = this._default_mangler_options(options);
+ var tw = new TreeWalker(function(node){
+ if (node instanceof AST_Constant)
+ base54.consider(node.print_to_string());
+ else if (node instanceof AST_Return)
+ base54.consider("return");
+ else if (node instanceof AST_Throw)
+ base54.consider("throw");
+ else if (node instanceof AST_Continue)
+ base54.consider("continue");
+ else if (node instanceof AST_Break)
+ base54.consider("break");
+ else if (node instanceof AST_Debugger)
+ base54.consider("debugger");
+ else if (node instanceof AST_Directive)
+ base54.consider(node.value);
+ else if (node instanceof AST_While)
+ base54.consider("while");
+ else if (node instanceof AST_Do)
+ base54.consider("do while");
+ else if (node instanceof AST_If) {
+ base54.consider("if");
+ if (node.alternative) base54.consider("else");
+ }
+ else if (node instanceof AST_Var)
+ base54.consider("var");
+ else if (node instanceof AST_Const)
+ base54.consider("const");
+ else if (node instanceof AST_Lambda)
+ base54.consider("function");
+ else if (node instanceof AST_For)
+ base54.consider("for");
+ else if (node instanceof AST_ForIn)
+ base54.consider("for in");
+ else if (node instanceof AST_Switch)
+ base54.consider("switch");
+ else if (node instanceof AST_Case)
+ base54.consider("case");
+ else if (node instanceof AST_Default)
+ base54.consider("default");
+ else if (node instanceof AST_With)
+ base54.consider("with");
+ else if (node instanceof AST_ObjectSetter)
+ base54.consider("set" + node.key);
+ else if (node instanceof AST_ObjectGetter)
+ base54.consider("get" + node.key);
+ else if (node instanceof AST_ObjectKeyVal)
+ base54.consider(node.key);
+ else if (node instanceof AST_New)
+ base54.consider("new");
+ else if (node instanceof AST_This)
+ base54.consider("this");
+ else if (node instanceof AST_Try)
+ base54.consider("try");
+ else if (node instanceof AST_Catch)
+ base54.consider("catch");
+ else if (node instanceof AST_Finally)
+ base54.consider("finally");
+ else if (node instanceof AST_Symbol && node.unmangleable(options))
+ base54.consider(node.name);
+ else if (node instanceof AST_Unary || node instanceof AST_Binary)
+ base54.consider(node.operator);
+ else if (node instanceof AST_Dot)
+ base54.consider(node.property);
+ });
+ this.walk(tw);
+ base54.sort();
+});
+
+var base54 = (function() {
+ var string = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ$_0123456789";
+ var chars, frequency;
+ function reset() {
+ frequency = Object.create(null);
+ chars = string.split("").map(function(ch){ return ch.charCodeAt(0) });
+ chars.forEach(function(ch){ frequency[ch] = 0 });
+ }
+ base54.consider = function(str){
+ for (var i = str.length; --i >= 0;) {
+ var code = str.charCodeAt(i);
+ if (code in frequency) ++frequency[code];
+ }
+ };
+ base54.sort = function() {
+ chars = mergeSort(chars, function(a, b){
+ if (is_digit(a) && !is_digit(b)) return 1;
+ if (is_digit(b) && !is_digit(a)) return -1;
+ return frequency[b] - frequency[a];
+ });
+ };
+ base54.reset = reset;
+ reset();
+ base54.get = function(){ return chars };
+ base54.freq = function(){ return frequency };
+ function base54(num) {
+ var ret = "", base = 54;
+ do {
+ ret += String.fromCharCode(chars[num % base]);
+ num = Math.floor(num / base);
+ base = 64;
+ } while (num > 0);
+ return ret;
+ };
+ return base54;
+})();
+
+AST_Toplevel.DEFMETHOD("scope_warnings", function(options){
+ options = defaults(options, {
+ undeclared : false, // this makes a lot of noise
+ unreferenced : true,
+ assign_to_global : true,
+ func_arguments : true,
+ nested_defuns : true,
+ eval : true
+ });
+ var tw = new TreeWalker(function(node){
+ if (options.undeclared
+ && node instanceof AST_SymbolRef
+ && node.undeclared())
+ {
+ // XXX: this also warns about JS standard names,
+ // i.e. Object, Array, parseInt etc. Should add a list of
+ // exceptions.
+ AST_Node.warn("Undeclared symbol: {name} [{file}:{line},{col}]", {
+ name: node.name,
+ file: node.start.file,
+ line: node.start.line,
+ col: node.start.col
+ });
+ }
+ if (options.assign_to_global)
+ {
+ var sym = null;
+ if (node instanceof AST_Assign && node.left instanceof AST_SymbolRef)
+ sym = node.left;
+ else if (node instanceof AST_ForIn && node.init instanceof AST_SymbolRef)
+ sym = node.init;
+ if (sym
+ && (sym.undeclared()
+ || (sym.global() && sym.scope !== sym.definition().scope))) {
+ AST_Node.warn("{msg}: {name} [{file}:{line},{col}]", {
+ msg: sym.undeclared() ? "Accidental global?" : "Assignment to global",
+ name: sym.name,
+ file: sym.start.file,
+ line: sym.start.line,
+ col: sym.start.col
+ });
+ }
+ }
+ if (options.eval
+ && node instanceof AST_SymbolRef
+ && node.undeclared()
+ && node.name == "eval") {
+ AST_Node.warn("Eval is used [{file}:{line},{col}]", node.start);
+ }
+ if (options.unreferenced
+ && (node instanceof AST_SymbolDeclaration || node instanceof AST_Label)
+ && node.unreferenced()) {
+ AST_Node.warn("{type} {name} is declared but not referenced [{file}:{line},{col}]", {
+ type: node instanceof AST_Label ? "Label" : "Symbol",
+ name: node.name,
+ file: node.start.file,
+ line: node.start.line,
+ col: node.start.col
+ });
+ }
+ if (options.func_arguments
+ && node instanceof AST_Lambda
+ && node.uses_arguments) {
+ AST_Node.warn("arguments used in function {name} [{file}:{line},{col}]", {
+ name: node.name ? node.name.name : "anonymous",
+ file: node.start.file,
+ line: node.start.line,
+ col: node.start.col
+ });
+ }
+ if (options.nested_defuns
+ && node instanceof AST_Defun
+ && !(tw.parent() instanceof AST_Scope)) {
+ AST_Node.warn("Function {name} declared in nested statement \"{type}\" [{file}:{line},{col}]", {
+ name: node.name.name,
+ type: tw.parent().TYPE,
+ file: node.start.file,
+ line: node.start.line,
+ col: node.start.col
+ });
+ }
+ });
+ this.walk(tw);
+});
+
+/***********************************************************************
+
+ A JavaScript tokenizer / parser / beautifier / compressor.
+ https://github.com/mishoo/UglifyJS2
+
+ -------------------------------- (C) ---------------------------------
+
+ Author: Mihai Bazon
+ <mihai.bazon@gmail.com>
+ http://mihai.bazon.net/blog
+
+ Distributed under the BSD license:
+
+ Copyright 2012 (c) Mihai Bazon <mihai.bazon@gmail.com>
+
+ Redistribution and use in source and binary forms, with or without
+ modification, are permitted provided that the following conditions
+ are met:
+
+ * Redistributions of source code must retain the above
+ copyright notice, this list of conditions and the following
+ disclaimer.
+
+ * Redistributions in binary form must reproduce the above
+ copyright notice, this list of conditions and the following
+ disclaimer in the documentation and/or other materials
+ provided with the distribution.
+
+ THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDER “AS IS” AND ANY
+ EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
+ PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE
+ LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY,
+ OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
+ PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
+ PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+ THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR
+ TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF
+ THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ SUCH DAMAGE.
+
+ ***********************************************************************/
+
+"use strict";
+
+function OutputStream(options) {
+
+ options = defaults(options, {
+ indent_start : 0,
+ indent_level : 4,
+ quote_keys : false,
+ space_colon : true,
+ ascii_only : false,
+ unescape_regexps : false,
+ inline_script : false,
+ width : 80,
+ max_line_len : 32000,
+ beautify : false,
+ source_map : null,
+ bracketize : false,
+ semicolons : true,
+ comments : false,
+ preserve_line : false,
+ screw_ie8 : false,
+ preamble : null,
+ }, true);
+
+ var indentation = 0;
+ var current_col = 0;
+ var current_line = 1;
+ var current_pos = 0;
+ var OUTPUT = "";
+
+ function to_ascii(str, identifier) {
+ return str.replace(/[\u0080-\uffff]/g, function(ch) {
+ var code = ch.charCodeAt(0).toString(16);
+ if (code.length <= 2 && !identifier) {
+ while (code.length < 2) code = "0" + code;
+ return "\\x" + code;
+ } else {
+ while (code.length < 4) code = "0" + code;
+ return "\\u" + code;
+ }
+ });
+ };
+
+ function make_string(str) {
+ var dq = 0, sq = 0;
+ str = str.replace(/[\\\b\f\n\r\t\x22\x27\u2028\u2029\0]/g, function(s){
+ switch (s) {
+ case "\\": return "\\\\";
+ case "\b": return "\\b";
+ case "\f": return "\\f";
+ case "\n": return "\\n";
+ case "\r": return "\\r";
+ case "\u2028": return "\\u2028";
+ case "\u2029": return "\\u2029";
+ case '"': ++dq; return '"';
+ case "'": ++sq; return "'";
+ case "\0": return "\\x00";
+ }
+ return s;
+ });
+ if (options.ascii_only) str = to_ascii(str);
+ if (dq > sq) return "'" + str.replace(/\x27/g, "\\'") + "'";
+ else return '"' + str.replace(/\x22/g, '\\"') + '"';
+ };
+
+ function encode_string(str) {
+ var ret = make_string(str);
+ if (options.inline_script)
+ ret = ret.replace(/<\x2fscript([>\/\t\n\f\r ])/gi, "<\\/script$1");
+ return ret;
+ };
+
+ function make_name(name) {
+ name = name.toString();
+ if (options.ascii_only)
+ name = to_ascii(name, true);
+ return name;
+ };
+
+ function make_indent(back) {
+ return repeat_string(" ", options.indent_start + indentation - back * options.indent_level);
+ };
+
+ /* -----[ beautification/minification ]----- */
+
+ var might_need_space = false;
+ var might_need_semicolon = false;
+ var last = null;
+
+ function last_char() {
+ return last.charAt(last.length - 1);
+ };
+
+ function maybe_newline() {
+ if (options.max_line_len && current_col > options.max_line_len)
+ print("\n");
+ };
+
+ var requireSemicolonChars = makePredicate("( [ + * / - , .");
+
+ function print(str) {
+ str = String(str);
+ var ch = str.charAt(0);
+ if (might_need_semicolon) {
+ if ((!ch || ";}".indexOf(ch) < 0) && !/[;]$/.test(last)) {
+ if (options.semicolons || requireSemicolonChars(ch)) {
+ OUTPUT += ";";
+ current_col++;
+ current_pos++;
+ } else {
+ OUTPUT += "\n";
+ current_pos++;
+ current_line++;
+ current_col = 0;
+ }
+ if (!options.beautify)
+ might_need_space = false;
+ }
+ might_need_semicolon = false;
+ maybe_newline();
+ }
+
+ if (!options.beautify && options.preserve_line && stack[stack.length - 1]) {
+ var target_line = stack[stack.length - 1].start.line;
+ while (current_line < target_line) {
+ OUTPUT += "\n";
+ current_pos++;
+ current_line++;
+ current_col = 0;
+ might_need_space = false;
+ }
+ }
+
+ if (might_need_space) {
+ var prev = last_char();
+ if ((is_identifier_char(prev)
+ && (is_identifier_char(ch) || ch == "\\"))
+ || (/^[\+\-\/]$/.test(ch) && ch == prev))
+ {
+ OUTPUT += " ";
+ current_col++;
+ current_pos++;
+ }
+ might_need_space = false;
+ }
+ var a = str.split(/\r?\n/), n = a.length - 1;
+ current_line += n;
+ if (n == 0) {
+ current_col += a[n].length;
+ } else {
+ current_col = a[n].length;
+ }
+ current_pos += str.length;
+ last = str;
+ OUTPUT += str;
+ };
+
+ var space = options.beautify ? function() {
+ print(" ");
+ } : function() {
+ might_need_space = true;
+ };
+
+ var indent = options.beautify ? function(half) {
+ if (options.beautify) {
+ print(make_indent(half ? 0.5 : 0));
+ }
+ } : noop;
+
+ var with_indent = options.beautify ? function(col, cont) {
+ if (col === true) col = next_indent();
+ var save_indentation = indentation;
+ indentation = col;
+ var ret = cont();
+ indentation = save_indentation;
+ return ret;
+ } : function(col, cont) { return cont() };
+
+ var newline = options.beautify ? function() {
+ print("\n");
+ } : noop;
+
+ var semicolon = options.beautify ? function() {
+ print(";");
+ } : function() {
+ might_need_semicolon = true;
+ };
+
+ function force_semicolon() {
+ might_need_semicolon = false;
+ print(";");
+ };
+
+ function next_indent() {
+ return indentation + options.indent_level;
+ };
+
+ function with_block(cont) {
+ var ret;
+ print("{");
+ newline();
+ with_indent(next_indent(), function(){
+ ret = cont();
+ });
+ indent();
+ print("}");
+ return ret;
+ };
+
+ function with_parens(cont) {
+ print("(");
+ //XXX: still nice to have that for argument lists
+ //var ret = with_indent(current_col, cont);
+ var ret = cont();
+ print(")");
+ return ret;
+ };
+
+ function with_square(cont) {
+ print("[");
+ //var ret = with_indent(current_col, cont);
+ var ret = cont();
+ print("]");
+ return ret;
+ };
+
+ function comma() {
+ print(",");
+ space();
+ };
+
+ function colon() {
+ print(":");
+ if (options.space_colon) space();
+ };
+
+ var add_mapping = options.source_map ? function(token, name) {
+ try {
+ if (token) options.source_map.add(
+ token.file || "?",
+ current_line, current_col,
+ token.line, token.col,
+ (!name && token.type == "name") ? token.value : name
+ );
+ } catch(ex) {
+ AST_Node.warn("Couldn't figure out mapping for {file}:{line},{col} → {cline},{ccol} [{name}]", {
+ file: token.file,
+ line: token.line,
+ col: token.col,
+ cline: current_line,
+ ccol: current_col,
+ name: name || ""
+ })
+ }
+ } : noop;
+
+ function get() {
+ return OUTPUT;
+ };
+
+ if (options.preamble) {
+ print(options.preamble.replace(/\r\n?|[\n\u2028\u2029]|\s*$/g, "\n"));
+ }
+
+ var stack = [];
+ return {
+ get : get,
+ toString : get,
+ indent : indent,
+ indentation : function() { return indentation },
+ current_width : function() { return current_col - indentation },
+ should_break : function() { return options.width && this.current_width() >= options.width },
+ newline : newline,
+ print : print,
+ space : space,
+ comma : comma,
+ colon : colon,
+ last : function() { return last },
+ semicolon : semicolon,
+ force_semicolon : force_semicolon,
+ to_ascii : to_ascii,
+ print_name : function(name) { print(make_name(name)) },
+ print_string : function(str) { print(encode_string(str)) },
+ next_indent : next_indent,
+ with_indent : with_indent,
+ with_block : with_block,
+ with_parens : with_parens,
+ with_square : with_square,
+ add_mapping : add_mapping,
+ option : function(opt) { return options[opt] },
+ line : function() { return current_line },
+ col : function() { return current_col },
+ pos : function() { return current_pos },
+ push_node : function(node) { stack.push(node) },
+ pop_node : function() { return stack.pop() },
+ stack : function() { return stack },
+ parent : function(n) {
+ return stack[stack.length - 2 - (n || 0)];
+ }
+ };
+
+};
+
+/* -----[ code generators ]----- */
+
+(function(){
+
+ /* -----[ utils ]----- */
+
+ function DEFPRINT(nodetype, generator) {
+ nodetype.DEFMETHOD("_codegen", generator);
+ };
+
+ AST_Node.DEFMETHOD("print", function(stream, force_parens){
+ var self = this, generator = self._codegen;
+ function doit() {
+ self.add_comments(stream);
+ self.add_source_map(stream);
+ generator(self, stream);
+ }
+ stream.push_node(self);
+ if (force_parens || self.needs_parens(stream)) {
+ stream.with_parens(doit);
+ } else {
+ doit();
+ }
+ stream.pop_node();
+ });
+
+ AST_Node.DEFMETHOD("print_to_string", function(options){
+ var s = OutputStream(options);
+ this.print(s);
+ return s.get();
+ });
+
+ /* -----[ comments ]----- */
+
+ AST_Node.DEFMETHOD("add_comments", function(output){
+ var c = output.option("comments"), self = this;
+ if (c) {
+ var start = self.start;
+ if (start && !start._comments_dumped) {
+ start._comments_dumped = true;
+ var comments = start.comments_before || [];
+
+ // XXX: ugly fix for https://github.com/mishoo/UglifyJS2/issues/112
+ // and https://github.com/mishoo/UglifyJS2/issues/372
+ if (self instanceof AST_Exit && self.value) {
+ self.value.walk(new TreeWalker(function(node){
+ if (node.start && node.start.comments_before) {
+ comments = comments.concat(node.start.comments_before);
+ node.start.comments_before = [];
+ }
+ if (node instanceof AST_Function ||
+ node instanceof AST_Array ||
+ node instanceof AST_Object)
+ {
+ return true; // don't go inside.
+ }
+ }));
+ }
+
+ if (c.test) {
+ comments = comments.filter(function(comment){
+ return c.test(comment.value);
+ });
+ } else if (typeof c == "function") {
+ comments = comments.filter(function(comment){
+ return c(self, comment);
+ });
+ }
+ comments.forEach(function(c){
+ if (/comment[134]/.test(c.type)) {
+ output.print("//" + c.value + "\n");
+ output.indent();
+ }
+ else if (c.type == "comment2") {
+ output.print("/*" + c.value + "*/");
+ if (start.nlb) {
+ output.print("\n");
+ output.indent();
+ } else {
+ output.space();
+ }
+ }
+ });
+ }
+ }
+ });
+
+ /* -----[ PARENTHESES ]----- */
+
+ function PARENS(nodetype, func) {
+ nodetype.DEFMETHOD("needs_parens", func);
+ };
+
+ PARENS(AST_Node, function(){
+ return false;
+ });
+
+ // a function expression needs parens around it when it's provably
+ // the first token to appear in a statement.
+ PARENS(AST_Function, function(output){
+ return first_in_statement(output);
+ });
+
+ // same goes for an object literal, because otherwise it would be
+ // interpreted as a block of code.
+ PARENS(AST_Object, function(output){
+ return first_in_statement(output);
+ });
+
+ PARENS(AST_Unary, function(output){
+ var p = output.parent();
+ return p instanceof AST_PropAccess && p.expression === this;
+ });
+
+ PARENS(AST_Seq, function(output){
+ var p = output.parent();
+ return p instanceof AST_Call // (foo, bar)() or foo(1, (2, 3), 4)
+ || p instanceof AST_Unary // !(foo, bar, baz)
+ || p instanceof AST_Binary // 1 + (2, 3) + 4 ==> 8
+ || p instanceof AST_VarDef // var a = (1, 2), b = a + a; ==> b == 4
+ || p instanceof AST_PropAccess // (1, {foo:2}).foo or (1, {foo:2})["foo"] ==> 2
+ || p instanceof AST_Array // [ 1, (2, 3), 4 ] ==> [ 1, 3, 4 ]
+ || p instanceof AST_ObjectProperty // { foo: (1, 2) }.foo ==> 2
+ || p instanceof AST_Conditional /* (false, true) ? (a = 10, b = 20) : (c = 30)
+ * ==> 20 (side effect, set a := 10 and b := 20) */
+ ;
+ });
+
+ PARENS(AST_Binary, function(output){
+ var p = output.parent();
+ // (foo && bar)()
+ if (p instanceof AST_Call && p.expression === this)
+ return true;
+ // typeof (foo && bar)
+ if (p instanceof AST_Unary)
+ return true;
+ // (foo && bar)["prop"], (foo && bar).prop
+ if (p instanceof AST_PropAccess && p.expression === this)
+ return true;
+ // this deals with precedence: 3 * (2 + 1)
+ if (p instanceof AST_Binary) {
+ var po = p.operator, pp = PRECEDENCE[po];
+ var so = this.operator, sp = PRECEDENCE[so];
+ if (pp > sp
+ || (pp == sp
+ && this === p.right)) {
+ return true;
+ }
+ }
+ });
+
+ PARENS(AST_PropAccess, function(output){
+ var p = output.parent();
+ if (p instanceof AST_New && p.expression === this) {
+ // i.e. new (foo.bar().baz)
+ //
+ // if there's one call into this subtree, then we need
+ // parens around it too, otherwise the call will be
+ // interpreted as passing the arguments to the upper New
+ // expression.
+ try {
+ this.walk(new TreeWalker(function(node){
+ if (node instanceof AST_Call) throw p;
+ }));
+ } catch(ex) {
+ if (ex !== p) throw ex;
+ return true;
+ }
+ }
+ });
+
+ PARENS(AST_Call, function(output){
+ var p = output.parent(), p1;
+ if (p instanceof AST_New && p.expression === this)
+ return true;
+
+ // workaround for Safari bug.
+ // https://bugs.webkit.org/show_bug.cgi?id=123506
+ return this.expression instanceof AST_Function
+ && p instanceof AST_PropAccess
+ && p.expression === this
+ && (p1 = output.parent(1)) instanceof AST_Assign
+ && p1.left === p;
+ });
+
+ PARENS(AST_New, function(output){
+ var p = output.parent();
+ if (no_constructor_parens(this, output)
+ && (p instanceof AST_PropAccess // (new Date).getTime(), (new Date)["getTime"]()
+ || p instanceof AST_Call && p.expression === this)) // (new foo)(bar)
+ return true;
+ });
+
+ PARENS(AST_Number, function(output){
+ var p = output.parent();
+ if (this.getValue() < 0 && p instanceof AST_PropAccess && p.expression === this)
+ return true;
+ });
+
+ PARENS(AST_NaN, function(output){
+ var p = output.parent();
+ if (p instanceof AST_PropAccess && p.expression === this)
+ return true;
+ });
+
+ function assign_and_conditional_paren_rules(output) {
+ var p = output.parent();
+ // !(a = false) → true
+ if (p instanceof AST_Unary)
+ return true;
+ // 1 + (a = 2) + 3 → 6, side effect setting a = 2
+ if (p instanceof AST_Binary && !(p instanceof AST_Assign))
+ return true;
+ // (a = func)() —or— new (a = Object)()
+ if (p instanceof AST_Call && p.expression === this)
+ return true;
+ // (a = foo) ? bar : baz
+ if (p instanceof AST_Conditional && p.condition === this)
+ return true;
+ // (a = foo)["prop"] —or— (a = foo).prop
+ if (p instanceof AST_PropAccess && p.expression === this)
+ return true;
+ };
+
+ PARENS(AST_Assign, assign_and_conditional_paren_rules);
+ PARENS(AST_Conditional, assign_and_conditional_paren_rules);
+
+ /* -----[ PRINTERS ]----- */
+
+ DEFPRINT(AST_Directive, function(self, output){
+ output.print_string(self.value);
+ output.semicolon();
+ });
+ DEFPRINT(AST_Debugger, function(self, output){
+ output.print("debugger");
+ output.semicolon();
+ });
+
+ /* -----[ statements ]----- */
+
+ function display_body(body, is_toplevel, output) {
+ var last = body.length - 1;
+ body.forEach(function(stmt, i){
+ if (!(stmt instanceof AST_EmptyStatement)) {
+ output.indent();
+ stmt.print(output);
+ if (!(i == last && is_toplevel)) {
+ output.newline();
+ if (is_toplevel) output.newline();
+ }
+ }
+ });
+ };
+
+ AST_StatementWithBody.DEFMETHOD("_do_print_body", function(output){
+ force_statement(this.body, output);
+ });
+
+ DEFPRINT(AST_Statement, function(self, output){
+ self.body.print(output);
+ output.semicolon();
+ });
+ DEFPRINT(AST_Toplevel, function(self, output){
+ display_body(self.body, true, output);
+ output.print("");
+ });
+ DEFPRINT(AST_LabeledStatement, function(self, output){
+ self.label.print(output);
+ output.colon();
+ self.body.print(output);
+ });
+ DEFPRINT(AST_SimpleStatement, function(self, output){
+ self.body.print(output);
+ output.semicolon();
+ });
+ function print_bracketed(body, output) {
+ if (body.length > 0) output.with_block(function(){
+ display_body(body, false, output);
+ });
+ else output.print("{}");
+ };
+ DEFPRINT(AST_BlockStatement, function(self, output){
+ print_bracketed(self.body, output);
+ });
+ DEFPRINT(AST_EmptyStatement, function(self, output){
+ output.semicolon();
+ });
+ DEFPRINT(AST_Do, function(self, output){
+ output.print("do");
+ output.space();
+ self._do_print_body(output);
+ output.space();
+ output.print("while");
+ output.space();
+ output.with_parens(function(){
+ self.condition.print(output);
+ });
+ output.semicolon();
+ });
+ DEFPRINT(AST_While, function(self, output){
+ output.print("while");
+ output.space();
+ output.with_parens(function(){
+ self.condition.print(output);
+ });
+ output.space();
+ self._do_print_body(output);
+ });
+ DEFPRINT(AST_For, function(self, output){
+ output.print("for");
+ output.space();
+ output.with_parens(function(){
+ if (self.init) {
+ if (self.init instanceof AST_Definitions) {
+ self.init.print(output);
+ } else {
+ parenthesize_for_noin(self.init, output, true);
+ }
+ output.print(";");
+ output.space();
+ } else {
+ output.print(";");
+ }
+ if (self.condition) {
+ self.condition.print(output);
+ output.print(";");
+ output.space();
+ } else {
+ output.print(";");
+ }
+ if (self.step) {
+ self.step.print(output);
+ }
+ });
+ output.space();
+ self._do_print_body(output);
+ });
+ DEFPRINT(AST_ForIn, function(self, output){
+ output.print("for");
+ output.space();
+ output.with_parens(function(){
+ self.init.print(output);
+ output.space();
+ output.print("in");
+ output.space();
+ self.object.print(output);
+ });
+ output.space();
+ self._do_print_body(output);
+ });
+ DEFPRINT(AST_With, function(self, output){
+ output.print("with");
+ output.space();
+ output.with_parens(function(){
+ self.expression.print(output);
+ });
+ output.space();
+ self._do_print_body(output);
+ });
+
+ /* -----[ functions ]----- */
+ AST_Lambda.DEFMETHOD("_do_print", function(output, nokeyword){
+ var self = this;
+ if (!nokeyword) {
+ output.print("function");
+ }
+ if (self.name) {
+ output.space();
+ self.name.print(output);
+ }
+ output.with_parens(function(){
+ self.argnames.forEach(function(arg, i){
+ if (i) output.comma();
+ arg.print(output);
+ });
+ });
+ output.space();
+ print_bracketed(self.body, output);
+ });
+ DEFPRINT(AST_Lambda, function(self, output){
+ self._do_print(output);
+ });
+
+ /* -----[ exits ]----- */
+ AST_Exit.DEFMETHOD("_do_print", function(output, kind){
+ output.print(kind);
+ if (this.value) {
+ output.space();
+ this.value.print(output);
+ }
+ output.semicolon();
+ });
+ DEFPRINT(AST_Return, function(self, output){
+ self._do_print(output, "return");
+ });
+ DEFPRINT(AST_Throw, function(self, output){
+ self._do_print(output, "throw");
+ });
+
+ /* -----[ loop control ]----- */
+ AST_LoopControl.DEFMETHOD("_do_print", function(output, kind){
+ output.print(kind);
+ if (this.label) {
+ output.space();
+ this.label.print(output);
+ }
+ output.semicolon();
+ });
+ DEFPRINT(AST_Break, function(self, output){
+ self._do_print(output, "break");
+ });
+ DEFPRINT(AST_Continue, function(self, output){
+ self._do_print(output, "continue");
+ });
+
+ /* -----[ if ]----- */
+ function make_then(self, output) {
+ if (output.option("bracketize")) {
+ make_block(self.body, output);
+ return;
+ }
+ // The squeezer replaces "block"-s that contain only a single
+ // statement with the statement itself; technically, the AST
+ // is correct, but this can create problems when we output an
+ // IF having an ELSE clause where the THEN clause ends in an
+ // IF *without* an ELSE block (then the outer ELSE would refer
+ // to the inner IF). This function checks for this case and
+ // adds the block brackets if needed.
+ if (!self.body)
+ return output.force_semicolon();
+ if (self.body instanceof AST_Do
+ && !output.option("screw_ie8")) {
+ // https://github.com/mishoo/UglifyJS/issues/#issue/57 IE
+ // croaks with "syntax error" on code like this: if (foo)
+ // do ... while(cond); else ... we need block brackets
+ // around do/while
+ make_block(self.body, output);
+ return;
+ }
+ var b = self.body;
+ while (true) {
+ if (b instanceof AST_If) {
+ if (!b.alternative) {
+ make_block(self.body, output);
+ return;
+ }
+ b = b.alternative;
+ }
+ else if (b instanceof AST_StatementWithBody) {
+ b = b.body;
+ }
+ else break;
+ }
+ force_statement(self.body, output);
+ };
+ DEFPRINT(AST_If, function(self, output){
+ output.print("if");
+ output.space();
+ output.with_parens(function(){
+ self.condition.print(output);
+ });
+ output.space();
+ if (self.alternative) {
+ make_then(self, output);
+ output.space();
+ output.print("else");
+ output.space();
+ force_statement(self.alternative, output);
+ } else {
+ self._do_print_body(output);
+ }
+ });
+
+ /* -----[ switch ]----- */
+ DEFPRINT(AST_Switch, function(self, output){
+ output.print("switch");
+ output.space();
+ output.with_parens(function(){
+ self.expression.print(output);
+ });
+ output.space();
+ if (self.body.length > 0) output.with_block(function(){
+ self.body.forEach(function(stmt, i){
+ if (i) output.newline();
+ output.indent(true);
+ stmt.print(output);
+ });
+ });
+ else output.print("{}");
+ });
+ AST_SwitchBranch.DEFMETHOD("_do_print_body", function(output){
+ if (this.body.length > 0) {
+ output.newline();
+ this.body.forEach(function(stmt){
+ output.indent();
+ stmt.print(output);
+ output.newline();
+ });
+ }
+ });
+ DEFPRINT(AST_Default, function(self, output){
+ output.print("default:");
+ self._do_print_body(output);
+ });
+ DEFPRINT(AST_Case, function(self, output){
+ output.print("case");
+ output.space();
+ self.expression.print(output);
+ output.print(":");
+ self._do_print_body(output);
+ });
+
+ /* -----[ exceptions ]----- */
+ DEFPRINT(AST_Try, function(self, output){
+ output.print("try");
+ output.space();
+ print_bracketed(self.body, output);
+ if (self.bcatch) {
+ output.space();
+ self.bcatch.print(output);
+ }
+ if (self.bfinally) {
+ output.space();
+ self.bfinally.print(output);
+ }
+ });
+ DEFPRINT(AST_Catch, function(self, output){
+ output.print("catch");
+ output.space();
+ output.with_parens(function(){
+ self.argname.print(output);
+ });
+ output.space();
+ print_bracketed(self.body, output);
+ });
+ DEFPRINT(AST_Finally, function(self, output){
+ output.print("finally");
+ output.space();
+ print_bracketed(self.body, output);
+ });
+
+ /* -----[ var/const ]----- */
+ AST_Definitions.DEFMETHOD("_do_print", function(output, kind){
+ output.print(kind);
+ output.space();
+ this.definitions.forEach(function(def, i){
+ if (i) output.comma();
+ def.print(output);
+ });
+ var p = output.parent();
+ var in_for = p instanceof AST_For || p instanceof AST_ForIn;
+ var avoid_semicolon = in_for && p.init === this;
+ if (!avoid_semicolon)
+ output.semicolon();
+ });
+ DEFPRINT(AST_Var, function(self, output){
+ self._do_print(output, "var");
+ });
+ DEFPRINT(AST_Const, function(self, output){
+ self._do_print(output, "const");
+ });
+
+ function parenthesize_for_noin(node, output, noin) {
+ if (!noin) node.print(output);
+ else try {
+ // need to take some precautions here:
+ // https://github.com/mishoo/UglifyJS2/issues/60
+ node.walk(new TreeWalker(function(node){
+ if (node instanceof AST_Binary && node.operator == "in")
+ throw output;
+ }));
+ node.print(output);
+ } catch(ex) {
+ if (ex !== output) throw ex;
+ node.print(output, true);
+ }
+ };
+
+ DEFPRINT(AST_VarDef, function(self, output){
+ self.name.print(output);
+ if (self.value) {
+ output.space();
+ output.print("=");
+ output.space();
+ var p = output.parent(1);
+ var noin = p instanceof AST_For || p instanceof AST_ForIn;
+ parenthesize_for_noin(self.value, output, noin);
+ }
+ });
+
+ /* -----[ other expressions ]----- */
+ DEFPRINT(AST_Call, function(self, output){
+ self.expression.print(output);
+ if (self instanceof AST_New && no_constructor_parens(self, output))
+ return;
+ output.with_parens(function(){
+ self.args.forEach(function(expr, i){
+ if (i) output.comma();
+ expr.print(output);
+ });
+ });
+ });
+ DEFPRINT(AST_New, function(self, output){
+ output.print("new");
+ output.space();
+ AST_Call.prototype._codegen(self, output);
+ });
+
+ AST_Seq.DEFMETHOD("_do_print", function(output){
+ this.car.print(output);
+ if (this.cdr) {
+ output.comma();
+ if (output.should_break()) {
+ output.newline();
+ output.indent();
+ }
+ this.cdr.print(output);
+ }
+ });
+ DEFPRINT(AST_Seq, function(self, output){
+ self._do_print(output);
+ // var p = output.parent();
+ // if (p instanceof AST_Statement) {
+ // output.with_indent(output.next_indent(), function(){
+ // self._do_print(output);
+ // });
+ // } else {
+ // self._do_print(output);
+ // }
+ });
+ DEFPRINT(AST_Dot, function(self, output){
+ var expr = self.expression;
+ expr.print(output);
+ if (expr instanceof AST_Number && expr.getValue() >= 0) {
+ if (!/[xa-f.]/i.test(output.last())) {
+ output.print(".");
+ }
+ }
+ output.print(".");
+ // the name after dot would be mapped about here.
+ output.add_mapping(self.end);
+ output.print_name(self.property);
+ });
+ DEFPRINT(AST_Sub, function(self, output){
+ self.expression.print(output);
+ output.print("[");
+ self.property.print(output);
+ output.print("]");
+ });
+ DEFPRINT(AST_UnaryPrefix, function(self, output){
+ var op = self.operator;
+ output.print(op);
+ if (/^[a-z]/i.test(op))
+ output.space();
+ self.expression.print(output);
+ });
+ DEFPRINT(AST_UnaryPostfix, function(self, output){
+ self.expression.print(output);
+ output.print(self.operator);
+ });
+ DEFPRINT(AST_Binary, function(self, output){
+ self.left.print(output);
+ output.space();
+ output.print(self.operator);
+ if (self.operator == "<"
+ && self.right instanceof AST_UnaryPrefix
+ && self.right.operator == "!"
+ && self.right.expression instanceof AST_UnaryPrefix
+ && self.right.expression.operator == "--") {
+ // space is mandatory to avoid outputting <!--
+ // http://javascript.spec.whatwg.org/#comment-syntax
+ output.print(" ");
+ } else {
+ // the space is optional depending on "beautify"
+ output.space();
+ }
+ self.right.print(output);
+ });
+ DEFPRINT(AST_Conditional, function(self, output){
+ self.condition.print(output);
+ output.space();
+ output.print("?");
+ output.space();
+ self.consequent.print(output);
+ output.space();
+ output.colon();
+ self.alternative.print(output);
+ });
+
+ /* -----[ literals ]----- */
+ DEFPRINT(AST_Array, function(self, output){
+ output.with_square(function(){
+ var a = self.elements, len = a.length;
+ if (len > 0) output.space();
+ a.forEach(function(exp, i){
+ if (i) output.comma();
+ exp.print(output);
+ // If the final element is a hole, we need to make sure it
+ // doesn't look like a trailing comma, by inserting an actual
+ // trailing comma.
+ if (i === len - 1 && exp instanceof AST_Hole)
+ output.comma();
+ });
+ if (len > 0) output.space();
+ });
+ });
+ DEFPRINT(AST_Object, function(self, output){
+ if (self.properties.length > 0) output.with_block(function(){
+ self.properties.forEach(function(prop, i){
+ if (i) {
+ output.print(",");
+ output.newline();
+ }
+ output.indent();
+ prop.print(output);
+ });
+ output.newline();
+ });
+ else output.print("{}");
+ });
+ DEFPRINT(AST_ObjectKeyVal, function(self, output){
+ var key = self.key;
+ if (output.option("quote_keys")) {
+ output.print_string(key + "");
+ } else if ((typeof key == "number"
+ || !output.option("beautify")
+ && +key + "" == key)
+ && parseFloat(key) >= 0) {
+ output.print(make_num(key));
+ } else if (RESERVED_WORDS(key) ? output.option("screw_ie8") : is_identifier_string(key)) {
+ output.print_name(key);
+ } else {
+ output.print_string(key);
+ }
+ output.colon();
+ self.value.print(output);
+ });
+ DEFPRINT(AST_ObjectSetter, function(self, output){
+ output.print("set");
+ output.space();
+ self.key.print(output);
+ self.value._do_print(output, true);
+ });
+ DEFPRINT(AST_ObjectGetter, function(self, output){
+ output.print("get");
+ output.space();
+ self.key.print(output);
+ self.value._do_print(output, true);
+ });
+ DEFPRINT(AST_Symbol, function(self, output){
+ var def = self.definition();
+ output.print_name(def ? def.mangled_name || def.name : self.name);
+ });
+ DEFPRINT(AST_Undefined, function(self, output){
+ output.print("void 0");
+ });
+ DEFPRINT(AST_Hole, noop);
+ DEFPRINT(AST_Infinity, function(self, output){
+ output.print("1/0");
+ });
+ DEFPRINT(AST_NaN, function(self, output){
+ output.print("0/0");
+ });
+ DEFPRINT(AST_This, function(self, output){
+ output.print("this");
+ });
+ DEFPRINT(AST_Constant, function(self, output){
+ output.print(self.getValue());
+ });
+ DEFPRINT(AST_String, function(self, output){
+ output.print_string(self.getValue());
+ });
+ DEFPRINT(AST_Number, function(self, output){
+ output.print(make_num(self.getValue()));
+ });
+
+ function regexp_safe_literal(code) {
+ return [
+ 0x5c , // \
+ 0x2f , // /
+ 0x2e , // .
+ 0x2b , // +
+ 0x2a , // *
+ 0x3f , // ?
+ 0x28 , // (
+ 0x29 , // )
+ 0x5b , // [
+ 0x5d , // ]
+ 0x7b , // {
+ 0x7d , // }
+ 0x24 , // $
+ 0x5e , // ^
+ 0x3a , // :
+ 0x7c , // |
+ 0x21 , // !
+ 0x0a , // \n
+ 0x0d , // \r
+ 0x00 , // \0
+ 0xfeff , // Unicode BOM
+ 0x2028 , // unicode "line separator"
+ 0x2029 , // unicode "paragraph separator"
+ ].indexOf(code) < 0;
+ };
+
+ DEFPRINT(AST_RegExp, function(self, output){
+ var str = self.getValue().toString();
+ if (output.option("ascii_only")) {
+ str = output.to_ascii(str);
+ } else if (output.option("unescape_regexps")) {
+ str = str.split("\\\\").map(function(str){
+ return str.replace(/\\u[0-9a-fA-F]{4}|\\x[0-9a-fA-F]{2}/g, function(s){
+ var code = parseInt(s.substr(2), 16);
+ return regexp_safe_literal(code) ? String.fromCharCode(code) : s;
+ });
+ }).join("\\\\");
+ }
+ output.print(str);
+ var p = output.parent();
+ if (p instanceof AST_Binary && /^in/.test(p.operator) && p.left === self)
+ output.print(" ");
+ });
+
+ function force_statement(stat, output) {
+ if (output.option("bracketize")) {
+ if (!stat || stat instanceof AST_EmptyStatement)
+ output.print("{}");
+ else if (stat instanceof AST_BlockStatement)
+ stat.print(output);
+ else output.with_block(function(){
+ output.indent();
+ stat.print(output);
+ output.newline();
+ });
+ } else {
+ if (!stat || stat instanceof AST_EmptyStatement)
+ output.force_semicolon();
+ else
+ stat.print(output);
+ }
+ };
+
+ // return true if the node at the top of the stack (that means the
+ // innermost node in the current output) is lexically the first in
+ // a statement.
+ function first_in_statement(output) {
+ var a = output.stack(), i = a.length, node = a[--i], p = a[--i];
+ while (i > 0) {
+ if (p instanceof AST_Statement && p.body === node)
+ return true;
+ if ((p instanceof AST_Seq && p.car === node ) ||
+ (p instanceof AST_Call && p.expression === node && !(p instanceof AST_New) ) ||
+ (p instanceof AST_Dot && p.expression === node ) ||
+ (p instanceof AST_Sub && p.expression === node ) ||
+ (p instanceof AST_Conditional && p.condition === node ) ||
+ (p instanceof AST_Binary && p.left === node ) ||
+ (p instanceof AST_UnaryPostfix && p.expression === node ))
+ {
+ node = p;
+ p = a[--i];
+ } else {
+ return false;
+ }
+ }
+ };
+
+ // self should be AST_New. decide if we want to show parens or not.
+ function no_constructor_parens(self, output) {
+ return self.args.length == 0 && !output.option("beautify");
+ };
+
+ function best_of(a) {
+ var best = a[0], len = best.length;
+ for (var i = 1; i < a.length; ++i) {
+ if (a[i].length < len) {
+ best = a[i];
+ len = best.length;
+ }
+ }
+ return best;
+ };
+
+ function make_num(num) {
+ var str = num.toString(10), a = [ str.replace(/^0\./, ".").replace('e+', 'e') ], m;
+ if (Math.floor(num) === num) {
+ if (num >= 0) {
+ a.push("0x" + num.toString(16).toLowerCase(), // probably pointless
+ "0" + num.toString(8)); // same.
+ } else {
+ a.push("-0x" + (-num).toString(16).toLowerCase(), // probably pointless
+ "-0" + (-num).toString(8)); // same.
+ }
+ if ((m = /^(.*?)(0+)$/.exec(num))) {
+ a.push(m[1] + "e" + m[2].length);
+ }
+ } else if ((m = /^0?\.(0+)(.*)$/.exec(num))) {
+ a.push(m[2] + "e-" + (m[1].length + m[2].length),
+ str.substr(str.indexOf(".")));
+ }
+ return best_of(a);
+ };
+
+ function make_block(stmt, output) {
+ if (stmt instanceof AST_BlockStatement) {
+ stmt.print(output);
+ return;
+ }
+ output.with_block(function(){
+ output.indent();
+ stmt.print(output);
+ output.newline();
+ });
+ };
+
+ /* -----[ source map generators ]----- */
+
+ function DEFMAP(nodetype, generator) {
+ nodetype.DEFMETHOD("add_source_map", function(stream){
+ generator(this, stream);
+ });
+ };
+
+ // We could easily add info for ALL nodes, but it seems to me that
+ // would be quite wasteful, hence this noop in the base class.
+ DEFMAP(AST_Node, noop);
+
+ function basic_sourcemap_gen(self, output) {
+ output.add_mapping(self.start);
+ };
+
+ // XXX: I'm not exactly sure if we need it for all of these nodes,
+ // or if we should add even more.
+
+ DEFMAP(AST_Directive, basic_sourcemap_gen);
+ DEFMAP(AST_Debugger, basic_sourcemap_gen);
+ DEFMAP(AST_Symbol, basic_sourcemap_gen);
+ DEFMAP(AST_Jump, basic_sourcemap_gen);
+ DEFMAP(AST_StatementWithBody, basic_sourcemap_gen);
+ DEFMAP(AST_LabeledStatement, noop); // since the label symbol will mark it
+ DEFMAP(AST_Lambda, basic_sourcemap_gen);
+ DEFMAP(AST_Switch, basic_sourcemap_gen);
+ DEFMAP(AST_SwitchBranch, basic_sourcemap_gen);
+ DEFMAP(AST_BlockStatement, basic_sourcemap_gen);
+ DEFMAP(AST_Toplevel, noop);
+ DEFMAP(AST_New, basic_sourcemap_gen);
+ DEFMAP(AST_Try, basic_sourcemap_gen);
+ DEFMAP(AST_Catch, basic_sourcemap_gen);
+ DEFMAP(AST_Finally, basic_sourcemap_gen);
+ DEFMAP(AST_Definitions, basic_sourcemap_gen);
+ DEFMAP(AST_Constant, basic_sourcemap_gen);
+ DEFMAP(AST_ObjectProperty, function(self, output){
+ output.add_mapping(self.start, self.key);
+ });
+
+})();
+
+/***********************************************************************
+
+ A JavaScript tokenizer / parser / beautifier / compressor.
+ https://github.com/mishoo/UglifyJS2
+
+ -------------------------------- (C) ---------------------------------
+
+ Author: Mihai Bazon
+ <mihai.bazon@gmail.com>
+ http://mihai.bazon.net/blog
+
+ Distributed under the BSD license:
+
+ Copyright 2012 (c) Mihai Bazon <mihai.bazon@gmail.com>
+
+ Redistribution and use in source and binary forms, with or without
+ modification, are permitted provided that the following conditions
+ are met:
+
+ * Redistributions of source code must retain the above
+ copyright notice, this list of conditions and the following
+ disclaimer.
+
+ * Redistributions in binary form must reproduce the above
+ copyright notice, this list of conditions and the following
+ disclaimer in the documentation and/or other materials
+ provided with the distribution.
+
+ THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDER “AS IS” AND ANY
+ EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
+ PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE
+ LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY,
+ OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
+ PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
+ PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+ THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR
+ TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF
+ THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ SUCH DAMAGE.
+
+ ***********************************************************************/
+
+"use strict";
+
+function Compressor(options, false_by_default) {
+ if (!(this instanceof Compressor))
+ return new Compressor(options, false_by_default);
+ TreeTransformer.call(this, this.before, this.after);
+ this.options = defaults(options, {
+ sequences : !false_by_default,
+ properties : !false_by_default,
+ dead_code : !false_by_default,
+ drop_debugger : !false_by_default,
+ unsafe : false,
+ unsafe_comps : false,
+ conditionals : !false_by_default,
+ comparisons : !false_by_default,
+ evaluate : !false_by_default,
+ booleans : !false_by_default,
+ loops : !false_by_default,
+ unused : !false_by_default,
+ hoist_funs : !false_by_default,
+ hoist_vars : false,
+ if_return : !false_by_default,
+ join_vars : !false_by_default,
+ cascade : !false_by_default,
+ side_effects : !false_by_default,
+ pure_getters : false,
+ pure_funcs : null,
+ negate_iife : !false_by_default,
+ screw_ie8 : false,
+ drop_console : false,
+ angular : false,
+
+ warnings : true,
+ global_defs : {}
+ }, true);
+};
+
+Compressor.prototype = new TreeTransformer;
+merge(Compressor.prototype, {
+ option: function(key) { return this.options[key] },
+ warn: function() {
+ if (this.options.warnings)
+ AST_Node.warn.apply(AST_Node, arguments);
+ },
+ before: function(node, descend, in_list) {
+ if (node._squeezed) return node;
+ var was_scope = false;
+ if (node instanceof AST_Scope) {
+ node = node.hoist_declarations(this);
+ was_scope = true;
+ }
+ descend(node, this);
+ node = node.optimize(this);
+ if (was_scope && node instanceof AST_Scope) {
+ node.drop_unused(this);
+ descend(node, this);
+ }
+ node._squeezed = true;
+ return node;
+ }
+});
+
+(function(){
+
+ function OPT(node, optimizer) {
+ node.DEFMETHOD("optimize", function(compressor){
+ var self = this;
+ if (self._optimized) return self;
+ var opt = optimizer(self, compressor);
+ opt._optimized = true;
+ if (opt === self) return opt;
+ return opt.transform(compressor);
+ });
+ };
+
+ OPT(AST_Node, function(self, compressor){
+ return self;
+ });
+
+ AST_Node.DEFMETHOD("equivalent_to", function(node){
+ // XXX: this is a rather expensive way to test two node's equivalence:
+ return this.print_to_string() == node.print_to_string();
+ });
+
+ function make_node(ctor, orig, props) {
+ if (!props) props = {};
+ if (orig) {
+ if (!props.start) props.start = orig.start;
+ if (!props.end) props.end = orig.end;
+ }
+ return new ctor(props);
+ };
+
+ function make_node_from_constant(compressor, val, orig) {
+ // XXX: WIP.
+ // if (val instanceof AST_Node) return val.transform(new TreeTransformer(null, function(node){
+ // if (node instanceof AST_SymbolRef) {
+ // var scope = compressor.find_parent(AST_Scope);
+ // var def = scope.find_variable(node);
+ // node.thedef = def;
+ // return node;
+ // }
+ // })).transform(compressor);
+
+ if (val instanceof AST_Node) return val.transform(compressor);
+ switch (typeof val) {
+ case "string":
+ return make_node(AST_String, orig, {
+ value: val
+ }).optimize(compressor);
+ case "number":
+ return make_node(isNaN(val) ? AST_NaN : AST_Number, orig, {
+ value: val
+ }).optimize(compressor);
+ case "boolean":
+ return make_node(val ? AST_True : AST_False, orig).optimize(compressor);
+ case "undefined":
+ return make_node(AST_Undefined, orig).optimize(compressor);
+ default:
+ if (val === null) {
+ return make_node(AST_Null, orig).optimize(compressor);
+ }
+ if (val instanceof RegExp) {
+ return make_node(AST_RegExp, orig).optimize(compressor);
+ }
+ throw new Error(string_template("Can't handle constant of type: {type}", {
+ type: typeof val
+ }));
+ }
+ };
+
+ function as_statement_array(thing) {
+ if (thing === null) return [];
+ if (thing instanceof AST_BlockStatement) return thing.body;
+ if (thing instanceof AST_EmptyStatement) return [];
+ if (thing instanceof AST_Statement) return [ thing ];
+ throw new Error("Can't convert thing to statement array");
+ };
+
+ function is_empty(thing) {
+ if (thing === null) return true;
+ if (thing instanceof AST_EmptyStatement) return true;
+ if (thing instanceof AST_BlockStatement) return thing.body.length == 0;
+ return false;
+ };
+
+ function loop_body(x) {
+ if (x instanceof AST_Switch) return x;
+ if (x instanceof AST_For || x instanceof AST_ForIn || x instanceof AST_DWLoop) {
+ return (x.body instanceof AST_BlockStatement ? x.body : x);
+ }
+ return x;
+ };
+
+ function tighten_body(statements, compressor) {
+ var CHANGED;
+ do {
+ CHANGED = false;
+ if (compressor.option("angular")) {
+ statements = process_for_angular(statements);
+ }
+ statements = eliminate_spurious_blocks(statements);
+ if (compressor.option("dead_code")) {
+ statements = eliminate_dead_code(statements, compressor);
+ }
+ if (compressor.option("if_return")) {
+ statements = handle_if_return(statements, compressor);
+ }
+ if (compressor.option("sequences")) {
+ statements = sequencesize(statements, compressor);
+ }
+ if (compressor.option("join_vars")) {
+ statements = join_consecutive_vars(statements, compressor);
+ }
+ } while (CHANGED);
+
+ if (compressor.option("negate_iife")) {
+ negate_iifes(statements, compressor);
+ }
+
+ return statements;
+
+ function process_for_angular(statements) {
+ function make_injector(func, name) {
+ return make_node(AST_SimpleStatement, func, {
+ body: make_node(AST_Assign, func, {
+ operator: "=",
+ left: make_node(AST_Dot, name, {
+ expression: make_node(AST_SymbolRef, name, name),
+ property: "$inject"
+ }),
+ right: make_node(AST_Array, func, {
+ elements: func.argnames.map(function(sym){
+ return make_node(AST_String, sym, { value: sym.name });
+ })
+ })
+ })
+ });
+ }
+ return statements.reduce(function(a, stat){
+ a.push(stat);
+ var token = stat.start;
+ var comments = token.comments_before;
+ if (comments && comments.length > 0) {
+ var last = comments.pop();
+ if (/@ngInject/.test(last.value)) {
+ // case 1: defun
+ if (stat instanceof AST_Defun) {
+ a.push(make_injector(stat, stat.name));
+ }
+ else if (stat instanceof AST_Definitions) {
+ stat.definitions.forEach(function(def){
+ if (def.value && def.value instanceof AST_Lambda) {
+ a.push(make_injector(def.value, def.name));
+ }
+ });
+ }
+ else {
+ compressor.warn("Unknown statement marked with @ngInject [{file}:{line},{col}]", token);
+ }
+ }
+ }
+ return a;
+ }, []);
+ }
+
+ function eliminate_spurious_blocks(statements) {
+ var seen_dirs = [];
+ return statements.reduce(function(a, stat){
+ if (stat instanceof AST_BlockStatement) {
+ CHANGED = true;
+ a.push.apply(a, eliminate_spurious_blocks(stat.body));
+ } else if (stat instanceof AST_EmptyStatement) {
+ CHANGED = true;
+ } else if (stat instanceof AST_Directive) {
+ if (seen_dirs.indexOf(stat.value) < 0) {
+ a.push(stat);
+ seen_dirs.push(stat.value);
+ } else {
+ CHANGED = true;
+ }
+ } else {
+ a.push(stat);
+ }
+ return a;
+ }, []);
+ };
+
+ function handle_if_return(statements, compressor) {
+ var self = compressor.self();
+ var in_lambda = self instanceof AST_Lambda;
+ var ret = [];
+ loop: for (var i = statements.length; --i >= 0;) {
+ var stat = statements[i];
+ switch (true) {
+ case (in_lambda && stat instanceof AST_Return && !stat.value && ret.length == 0):
+ CHANGED = true;
+ // note, ret.length is probably always zero
+ // because we drop unreachable code before this
+ // step. nevertheless, it's good to check.
+ continue loop;
+ case stat instanceof AST_If:
+ if (stat.body instanceof AST_Return) {
+ //---
+ // pretty silly case, but:
+ // if (foo()) return; return; ==> foo(); return;
+ if (((in_lambda && ret.length == 0)
+ || (ret[0] instanceof AST_Return && !ret[0].value))
+ && !stat.body.value && !stat.alternative) {
+ CHANGED = true;
+ var cond = make_node(AST_SimpleStatement, stat.condition, {
+ body: stat.condition
+ });
+ ret.unshift(cond);
+ continue loop;
+ }
+ //---
+ // if (foo()) return x; return y; ==> return foo() ? x : y;
+ if (ret[0] instanceof AST_Return && stat.body.value && ret[0].value && !stat.alternative) {
+ CHANGED = true;
+ stat = stat.clone();
+ stat.alternative = ret[0];
+ ret[0] = stat.transform(compressor);
+ continue loop;
+ }
+ //---
+ // if (foo()) return x; [ return ; ] ==> return foo() ? x : undefined;
+ if ((ret.length == 0 || ret[0] instanceof AST_Return) && stat.body.value && !stat.alternative && in_lambda) {
+ CHANGED = true;
+ stat = stat.clone();
+ stat.alternative = ret[0] || make_node(AST_Return, stat, {
+ value: make_node(AST_Undefined, stat)
+ });
+ ret[0] = stat.transform(compressor);
+ continue loop;
+ }
+ //---
+ // if (foo()) return; [ else x... ]; y... ==> if (!foo()) { x...; y... }
+ if (!stat.body.value && in_lambda) {
+ CHANGED = true;
+ stat = stat.clone();
+ stat.condition = stat.condition.negate(compressor);
+ stat.body = make_node(AST_BlockStatement, stat, {
+ body: as_statement_array(stat.alternative).concat(ret)
+ });
+ stat.alternative = null;
+ ret = [ stat.transform(compressor) ];
+ continue loop;
+ }
+ //---
+ if (ret.length == 1 && in_lambda && ret[0] instanceof AST_SimpleStatement
+ && (!stat.alternative || stat.alternative instanceof AST_SimpleStatement)) {
+ CHANGED = true;
+ ret.push(make_node(AST_Return, ret[0], {
+ value: make_node(AST_Undefined, ret[0])
+ }).transform(compressor));
+ ret = as_statement_array(stat.alternative).concat(ret);
+ ret.unshift(stat);
+ continue loop;
+ }
+ }
+
+ var ab = aborts(stat.body);
+ var lct = ab instanceof AST_LoopControl ? compressor.loopcontrol_target(ab.label) : null;
+ if (ab && ((ab instanceof AST_Return && !ab.value && in_lambda)
+ || (ab instanceof AST_Continue && self === loop_body(lct))
+ || (ab instanceof AST_Break && lct instanceof AST_BlockStatement && self === lct))) {
+ if (ab.label) {
+ remove(ab.label.thedef.references, ab);
+ }
+ CHANGED = true;
+ var body = as_statement_array(stat.body).slice(0, -1);
+ stat = stat.clone();
+ stat.condition = stat.condition.negate(compressor);
+ stat.body = make_node(AST_BlockStatement, stat, {
+ body: ret
+ });
+ stat.alternative = make_node(AST_BlockStatement, stat, {
+ body: body
+ });
+ ret = [ stat.transform(compressor) ];
+ continue loop;
+ }
+
+ var ab = aborts(stat.alternative);
+ var lct = ab instanceof AST_LoopControl ? compressor.loopcontrol_target(ab.label) : null;
+ if (ab && ((ab instanceof AST_Return && !ab.value && in_lambda)
+ || (ab instanceof AST_Continue && self === loop_body(lct))
+ || (ab instanceof AST_Break && lct instanceof AST_BlockStatement && self === lct))) {
+ if (ab.label) {
+ remove(ab.label.thedef.references, ab);
+ }
+ CHANGED = true;
+ stat = stat.clone();
+ stat.body = make_node(AST_BlockStatement, stat.body, {
+ body: as_statement_array(stat.body).concat(ret)
+ });
+ stat.alternative = make_node(AST_BlockStatement, stat.alternative, {
+ body: as_statement_array(stat.alternative).slice(0, -1)
+ });
+ ret = [ stat.transform(compressor) ];
+ continue loop;
+ }
+
+ ret.unshift(stat);
+ break;
+ default:
+ ret.unshift(stat);
+ break;
+ }
+ }
+ return ret;
+ };
+
+ function eliminate_dead_code(statements, compressor) {
+ var has_quit = false;
+ var orig = statements.length;
+ var self = compressor.self();
+ statements = statements.reduce(function(a, stat){
+ if (has_quit) {
+ extract_declarations_from_unreachable_code(compressor, stat, a);
+ } else {
+ if (stat instanceof AST_LoopControl) {
+ var lct = compressor.loopcontrol_target(stat.label);
+ if ((stat instanceof AST_Break
+ && lct instanceof AST_BlockStatement
+ && loop_body(lct) === self) || (stat instanceof AST_Continue
+ && loop_body(lct) === self)) {
+ if (stat.label) {
+ remove(stat.label.thedef.references, stat);
+ }
+ } else {
+ a.push(stat);
+ }
+ } else {
+ a.push(stat);
+ }
+ if (aborts(stat)) has_quit = true;
+ }
+ return a;
+ }, []);
+ CHANGED = statements.length != orig;
+ return statements;
+ };
+
+ function sequencesize(statements, compressor) {
+ if (statements.length < 2) return statements;
+ var seq = [], ret = [];
+ function push_seq() {
+ seq = AST_Seq.from_array(seq);
+ if (seq) ret.push(make_node(AST_SimpleStatement, seq, {
+ body: seq
+ }));
+ seq = [];
+ };
+ statements.forEach(function(stat){
+ if (stat instanceof AST_SimpleStatement) seq.push(stat.body);
+ else push_seq(), ret.push(stat);
+ });
+ push_seq();
+ ret = sequencesize_2(ret, compressor);
+ CHANGED = ret.length != statements.length;
+ return ret;
+ };
+
+ function sequencesize_2(statements, compressor) {
+ function cons_seq(right) {
+ ret.pop();
+ var left = prev.body;
+ if (left instanceof AST_Seq) {
+ left.add(right);
+ } else {
+ left = AST_Seq.cons(left, right);
+ }
+ return left.transform(compressor);
+ };
+ var ret = [], prev = null;
+ statements.forEach(function(stat){
+ if (prev) {
+ if (stat instanceof AST_For) {
+ var opera = {};
+ try {
+ prev.body.walk(new TreeWalker(function(node){
+ if (node instanceof AST_Binary && node.operator == "in")
+ throw opera;
+ }));
+ if (stat.init && !(stat.init instanceof AST_Definitions)) {
+ stat.init = cons_seq(stat.init);
+ }
+ else if (!stat.init) {
+ stat.init = prev.body;
+ ret.pop();
+ }
+ } catch(ex) {
+ if (ex !== opera) throw ex;
+ }
+ }
+ else if (stat instanceof AST_If) {
+ stat.condition = cons_seq(stat.condition);
+ }
+ else if (stat instanceof AST_With) {
+ stat.expression = cons_seq(stat.expression);
+ }
+ else if (stat instanceof AST_Exit && stat.value) {
+ stat.value = cons_seq(stat.value);
+ }
+ else if (stat instanceof AST_Exit) {
+ stat.value = cons_seq(make_node(AST_Undefined, stat));
+ }
+ else if (stat instanceof AST_Switch) {
+ stat.expression = cons_seq(stat.expression);
+ }
+ }
+ ret.push(stat);
+ prev = stat instanceof AST_SimpleStatement ? stat : null;
+ });
+ return ret;
+ };
+
+ function join_consecutive_vars(statements, compressor) {
+ var prev = null;
+ return statements.reduce(function(a, stat){
+ if (stat instanceof AST_Definitions && prev && prev.TYPE == stat.TYPE) {
+ prev.definitions = prev.definitions.concat(stat.definitions);
+ CHANGED = true;
+ }
+ else if (stat instanceof AST_For
+ && prev instanceof AST_Definitions
+ && (!stat.init || stat.init.TYPE == prev.TYPE)) {
+ CHANGED = true;
+ a.pop();
+ if (stat.init) {
+ stat.init.definitions = prev.definitions.concat(stat.init.definitions);
+ } else {
+ stat.init = prev;
+ }
+ a.push(stat);
+ prev = stat;
+ }
+ else {
+ prev = stat;
+ a.push(stat);
+ }
+ return a;
+ }, []);
+ };
+
+ function negate_iifes(statements, compressor) {
+ statements.forEach(function(stat){
+ if (stat instanceof AST_SimpleStatement) {
+ stat.body = (function transform(thing) {
+ return thing.transform(new TreeTransformer(function(node){
+ if (node instanceof AST_Call && node.expression instanceof AST_Function) {
+ return make_node(AST_UnaryPrefix, node, {
+ operator: "!",
+ expression: node
+ });
+ }
+ else if (node instanceof AST_Call) {
+ node.expression = transform(node.expression);
+ }
+ else if (node instanceof AST_Seq) {
+ node.car = transform(node.car);
+ }
+ else if (node instanceof AST_Conditional) {
+ var expr = transform(node.condition);
+ if (expr !== node.condition) {
+ // it has been negated, reverse
+ node.condition = expr;
+ var tmp = node.consequent;
+ node.consequent = node.alternative;
+ node.alternative = tmp;
+ }
+ }
+ return node;
+ }));
+ })(stat.body);
+ }
+ });
+ };
+
+ };
+
+ function extract_declarations_from_unreachable_code(compressor, stat, target) {
+ compressor.warn("Dropping unreachable code [{file}:{line},{col}]", stat.start);
+ stat.walk(new TreeWalker(function(node){
+ if (node instanceof AST_Definitions) {
+ compressor.warn("Declarations in unreachable code! [{file}:{line},{col}]", node.start);
+ node.remove_initializers();
+ target.push(node);
+ return true;
+ }
+ if (node instanceof AST_Defun) {
+ target.push(node);
+ return true;
+ }
+ if (node instanceof AST_Scope) {
+ return true;
+ }
+ }));
+ };
+
+ /* -----[ boolean/negation helpers ]----- */
+
+ // methods to determine whether an expression has a boolean result type
+ (function (def){
+ var unary_bool = [ "!", "delete" ];
+ var binary_bool = [ "in", "instanceof", "==", "!=", "===", "!==", "<", "<=", ">=", ">" ];
+ def(AST_Node, function(){ return false });
+ def(AST_UnaryPrefix, function(){
+ return member(this.operator, unary_bool);
+ });
+ def(AST_Binary, function(){
+ return member(this.operator, binary_bool) ||
+ ( (this.operator == "&&" || this.operator == "||") &&
+ this.left.is_boolean() && this.right.is_boolean() );
+ });
+ def(AST_Conditional, function(){
+ return this.consequent.is_boolean() && this.alternative.is_boolean();
+ });
+ def(AST_Assign, function(){
+ return this.operator == "=" && this.right.is_boolean();
+ });
+ def(AST_Seq, function(){
+ return this.cdr.is_boolean();
+ });
+ def(AST_True, function(){ return true });
+ def(AST_False, function(){ return true });
+ })(function(node, func){
+ node.DEFMETHOD("is_boolean", func);
+ });
+
+ // methods to determine if an expression has a string result type
+ (function (def){
+ def(AST_Node, function(){ return false });
+ def(AST_String, function(){ return true });
+ def(AST_UnaryPrefix, function(){
+ return this.operator == "typeof";
+ });
+ def(AST_Binary, function(compressor){
+ return this.operator == "+" &&
+ (this.left.is_string(compressor) || this.right.is_string(compressor));
+ });
+ def(AST_Assign, function(compressor){
+ return (this.operator == "=" || this.operator == "+=") && this.right.is_string(compressor);
+ });
+ def(AST_Seq, function(compressor){
+ return this.cdr.is_string(compressor);
+ });
+ def(AST_Conditional, function(compressor){
+ return this.consequent.is_string(compressor) && this.alternative.is_string(compressor);
+ });
+ def(AST_Call, function(compressor){
+ return compressor.option("unsafe")
+ && this.expression instanceof AST_SymbolRef
+ && this.expression.name == "String"
+ && this.expression.undeclared();
+ });
+ })(function(node, func){
+ node.DEFMETHOD("is_string", func);
+ });
+
+ function best_of(ast1, ast2) {
+ return ast1.print_to_string().length >
+ ast2.print_to_string().length
+ ? ast2 : ast1;
+ };
+
+ // methods to evaluate a constant expression
+ (function (def){
+ // The evaluate method returns an array with one or two
+ // elements. If the node has been successfully reduced to a
+ // constant, then the second element tells us the value;
+ // otherwise the second element is missing. The first element
+ // of the array is always an AST_Node descendant; if
+ // evaluation was successful it's a node that represents the
+ // constant; otherwise it's the original or a replacement node.
+ AST_Node.DEFMETHOD("evaluate", function(compressor){
+ if (!compressor.option("evaluate")) return [ this ];
+ try {
+ var val = this._eval(compressor);
+ return [ best_of(make_node_from_constant(compressor, val, this), this), val ];
+ } catch(ex) {
+ if (ex !== def) throw ex;
+ return [ this ];
+ }
+ });
+ def(AST_Statement, function(){
+ throw new Error(string_template("Cannot evaluate a statement [{file}:{line},{col}]", this.start));
+ });
+ def(AST_Function, function(){
+ // XXX: AST_Function inherits from AST_Scope, which itself
+ // inherits from AST_Statement; however, an AST_Function
+ // isn't really a statement. This could byte in other
+ // places too. :-( Wish JS had multiple inheritance.
+ throw def;
+ });
+ function ev(node, compressor) {
+ if (!compressor) throw new Error("Compressor must be passed");
+
+ return node._eval(compressor);
+ };
+ def(AST_Node, function(){
+ throw def; // not constant
+ });
+ def(AST_Constant, function(){
+ return this.getValue();
+ });
+ def(AST_UnaryPrefix, function(compressor){
+ var e = this.expression;
+ switch (this.operator) {
+ case "!": return !ev(e, compressor);
+ case "typeof":
+ // Function would be evaluated to an array and so typeof would
+ // incorrectly return 'object'. Hence making is a special case.
+ if (e instanceof AST_Function) return typeof function(){};
+
+ e = ev(e, compressor);
+
+ // typeof <RegExp> returns "object" or "function" on different platforms
+ // so cannot evaluate reliably
+ if (e instanceof RegExp) throw def;
+
+ return typeof e;
+ case "void": return void ev(e, compressor);
+ case "~": return ~ev(e, compressor);
+ case "-":
+ e = ev(e, compressor);
+ if (e === 0) throw def;
+ return -e;
+ case "+": return +ev(e, compressor);
+ }
+ throw def;
+ });
+ def(AST_Binary, function(c){
+ var left = this.left, right = this.right;
+ switch (this.operator) {
+ case "&&" : return ev(left, c) && ev(right, c);
+ case "||" : return ev(left, c) || ev(right, c);
+ case "|" : return ev(left, c) | ev(right, c);
+ case "&" : return ev(left, c) & ev(right, c);
+ case "^" : return ev(left, c) ^ ev(right, c);
+ case "+" : return ev(left, c) + ev(right, c);
+ case "*" : return ev(left, c) * ev(right, c);
+ case "/" : return ev(left, c) / ev(right, c);
+ case "%" : return ev(left, c) % ev(right, c);
+ case "-" : return ev(left, c) - ev(right, c);
+ case "<<" : return ev(left, c) << ev(right, c);
+ case ">>" : return ev(left, c) >> ev(right, c);
+ case ">>>" : return ev(left, c) >>> ev(right, c);
+ case "==" : return ev(left, c) == ev(right, c);
+ case "===" : return ev(left, c) === ev(right, c);
+ case "!=" : return ev(left, c) != ev(right, c);
+ case "!==" : return ev(left, c) !== ev(right, c);
+ case "<" : return ev(left, c) < ev(right, c);
+ case "<=" : return ev(left, c) <= ev(right, c);
+ case ">" : return ev(left, c) > ev(right, c);
+ case ">=" : return ev(left, c) >= ev(right, c);
+ case "in" : return ev(left, c) in ev(right, c);
+ case "instanceof" : return ev(left, c) instanceof ev(right, c);
+ }
+ throw def;
+ });
+ def(AST_Conditional, function(compressor){
+ return ev(this.condition, compressor)
+ ? ev(this.consequent, compressor)
+ : ev(this.alternative, compressor);
+ });
+ def(AST_SymbolRef, function(compressor){
+ var d = this.definition();
+ if (d && d.constant && d.init) return ev(d.init, compressor);
+ throw def;
+ });
+ })(function(node, func){
+ node.DEFMETHOD("_eval", func);
+ });
+
+ // method to negate an expression
+ (function(def){
+ function basic_negation(exp) {
+ return make_node(AST_UnaryPrefix, exp, {
+ operator: "!",
+ expression: exp
+ });
+ };
+ def(AST_Node, function(){
+ return basic_negation(this);
+ });
+ def(AST_Statement, function(){
+ throw new Error("Cannot negate a statement");
+ });
+ def(AST_Function, function(){
+ return basic_negation(this);
+ });
+ def(AST_UnaryPrefix, function(){
+ if (this.operator == "!")
+ return this.expression;
+ return basic_negation(this);
+ });
+ def(AST_Seq, function(compressor){
+ var self = this.clone();
+ self.cdr = self.cdr.negate(compressor);
+ return self;
+ });
+ def(AST_Conditional, function(compressor){
+ var self = this.clone();
+ self.consequent = self.consequent.negate(compressor);
+ self.alternative = self.alternative.negate(compressor);
+ return best_of(basic_negation(this), self);
+ });
+ def(AST_Binary, function(compressor){
+ var self = this.clone(), op = this.operator;
+ if (compressor.option("unsafe_comps")) {
+ switch (op) {
+ case "<=" : self.operator = ">" ; return self;
+ case "<" : self.operator = ">=" ; return self;
+ case ">=" : self.operator = "<" ; return self;
+ case ">" : self.operator = "<=" ; return self;
+ }
+ }
+ switch (op) {
+ case "==" : self.operator = "!="; return self;
+ case "!=" : self.operator = "=="; return self;
+ case "===": self.operator = "!=="; return self;
+ case "!==": self.operator = "==="; return self;
+ case "&&":
+ self.operator = "||";
+ self.left = self.left.negate(compressor);
+ self.right = self.right.negate(compressor);
+ return best_of(basic_negation(this), self);
+ case "||":
+ self.operator = "&&";
+ self.left = self.left.negate(compressor);
+ self.right = self.right.negate(compressor);
+ return best_of(basic_negation(this), self);
+ }
+ return basic_negation(this);
+ });
+ })(function(node, func){
+ node.DEFMETHOD("negate", function(compressor){
+ return func.call(this, compressor);
+ });
+ });
+
+ // determine if expression has side effects
+ (function(def){
+ def(AST_Node, function(compressor){ return true });
+
+ def(AST_EmptyStatement, function(compressor){ return false });
+ def(AST_Constant, function(compressor){ return false });
+ def(AST_This, function(compressor){ return false });
+
+ def(AST_Call, function(compressor){
+ var pure = compressor.option("pure_funcs");
+ if (!pure) return true;
+ return pure.indexOf(this.expression.print_to_string()) < 0;
+ });
+
+ def(AST_Block, function(compressor){
+ for (var i = this.body.length; --i >= 0;) {
+ if (this.body[i].has_side_effects(compressor))
+ return true;
+ }
+ return false;
+ });
+
+ def(AST_SimpleStatement, function(compressor){
+ return this.body.has_side_effects(compressor);
+ });
+ def(AST_Defun, function(compressor){ return true });
+ def(AST_Function, function(compressor){ return false });
+ def(AST_Binary, function(compressor){
+ return this.left.has_side_effects(compressor)
+ || this.right.has_side_effects(compressor);
+ });
+ def(AST_Assign, function(compressor){ return true });
+ def(AST_Conditional, function(compressor){
+ return this.condition.has_side_effects(compressor)
+ || this.consequent.has_side_effects(compressor)
+ || this.alternative.has_side_effects(compressor);
+ });
+ def(AST_Unary, function(compressor){
+ return this.operator == "delete"
+ || this.operator == "++"
+ || this.operator == "--"
+ || this.expression.has_side_effects(compressor);
+ });
+ def(AST_SymbolRef, function(compressor){ return false });
+ def(AST_Object, function(compressor){
+ for (var i = this.properties.length; --i >= 0;)
+ if (this.properties[i].has_side_effects(compressor))
+ return true;
+ return false;
+ });
+ def(AST_ObjectProperty, function(compressor){
+ return this.value.has_side_effects(compressor);
+ });
+ def(AST_Array, function(compressor){
+ for (var i = this.elements.length; --i >= 0;)
+ if (this.elements[i].has_side_effects(compressor))
+ return true;
+ return false;
+ });
+ def(AST_Dot, function(compressor){
+ if (!compressor.option("pure_getters")) return true;
+ return this.expression.has_side_effects(compressor);
+ });
+ def(AST_Sub, function(compressor){
+ if (!compressor.option("pure_getters")) return true;
+ return this.expression.has_side_effects(compressor)
+ || this.property.has_side_effects(compressor);
+ });
+ def(AST_PropAccess, function(compressor){
+ return !compressor.option("pure_getters");
+ });
+ def(AST_Seq, function(compressor){
+ return this.car.has_side_effects(compressor)
+ || this.cdr.has_side_effects(compressor);
+ });
+ })(function(node, func){
+ node.DEFMETHOD("has_side_effects", func);
+ });
+
+ // tell me if a statement aborts
+ function aborts(thing) {
+ return thing && thing.aborts();
+ };
+ (function(def){
+ def(AST_Statement, function(){ return null });
+ def(AST_Jump, function(){ return this });
+ function block_aborts(){
+ var n = this.body.length;
+ return n > 0 && aborts(this.body[n - 1]);
+ };
+ def(AST_BlockStatement, block_aborts);
+ def(AST_SwitchBranch, block_aborts);
+ def(AST_If, function(){
+ return this.alternative && aborts(this.body) && aborts(this.alternative);
+ });
+ })(function(node, func){
+ node.DEFMETHOD("aborts", func);
+ });
+
+ /* -----[ optimizers ]----- */
+
+ OPT(AST_Directive, function(self, compressor){
+ if (self.scope.has_directive(self.value) !== self.scope) {
+ return make_node(AST_EmptyStatement, self);
+ }
+ return self;
+ });
+
+ OPT(AST_Debugger, function(self, compressor){
+ if (compressor.option("drop_debugger"))
+ return make_node(AST_EmptyStatement, self);
+ return self;
+ });
+
+ OPT(AST_LabeledStatement, function(self, compressor){
+ if (self.body instanceof AST_Break
+ && compressor.loopcontrol_target(self.body.label) === self.body) {
+ return make_node(AST_EmptyStatement, self);
+ }
+ return self.label.references.length == 0 ? self.body : self;
+ });
+
+ OPT(AST_Block, function(self, compressor){
+ self.body = tighten_body(self.body, compressor);
+ return self;
+ });
+
+ OPT(AST_BlockStatement, function(self, compressor){
+ self.body = tighten_body(self.body, compressor);
+ switch (self.body.length) {
+ case 1: return self.body[0];
+ case 0: return make_node(AST_EmptyStatement, self);
+ }
+ return self;
+ });
+
+ AST_Scope.DEFMETHOD("drop_unused", function(compressor){
+ var self = this;
+ if (compressor.option("unused")
+ && !(self instanceof AST_Toplevel)
+ && !self.uses_eval
+ ) {
+ var in_use = [];
+ var initializations = new Dictionary();
+ // pass 1: find out which symbols are directly used in
+ // this scope (not in nested scopes).
+ var scope = this;
+ var tw = new TreeWalker(function(node, descend){
+ if (node !== self) {
+ if (node instanceof AST_Defun) {
+ initializations.add(node.name.name, node);
+ return true; // don't go in nested scopes
+ }
+ if (node instanceof AST_Definitions && scope === self) {
+ node.definitions.forEach(function(def){
+ if (def.value) {
+ initializations.add(def.name.name, def.value);
+ if (def.value.has_side_effects(compressor)) {
+ def.value.walk(tw);
+ }
+ }
+ });
+ return true;
+ }
+ if (node instanceof AST_SymbolRef) {
+ push_uniq(in_use, node.definition());
+ return true;
+ }
+ if (node instanceof AST_Scope) {
+ var save_scope = scope;
+ scope = node;
+ descend();
+ scope = save_scope;
+ return true;
+ }
+ }
+ });
+ self.walk(tw);
+ // pass 2: for every used symbol we need to walk its
+ // initialization code to figure out if it uses other
+ // symbols (that may not be in_use).
+ for (var i = 0; i < in_use.length; ++i) {
+ in_use[i].orig.forEach(function(decl){
+ // undeclared globals will be instanceof AST_SymbolRef
+ var init = initializations.get(decl.name);
+ if (init) init.forEach(function(init){
+ var tw = new TreeWalker(function(node){
+ if (node instanceof AST_SymbolRef) {
+ push_uniq(in_use, node.definition());
+ }
+ });
+ init.walk(tw);
+ });
+ });
+ }
+ // pass 3: we should drop declarations not in_use
+ var tt = new TreeTransformer(
+ function before(node, descend, in_list) {
+ if (node instanceof AST_Lambda && !(node instanceof AST_Accessor)) {
+ for (var a = node.argnames, i = a.length; --i >= 0;) {
+ var sym = a[i];
+ if (sym.unreferenced()) {
+ a.pop();
+ compressor.warn("Dropping unused function argument {name} [{file}:{line},{col}]", {
+ name : sym.name,
+ file : sym.start.file,
+ line : sym.start.line,
+ col : sym.start.col
+ });
+ }
+ else break;
+ }
+ }
+ if (node instanceof AST_Defun && node !== self) {
+ if (!member(node.name.definition(), in_use)) {
+ compressor.warn("Dropping unused function {name} [{file}:{line},{col}]", {
+ name : node.name.name,
+ file : node.name.start.file,
+ line : node.name.start.line,
+ col : node.name.start.col
+ });
+ return make_node(AST_EmptyStatement, node);
+ }
+ return node;
+ }
+ if (node instanceof AST_Definitions && !(tt.parent() instanceof AST_ForIn)) {
+ var def = node.definitions.filter(function(def){
+ if (member(def.name.definition(), in_use)) return true;
+ var w = {
+ name : def.name.name,
+ file : def.name.start.file,
+ line : def.name.start.line,
+ col : def.name.start.col
+ };
+ if (def.value && def.value.has_side_effects(compressor)) {
+ def._unused_side_effects = true;
+ compressor.warn("Side effects in initialization of unused variable {name} [{file}:{line},{col}]", w);
+ return true;
+ }
+ compressor.warn("Dropping unused variable {name} [{file}:{line},{col}]", w);
+ return false;
+ });
+ // place uninitialized names at the start
+ def = mergeSort(def, function(a, b){
+ if (!a.value && b.value) return -1;
+ if (!b.value && a.value) return 1;
+ return 0;
+ });
+ // for unused names whose initialization has
+ // side effects, we can cascade the init. code
+ // into the next one, or next statement.
+ var side_effects = [];
+ for (var i = 0; i < def.length;) {
+ var x = def[i];
+ if (x._unused_side_effects) {
+ side_effects.push(x.value);
+ def.splice(i, 1);
+ } else {
+ if (side_effects.length > 0) {
+ side_effects.push(x.value);
+ x.value = AST_Seq.from_array(side_effects);
+ side_effects = [];
+ }
+ ++i;
+ }
+ }
+ if (side_effects.length > 0) {
+ side_effects = make_node(AST_BlockStatement, node, {
+ body: [ make_node(AST_SimpleStatement, node, {
+ body: AST_Seq.from_array(side_effects)
+ }) ]
+ });
+ } else {
+ side_effects = null;
+ }
+ if (def.length == 0 && !side_effects) {
+ return make_node(AST_EmptyStatement, node);
+ }
+ if (def.length == 0) {
+ return side_effects;
+ }
+ node.definitions = def;
+ if (side_effects) {
+ side_effects.body.unshift(node);
+ node = side_effects;
+ }
+ return node;
+ }
+ if (node instanceof AST_For) {
+ descend(node, this);
+
+ if (node.init instanceof AST_BlockStatement) {
+ // certain combination of unused name + side effect leads to:
+ // https://github.com/mishoo/UglifyJS2/issues/44
+ // that's an invalid AST.
+ // We fix it at this stage by moving the `var` outside the `for`.
+
+ var body = node.init.body.slice(0, -1);
+ node.init = node.init.body.slice(-1)[0].body;
+ body.push(node);
+
+ return in_list ? MAP.splice(body) : make_node(AST_BlockStatement, node, {
+ body: body
+ });
+ }
+ }
+ if (node instanceof AST_Scope && node !== self)
+ return node;
+ }
+ );
+ self.transform(tt);
+ }
+ });
+
+ AST_Scope.DEFMETHOD("hoist_declarations", function(compressor){
+ var hoist_funs = compressor.option("hoist_funs");
+ var hoist_vars = compressor.option("hoist_vars");
+ var self = this;
+ if (hoist_funs || hoist_vars) {
+ var dirs = [];
+ var hoisted = [];
+ var vars = new Dictionary(), vars_found = 0, var_decl = 0;
+ // let's count var_decl first, we seem to waste a lot of
+ // space if we hoist `var` when there's only one.
+ self.walk(new TreeWalker(function(node){
+ if (node instanceof AST_Scope && node !== self)
+ return true;
+ if (node instanceof AST_Var) {
+ ++var_decl;
+ return true;
+ }
+ }));
+ hoist_vars = hoist_vars && var_decl > 1;
+ var tt = new TreeTransformer(
+ function before(node) {
+ if (node !== self) {
+ if (node instanceof AST_Directive) {
+ dirs.push(node);
+ return make_node(AST_EmptyStatement, node);
+ }
+ if (node instanceof AST_Defun && hoist_funs) {
+ hoisted.push(node);
+ return make_node(AST_EmptyStatement, node);
+ }
+ if (node instanceof AST_Var && hoist_vars) {
+ node.definitions.forEach(function(def){
+ vars.set(def.name.name, def);
+ ++vars_found;
+ });
+ var seq = node.to_assignments();
+ var p = tt.parent();
+ if (p instanceof AST_ForIn && p.init === node) {
+ if (seq == null) return node.definitions[0].name;
+ return seq;
+ }
+ if (p instanceof AST_For && p.init === node) {
+ return seq;
+ }
+ if (!seq) return make_node(AST_EmptyStatement, node);
+ return make_node(AST_SimpleStatement, node, {
+ body: seq
+ });
+ }
+ if (node instanceof AST_Scope)
+ return node; // to avoid descending in nested scopes
+ }
+ }
+ );
+ self = self.transform(tt);
+ if (vars_found > 0) {
+ // collect only vars which don't show up in self's arguments list
+ var defs = [];
+ vars.each(function(def, name){
+ if (self instanceof AST_Lambda
+ && find_if(function(x){ return x.name == def.name.name },
+ self.argnames)) {
+ vars.del(name);
+ } else {
+ def = def.clone();
+ def.value = null;
+ defs.push(def);
+ vars.set(name, def);
+ }
+ });
+ if (defs.length > 0) {
+ // try to merge in assignments
+ for (var i = 0; i < self.body.length;) {
+ if (self.body[i] instanceof AST_SimpleStatement) {
+ var expr = self.body[i].body, sym, assign;
+ if (expr instanceof AST_Assign
+ && expr.operator == "="
+ && (sym = expr.left) instanceof AST_Symbol
+ && vars.has(sym.name))
+ {
+ var def = vars.get(sym.name);
+ if (def.value) break;
+ def.value = expr.right;
+ remove(defs, def);
+ defs.push(def);
+ self.body.splice(i, 1);
+ continue;
+ }
+ if (expr instanceof AST_Seq
+ && (assign = expr.car) instanceof AST_Assign
+ && assign.operator == "="
+ && (sym = assign.left) instanceof AST_Symbol
+ && vars.has(sym.name))
+ {
+ var def = vars.get(sym.name);
+ if (def.value) break;
+ def.value = assign.right;
+ remove(defs, def);
+ defs.push(def);
+ self.body[i].body = expr.cdr;
+ continue;
+ }
+ }
+ if (self.body[i] instanceof AST_EmptyStatement) {
+ self.body.splice(i, 1);
+ continue;
+ }
+ if (self.body[i] instanceof AST_BlockStatement) {
+ var tmp = [ i, 1 ].concat(self.body[i].body);
+ self.body.splice.apply(self.body, tmp);
+ continue;
+ }
+ break;
+ }
+ defs = make_node(AST_Var, self, {
+ definitions: defs
+ });
+ hoisted.push(defs);
+ };
+ }
+ self.body = dirs.concat(hoisted, self.body);
+ }
+ return self;
+ });
+
+ OPT(AST_SimpleStatement, function(self, compressor){
+ if (compressor.option("side_effects")) {
+ if (!self.body.has_side_effects(compressor)) {
+ compressor.warn("Dropping side-effect-free statement [{file}:{line},{col}]", self.start);
+ return make_node(AST_EmptyStatement, self);
+ }
+ }
+ return self;
+ });
+
+ OPT(AST_DWLoop, function(self, compressor){
+ var cond = self.condition.evaluate(compressor);
+ self.condition = cond[0];
+ if (!compressor.option("loops")) return self;
+ if (cond.length > 1) {
+ if (cond[1]) {
+ return make_node(AST_For, self, {
+ body: self.body
+ });
+ } else if (self instanceof AST_While) {
+ if (compressor.option("dead_code")) {
+ var a = [];
+ extract_declarations_from_unreachable_code(compressor, self.body, a);
+ return make_node(AST_BlockStatement, self, { body: a });
+ }
+ }
+ }
+ return self;
+ });
+
+ function if_break_in_loop(self, compressor) {
+ function drop_it(rest) {
+ rest = as_statement_array(rest);
+ if (self.body instanceof AST_BlockStatement) {
+ self.body = self.body.clone();
+ self.body.body = rest.concat(self.body.body.slice(1));
+ self.body = self.body.transform(compressor);
+ } else {
+ self.body = make_node(AST_BlockStatement, self.body, {
+ body: rest
+ }).transform(compressor);
+ }
+ if_break_in_loop(self, compressor);
+ }
+ var first = self.body instanceof AST_BlockStatement ? self.body.body[0] : self.body;
+ if (first instanceof AST_If) {
+ if (first.body instanceof AST_Break
+ && compressor.loopcontrol_target(first.body.label) === self) {
+ if (self.condition) {
+ self.condition = make_node(AST_Binary, self.condition, {
+ left: self.condition,
+ operator: "&&",
+ right: first.condition.negate(compressor),
+ });
+ } else {
+ self.condition = first.condition.negate(compressor);
+ }
+ drop_it(first.alternative);
+ }
+ else if (first.alternative instanceof AST_Break
+ && compressor.loopcontrol_target(first.alternative.label) === self) {
+ if (self.condition) {
+ self.condition = make_node(AST_Binary, self.condition, {
+ left: self.condition,
+ operator: "&&",
+ right: first.condition,
+ });
+ } else {
+ self.condition = first.condition;
+ }
+ drop_it(first.body);
+ }
+ }
+ };
+
+ OPT(AST_While, function(self, compressor) {
+ if (!compressor.option("loops")) return self;
+ self = AST_DWLoop.prototype.optimize.call(self, compressor);
+ if (self instanceof AST_While) {
+ if_break_in_loop(self, compressor);
+ self = make_node(AST_For, self, self).transform(compressor);
+ }
+ return self;
+ });
+
+ OPT(AST_For, function(self, compressor){
+ var cond = self.condition;
+ if (cond) {
+ cond = cond.evaluate(compressor);
+ self.condition = cond[0];
+ }
+ if (!compressor.option("loops")) return self;
+ if (cond) {
+ if (cond.length > 1 && !cond[1]) {
+ if (compressor.option("dead_code")) {
+ var a = [];
+ if (self.init instanceof AST_Statement) {
+ a.push(self.init);
+ }
+ else if (self.init) {
+ a.push(make_node(AST_SimpleStatement, self.init, {
+ body: self.init
+ }));
+ }
+ extract_declarations_from_unreachable_code(compressor, self.body, a);
+ return make_node(AST_BlockStatement, self, { body: a });
+ }
+ }
+ }
+ if_break_in_loop(self, compressor);
+ return self;
+ });
+
+ OPT(AST_If, function(self, compressor){
+ if (!compressor.option("conditionals")) return self;
+ // if condition can be statically determined, warn and drop
+ // one of the blocks. note, statically determined implies
+ // “has no side effects”; also it doesn't work for cases like
+ // `x && true`, though it probably should.
+ var cond = self.condition.evaluate(compressor);
+ self.condition = cond[0];
+ if (cond.length > 1) {
+ if (cond[1]) {
+ compressor.warn("Condition always true [{file}:{line},{col}]", self.condition.start);
+ if (compressor.option("dead_code")) {
+ var a = [];
+ if (self.alternative) {
+ extract_declarations_from_unreachable_code(compressor, self.alternative, a);
+ }
+ a.push(self.body);
+ return make_node(AST_BlockStatement, self, { body: a }).transform(compressor);
+ }
+ } else {
+ compressor.warn("Condition always false [{file}:{line},{col}]", self.condition.start);
+ if (compressor.option("dead_code")) {
+ var a = [];
+ extract_declarations_from_unreachable_code(compressor, self.body, a);
+ if (self.alternative) a.push(self.alternative);
+ return make_node(AST_BlockStatement, self, { body: a }).transform(compressor);
+ }
+ }
+ }
+ if (is_empty(self.alternative)) self.alternative = null;
+ var negated = self.condition.negate(compressor);
+ var negated_is_best = best_of(self.condition, negated) === negated;
+ if (self.alternative && negated_is_best) {
+ negated_is_best = false; // because we already do the switch here.
+ self.condition = negated;
+ var tmp = self.body;
+ self.body = self.alternative || make_node(AST_EmptyStatement);
+ self.alternative = tmp;
+ }
+ if (is_empty(self.body) && is_empty(self.alternative)) {
+ return make_node(AST_SimpleStatement, self.condition, {
+ body: self.condition
+ }).transform(compressor);
+ }
+ if (self.body instanceof AST_SimpleStatement
+ && self.alternative instanceof AST_SimpleStatement) {
+ return make_node(AST_SimpleStatement, self, {
+ body: make_node(AST_Conditional, self, {
+ condition : self.condition,
+ consequent : self.body.body,
+ alternative : self.alternative.body
+ })
+ }).transform(compressor);
+ }
+ if (is_empty(self.alternative) && self.body instanceof AST_SimpleStatement) {
+ if (negated_is_best) return make_node(AST_SimpleStatement, self, {
+ body: make_node(AST_Binary, self, {
+ operator : "||",
+ left : negated,
+ right : self.body.body
+ })
+ }).transform(compressor);
+ return make_node(AST_SimpleStatement, self, {
+ body: make_node(AST_Binary, self, {
+ operator : "&&",
+ left : self.condition,
+ right : self.body.body
+ })
+ }).transform(compressor);
+ }
+ if (self.body instanceof AST_EmptyStatement
+ && self.alternative
+ && self.alternative instanceof AST_SimpleStatement) {
+ return make_node(AST_SimpleStatement, self, {
+ body: make_node(AST_Binary, self, {
+ operator : "||",
+ left : self.condition,
+ right : self.alternative.body
+ })
+ }).transform(compressor);
+ }
+ if (self.body instanceof AST_Exit
+ && self.alternative instanceof AST_Exit
+ && self.body.TYPE == self.alternative.TYPE) {
+ return make_node(self.body.CTOR, self, {
+ value: make_node(AST_Conditional, self, {
+ condition : self.condition,
+ consequent : self.body.value || make_node(AST_Undefined, self.body).optimize(compressor),
+ alternative : self.alternative.value || make_node(AST_Undefined, self.alternative).optimize(compressor)
+ })
+ }).transform(compressor);
+ }
+ if (self.body instanceof AST_If
+ && !self.body.alternative
+ && !self.alternative) {
+ self.condition = make_node(AST_Binary, self.condition, {
+ operator: "&&",
+ left: self.condition,
+ right: self.body.condition
+ }).transform(compressor);
+ self.body = self.body.body;
+ }
+ if (aborts(self.body)) {
+ if (self.alternative) {
+ var alt = self.alternative;
+ self.alternative = null;
+ return make_node(AST_BlockStatement, self, {
+ body: [ self, alt ]
+ }).transform(compressor);
+ }
+ }
+ if (aborts(self.alternative)) {
+ var body = self.body;
+ self.body = self.alternative;
+ self.condition = negated_is_best ? negated : self.condition.negate(compressor);
+ self.alternative = null;
+ return make_node(AST_BlockStatement, self, {
+ body: [ self, body ]
+ }).transform(compressor);
+ }
+ return self;
+ });
+
+ OPT(AST_Switch, function(self, compressor){
+ if (self.body.length == 0 && compressor.option("conditionals")) {
+ return make_node(AST_SimpleStatement, self, {
+ body: self.expression
+ }).transform(compressor);
+ }
+ for(;;) {
+ var last_branch = self.body[self.body.length - 1];
+ if (last_branch) {
+ var stat = last_branch.body[last_branch.body.length - 1]; // last statement
+ if (stat instanceof AST_Break && loop_body(compressor.loopcontrol_target(stat.label)) === self)
+ last_branch.body.pop();
+ if (last_branch instanceof AST_Default && last_branch.body.length == 0) {
+ self.body.pop();
+ continue;
+ }
+ }
+ break;
+ }
+ var exp = self.expression.evaluate(compressor);
+ out: if (exp.length == 2) try {
+ // constant expression
+ self.expression = exp[0];
+ if (!compressor.option("dead_code")) break out;
+ var value = exp[1];
+ var in_if = false;
+ var in_block = false;
+ var started = false;
+ var stopped = false;
+ var ruined = false;
+ var tt = new TreeTransformer(function(node, descend, in_list){
+ if (node instanceof AST_Lambda || node instanceof AST_SimpleStatement) {
+ // no need to descend these node types
+ return node;
+ }
+ else if (node instanceof AST_Switch && node === self) {
+ node = node.clone();
+ descend(node, this);
+ return ruined ? node : make_node(AST_BlockStatement, node, {
+ body: node.body.reduce(function(a, branch){
+ return a.concat(branch.body);
+ }, [])
+ }).transform(compressor);
+ }
+ else if (node instanceof AST_If || node instanceof AST_Try) {
+ var save = in_if;
+ in_if = !in_block;
+ descend(node, this);
+ in_if = save;
+ return node;
+ }
+ else if (node instanceof AST_StatementWithBody || node instanceof AST_Switch) {
+ var save = in_block;
+ in_block = true;
+ descend(node, this);
+ in_block = save;
+ return node;
+ }
+ else if (node instanceof AST_Break && this.loopcontrol_target(node.label) === self) {
+ if (in_if) {
+ ruined = true;
+ return node;
+ }
+ if (in_block) return node;
+ stopped = true;
+ return in_list ? MAP.skip : make_node(AST_EmptyStatement, node);
+ }
+ else if (node instanceof AST_SwitchBranch && this.parent() === self) {
+ if (stopped) return MAP.skip;
+ if (node instanceof AST_Case) {
+ var exp = node.expression.evaluate(compressor);
+ if (exp.length < 2) {
+ // got a case with non-constant expression, baling out
+ throw self;
+ }
+ if (exp[1] === value || started) {
+ started = true;
+ if (aborts(node)) stopped = true;
+ descend(node, this);
+ return node;
+ }
+ return MAP.skip;
+ }
+ descend(node, this);
+ return node;
+ }
+ });
+ tt.stack = compressor.stack.slice(); // so that's able to see parent nodes
+ self = self.transform(tt);
+ } catch(ex) {
+ if (ex !== self) throw ex;
+ }
+ return self;
+ });
+
+ OPT(AST_Case, function(self, compressor){
+ self.body = tighten_body(self.body, compressor);
+ return self;
+ });
+
+ OPT(AST_Try, function(self, compressor){
+ self.body = tighten_body(self.body, compressor);
+ return self;
+ });
+
+ AST_Definitions.DEFMETHOD("remove_initializers", function(){
+ this.definitions.forEach(function(def){ def.value = null });
+ });
+
+ AST_Definitions.DEFMETHOD("to_assignments", function(){
+ var assignments = this.definitions.reduce(function(a, def){
+ if (def.value) {
+ var name = make_node(AST_SymbolRef, def.name, def.name);
+ a.push(make_node(AST_Assign, def, {
+ operator : "=",
+ left : name,
+ right : def.value
+ }));
+ }
+ return a;
+ }, []);
+ if (assignments.length == 0) return null;
+ return AST_Seq.from_array(assignments);
+ });
+
+ OPT(AST_Definitions, function(self, compressor){
+ if (self.definitions.length == 0)
+ return make_node(AST_EmptyStatement, self);
+ return self;
+ });
+
+ OPT(AST_Function, function(self, compressor){
+ self = AST_Lambda.prototype.optimize.call(self, compressor);
+ if (compressor.option("unused")) {
+ if (self.name && self.name.unreferenced()) {
+ self.name = null;
+ }
+ }
+ return self;
+ });
+
+ OPT(AST_Call, function(self, compressor){
+ if (compressor.option("unsafe")) {
+ var exp = self.expression;
+ if (exp instanceof AST_SymbolRef && exp.undeclared()) {
+ switch (exp.name) {
+ case "Array":
+ if (self.args.length != 1) {
+ return make_node(AST_Array, self, {
+ elements: self.args
+ }).transform(compressor);
+ }
+ break;
+ case "Object":
+ if (self.args.length == 0) {
+ return make_node(AST_Object, self, {
+ properties: []
+ });
+ }
+ break;
+ case "String":
+ if (self.args.length == 0) return make_node(AST_String, self, {
+ value: ""
+ });
+ if (self.args.length <= 1) return make_node(AST_Binary, self, {
+ left: self.args[0],
+ operator: "+",
+ right: make_node(AST_String, self, { value: "" })
+ }).transform(compressor);
+ break;
+ case "Number":
+ if (self.args.length == 0) return make_node(AST_Number, self, {
+ value: 0
+ });
+ if (self.args.length == 1) return make_node(AST_UnaryPrefix, self, {
+ expression: self.args[0],
+ operator: "+"
+ }).transform(compressor);
+ case "Boolean":
+ if (self.args.length == 0) return make_node(AST_False, self);
+ if (self.args.length == 1) return make_node(AST_UnaryPrefix, self, {
+ expression: make_node(AST_UnaryPrefix, null, {
+ expression: self.args[0],
+ operator: "!"
+ }),
+ operator: "!"
+ }).transform(compressor);
+ break;
+ case "Function":
+ if (all(self.args, function(x){ return x instanceof AST_String })) {
+ // quite a corner-case, but we can handle it:
+ // https://github.com/mishoo/UglifyJS2/issues/203
+ // if the code argument is a constant, then we can minify it.
+ try {
+ var code = "(function(" + self.args.slice(0, -1).map(function(arg){
+ return arg.value;
+ }).join(",") + "){" + self.args[self.args.length - 1].value + "})()";
+ var ast = parse(code);
+ ast.figure_out_scope({ screw_ie8: compressor.option("screw_ie8") });
+ var comp = new Compressor(compressor.options);
+ ast = ast.transform(comp);
+ ast.figure_out_scope({ screw_ie8: compressor.option("screw_ie8") });
+ ast.mangle_names();
+ var fun;
+ try {
+ ast.walk(new TreeWalker(function(node){
+ if (node instanceof AST_Lambda) {
+ fun = node;
+ throw ast;
+ }
+ }));
+ } catch(ex) {
+ if (ex !== ast) throw ex;
+ };
+ var args = fun.argnames.map(function(arg, i){
+ return make_node(AST_String, self.args[i], {
+ value: arg.print_to_string()
+ });
+ });
+ var code = OutputStream();
+ AST_BlockStatement.prototype._codegen.call(fun, fun, code);
+ code = code.toString().replace(/^\{|\}$/g, "");
+ args.push(make_node(AST_String, self.args[self.args.length - 1], {
+ value: code
+ }));
+ self.args = args;
+ return self;
+ } catch(ex) {
+ if (ex instanceof JS_Parse_Error) {
+ compressor.warn("Error parsing code passed to new Function [{file}:{line},{col}]", self.args[self.args.length - 1].start);
+ compressor.warn(ex.toString());
+ } else {
+ console.log(ex);
+ throw ex;
+ }
+ }
+ }
+ break;
+ }
+ }
+ else if (exp instanceof AST_Dot && exp.property == "toString" && self.args.length == 0) {
+ return make_node(AST_Binary, self, {
+ left: make_node(AST_String, self, { value: "" }),
+ operator: "+",
+ right: exp.expression
+ }).transform(compressor);
+ }
+ else if (exp instanceof AST_Dot && exp.expression instanceof AST_Array && exp.property == "join") EXIT: {
+ var separator = self.args.length == 0 ? "," : self.args[0].evaluate(compressor)[1];
+ if (separator == null) break EXIT; // not a constant
+ var elements = exp.expression.elements.reduce(function(a, el){
+ el = el.evaluate(compressor);
+ if (a.length == 0 || el.length == 1) {
+ a.push(el);
+ } else {
+ var last = a[a.length - 1];
+ if (last.length == 2) {
+ // it's a constant
+ var val = "" + last[1] + separator + el[1];
+ a[a.length - 1] = [ make_node_from_constant(compressor, val, last[0]), val ];
+ } else {
+ a.push(el);
+ }
+ }
+ return a;
+ }, []);
+ if (elements.length == 0) return make_node(AST_String, self, { value: "" });
+ if (elements.length == 1) return elements[0][0];
+ if (separator == "") {
+ var first;
+ if (elements[0][0] instanceof AST_String
+ || elements[1][0] instanceof AST_String) {
+ first = elements.shift()[0];
+ } else {
+ first = make_node(AST_String, self, { value: "" });
+ }
+ return elements.reduce(function(prev, el){
+ return make_node(AST_Binary, el[0], {
+ operator : "+",
+ left : prev,
+ right : el[0],
+ });
+ }, first).transform(compressor);
+ }
+ // need this awkward cloning to not affect original element
+ // best_of will decide which one to get through.
+ var node = self.clone();
+ node.expression = node.expression.clone();
+ node.expression.expression = node.expression.expression.clone();
+ node.expression.expression.elements = elements.map(function(el){
+ return el[0];
+ });
+ return best_of(self, node);
+ }
+ }
+ if (compressor.option("side_effects")) {
+ if (self.expression instanceof AST_Function
+ && self.args.length == 0
+ && !AST_Block.prototype.has_side_effects.call(self.expression, compressor)) {
+ return make_node(AST_Undefined, self).transform(compressor);
+ }
+ }
+ if (compressor.option("drop_console")) {
+ if (self.expression instanceof AST_PropAccess &&
+ self.expression.expression instanceof AST_SymbolRef &&
+ self.expression.expression.name == "console" &&
+ self.expression.expression.undeclared()) {
+ return make_node(AST_Undefined, self).transform(compressor);
+ }
+ }
+ return self.evaluate(compressor)[0];
+ });
+
+ OPT(AST_New, function(self, compressor){
+ if (compressor.option("unsafe")) {
+ var exp = self.expression;
+ if (exp instanceof AST_SymbolRef && exp.undeclared()) {
+ switch (exp.name) {
+ case "Object":
+ case "RegExp":
+ case "Function":
+ case "Error":
+ case "Array":
+ return make_node(AST_Call, self, self).transform(compressor);
+ }
+ }
+ }
+ return self;
+ });
+
+ OPT(AST_Seq, function(self, compressor){
+ if (!compressor.option("side_effects"))
+ return self;
+ if (!self.car.has_side_effects(compressor)) {
+ // we shouldn't compress (1,eval)(something) to
+ // eval(something) because that changes the meaning of
+ // eval (becomes lexical instead of global).
+ var p;
+ if (!(self.cdr instanceof AST_SymbolRef
+ && self.cdr.name == "eval"
+ && self.cdr.undeclared()
+ && (p = compressor.parent()) instanceof AST_Call
+ && p.expression === self)) {
+ return self.cdr;
+ }
+ }
+ if (compressor.option("cascade")) {
+ if (self.car instanceof AST_Assign
+ && !self.car.left.has_side_effects(compressor)) {
+ if (self.car.left.equivalent_to(self.cdr)) {
+ return self.car;
+ }
+ if (self.cdr instanceof AST_Call
+ && self.cdr.expression.equivalent_to(self.car.left)) {
+ self.cdr.expression = self.car;
+ return self.cdr;
+ }
+ }
+ if (!self.car.has_side_effects(compressor)
+ && !self.cdr.has_side_effects(compressor)
+ && self.car.equivalent_to(self.cdr)) {
+ return self.car;
+ }
+ }
+ if (self.cdr instanceof AST_UnaryPrefix
+ && self.cdr.operator == "void"
+ && !self.cdr.expression.has_side_effects(compressor)) {
+ self.cdr.operator = self.car;
+ return self.cdr;
+ }
+ if (self.cdr instanceof AST_Undefined) {
+ return make_node(AST_UnaryPrefix, self, {
+ operator : "void",
+ expression : self.car
+ });
+ }
+ return self;
+ });
+
+ AST_Unary.DEFMETHOD("lift_sequences", function(compressor){
+ if (compressor.option("sequences")) {
+ if (this.expression instanceof AST_Seq) {
+ var seq = this.expression;
+ var x = seq.to_array();
+ this.expression = x.pop();
+ x.push(this);
+ seq = AST_Seq.from_array(x).transform(compressor);
+ return seq;
+ }
+ }
+ return this;
+ });
+
+ OPT(AST_UnaryPostfix, function(self, compressor){
+ return self.lift_sequences(compressor);
+ });
+
+ OPT(AST_UnaryPrefix, function(self, compressor){
+ self = self.lift_sequences(compressor);
+ var e = self.expression;
+ if (compressor.option("booleans") && compressor.in_boolean_context()) {
+ switch (self.operator) {
+ case "!":
+ if (e instanceof AST_UnaryPrefix && e.operator == "!") {
+ // !!foo ==> foo, if we're in boolean context
+ return e.expression;
+ }
+ break;
+ case "typeof":
+ // typeof always returns a non-empty string, thus it's
+ // always true in booleans
+ compressor.warn("Boolean expression always true [{file}:{line},{col}]", self.start);
+ return make_node(AST_True, self);
+ }
+ if (e instanceof AST_Binary && self.operator == "!") {
+ self = best_of(self, e.negate(compressor));
+ }
+ }
+ return self.evaluate(compressor)[0];
+ });
+
+ function has_side_effects_or_prop_access(node, compressor) {
+ var save_pure_getters = compressor.option("pure_getters");
+ compressor.options.pure_getters = false;
+ var ret = node.has_side_effects(compressor);
+ compressor.options.pure_getters = save_pure_getters;
+ return ret;
+ }
+
+ AST_Binary.DEFMETHOD("lift_sequences", function(compressor){
+ if (compressor.option("sequences")) {
+ if (this.left instanceof AST_Seq) {
+ var seq = this.left;
+ var x = seq.to_array();
+ this.left = x.pop();
+ x.push(this);
+ seq = AST_Seq.from_array(x).transform(compressor);
+ return seq;
+ }
+ if (this.right instanceof AST_Seq
+ && this instanceof AST_Assign
+ && !has_side_effects_or_prop_access(this.left, compressor)) {
+ var seq = this.right;
+ var x = seq.to_array();
+ this.right = x.pop();
+ x.push(this);
+ seq = AST_Seq.from_array(x).transform(compressor);
+ return seq;
+ }
+ }
+ return this;
+ });
+
+ var commutativeOperators = makePredicate("== === != !== * & | ^");
+
+ OPT(AST_Binary, function(self, compressor){
+ var reverse = compressor.has_directive("use asm") ? noop
+ : function(op, force) {
+ if (force || !(self.left.has_side_effects(compressor) || self.right.has_side_effects(compressor))) {
+ if (op) self.operator = op;
+ var tmp = self.left;
+ self.left = self.right;
+ self.right = tmp;
+ }
+ };
+ if (commutativeOperators(self.operator)) {
+ if (self.right instanceof AST_Constant
+ && !(self.left instanceof AST_Constant)) {
+ // if right is a constant, whatever side effects the
+ // left side might have could not influence the
+ // result. hence, force switch.
+
+ if (!(self.left instanceof AST_Binary
+ && PRECEDENCE[self.left.operator] >= PRECEDENCE[self.operator])) {
+ reverse(null, true);
+ }
+ }
+ if (/^[!=]==?$/.test(self.operator)) {
+ if (self.left instanceof AST_SymbolRef && self.right instanceof AST_Conditional) {
+ if (self.right.consequent instanceof AST_SymbolRef
+ && self.right.consequent.definition() === self.left.definition()) {
+ if (/^==/.test(self.operator)) return self.right.condition;
+ if (/^!=/.test(self.operator)) return self.right.condition.negate(compressor);
+ }
+ if (self.right.alternative instanceof AST_SymbolRef
+ && self.right.alternative.definition() === self.left.definition()) {
+ if (/^==/.test(self.operator)) return self.right.condition.negate(compressor);
+ if (/^!=/.test(self.operator)) return self.right.condition;
+ }
+ }
+ if (self.right instanceof AST_SymbolRef && self.left instanceof AST_Conditional) {
+ if (self.left.consequent instanceof AST_SymbolRef
+ && self.left.consequent.definition() === self.right.definition()) {
+ if (/^==/.test(self.operator)) return self.left.condition;
+ if (/^!=/.test(self.operator)) return self.left.condition.negate(compressor);
+ }
+ if (self.left.alternative instanceof AST_SymbolRef
+ && self.left.alternative.definition() === self.right.definition()) {
+ if (/^==/.test(self.operator)) return self.left.condition.negate(compressor);
+ if (/^!=/.test(self.operator)) return self.left.condition;
+ }
+ }
+ }
+ }
+ self = self.lift_sequences(compressor);
+ if (compressor.option("comparisons")) switch (self.operator) {
+ case "===":
+ case "!==":
+ if ((self.left.is_string(compressor) && self.right.is_string(compressor)) ||
+ (self.left.is_boolean() && self.right.is_boolean())) {
+ self.operator = self.operator.substr(0, 2);
+ }
+ // XXX: intentionally falling down to the next case
+ case "==":
+ case "!=":
+ if (self.left instanceof AST_String
+ && self.left.value == "undefined"
+ && self.right instanceof AST_UnaryPrefix
+ && self.right.operator == "typeof"
+ && compressor.option("unsafe")) {
+ if (!(self.right.expression instanceof AST_SymbolRef)
+ || !self.right.expression.undeclared()) {
+ self.right = self.right.expression;
+ self.left = make_node(AST_Undefined, self.left).optimize(compressor);
+ if (self.operator.length == 2) self.operator += "=";
+ }
+ }
+ break;
+ }
+ if (compressor.option("booleans") && compressor.in_boolean_context()) switch (self.operator) {
+ case "&&":
+ var ll = self.left.evaluate(compressor);
+ var rr = self.right.evaluate(compressor);
+ if ((ll.length > 1 && !ll[1]) || (rr.length > 1 && !rr[1])) {
+ compressor.warn("Boolean && always false [{file}:{line},{col}]", self.start);
+ return make_node(AST_False, self);
+ }
+ if (ll.length > 1 && ll[1]) {
+ return rr[0];
+ }
+ if (rr.length > 1 && rr[1]) {
+ return ll[0];
+ }
+ break;
+ case "||":
+ var ll = self.left.evaluate(compressor);
+ var rr = self.right.evaluate(compressor);
+ if ((ll.length > 1 && ll[1]) || (rr.length > 1 && rr[1])) {
+ compressor.warn("Boolean || always true [{file}:{line},{col}]", self.start);
+ return make_node(AST_True, self);
+ }
+ if (ll.length > 1 && !ll[1]) {
+ return rr[0];
+ }
+ if (rr.length > 1 && !rr[1]) {
+ return ll[0];
+ }
+ break;
+ case "+":
+ var ll = self.left.evaluate(compressor);
+ var rr = self.right.evaluate(compressor);
+ if ((ll.length > 1 && ll[0] instanceof AST_String && ll[1]) ||
+ (rr.length > 1 && rr[0] instanceof AST_String && rr[1])) {
+ compressor.warn("+ in boolean context always true [{file}:{line},{col}]", self.start);
+ return make_node(AST_True, self);
+ }
+ break;
+ }
+ if (compressor.option("comparisons")) {
+ if (!(compressor.parent() instanceof AST_Binary)
+ || compressor.parent() instanceof AST_Assign) {
+ var negated = make_node(AST_UnaryPrefix, self, {
+ operator: "!",
+ expression: self.negate(compressor)
+ });
+ self = best_of(self, negated);
+ }
+ switch (self.operator) {
+ case "<": reverse(">"); break;
+ case "<=": reverse(">="); break;
+ }
+ }
+ if (self.operator == "+" && self.right instanceof AST_String
+ && self.right.getValue() === "" && self.left instanceof AST_Binary
+ && self.left.operator == "+" && self.left.is_string(compressor)) {
+ return self.left;
+ }
+ if (compressor.option("evaluate")) {
+ if (self.operator == "+") {
+ if (self.left instanceof AST_Constant
+ && self.right instanceof AST_Binary
+ && self.right.operator == "+"
+ && self.right.left instanceof AST_Constant
+ && self.right.is_string(compressor)) {
+ self = make_node(AST_Binary, self, {
+ operator: "+",
+ left: make_node(AST_String, null, {
+ value: "" + self.left.getValue() + self.right.left.getValue(),
+ start: self.left.start,
+ end: self.right.left.end
+ }),
+ right: self.right.right
+ });
+ }
+ if (self.right instanceof AST_Constant
+ && self.left instanceof AST_Binary
+ && self.left.operator == "+"
+ && self.left.right instanceof AST_Constant
+ && self.left.is_string(compressor)) {
+ self = make_node(AST_Binary, self, {
+ operator: "+",
+ left: self.left.left,
+ right: make_node(AST_String, null, {
+ value: "" + self.left.right.getValue() + self.right.getValue(),
+ start: self.left.right.start,
+ end: self.right.end
+ })
+ });
+ }
+ if (self.left instanceof AST_Binary
+ && self.left.operator == "+"
+ && self.left.is_string(compressor)
+ && self.left.right instanceof AST_Constant
+ && self.right instanceof AST_Binary
+ && self.right.operator == "+"
+ && self.right.left instanceof AST_Constant
+ && self.right.is_string(compressor)) {
+ self = make_node(AST_Binary, self, {
+ operator: "+",
+ left: make_node(AST_Binary, self.left, {
+ operator: "+",
+ left: self.left.left,
+ right: make_node(AST_String, null, {
+ value: "" + self.left.right.getValue() + self.right.left.getValue(),
+ start: self.left.right.start,
+ end: self.right.left.end
+ })
+ }),
+ right: self.right.right
+ });
+ }
+ }
+ }
+ // x * (y * z) ==> x * y * z
+ if (self.right instanceof AST_Binary
+ && self.right.operator == self.operator
+ && (self.operator == "*" || self.operator == "&&" || self.operator == "||"))
+ {
+ self.left = make_node(AST_Binary, self.left, {
+ operator : self.operator,
+ left : self.left,
+ right : self.right.left
+ });
+ self.right = self.right.right;
+ return self.transform(compressor);
+ }
+ return self.evaluate(compressor)[0];
+ });
+
+ OPT(AST_SymbolRef, function(self, compressor){
+ if (self.undeclared()) {
+ var defines = compressor.option("global_defs");
+ if (defines && defines.hasOwnProperty(self.name)) {
+ return make_node_from_constant(compressor, defines[self.name], self);
+ }
+ switch (self.name) {
+ case "undefined":
+ return make_node(AST_Undefined, self);
+ case "NaN":
+ return make_node(AST_NaN, self);
+ case "Infinity":
+ return make_node(AST_Infinity, self);
+ }
+ }
+ return self;
+ });
+
+ OPT(AST_Undefined, function(self, compressor){
+ if (compressor.option("unsafe")) {
+ var scope = compressor.find_parent(AST_Scope);
+ var undef = scope.find_variable("undefined");
+ if (undef) {
+ var ref = make_node(AST_SymbolRef, self, {
+ name : "undefined",
+ scope : scope,
+ thedef : undef
+ });
+ ref.reference();
+ return ref;
+ }
+ }
+ return self;
+ });
+
+ var ASSIGN_OPS = [ '+', '-', '/', '*', '%', '>>', '<<', '>>>', '|', '^', '&' ];
+ OPT(AST_Assign, function(self, compressor){
+ self = self.lift_sequences(compressor);
+ if (self.operator == "="
+ && self.left instanceof AST_SymbolRef
+ && self.right instanceof AST_Binary
+ && self.right.left instanceof AST_SymbolRef
+ && self.right.left.name == self.left.name
+ && member(self.right.operator, ASSIGN_OPS)) {
+ self.operator = self.right.operator + "=";
+ self.right = self.right.right;
+ }
+ return self;
+ });
+
+ OPT(AST_Conditional, function(self, compressor){
+ if (!compressor.option("conditionals")) return self;
+ if (self.condition instanceof AST_Seq) {
+ var car = self.condition.car;
+ self.condition = self.condition.cdr;
+ return AST_Seq.cons(car, self);
+ }
+ var cond = self.condition.evaluate(compressor);
+ if (cond.length > 1) {
+ if (cond[1]) {
+ compressor.warn("Condition always true [{file}:{line},{col}]", self.start);
+ return self.consequent;
+ } else {
+ compressor.warn("Condition always false [{file}:{line},{col}]", self.start);
+ return self.alternative;
+ }
+ }
+ var negated = cond[0].negate(compressor);
+ if (best_of(cond[0], negated) === negated) {
+ self = make_node(AST_Conditional, self, {
+ condition: negated,
+ consequent: self.alternative,
+ alternative: self.consequent
+ });
+ }
+ var consequent = self.consequent;
+ var alternative = self.alternative;
+ if (consequent instanceof AST_Assign
+ && alternative instanceof AST_Assign
+ && consequent.operator == alternative.operator
+ && consequent.left.equivalent_to(alternative.left)
+ ) {
+ /*
+ * Stuff like this:
+ * if (foo) exp = something; else exp = something_else;
+ * ==>
+ * exp = foo ? something : something_else;
+ */
+ return make_node(AST_Assign, self, {
+ operator: consequent.operator,
+ left: consequent.left,
+ right: make_node(AST_Conditional, self, {
+ condition: self.condition,
+ consequent: consequent.right,
+ alternative: alternative.right
+ })
+ });
+ }
+ if (consequent instanceof AST_Call
+ && alternative.TYPE === consequent.TYPE
+ && consequent.args.length == alternative.args.length
+ && consequent.expression.equivalent_to(alternative.expression)) {
+ if (consequent.args.length == 0) {
+ return make_node(AST_Seq, self, {
+ car: self.condition,
+ cdr: consequent
+ });
+ }
+ if (consequent.args.length == 1) {
+ consequent.args[0] = make_node(AST_Conditional, self, {
+ condition: self.condition,
+ consequent: consequent.args[0],
+ alternative: alternative.args[0]
+ });
+ return consequent;
+ }
+ }
+ return self;
+ });
+
+ OPT(AST_Boolean, function(self, compressor){
+ if (compressor.option("booleans")) {
+ var p = compressor.parent();
+ if (p instanceof AST_Binary && (p.operator == "=="
+ || p.operator == "!=")) {
+ compressor.warn("Non-strict equality against boolean: {operator} {value} [{file}:{line},{col}]", {
+ operator : p.operator,
+ value : self.value,
+ file : p.start.file,
+ line : p.start.line,
+ col : p.start.col,
+ });
+ return make_node(AST_Number, self, {
+ value: +self.value
+ });
+ }
+ return make_node(AST_UnaryPrefix, self, {
+ operator: "!",
+ expression: make_node(AST_Number, self, {
+ value: 1 - self.value
+ })
+ });
+ }
+ return self;
+ });
+
+ OPT(AST_Sub, function(self, compressor){
+ var prop = self.property;
+ if (prop instanceof AST_String && compressor.option("properties")) {
+ prop = prop.getValue();
+ if (RESERVED_WORDS(prop) ? compressor.option("screw_ie8") : is_identifier_string(prop)) {
+ return make_node(AST_Dot, self, {
+ expression : self.expression,
+ property : prop
+ });
+ }
+ var v = parseFloat(prop);
+ if (!isNaN(v) && v.toString() == prop) {
+ self.property = make_node(AST_Number, self.property, {
+ value: v
+ });
+ }
+ }
+ return self;
+ });
+
+ function literals_in_boolean_context(self, compressor) {
+ if (compressor.option("booleans") && compressor.in_boolean_context()) {
+ return make_node(AST_True, self);
+ }
+ return self;
+ };
+ OPT(AST_Array, literals_in_boolean_context);
+ OPT(AST_Object, literals_in_boolean_context);
+ OPT(AST_RegExp, literals_in_boolean_context);
+
+})();
+
+/***********************************************************************
+
+ A JavaScript tokenizer / parser / beautifier / compressor.
+ https://github.com/mishoo/UglifyJS2
+
+ -------------------------------- (C) ---------------------------------
+
+ Author: Mihai Bazon
+ <mihai.bazon@gmail.com>
+ http://mihai.bazon.net/blog
+
+ Distributed under the BSD license:
+
+ Copyright 2012 (c) Mihai Bazon <mihai.bazon@gmail.com>
+
+ Redistribution and use in source and binary forms, with or without
+ modification, are permitted provided that the following conditions
+ are met:
+
+ * Redistributions of source code must retain the above
+ copyright notice, this list of conditions and the following
+ disclaimer.
+
+ * Redistributions in binary form must reproduce the above
+ copyright notice, this list of conditions and the following
+ disclaimer in the documentation and/or other materials
+ provided with the distribution.
+
+ THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDER “AS IS” AND ANY
+ EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
+ PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE
+ LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY,
+ OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
+ PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
+ PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+ THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR
+ TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF
+ THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ SUCH DAMAGE.
+
+ ***********************************************************************/
+
+"use strict";
+
+// a small wrapper around fitzgen's source-map library
+function SourceMap(options) {
+ options = defaults(options, {
+ file : null,
+ root : null,
+ orig : null,
+
+ orig_line_diff : 0,
+ dest_line_diff : 0,
+ });
+ var generator = new MOZ_SourceMap.SourceMapGenerator({
+ file : options.file,
+ sourceRoot : options.root
+ });
+ var orig_map = options.orig && new MOZ_SourceMap.SourceMapConsumer(options.orig);
+ function add(source, gen_line, gen_col, orig_line, orig_col, name) {
+ if (orig_map) {
+ var info = orig_map.originalPositionFor({
+ line: orig_line,
+ column: orig_col
+ });
+ source = info.source;
+ orig_line = info.line;
+ orig_col = info.column;
+ name = info.name;
+ }
+ generator.addMapping({
+ generated : { line: gen_line + options.dest_line_diff, column: gen_col },
+ original : { line: orig_line + options.orig_line_diff, column: orig_col },
+ source : source,
+ name : name
+ });
+ };
+ return {
+ add : add,
+ get : function() { return generator },
+ toString : function() { return generator.toString() }
+ };
+};
+
+/***********************************************************************
+
+ A JavaScript tokenizer / parser / beautifier / compressor.
+ https://github.com/mishoo/UglifyJS2
+
+ -------------------------------- (C) ---------------------------------
+
+ Author: Mihai Bazon
+ <mihai.bazon@gmail.com>
+ http://mihai.bazon.net/blog
+
+ Distributed under the BSD license:
+
+ Copyright 2012 (c) Mihai Bazon <mihai.bazon@gmail.com>
+
+ Redistribution and use in source and binary forms, with or without
+ modification, are permitted provided that the following conditions
+ are met:
+
+ * Redistributions of source code must retain the above
+ copyright notice, this list of conditions and the following
+ disclaimer.
+
+ * Redistributions in binary form must reproduce the above
+ copyright notice, this list of conditions and the following
+ disclaimer in the documentation and/or other materials
+ provided with the distribution.
+
+ THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDER “AS IS” AND ANY
+ EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
+ PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE
+ LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY,
+ OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
+ PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
+ PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+ THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR
+ TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF
+ THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
+ SUCH DAMAGE.
+
+ ***********************************************************************/
+
+"use strict";
+
+(function(){
+
+ var MOZ_TO_ME = {
+ TryStatement : function(M) {
+ return new AST_Try({
+ start : my_start_token(M),
+ end : my_end_token(M),
+ body : from_moz(M.block).body,
+ bcatch : from_moz(M.handlers[0]),
+ bfinally : M.finalizer ? new AST_Finally(from_moz(M.finalizer)) : null
+ });
+ },
+ CatchClause : function(M) {
+ return new AST_Catch({
+ start : my_start_token(M),
+ end : my_end_token(M),
+ argname : from_moz(M.param),
+ body : from_moz(M.body).body
+ });
+ },
+ ObjectExpression : function(M) {
+ return new AST_Object({
+ start : my_start_token(M),
+ end : my_end_token(M),
+ properties : M.properties.map(function(prop){
+ var key = prop.key;
+ var name = key.type == "Identifier" ? key.name : key.value;
+ var args = {
+ start : my_start_token(key),
+ end : my_end_token(prop.value),
+ key : name,
+ value : from_moz(prop.value)
+ };
+ switch (prop.kind) {
+ case "init":
+ return new AST_ObjectKeyVal(args);
+ case "set":
+ args.value.name = from_moz(key);
+ return new AST_ObjectSetter(args);
+ case "get":
+ args.value.name = from_moz(key);
+ return new AST_ObjectGetter(args);
+ }
+ })
+ });
+ },
+ SequenceExpression : function(M) {
+ return AST_Seq.from_array(M.expressions.map(from_moz));
+ },
+ MemberExpression : function(M) {
+ return new (M.computed ? AST_Sub : AST_Dot)({
+ start : my_start_token(M),
+ end : my_end_token(M),
+ property : M.computed ? from_moz(M.property) : M.property.name,
+ expression : from_moz(M.object)
+ });
+ },
+ SwitchCase : function(M) {
+ return new (M.test ? AST_Case : AST_Default)({
+ start : my_start_token(M),
+ end : my_end_token(M),
+ expression : from_moz(M.test),
+ body : M.consequent.map(from_moz)
+ });
+ },
+ Literal : function(M) {
+ var val = M.value, args = {
+ start : my_start_token(M),
+ end : my_end_token(M)
+ };
+ if (val === null) return new AST_Null(args);
+ switch (typeof val) {
+ case "string":
+ args.value = val;
+ return new AST_String(args);
+ case "number":
+ args.value = val;
+ return new AST_Number(args);
+ case "boolean":
+ return new (val ? AST_True : AST_False)(args);
+ default:
+ args.value = val;
+ return new AST_RegExp(args);
+ }
+ },
+ UnaryExpression: From_Moz_Unary,
+ UpdateExpression: From_Moz_Unary,
+ Identifier: function(M) {
+ var p = FROM_MOZ_STACK[FROM_MOZ_STACK.length - 2];
+ return new (M.name == "this" ? AST_This
+ : p.type == "LabeledStatement" ? AST_Label
+ : p.type == "VariableDeclarator" && p.id === M ? (p.kind == "const" ? AST_SymbolConst : AST_SymbolVar)
+ : p.type == "FunctionExpression" ? (p.id === M ? AST_SymbolLambda : AST_SymbolFunarg)
+ : p.type == "FunctionDeclaration" ? (p.id === M ? AST_SymbolDefun : AST_SymbolFunarg)
+ : p.type == "CatchClause" ? AST_SymbolCatch
+ : p.type == "BreakStatement" || p.type == "ContinueStatement" ? AST_LabelRef
+ : AST_SymbolRef)({
+ start : my_start_token(M),
+ end : my_end_token(M),
+ name : M.name
+ });
+ }
+ };
+
+ function From_Moz_Unary(M) {
+ var prefix = "prefix" in M ? M.prefix
+ : M.type == "UnaryExpression" ? true : false;
+ return new (prefix ? AST_UnaryPrefix : AST_UnaryPostfix)({
+ start : my_start_token(M),
+ end : my_end_token(M),
+ operator : M.operator,
+ expression : from_moz(M.argument)
+ });
+ };
+
+ var ME_TO_MOZ = {};
+
+ map("Node", AST_Node);
+ map("Program", AST_Toplevel, "body@body");
+ map("Function", AST_Function, "id>name, params@argnames, body%body");
+ map("EmptyStatement", AST_EmptyStatement);
+ map("BlockStatement", AST_BlockStatement, "body@body");
+ map("ExpressionStatement", AST_SimpleStatement, "expression>body");
+ map("IfStatement", AST_If, "test>condition, consequent>body, alternate>alternative");
+ map("LabeledStatement", AST_LabeledStatement, "label>label, body>body");
+ map("BreakStatement", AST_Break, "label>label");
+ map("ContinueStatement", AST_Continue, "label>label");
+ map("WithStatement", AST_With, "object>expression, body>body");
+ map("SwitchStatement", AST_Switch, "discriminant>expression, cases@body");
+ map("ReturnStatement", AST_Return, "argument>value");
+ map("ThrowStatement", AST_Throw, "argument>value");
+ map("WhileStatement", AST_While, "test>condition, body>body");
+ map("DoWhileStatement", AST_Do, "test>condition, body>body");
+ map("ForStatement", AST_For, "init>init, test>condition, update>step, body>body");
+ map("ForInStatement", AST_ForIn, "left>init, right>object, body>body");
+ map("DebuggerStatement", AST_Debugger);
+ map("FunctionDeclaration", AST_Defun, "id>name, params@argnames, body%body");
+ map("VariableDeclaration", AST_Var, "declarations@definitions");
+ map("VariableDeclarator", AST_VarDef, "id>name, init>value");
+
+ map("ThisExpression", AST_This);
+ map("ArrayExpression", AST_Array, "elements@elements");
+ map("FunctionExpression", AST_Function, "id>name, params@argnames, body%body");
+ map("BinaryExpression", AST_Binary, "operator=operator, left>left, right>right");
+ map("AssignmentExpression", AST_Assign, "operator=operator, left>left, right>right");
+ map("LogicalExpression", AST_Binary, "operator=operator, left>left, right>right");
+ map("ConditionalExpression", AST_Conditional, "test>condition, consequent>consequent, alternate>alternative");
+ map("NewExpression", AST_New, "callee>expression, arguments@args");
+ map("CallExpression", AST_Call, "callee>expression, arguments@args");
+
+ /* -----[ tools ]----- */
+
+ function my_start_token(moznode) {
+ return new AST_Token({
+ file : moznode.loc && moznode.loc.source,
+ line : moznode.loc && moznode.loc.start.line,
+ col : moznode.loc && moznode.loc.start.column,
+ pos : moznode.start,
+ endpos : moznode.start
+ });
+ };
+
+ function my_end_token(moznode) {
+ return new AST_Token({
+ file : moznode.loc && moznode.loc.source,
+ line : moznode.loc && moznode.loc.end.line,
+ col : moznode.loc && moznode.loc.end.column,
+ pos : moznode.end,
+ endpos : moznode.end
+ });
+ };
+
+ function map(moztype, mytype, propmap) {
+ var moz_to_me = "function From_Moz_" + moztype + "(M){\n";
+ moz_to_me += "return new mytype({\n" +
+ "start: my_start_token(M),\n" +
+ "end: my_end_token(M)";
+
+ if (propmap) propmap.split(/\s*,\s*/).forEach(function(prop){
+ var m = /([a-z0-9$_]+)(=|@|>|%)([a-z0-9$_]+)/i.exec(prop);
+ if (!m) throw new Error("Can't understand property map: " + prop);
+ var moz = "M." + m[1], how = m[2], my = m[3];
+ moz_to_me += ",\n" + my + ": ";
+ if (how == "@") {
+ moz_to_me += moz + ".map(from_moz)";
+ } else if (how == ">") {
+ moz_to_me += "from_moz(" + moz + ")";
+ } else if (how == "=") {
+ moz_to_me += moz;
+ } else if (how == "%") {
+ moz_to_me += "from_moz(" + moz + ").body";
+ } else throw new Error("Can't understand operator in propmap: " + prop);
+ });
+ moz_to_me += "\n})}";
+
+ // moz_to_me = parse(moz_to_me).print_to_string({ beautify: true });
+ // console.log(moz_to_me);
+
+ moz_to_me = new Function("mytype", "my_start_token", "my_end_token", "from_moz", "return(" + moz_to_me + ")")(
+ mytype, my_start_token, my_end_token, from_moz
+ );
+ return MOZ_TO_ME[moztype] = moz_to_me;
+ };
+
+ var FROM_MOZ_STACK = null;
+
+ function from_moz(node) {
+ FROM_MOZ_STACK.push(node);
+ var ret = node != null ? MOZ_TO_ME[node.type](node) : null;
+ FROM_MOZ_STACK.pop();
+ return ret;
+ };
+
+ AST_Node.from_mozilla_ast = function(node){
+ var save_stack = FROM_MOZ_STACK;
+ FROM_MOZ_STACK = [];
+ var ast = from_moz(node);
+ FROM_MOZ_STACK = save_stack;
+ return ast;
+ };
+
+})();
+
+AST_Node.warn_function = function(txt) { logger.error("uglifyjs2 WARN: " + txt); };
+exports.minify = function(files, options, name) {
+ options = defaults(options, {
+ spidermonkey : false,
+ outSourceMap : null,
+ sourceRoot : null,
+ inSourceMap : null,
+ fromString : false,
+ warnings : false,
+ mangle : {},
+ output : null,
+ compress : {}
+ });
+ base54.reset();
+
+ // 1. parse
+ var toplevel = null;
+
+ if (options.spidermonkey) {
+ toplevel = AST_Node.from_mozilla_ast(files);
+ } else {
+ if (typeof files == "string")
+ files = [ files ];
+ files.forEach(function(file){
+ var code = options.fromString
+ ? file
+ : rjsFile.readFile(file, "utf8");
+ toplevel = parse(code, {
+ filename: options.fromString ? name : file,
+ toplevel: toplevel
+ });
+ });
+ }
+
+ // 2. compress
+ if (options.compress) {
+ var compress = { warnings: options.warnings };
+ merge(compress, options.compress);
+ toplevel.figure_out_scope();
+ var sq = Compressor(compress);
+ toplevel = toplevel.transform(sq);
+ }
+
+ // 3. mangle
+ if (options.mangle) {
+ toplevel.figure_out_scope();
+ toplevel.compute_char_frequency();
+ toplevel.mangle_names(options.mangle);
+ }
+
+ // 4. output
+ var inMap = options.inSourceMap;
+ var output = {};
+ if (typeof options.inSourceMap == "string") {
+ inMap = rjsFile.readFile(options.inSourceMap, "utf8");
+ }
+ if (options.outSourceMap) {
+ output.source_map = SourceMap({
+ file: options.outSourceMap,
+ orig: inMap,
+ root: options.sourceRoot
+ });
+ }
+ if (options.output) {
+ merge(output, options.output);
+ }
+ var stream = OutputStream(output);
+ toplevel.print(stream);
+ return {
+ code : stream + "",
+ map : output.source_map + ""
+ };
+};
+
+// exports.describe_ast = function() {
+// function doitem(ctor) {
+// var sub = {};
+// ctor.SUBCLASSES.forEach(function(ctor){
+// sub[ctor.TYPE] = doitem(ctor);
+// });
+// var ret = {};
+// if (ctor.SELF_PROPS.length > 0) ret.props = ctor.SELF_PROPS;
+// if (ctor.SUBCLASSES.length > 0) ret.sub = sub;
+// return ret;
+// }
+// return doitem(AST_Node).sub;
+// }
+
+exports.describe_ast = function() {
+ var out = OutputStream({ beautify: true });
+ function doitem(ctor) {
+ out.print("AST_" + ctor.TYPE);
+ var props = ctor.SELF_PROPS.filter(function(prop){
+ return !/^\$/.test(prop);
+ });
+ if (props.length > 0) {
+ out.space();
+ out.with_parens(function(){
+ props.forEach(function(prop, i){
+ if (i) out.space();
+ out.print(prop);
+ });
+ });
+ }
+ if (ctor.documentation) {
+ out.space();
+ out.print_string(ctor.documentation);
+ }
+ if (ctor.SUBCLASSES.length > 0) {
+ out.space();
+ out.with_block(function(){
+ ctor.SUBCLASSES.forEach(function(ctor, i){
+ out.indent();
+ doitem(ctor);
+ out.newline();
+ });
+ });
+ }
+ };
+ doitem(AST_Node);
+ return out + "";
+};
+
+
+});
+/**
+ * @license Copyright (c) 2010-2014, The Dojo Foundation All Rights Reserved.
+ * Available via the MIT or new BSD license.
+ * see: http://github.com/jrburke/requirejs for details
+ */
+
+/*jslint plusplus: true */
+/*global define: false */
+
+define('parse', ['./esprimaAdapter', 'lang'], function (esprima, lang) {
+ 'use strict';
+
+ function arrayToString(ary) {
+ var output = '[';
+ if (ary) {
+ ary.forEach(function (item, i) {
+ output += (i > 0 ? ',' : '') + '"' + lang.jsEscape(item) + '"';
+ });
+ }
+ output += ']';
+
+ return output;
+ }
+
+ //This string is saved off because JSLint complains
+ //about obj.arguments use, as 'reserved word'
+ var argPropName = 'arguments';
+
+ //From an esprima example for traversing its ast.
+ function traverse(object, visitor) {
+ var key, child;
+
+ if (!object) {
+ return;
+ }
+
+ if (visitor.call(null, object) === false) {
+ return false;
+ }
+ for (key in object) {
+ if (object.hasOwnProperty(key)) {
+ child = object[key];
+ if (typeof child === 'object' && child !== null) {
+ if (traverse(child, visitor) === false) {
+ return false;
+ }
+ }
+ }
+ }
+ }
+
+ //Like traverse, but visitor returning false just
+ //stops that subtree analysis, not the rest of tree
+ //visiting.
+ function traverseBroad(object, visitor) {
+ var key, child;
+
+ if (!object) {
+ return;
+ }
+
+ if (visitor.call(null, object) === false) {
+ return false;
+ }
+ for (key in object) {
+ if (object.hasOwnProperty(key)) {
+ child = object[key];
+ if (typeof child === 'object' && child !== null) {
+ traverseBroad(child, visitor);
+ }
+ }
+ }
+ }
+
+ /**
+ * Pulls out dependencies from an array literal with just string members.
+ * If string literals, will just return those string values in an array,
+ * skipping other items in the array.
+ *
+ * @param {Node} node an AST node.
+ *
+ * @returns {Array} an array of strings.
+ * If null is returned, then it means the input node was not a valid
+ * dependency.
+ */
+ function getValidDeps(node) {
+ if (!node || node.type !== 'ArrayExpression' || !node.elements) {
+ return;
+ }
+
+ var deps = [];
+
+ node.elements.some(function (elem) {
+ if (elem.type === 'Literal') {
+ deps.push(elem.value);
+ }
+ });
+
+ return deps.length ? deps : undefined;
+ }
+
+ /**
+ * Main parse function. Returns a string of any valid require or
+ * define/require.def calls as part of one JavaScript source string.
+ * @param {String} moduleName the module name that represents this file.
+ * It is used to create a default define if there is not one already for the
+ * file. This allows properly tracing dependencies for builds. Otherwise, if
+ * the file just has a require() call, the file dependencies will not be
+ * properly reflected: the file will come before its dependencies.
+ * @param {String} moduleName
+ * @param {String} fileName
+ * @param {String} fileContents
+ * @param {Object} options optional options. insertNeedsDefine: true will
+ * add calls to require.needsDefine() if appropriate.
+ * @returns {String} JS source string or null, if no require or
+ * define/require.def calls are found.
+ */
+ function parse(moduleName, fileName, fileContents, options) {
+ options = options || {};
+
+ //Set up source input
+ var i, moduleCall, depString,
+ moduleDeps = [],
+ result = '',
+ moduleList = [],
+ needsDefine = true,
+ astRoot = esprima.parse(fileContents);
+
+ parse.recurse(astRoot, function (callName, config, name, deps) {
+ if (!deps) {
+ deps = [];
+ }
+
+ if (callName === 'define' && (!name || name === moduleName)) {
+ needsDefine = false;
+ }
+
+ if (!name) {
+ //If there is no module name, the dependencies are for
+ //this file/default module name.
+ moduleDeps = moduleDeps.concat(deps);
+ } else {
+ moduleList.push({
+ name: name,
+ deps: deps
+ });
+ }
+
+ //If define was found, no need to dive deeper, unless
+ //the config explicitly wants to dig deeper.
+ return !!options.findNestedDependencies;
+ }, options);
+
+ if (options.insertNeedsDefine && needsDefine) {
+ result += 'require.needsDefine("' + moduleName + '");';
+ }
+
+ if (moduleDeps.length || moduleList.length) {
+ for (i = 0; i < moduleList.length; i++) {
+ moduleCall = moduleList[i];
+ if (result) {
+ result += '\n';
+ }
+
+ //If this is the main module for this file, combine any
+ //"anonymous" dependencies (could come from a nested require
+ //call) with this module.
+ if (moduleCall.name === moduleName) {
+ moduleCall.deps = moduleCall.deps.concat(moduleDeps);
+ moduleDeps = [];
+ }
+
+ depString = arrayToString(moduleCall.deps);
+ result += 'define("' + moduleCall.name + '",' +
+ depString + ');';
+ }
+ if (moduleDeps.length) {
+ if (result) {
+ result += '\n';
+ }
+ depString = arrayToString(moduleDeps);
+ result += 'define("' + moduleName + '",' + depString + ');';
+ }
+ }
+
+ return result || null;
+ }
+
+ parse.traverse = traverse;
+ parse.traverseBroad = traverseBroad;
+
+ /**
+ * Handles parsing a file recursively for require calls.
+ * @param {Array} parentNode the AST node to start with.
+ * @param {Function} onMatch function to call on a parse match.
+ * @param {Object} [options] This is normally the build config options if
+ * it is passed.
+ */
+ parse.recurse = function (object, onMatch, options) {
+ //Like traverse, but skips if branches that would not be processed
+ //after has application that results in tests of true or false boolean
+ //literal values.
+ var key, child,
+ hasHas = options && options.has;
+
+ if (!object) {
+ return;
+ }
+
+ //If has replacement has resulted in if(true){} or if(false){}, take
+ //the appropriate branch and skip the other one.
+ if (hasHas && object.type === 'IfStatement' && object.test.type &&
+ object.test.type === 'Literal') {
+ if (object.test.value) {
+ //Take the if branch
+ this.recurse(object.consequent, onMatch, options);
+ } else {
+ //Take the else branch
+ this.recurse(object.alternate, onMatch, options);
+ }
+ } else {
+ if (this.parseNode(object, onMatch) === false) {
+ return;
+ }
+ for (key in object) {
+ if (object.hasOwnProperty(key)) {
+ child = object[key];
+ if (typeof child === 'object' && child !== null) {
+ this.recurse(child, onMatch, options);
+ }
+ }
+ }
+ }
+ };
+
+ /**
+ * Determines if the file defines the require/define module API.
+ * Specifically, it looks for the `define.amd = ` expression.
+ * @param {String} fileName
+ * @param {String} fileContents
+ * @returns {Boolean}
+ */
+ parse.definesRequire = function (fileName, fileContents) {
+ var found = false;
+
+ traverse(esprima.parse(fileContents), function (node) {
+ if (parse.hasDefineAmd(node)) {
+ found = true;
+
+ //Stop traversal
+ return false;
+ }
+ });
+
+ return found;
+ };
+
+ /**
+ * Finds require("") calls inside a CommonJS anonymous module wrapped in a
+ * define(function(require, exports, module){}) wrapper. These dependencies
+ * will be added to a modified define() call that lists the dependencies
+ * on the outside of the function.
+ * @param {String} fileName
+ * @param {String|Object} fileContents: a string of contents, or an already
+ * parsed AST tree.
+ * @returns {Array} an array of module names that are dependencies. Always
+ * returns an array, but could be of length zero.
+ */
+ parse.getAnonDeps = function (fileName, fileContents) {
+ var astRoot = typeof fileContents === 'string' ?
+ esprima.parse(fileContents) : fileContents,
+ defFunc = this.findAnonDefineFactory(astRoot);
+
+ return parse.getAnonDepsFromNode(defFunc);
+ };
+
+ /**
+ * Finds require("") calls inside a CommonJS anonymous module wrapped
+ * in a define function, given an AST node for the definition function.
+ * @param {Node} node the AST node for the definition function.
+ * @returns {Array} and array of dependency names. Can be of zero length.
+ */
+ parse.getAnonDepsFromNode = function (node) {
+ var deps = [],
+ funcArgLength;
+
+ if (node) {
+ this.findRequireDepNames(node, deps);
+
+ //If no deps, still add the standard CommonJS require, exports,
+ //module, in that order, to the deps, but only if specified as
+ //function args. In particular, if exports is used, it is favored
+ //over the return value of the function, so only add it if asked.
+ funcArgLength = node.params && node.params.length;
+ if (funcArgLength) {
+ deps = (funcArgLength > 1 ? ["require", "exports", "module"] :
+ ["require"]).concat(deps);
+ }
+ }
+ return deps;
+ };
+
+ parse.isDefineNodeWithArgs = function (node) {
+ return node && node.type === 'CallExpression' &&
+ node.callee && node.callee.type === 'Identifier' &&
+ node.callee.name === 'define' && node[argPropName];
+ };
+
+ /**
+ * Finds the function in define(function (require, exports, module){});
+ * @param {Array} node
+ * @returns {Boolean}
+ */
+ parse.findAnonDefineFactory = function (node) {
+ var match;
+
+ traverse(node, function (node) {
+ var arg0, arg1;
+
+ if (parse.isDefineNodeWithArgs(node)) {
+
+ //Just the factory function passed to define
+ arg0 = node[argPropName][0];
+ if (arg0 && arg0.type === 'FunctionExpression') {
+ match = arg0;
+ return false;
+ }
+
+ //A string literal module ID followed by the factory function.
+ arg1 = node[argPropName][1];
+ if (arg0.type === 'Literal' &&
+ arg1 && arg1.type === 'FunctionExpression') {
+ match = arg1;
+ return false;
+ }
+ }
+ });
+
+ return match;
+ };
+
+ /**
+ * Finds any config that is passed to requirejs. That includes calls to
+ * require/requirejs.config(), as well as require({}, ...) and
+ * requirejs({}, ...)
+ * @param {String} fileContents
+ *
+ * @returns {Object} a config details object with the following properties:
+ * - config: {Object} the config object found. Can be undefined if no
+ * config found.
+ * - range: {Array} the start index and end index in the contents where
+ * the config was found. Can be undefined if no config found.
+ * Can throw an error if the config in the file cannot be evaluated in
+ * a build context to valid JavaScript.
+ */
+ parse.findConfig = function (fileContents) {
+ /*jslint evil: true */
+ var jsConfig, foundConfig, stringData, foundRange, quote, quoteMatch,
+ quoteRegExp = /(:\s|\[\s*)(['"])/,
+ astRoot = esprima.parse(fileContents, {
+ loc: true
+ });
+
+ traverse(astRoot, function (node) {
+ var arg,
+ requireType = parse.hasRequire(node);
+
+ if (requireType && (requireType === 'require' ||
+ requireType === 'requirejs' ||
+ requireType === 'requireConfig' ||
+ requireType === 'requirejsConfig')) {
+
+ arg = node[argPropName] && node[argPropName][0];
+
+ if (arg && arg.type === 'ObjectExpression') {
+ stringData = parse.nodeToString(fileContents, arg);
+ jsConfig = stringData.value;
+ foundRange = stringData.range;
+ return false;
+ }
+ } else {
+ arg = parse.getRequireObjectLiteral(node);
+ if (arg) {
+ stringData = parse.nodeToString(fileContents, arg);
+ jsConfig = stringData.value;
+ foundRange = stringData.range;
+ return false;
+ }
+ }
+ });
+
+ if (jsConfig) {
+ // Eval the config
+ quoteMatch = quoteRegExp.exec(jsConfig);
+ quote = (quoteMatch && quoteMatch[2]) || '"';
+ foundConfig = eval('(' + jsConfig + ')');
+ }
+
+ return {
+ config: foundConfig,
+ range: foundRange,
+ quote: quote
+ };
+ };
+
+ /** Returns the node for the object literal assigned to require/requirejs,
+ * for holding a declarative config.
+ */
+ parse.getRequireObjectLiteral = function (node) {
+ if (node.id && node.id.type === 'Identifier' &&
+ (node.id.name === 'require' || node.id.name === 'requirejs') &&
+ node.init && node.init.type === 'ObjectExpression') {
+ return node.init;
+ }
+ };
+
+ /**
+ * Renames require/requirejs/define calls to be ns + '.' + require/requirejs/define
+ * Does *not* do .config calls though. See pragma.namespace for the complete
+ * set of namespace transforms. This function is used because require calls
+ * inside a define() call should not be renamed, so a simple regexp is not
+ * good enough.
+ * @param {String} fileContents the contents to transform.
+ * @param {String} ns the namespace, *not* including trailing dot.
+ * @return {String} the fileContents with the namespace applied
+ */
+ parse.renameNamespace = function (fileContents, ns) {
+ var lines,
+ locs = [],
+ astRoot = esprima.parse(fileContents, {
+ loc: true
+ });
+
+ parse.recurse(astRoot, function (callName, config, name, deps, node) {
+ locs.push(node.loc);
+ //Do not recurse into define functions, they should be using
+ //local defines.
+ return callName !== 'define';
+ }, {});
+
+ if (locs.length) {
+ lines = fileContents.split('\n');
+
+ //Go backwards through the found locs, adding in the namespace name
+ //in front.
+ locs.reverse();
+ locs.forEach(function (loc) {
+ var startIndex = loc.start.column,
+ //start.line is 1-based, not 0 based.
+ lineIndex = loc.start.line - 1,
+ line = lines[lineIndex];
+
+ lines[lineIndex] = line.substring(0, startIndex) +
+ ns + '.' +
+ line.substring(startIndex,
+ line.length);
+ });
+
+ fileContents = lines.join('\n');
+ }
+
+ return fileContents;
+ };
+
+ /**
+ * Finds all dependencies specified in dependency arrays and inside
+ * simplified commonjs wrappers.
+ * @param {String} fileName
+ * @param {String} fileContents
+ *
+ * @returns {Array} an array of dependency strings. The dependencies
+ * have not been normalized, they may be relative IDs.
+ */
+ parse.findDependencies = function (fileName, fileContents, options) {
+ var dependencies = [],
+ astRoot = esprima.parse(fileContents);
+
+ parse.recurse(astRoot, function (callName, config, name, deps) {
+ if (deps) {
+ dependencies = dependencies.concat(deps);
+ }
+ }, options);
+
+ return dependencies;
+ };
+
+ /**
+ * Finds only CJS dependencies, ones that are the form
+ * require('stringLiteral')
+ */
+ parse.findCjsDependencies = function (fileName, fileContents) {
+ var dependencies = [];
+
+ traverse(esprima.parse(fileContents), function (node) {
+ var arg;
+
+ if (node && node.type === 'CallExpression' && node.callee &&
+ node.callee.type === 'Identifier' &&
+ node.callee.name === 'require' && node[argPropName] &&
+ node[argPropName].length === 1) {
+ arg = node[argPropName][0];
+ if (arg.type === 'Literal') {
+ dependencies.push(arg.value);
+ }
+ }
+ });
+
+ return dependencies;
+ };
+
+ //function define() {}
+ parse.hasDefDefine = function (node) {
+ return node.type === 'FunctionDeclaration' && node.id &&
+ node.id.type === 'Identifier' && node.id.name === 'define';
+ };
+
+ //define.amd = ...
+ parse.hasDefineAmd = function (node) {
+ return node && node.type === 'AssignmentExpression' &&
+ node.left && node.left.type === 'MemberExpression' &&
+ node.left.object && node.left.object.name === 'define' &&
+ node.left.property && node.left.property.name === 'amd';
+ };
+
+ //define.amd reference, as in: if (define.amd)
+ parse.refsDefineAmd = function (node) {
+ return node && node.type === 'MemberExpression' &&
+ node.object && node.object.name === 'define' &&
+ node.object.type === 'Identifier' &&
+ node.property && node.property.name === 'amd' &&
+ node.property.type === 'Identifier';
+ };
+
+ //require(), requirejs(), require.config() and requirejs.config()
+ parse.hasRequire = function (node) {
+ var callName,
+ c = node && node.callee;
+
+ if (node && node.type === 'CallExpression' && c) {
+ if (c.type === 'Identifier' &&
+ (c.name === 'require' ||
+ c.name === 'requirejs')) {
+ //A require/requirejs({}, ...) call
+ callName = c.name;
+ } else if (c.type === 'MemberExpression' &&
+ c.object &&
+ c.object.type === 'Identifier' &&
+ (c.object.name === 'require' ||
+ c.object.name === 'requirejs') &&
+ c.property && c.property.name === 'config') {
+ // require/requirejs.config({}) call
+ callName = c.object.name + 'Config';
+ }
+ }
+
+ return callName;
+ };
+
+ //define()
+ parse.hasDefine = function (node) {
+ return node && node.type === 'CallExpression' && node.callee &&
+ node.callee.type === 'Identifier' &&
+ node.callee.name === 'define';
+ };
+
+ /**
+ * If there is a named define in the file, returns the name. Does not
+ * scan for mulitple names, just the first one.
+ */
+ parse.getNamedDefine = function (fileContents) {
+ var name;
+ traverse(esprima.parse(fileContents), function (node) {
+ if (node && node.type === 'CallExpression' && node.callee &&
+ node.callee.type === 'Identifier' &&
+ node.callee.name === 'define' &&
+ node[argPropName] && node[argPropName][0] &&
+ node[argPropName][0].type === 'Literal') {
+ name = node[argPropName][0].value;
+ return false;
+ }
+ });
+
+ return name;
+ };
+
+ /**
+ * Determines if define(), require({}|[]) or requirejs was called in the
+ * file. Also finds out if define() is declared and if define.amd is called.
+ */
+ parse.usesAmdOrRequireJs = function (fileName, fileContents) {
+ var uses;
+
+ traverse(esprima.parse(fileContents), function (node) {
+ var type, callName, arg;
+
+ if (parse.hasDefDefine(node)) {
+ //function define() {}
+ type = 'declaresDefine';
+ } else if (parse.hasDefineAmd(node)) {
+ type = 'defineAmd';
+ } else {
+ callName = parse.hasRequire(node);
+ if (callName) {
+ arg = node[argPropName] && node[argPropName][0];
+ if (arg && (arg.type === 'ObjectExpression' ||
+ arg.type === 'ArrayExpression')) {
+ type = callName;
+ }
+ } else if (parse.hasDefine(node)) {
+ type = 'define';
+ }
+ }
+
+ if (type) {
+ if (!uses) {
+ uses = {};
+ }
+ uses[type] = true;
+ }
+ });
+
+ return uses;
+ };
+
+ /**
+ * Determines if require(''), exports.x =, module.exports =,
+ * __dirname, __filename are used. So, not strictly traditional CommonJS,
+ * also checks for Node variants.
+ */
+ parse.usesCommonJs = function (fileName, fileContents) {
+ var uses = null,
+ assignsExports = false;
+
+
+ traverse(esprima.parse(fileContents), function (node) {
+ var type,
+ exp = node.expression || node.init;
+
+ if (node.type === 'Identifier' &&
+ (node.name === '__dirname' || node.name === '__filename')) {
+ type = node.name.substring(2);
+ } else if (node.type === 'VariableDeclarator' && node.id &&
+ node.id.type === 'Identifier' &&
+ node.id.name === 'exports') {
+ //Hmm, a variable assignment for exports, so does not use cjs
+ //exports.
+ type = 'varExports';
+ } else if (exp && exp.type === 'AssignmentExpression' && exp.left &&
+ exp.left.type === 'MemberExpression' && exp.left.object) {
+ if (exp.left.object.name === 'module' && exp.left.property &&
+ exp.left.property.name === 'exports') {
+ type = 'moduleExports';
+ } else if (exp.left.object.name === 'exports' &&
+ exp.left.property) {
+ type = 'exports';
+ }
+
+ } else if (node && node.type === 'CallExpression' && node.callee &&
+ node.callee.type === 'Identifier' &&
+ node.callee.name === 'require' && node[argPropName] &&
+ node[argPropName].length === 1 &&
+ node[argPropName][0].type === 'Literal') {
+ type = 'require';
+ }
+
+ if (type) {
+ if (type === 'varExports') {
+ assignsExports = true;
+ } else if (type !== 'exports' || !assignsExports) {
+ if (!uses) {
+ uses = {};
+ }
+ uses[type] = true;
+ }
+ }
+ });
+
+ return uses;
+ };
+
+
+ parse.findRequireDepNames = function (node, deps) {
+ traverse(node, function (node) {
+ var arg;
+
+ if (node && node.type === 'CallExpression' && node.callee &&
+ node.callee.type === 'Identifier' &&
+ node.callee.name === 'require' &&
+ node[argPropName] && node[argPropName].length === 1) {
+
+ arg = node[argPropName][0];
+ if (arg.type === 'Literal') {
+ deps.push(arg.value);
+ }
+ }
+ });
+ };
+
+ /**
+ * Determines if a specific node is a valid require or define/require.def
+ * call.
+ * @param {Array} node
+ * @param {Function} onMatch a function to call when a match is found.
+ * It is passed the match name, and the config, name, deps possible args.
+ * The config, name and deps args are not normalized.
+ *
+ * @returns {String} a JS source string with the valid require/define call.
+ * Otherwise null.
+ */
+ parse.parseNode = function (node, onMatch) {
+ var name, deps, cjsDeps, arg, factory, exp, refsDefine, bodyNode,
+ args = node && node[argPropName],
+ callName = parse.hasRequire(node);
+
+ if (callName === 'require' || callName === 'requirejs') {
+ //A plain require/requirejs call
+ arg = node[argPropName] && node[argPropName][0];
+ if (arg.type !== 'ArrayExpression') {
+ if (arg.type === 'ObjectExpression') {
+ //A config call, try the second arg.
+ arg = node[argPropName][1];
+ }
+ }
+
+ deps = getValidDeps(arg);
+ if (!deps) {
+ return;
+ }
+
+ return onMatch("require", null, null, deps, node);
+ } else if (parse.hasDefine(node) && args && args.length) {
+ name = args[0];
+ deps = args[1];
+ factory = args[2];
+
+ if (name.type === 'ArrayExpression') {
+ //No name, adjust args
+ factory = deps;
+ deps = name;
+ name = null;
+ } else if (name.type === 'FunctionExpression') {
+ //Just the factory, no name or deps
+ factory = name;
+ name = deps = null;
+ } else if (name.type !== 'Literal') {
+ //An object literal, just null out
+ name = deps = factory = null;
+ }
+
+ if (name && name.type === 'Literal' && deps) {
+ if (deps.type === 'FunctionExpression') {
+ //deps is the factory
+ factory = deps;
+ deps = null;
+ } else if (deps.type === 'ObjectExpression') {
+ //deps is object literal, null out
+ deps = factory = null;
+ } else if (deps.type === 'Identifier' && args.length === 2) {
+ // define('id', factory)
+ deps = factory = null;
+ }
+ }
+
+ if (deps && deps.type === 'ArrayExpression') {
+ deps = getValidDeps(deps);
+ } else if (factory && factory.type === 'FunctionExpression') {
+ //If no deps and a factory function, could be a commonjs sugar
+ //wrapper, scan the function for dependencies.
+ cjsDeps = parse.getAnonDepsFromNode(factory);
+ if (cjsDeps.length) {
+ deps = cjsDeps;
+ }
+ } else if (deps || factory) {
+ //Does not match the shape of an AMD call.
+ return;
+ }
+
+ //Just save off the name as a string instead of an AST object.
+ if (name && name.type === 'Literal') {
+ name = name.value;
+ }
+
+ return onMatch("define", null, name, deps, node);
+ } else if (node.type === 'CallExpression' && node.callee &&
+ node.callee.type === 'FunctionExpression' &&
+ node.callee.body && node.callee.body.body &&
+ node.callee.body.body.length === 1 &&
+ node.callee.body.body[0].type === 'IfStatement') {
+ bodyNode = node.callee.body.body[0];
+ //Look for a define(Identifier) case, but only if inside an
+ //if that has a define.amd test
+ if (bodyNode.consequent && bodyNode.consequent.body) {
+ exp = bodyNode.consequent.body[0];
+ if (exp.type === 'ExpressionStatement' && exp.expression &&
+ parse.hasDefine(exp.expression) &&
+ exp.expression.arguments &&
+ exp.expression.arguments.length === 1 &&
+ exp.expression.arguments[0].type === 'Identifier') {
+
+ //Calls define(Identifier) as first statement in body.
+ //Confirm the if test references define.amd
+ traverse(bodyNode.test, function (node) {
+ if (parse.refsDefineAmd(node)) {
+ refsDefine = true;
+ return false;
+ }
+ });
+
+ if (refsDefine) {
+ return onMatch("define", null, null, null, exp.expression);
+ }
+ }
+ }
+ }
+ };
+
+ /**
+ * Converts an AST node into a JS source string by extracting
+ * the node's location from the given contents string. Assumes
+ * esprima.parse() with loc was done.
+ * @param {String} contents
+ * @param {Object} node
+ * @returns {String} a JS source string.
+ */
+ parse.nodeToString = function (contents, node) {
+ var extracted,
+ loc = node.loc,
+ lines = contents.split('\n'),
+ firstLine = loc.start.line > 1 ?
+ lines.slice(0, loc.start.line - 1).join('\n') + '\n' :
+ '',
+ preamble = firstLine +
+ lines[loc.start.line - 1].substring(0, loc.start.column);
+
+ if (loc.start.line === loc.end.line) {
+ extracted = lines[loc.start.line - 1].substring(loc.start.column,
+ loc.end.column);
+ } else {
+ extracted = lines[loc.start.line - 1].substring(loc.start.column) +
+ '\n' +
+ lines.slice(loc.start.line, loc.end.line - 1).join('\n') +
+ '\n' +
+ lines[loc.end.line - 1].substring(0, loc.end.column);
+ }
+
+ return {
+ value: extracted,
+ range: [
+ preamble.length,
+ preamble.length + extracted.length
+ ]
+ };
+ };
+
+ /**
+ * Extracts license comments from JS text.
+ * @param {String} fileName
+ * @param {String} contents
+ * @returns {String} a string of license comments.
+ */
+ parse.getLicenseComments = function (fileName, contents) {
+ var commentNode, refNode, subNode, value, i, j,
+ //xpconnect's Reflect does not support comment or range, but
+ //prefer continued operation vs strict parity of operation,
+ //as license comments can be expressed in other ways, like
+ //via wrap args, or linked via sourcemaps.
+ ast = esprima.parse(contents, {
+ comment: true,
+ range: true
+ }),
+ result = '',
+ existsMap = {},
+ lineEnd = contents.indexOf('\r') === -1 ? '\n' : '\r\n';
+
+ if (ast.comments) {
+ for (i = 0; i < ast.comments.length; i++) {
+ commentNode = ast.comments[i];
+
+ if (commentNode.type === 'Line') {
+ value = '//' + commentNode.value + lineEnd;
+ refNode = commentNode;
+
+ if (i + 1 >= ast.comments.length) {
+ value += lineEnd;
+ } else {
+ //Look for immediately adjacent single line comments
+ //since it could from a multiple line comment made out
+ //of single line comments. Like this comment.
+ for (j = i + 1; j < ast.comments.length; j++) {
+ subNode = ast.comments[j];
+ if (subNode.type === 'Line' &&
+ subNode.range[0] === refNode.range[1] + 1) {
+ //Adjacent single line comment. Collect it.
+ value += '//' + subNode.value + lineEnd;
+ refNode = subNode;
+ } else {
+ //No more single line comment blocks. Break out
+ //and continue outer looping.
+ break;
+ }
+ }
+ value += lineEnd;
+ i = j - 1;
+ }
+ } else {
+ value = '/*' + commentNode.value + '*/' + lineEnd + lineEnd;
+ }
+
+ if (!existsMap[value] && (value.indexOf('license') !== -1 ||
+ (commentNode.type === 'Block' &&
+ value.indexOf('/*!') === 0) ||
+ value.indexOf('opyright') !== -1 ||
+ value.indexOf('(c)') !== -1)) {
+
+ result += value;
+ existsMap[value] = true;
+ }
+
+ }
+ }
+
+ return result;
+ };
+
+ return parse;
+});
+/**
+ * @license Copyright (c) 2012-2014, The Dojo Foundation All Rights Reserved.
+ * Available via the MIT or new BSD license.
+ * see: http://github.com/jrburke/requirejs for details
+ */
+
+/*global define */
+
+define('transform', [ './esprimaAdapter', './parse', 'logger', 'lang'],
+function (esprima, parse, logger, lang) {
+ 'use strict';
+ var transform,
+ baseIndentRegExp = /^([ \t]+)/,
+ indentRegExp = /\{[\r\n]+([ \t]+)/,
+ keyRegExp = /^[_A-Za-z]([A-Za-z\d_]*)$/,
+ bulkIndentRegExps = {
+ '\n': /\n/g,
+ '\r\n': /\r\n/g
+ };
+
+ function applyIndent(str, indent, lineReturn) {
+ var regExp = bulkIndentRegExps[lineReturn];
+ return str.replace(regExp, '$&' + indent);
+ }
+
+ transform = {
+ toTransport: function (namespace, moduleName, path, contents, onFound, options) {
+ options = options || {};
+
+ var astRoot, contentLines, modLine,
+ foundAnon,
+ scanCount = 0,
+ scanReset = false,
+ defineInfos = [],
+ applySourceUrl = function (contents) {
+ if (options.useSourceUrl) {
+ contents = 'eval("' + lang.jsEscape(contents) +
+ '\\n//# sourceURL=' + (path.indexOf('/') === 0 ? '' : '/') +
+ path +
+ '");\n';
+ }
+ return contents;
+ };
+
+ try {
+ astRoot = esprima.parse(contents, {
+ loc: true
+ });
+ } catch (e) {
+ logger.trace('toTransport skipping ' + path + ': ' +
+ e.toString());
+ return contents;
+ }
+
+ //Find the define calls and their position in the files.
+ parse.traverse(astRoot, function (node) {
+ var args, firstArg, firstArgLoc, factoryNode,
+ needsId, depAction, foundId, init,
+ sourceUrlData, range,
+ namespaceExists = false;
+
+ // If a bundle script with a define declaration, do not
+ // parse any further at this level. Likely a built layer
+ // by some other tool.
+ if (node.type === 'VariableDeclarator' &&
+ node.id && node.id.name === 'define' &&
+ node.id.type === 'Identifier') {
+ init = node.init;
+ if (init && init.callee &&
+ init.callee.type === 'CallExpression' &&
+ init.callee.callee &&
+ init.callee.callee.type === 'Identifier' &&
+ init.callee.callee.name === 'require' &&
+ init.callee.arguments && init.callee.arguments.length === 1 &&
+ init.callee.arguments[0].type === 'Literal' &&
+ init.callee.arguments[0].value &&
+ init.callee.arguments[0].value.indexOf('amdefine') !== -1) {
+ // the var define = require('amdefine')(module) case,
+ // keep going in that case.
+ } else {
+ return false;
+ }
+ }
+
+ namespaceExists = namespace &&
+ node.type === 'CallExpression' &&
+ node.callee && node.callee.object &&
+ node.callee.object.type === 'Identifier' &&
+ node.callee.object.name === namespace &&
+ node.callee.property.type === 'Identifier' &&
+ node.callee.property.name === 'define';
+
+ if (namespaceExists || parse.isDefineNodeWithArgs(node)) {
+ //The arguments are where its at.
+ args = node.arguments;
+ if (!args || !args.length) {
+ return;
+ }
+
+ firstArg = args[0];
+ firstArgLoc = firstArg.loc;
+
+ if (args.length === 1) {
+ if (firstArg.type === 'Identifier') {
+ //The define(factory) case, but
+ //only allow it if one Identifier arg,
+ //to limit impact of false positives.
+ needsId = true;
+ depAction = 'empty';
+ } else if (firstArg.type === 'FunctionExpression') {
+ //define(function(){})
+ factoryNode = firstArg;
+ needsId = true;
+ depAction = 'scan';
+ } else if (firstArg.type === 'ObjectExpression') {
+ //define({});
+ needsId = true;
+ depAction = 'skip';
+ } else if (firstArg.type === 'Literal' &&
+ typeof firstArg.value === 'number') {
+ //define('12345');
+ needsId = true;
+ depAction = 'skip';
+ } else if (firstArg.type === 'UnaryExpression' &&
+ firstArg.operator === '-' &&
+ firstArg.argument &&
+ firstArg.argument.type === 'Literal' &&
+ typeof firstArg.argument.value === 'number') {
+ //define('-12345');
+ needsId = true;
+ depAction = 'skip';
+ } else if (firstArg.type === 'MemberExpression' &&
+ firstArg.object &&
+ firstArg.property &&
+ firstArg.property.type === 'Identifier') {
+ //define(this.key);
+ needsId = true;
+ depAction = 'empty';
+ }
+ } else if (firstArg.type === 'ArrayExpression') {
+ //define([], ...);
+ needsId = true;
+ depAction = 'skip';
+ } else if (firstArg.type === 'Literal' &&
+ typeof firstArg.value === 'string') {
+ //define('string', ....)
+ //Already has an ID.
+ needsId = false;
+ if (args.length === 2 &&
+ args[1].type === 'FunctionExpression') {
+ //Needs dependency scanning.
+ factoryNode = args[1];
+ depAction = 'scan';
+ } else {
+ depAction = 'skip';
+ }
+ } else {
+ //Unknown define entity, keep looking, even
+ //in the subtree for this node.
+ return;
+ }
+
+ range = {
+ foundId: foundId,
+ needsId: needsId,
+ depAction: depAction,
+ namespaceExists: namespaceExists,
+ node: node,
+ defineLoc: node.loc,
+ firstArgLoc: firstArgLoc,
+ factoryNode: factoryNode,
+ sourceUrlData: sourceUrlData
+ };
+
+ //Only transform ones that do not have IDs. If it has an
+ //ID but no dependency array, assume it is something like
+ //a phonegap implementation, that has its own internal
+ //define that cannot handle dependency array constructs,
+ //and if it is a named module, then it means it has been
+ //set for transport form.
+ if (range.needsId) {
+ if (foundAnon) {
+ logger.trace(path + ' has more than one anonymous ' +
+ 'define. May be a built file from another ' +
+ 'build system like, Ender. Skipping normalization.');
+ defineInfos = [];
+ return false;
+ } else {
+ foundAnon = range;
+ defineInfos.push(range);
+ }
+ } else if (depAction === 'scan') {
+ scanCount += 1;
+ if (scanCount > 1) {
+ //Just go back to an array that just has the
+ //anon one, since this is an already optimized
+ //file like the phonegap one.
+ if (!scanReset) {
+ defineInfos = foundAnon ? [foundAnon] : [];
+ scanReset = true;
+ }
+ } else {
+ defineInfos.push(range);
+ }
+ }
+ }
+ });
+
+
+ if (!defineInfos.length) {
+ return applySourceUrl(contents);
+ }
+
+ //Reverse the matches, need to start from the bottom of
+ //the file to modify it, so that the ranges are still true
+ //further up.
+ defineInfos.reverse();
+
+ contentLines = contents.split('\n');
+
+ modLine = function (loc, contentInsertion) {
+ var startIndex = loc.start.column,
+ //start.line is 1-based, not 0 based.
+ lineIndex = loc.start.line - 1,
+ line = contentLines[lineIndex];
+ contentLines[lineIndex] = line.substring(0, startIndex) +
+ contentInsertion +
+ line.substring(startIndex,
+ line.length);
+ };
+
+ defineInfos.forEach(function (info) {
+ var deps,
+ contentInsertion = '',
+ depString = '';
+
+ //Do the modifications "backwards", in other words, start with the
+ //one that is farthest down and work up, so that the ranges in the
+ //defineInfos still apply. So that means deps, id, then namespace.
+ if (info.needsId && moduleName) {
+ contentInsertion += "'" + moduleName + "',";
+ }
+
+ if (info.depAction === 'scan') {
+ deps = parse.getAnonDepsFromNode(info.factoryNode);
+
+ if (deps.length) {
+ depString = '[' + deps.map(function (dep) {
+ return "'" + dep + "'";
+ }) + ']';
+ } else {
+ depString = '[]';
+ }
+ depString += ',';
+
+ if (info.factoryNode) {
+ //Already have a named module, need to insert the
+ //dependencies after the name.
+ modLine(info.factoryNode.loc, depString);
+ } else {
+ contentInsertion += depString;
+ }
+ }
+
+ if (contentInsertion) {
+ modLine(info.firstArgLoc, contentInsertion);
+ }
+
+ //Do namespace last so that ui does not mess upthe parenRange
+ //used above.
+ if (namespace && !info.namespaceExists) {
+ modLine(info.defineLoc, namespace + '.');
+ }
+
+ //Notify any listener for the found info
+ if (onFound) {
+ onFound(info);
+ }
+ });
+
+ contents = contentLines.join('\n');
+
+ return applySourceUrl(contents);
+ },
+
+ /**
+ * Modify the contents of a require.config/requirejs.config call. This
+ * call will LOSE any existing comments that are in the config string.
+ *
+ * @param {String} fileContents String that may contain a config call
+ * @param {Function} onConfig Function called when the first config
+ * call is found. It will be passed an Object which is the current
+ * config, and the onConfig function should return an Object to use
+ * as the config.
+ * @return {String} the fileContents with the config changes applied.
+ */
+ modifyConfig: function (fileContents, onConfig) {
+ var details = parse.findConfig(fileContents),
+ config = details.config;
+
+ if (config) {
+ config = onConfig(config);
+ if (config) {
+ return transform.serializeConfig(config,
+ fileContents,
+ details.range[0],
+ details.range[1],
+ {
+ quote: details.quote
+ });
+ }
+ }
+
+ return fileContents;
+ },
+
+ serializeConfig: function (config, fileContents, start, end, options) {
+ //Calculate base level of indent
+ var indent, match, configString, outDentRegExp,
+ baseIndent = '',
+ startString = fileContents.substring(0, start),
+ existingConfigString = fileContents.substring(start, end),
+ lineReturn = existingConfigString.indexOf('\r') === -1 ? '\n' : '\r\n',
+ lastReturnIndex = startString.lastIndexOf('\n');
+
+ //Get the basic amount of indent for the require config call.
+ if (lastReturnIndex === -1) {
+ lastReturnIndex = 0;
+ }
+
+ match = baseIndentRegExp.exec(startString.substring(lastReturnIndex + 1, start));
+ if (match && match[1]) {
+ baseIndent = match[1];
+ }
+
+ //Calculate internal indentation for config
+ match = indentRegExp.exec(existingConfigString);
+ if (match && match[1]) {
+ indent = match[1];
+ }
+
+ if (!indent || indent.length < baseIndent) {
+ indent = ' ';
+ } else {
+ indent = indent.substring(baseIndent.length);
+ }
+
+ outDentRegExp = new RegExp('(' + lineReturn + ')' + indent, 'g');
+
+ configString = transform.objectToString(config, {
+ indent: indent,
+ lineReturn: lineReturn,
+ outDentRegExp: outDentRegExp,
+ quote: options && options.quote
+ });
+
+ //Add in the base indenting level.
+ configString = applyIndent(configString, baseIndent, lineReturn);
+
+ return startString + configString + fileContents.substring(end);
+ },
+
+ /**
+ * Tries converting a JS object to a string. This will likely suck, and
+ * is tailored to the type of config expected in a loader config call.
+ * So, hasOwnProperty fields, strings, numbers, arrays and functions,
+ * no weird recursively referenced stuff.
+ * @param {Object} obj the object to convert
+ * @param {Object} options options object with the following values:
+ * {String} indent the indentation to use for each level
+ * {String} lineReturn the type of line return to use
+ * {outDentRegExp} outDentRegExp the regexp to use to outdent functions
+ * {String} quote the quote type to use, ' or ". Optional. Default is "
+ * @param {String} totalIndent the total indent to print for this level
+ * @return {String} a string representation of the object.
+ */
+ objectToString: function (obj, options, totalIndent) {
+ var startBrace, endBrace, nextIndent,
+ first = true,
+ value = '',
+ lineReturn = options.lineReturn,
+ indent = options.indent,
+ outDentRegExp = options.outDentRegExp,
+ quote = options.quote || '"';
+
+ totalIndent = totalIndent || '';
+ nextIndent = totalIndent + indent;
+
+ if (obj === null) {
+ value = 'null';
+ } else if (obj === undefined) {
+ value = 'undefined';
+ } else if (typeof obj === 'number' || typeof obj === 'boolean') {
+ value = obj;
+ } else if (typeof obj === 'string') {
+ //Use double quotes in case the config may also work as JSON.
+ value = quote + lang.jsEscape(obj) + quote;
+ } else if (lang.isArray(obj)) {
+ lang.each(obj, function (item, i) {
+ value += (i !== 0 ? ',' + lineReturn : '' ) +
+ nextIndent +
+ transform.objectToString(item,
+ options,
+ nextIndent);
+ });
+
+ startBrace = '[';
+ endBrace = ']';
+ } else if (lang.isFunction(obj) || lang.isRegExp(obj)) {
+ //The outdent regexp just helps pretty up the conversion
+ //just in node. Rhino strips comments and does a different
+ //indent scheme for Function toString, so not really helpful
+ //there.
+ value = obj.toString().replace(outDentRegExp, '$1');
+ } else {
+ //An object
+ lang.eachProp(obj, function (v, prop) {
+ value += (first ? '': ',' + lineReturn) +
+ nextIndent +
+ (keyRegExp.test(prop) ? prop : quote + lang.jsEscape(prop) + quote )+
+ ': ' +
+ transform.objectToString(v,
+ options,
+ nextIndent);
+ first = false;
+ });
+ startBrace = '{';
+ endBrace = '}';
+ }
+
+ if (startBrace) {
+ value = startBrace +
+ lineReturn +
+ value +
+ lineReturn + totalIndent +
+ endBrace;
+ }
+
+ return value;
+ }
+ };
+
+ return transform;
+});
+/**
+ * @license Copyright (c) 2010-2014, The Dojo Foundation All Rights Reserved.
+ * Available via the MIT or new BSD license.
+ * see: http://github.com/jrburke/requirejs for details
+ */
+
+/*jslint regexp: true, plusplus: true */
+/*global define: false */
+
+define('pragma', ['parse', 'logger'], function (parse, logger) {
+ 'use strict';
+ function Temp() {}
+
+ function create(obj, mixin) {
+ Temp.prototype = obj;
+ var temp = new Temp(), prop;
+
+ //Avoid any extra memory hanging around
+ Temp.prototype = null;
+
+ if (mixin) {
+ for (prop in mixin) {
+ if (mixin.hasOwnProperty(prop) && !temp.hasOwnProperty(prop)) {
+ temp[prop] = mixin[prop];
+ }
+ }
+ }
+
+ return temp; // Object
+ }
+
+ var pragma = {
+ conditionalRegExp: /(exclude|include)Start\s*\(\s*["'](\w+)["']\s*,(.*)\)/,
+ useStrictRegExp: /['"]use strict['"];/g,
+ hasRegExp: /has\s*\(\s*['"]([^'"]+)['"]\s*\)/g,
+ configRegExp: /(^|[^\.])(requirejs|require)(\.config)\s*\(/g,
+ nsWrapRegExp: /\/\*requirejs namespace: true \*\//,
+ apiDefRegExp: /var requirejs,\s*require,\s*define;/,
+ defineCheckRegExp: /typeof\s+define\s*===\s*["']function["']\s*&&\s*define\s*\.\s*amd/g,
+ defineStringCheckRegExp: /typeof\s+define\s*===\s*["']function["']\s*&&\s*define\s*\[\s*["']amd["']\s*\]/g,
+ defineTypeFirstCheckRegExp: /\s*["']function["']\s*==(=?)\s*typeof\s+define\s*&&\s*define\s*\.\s*amd/g,
+ defineJQueryRegExp: /typeof\s+define\s*===\s*["']function["']\s*&&\s*define\s*\.\s*amd\s*&&\s*define\s*\.\s*amd\s*\.\s*jQuery/g,
+ defineHasRegExp: /typeof\s+define\s*==(=)?\s*['"]function['"]\s*&&\s*typeof\s+define\.amd\s*==(=)?\s*['"]object['"]\s*&&\s*define\.amd/g,
+ defineTernaryRegExp: /typeof\s+define\s*===\s*['"]function["']\s*&&\s*define\s*\.\s*amd\s*\?\s*define/,
+ amdefineRegExp: /if\s*\(\s*typeof define\s*\!==\s*'function'\s*\)\s*\{\s*[^\{\}]+amdefine[^\{\}]+\}/g,
+
+ removeStrict: function (contents, config) {
+ return config.useStrict ? contents : contents.replace(pragma.useStrictRegExp, '');
+ },
+
+ namespace: function (fileContents, ns, onLifecycleName) {
+ if (ns) {
+ //Namespace require/define calls
+ fileContents = fileContents.replace(pragma.configRegExp, '$1' + ns + '.$2$3(');
+
+
+ fileContents = parse.renameNamespace(fileContents, ns);
+
+ //Namespace define ternary use:
+ fileContents = fileContents.replace(pragma.defineTernaryRegExp,
+ "typeof " + ns + ".define === 'function' && " + ns + ".define.amd ? " + ns + ".define");
+
+ //Namespace define jquery use:
+ fileContents = fileContents.replace(pragma.defineJQueryRegExp,
+ "typeof " + ns + ".define === 'function' && " + ns + ".define.amd && " + ns + ".define.amd.jQuery");
+
+ //Namespace has.js define use:
+ fileContents = fileContents.replace(pragma.defineHasRegExp,
+ "typeof " + ns + ".define === 'function' && typeof " + ns + ".define.amd === 'object' && " + ns + ".define.amd");
+
+ //Namespace define checks.
+ //Do these ones last, since they are a subset of the more specific
+ //checks above.
+ fileContents = fileContents.replace(pragma.defineCheckRegExp,
+ "typeof " + ns + ".define === 'function' && " + ns + ".define.amd");
+ fileContents = fileContents.replace(pragma.defineStringCheckRegExp,
+ "typeof " + ns + ".define === 'function' && " + ns + ".define['amd']");
+ fileContents = fileContents.replace(pragma.defineTypeFirstCheckRegExp,
+ "'function' === typeof " + ns + ".define && " + ns + ".define.amd");
+
+ //Check for require.js with the require/define definitions
+ if (pragma.apiDefRegExp.test(fileContents) &&
+ fileContents.indexOf("if (!" + ns + " || !" + ns + ".requirejs)") === -1) {
+ //Wrap the file contents in a typeof check, and a function
+ //to contain the API globals.
+ fileContents = "var " + ns + ";(function () { if (!" + ns + " || !" + ns + ".requirejs) {\n" +
+ "if (!" + ns + ") { " + ns + ' = {}; } else { require = ' + ns + '; }\n' +
+ fileContents +
+ "\n" +
+ ns + ".requirejs = requirejs;" +
+ ns + ".require = require;" +
+ ns + ".define = define;\n" +
+ "}\n}());";
+ }
+
+ //Finally, if the file wants a special wrapper because it ties
+ //in to the requirejs internals in a way that would not fit
+ //the above matches, do that. Look for /*requirejs namespace: true*/
+ if (pragma.nsWrapRegExp.test(fileContents)) {
+ //Remove the pragma.
+ fileContents = fileContents.replace(pragma.nsWrapRegExp, '');
+
+ //Alter the contents.
+ fileContents = '(function () {\n' +
+ 'var require = ' + ns + '.require,' +
+ 'requirejs = ' + ns + '.requirejs,' +
+ 'define = ' + ns + '.define;\n' +
+ fileContents +
+ '\n}());';
+ }
+ }
+
+ return fileContents;
+ },
+
+ /**
+ * processes the fileContents for some //>> conditional statements
+ */
+ process: function (fileName, fileContents, config, onLifecycleName, pluginCollector) {
+ /*jslint evil: true */
+ var foundIndex = -1, startIndex = 0, lineEndIndex, conditionLine,
+ matches, type, marker, condition, isTrue, endRegExp, endMatches,
+ endMarkerIndex, shouldInclude, startLength, lifecycleHas, deps,
+ i, dep, moduleName, collectorMod,
+ lifecyclePragmas, pragmas = config.pragmas, hasConfig = config.has,
+ //Legacy arg defined to help in dojo conversion script. Remove later
+ //when dojo no longer needs conversion:
+ kwArgs = pragmas;
+
+ //Mix in a specific lifecycle scoped object, to allow targeting
+ //some pragmas/has tests to only when files are saved, or at different
+ //lifecycle events. Do not bother with kwArgs in this section, since
+ //the old dojo kwArgs were for all points in the build lifecycle.
+ if (onLifecycleName) {
+ lifecyclePragmas = config['pragmas' + onLifecycleName];
+ lifecycleHas = config['has' + onLifecycleName];
+
+ if (lifecyclePragmas) {
+ pragmas = create(pragmas || {}, lifecyclePragmas);
+ }
+
+ if (lifecycleHas) {
+ hasConfig = create(hasConfig || {}, lifecycleHas);
+ }
+ }
+
+ //Replace has references if desired
+ if (hasConfig) {
+ fileContents = fileContents.replace(pragma.hasRegExp, function (match, test) {
+ if (hasConfig.hasOwnProperty(test)) {
+ return !!hasConfig[test];
+ }
+ return match;
+ });
+ }
+
+ if (!config.skipPragmas) {
+
+ while ((foundIndex = fileContents.indexOf("//>>", startIndex)) !== -1) {
+ //Found a conditional. Get the conditional line.
+ lineEndIndex = fileContents.indexOf("\n", foundIndex);
+ if (lineEndIndex === -1) {
+ lineEndIndex = fileContents.length - 1;
+ }
+
+ //Increment startIndex past the line so the next conditional search can be done.
+ startIndex = lineEndIndex + 1;
+
+ //Break apart the conditional.
+ conditionLine = fileContents.substring(foundIndex, lineEndIndex + 1);
+ matches = conditionLine.match(pragma.conditionalRegExp);
+ if (matches) {
+ type = matches[1];
+ marker = matches[2];
+ condition = matches[3];
+ isTrue = false;
+ //See if the condition is true.
+ try {
+ isTrue = !!eval("(" + condition + ")");
+ } catch (e) {
+ throw "Error in file: " +
+ fileName +
+ ". Conditional comment: " +
+ conditionLine +
+ " failed with this error: " + e;
+ }
+
+ //Find the endpoint marker.
+ endRegExp = new RegExp('\\/\\/\\>\\>\\s*' + type + 'End\\(\\s*[\'"]' + marker + '[\'"]\\s*\\)', "g");
+ endMatches = endRegExp.exec(fileContents.substring(startIndex, fileContents.length));
+ if (endMatches) {
+ endMarkerIndex = startIndex + endRegExp.lastIndex - endMatches[0].length;
+
+ //Find the next line return based on the match position.
+ lineEndIndex = fileContents.indexOf("\n", endMarkerIndex);
+ if (lineEndIndex === -1) {
+ lineEndIndex = fileContents.length - 1;
+ }
+
+ //Should we include the segment?
+ shouldInclude = ((type === "exclude" && !isTrue) || (type === "include" && isTrue));
+
+ //Remove the conditional comments, and optionally remove the content inside
+ //the conditional comments.
+ startLength = startIndex - foundIndex;
+ fileContents = fileContents.substring(0, foundIndex) +
+ (shouldInclude ? fileContents.substring(startIndex, endMarkerIndex) : "") +
+ fileContents.substring(lineEndIndex + 1, fileContents.length);
+
+ //Move startIndex to foundIndex, since that is the new position in the file
+ //where we need to look for more conditionals in the next while loop pass.
+ startIndex = foundIndex;
+ } else {
+ throw "Error in file: " +
+ fileName +
+ ". Cannot find end marker for conditional comment: " +
+ conditionLine;
+
+ }
+ }
+ }
+ }
+
+ //If need to find all plugin resources to optimize, do that now,
+ //before namespacing, since the namespacing will change the API
+ //names.
+ //If there is a plugin collector, scan the file for plugin resources.
+ if (config.optimizeAllPluginResources && pluginCollector) {
+ try {
+ deps = parse.findDependencies(fileName, fileContents);
+ if (deps.length) {
+ for (i = 0; i < deps.length; i++) {
+ dep = deps[i];
+ if (dep.indexOf('!') !== -1) {
+ moduleName = dep.split('!')[0];
+ collectorMod = pluginCollector[moduleName];
+ if (!collectorMod) {
+ collectorMod = pluginCollector[moduleName] = [];
+ }
+ collectorMod.push(dep);
+ }
+ }
+ }
+ } catch (eDep) {
+ logger.error('Parse error looking for plugin resources in ' +
+ fileName + ', skipping.');
+ }
+ }
+
+ //Strip amdefine use for node-shared modules.
+ if (!config.keepAmdefine) {
+ fileContents = fileContents.replace(pragma.amdefineRegExp, '');
+ }
+
+ //Do namespacing
+ if (onLifecycleName === 'OnSave' && config.namespace) {
+ fileContents = pragma.namespace(fileContents, config.namespace, onLifecycleName);
+ }
+
+
+ return pragma.removeStrict(fileContents, config);
+ }
+ };
+
+ return pragma;
+});
+if(env === 'browser') {
+/**
+ * @license Copyright (c) 2010-2014, The Dojo Foundation All Rights Reserved.
+ * Available via the MIT or new BSD license.
+ * see: http://github.com/jrburke/requirejs for details
+ */
+
+/*jslint strict: false */
+/*global define: false */
+
+define('browser/optimize', {});
+
+}
+
+if(env === 'node') {
+/**
+ * @license Copyright (c) 2010-2014, The Dojo Foundation All Rights Reserved.
+ * Available via the MIT or new BSD license.
+ * see: http://github.com/jrburke/requirejs for details
+ */
+
+/*jslint strict: false */
+/*global define: false */
+
+define('node/optimize', {});
+
+}
+
+if(env === 'rhino') {
+/**
+ * @license Copyright (c) 2010-2014, The Dojo Foundation All Rights Reserved.
+ * Available via the MIT or new BSD license.
+ * see: http://github.com/jrburke/requirejs for details
+ */
+
+/*jslint sloppy: true, plusplus: true */
+/*global define, java, Packages, com */
+
+define('rhino/optimize', ['logger', 'env!env/file'], function (logger, file) {
+
+ //Add .reduce to Rhino so UglifyJS can run in Rhino,
+ //inspired by https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Array/reduce
+ //but rewritten for brevity, and to be good enough for use by UglifyJS.
+ if (!Array.prototype.reduce) {
+ Array.prototype.reduce = function (fn /*, initialValue */) {
+ var i = 0,
+ length = this.length,
+ accumulator;
+
+ if (arguments.length >= 2) {
+ accumulator = arguments[1];
+ } else {
+ if (length) {
+ while (!(i in this)) {
+ i++;
+ }
+ accumulator = this[i++];
+ }
+ }
+
+ for (; i < length; i++) {
+ if (i in this) {
+ accumulator = fn.call(undefined, accumulator, this[i], i, this);
+ }
+ }
+
+ return accumulator;
+ };
+ }
+
+ var JSSourceFilefromCode, optimize,
+ mapRegExp = /"file":"[^"]+"/;
+
+ //Bind to Closure compiler, but if it is not available, do not sweat it.
+ try {
+ JSSourceFilefromCode = java.lang.Class.forName('com.google.javascript.jscomp.JSSourceFile').getMethod('fromCode', [java.lang.String, java.lang.String]);
+ } catch (e) {}
+
+ //Helper for closure compiler, because of weird Java-JavaScript interactions.
+ function closurefromCode(filename, content) {
+ return JSSourceFilefromCode.invoke(null, [filename, content]);
+ }
+
+
+ function getFileWriter(fileName, encoding) {
+ var outFile = new java.io.File(fileName), outWriter, parentDir;
+
+ parentDir = outFile.getAbsoluteFile().getParentFile();
+ if (!parentDir.exists()) {
+ if (!parentDir.mkdirs()) {
+ throw "Could not create directory: " + parentDir.getAbsolutePath();
+ }
+ }
+
+ if (encoding) {
+ outWriter = new java.io.OutputStreamWriter(new java.io.FileOutputStream(outFile), encoding);
+ } else {
+ outWriter = new java.io.OutputStreamWriter(new java.io.FileOutputStream(outFile));
+ }
+
+ return new java.io.BufferedWriter(outWriter);
+ }
+
+ optimize = {
+ closure: function (fileName, fileContents, outFileName, keepLines, config) {
+ config = config || {};
+ var result, mappings, optimized, compressed, baseName, writer,
+ outBaseName, outFileNameMap, outFileNameMapContent,
+ srcOutFileName, concatNameMap,
+ jscomp = Packages.com.google.javascript.jscomp,
+ flags = Packages.com.google.common.flags,
+ //Set up source input
+ jsSourceFile = closurefromCode(String(fileName), String(fileContents)),
+ sourceListArray = new java.util.ArrayList(),
+ options, option, FLAG_compilation_level, compiler,
+ Compiler = Packages.com.google.javascript.jscomp.Compiler,
+ CommandLineRunner = Packages.com.google.javascript.jscomp.CommandLineRunner;
+
+ logger.trace("Minifying file: " + fileName);
+
+ baseName = (new java.io.File(fileName)).getName();
+
+ //Set up options
+ options = new jscomp.CompilerOptions();
+ for (option in config.CompilerOptions) {
+ // options are false by default and jslint wanted an if statement in this for loop
+ if (config.CompilerOptions[option]) {
+ options[option] = config.CompilerOptions[option];
+ }
+
+ }
+ options.prettyPrint = keepLines || options.prettyPrint;
+
+ FLAG_compilation_level = jscomp.CompilationLevel[config.CompilationLevel || 'SIMPLE_OPTIMIZATIONS'];
+ FLAG_compilation_level.setOptionsForCompilationLevel(options);
+
+ if (config.generateSourceMaps) {
+ mappings = new java.util.ArrayList();
+
+ mappings.add(new com.google.javascript.jscomp.SourceMap.LocationMapping(fileName, baseName + ".src.js"));
+ options.setSourceMapLocationMappings(mappings);
+ options.setSourceMapOutputPath(fileName + ".map");
+ }
+
+ //Trigger the compiler
+ Compiler.setLoggingLevel(Packages.java.util.logging.Level[config.loggingLevel || 'WARNING']);
+ compiler = new Compiler();
+
+ //fill the sourceArrrayList; we need the ArrayList because the only overload of compile
+ //accepting the getDefaultExterns return value (a List) also wants the sources as a List
+ sourceListArray.add(jsSourceFile);
+
+ result = compiler.compile(CommandLineRunner.getDefaultExterns(), sourceListArray, options);
+ if (result.success) {
+ optimized = String(compiler.toSource());
+
+ if (config.generateSourceMaps && result.sourceMap && outFileName) {
+ outBaseName = (new java.io.File(outFileName)).getName();
+
+ srcOutFileName = outFileName + ".src.js";
+ outFileNameMap = outFileName + ".map";
+
+ //If previous .map file exists, move it to the ".src.js"
+ //location. Need to update the sourceMappingURL part in the
+ //src.js file too.
+ if (file.exists(outFileNameMap)) {
+ concatNameMap = outFileNameMap.replace(/\.map$/, '.src.js.map');
+ file.saveFile(concatNameMap, file.readFile(outFileNameMap));
+ file.saveFile(srcOutFileName,
+ fileContents.replace(/\/\# sourceMappingURL=(.+).map/,
+ '/# sourceMappingURL=$1.src.js.map'));
+ } else {
+ file.saveUtf8File(srcOutFileName, fileContents);
+ }
+
+ writer = getFileWriter(outFileNameMap, "utf-8");
+ result.sourceMap.appendTo(writer, outFileName);
+ writer.close();
+
+ //Not sure how better to do this, but right now the .map file
+ //leaks the full OS path in the "file" property. Manually
+ //modify it to not do that.
+ file.saveFile(outFileNameMap,
+ file.readFile(outFileNameMap).replace(mapRegExp, '"file":"' + baseName + '"'));
+
+ fileContents = optimized + "\n//# sourceMappingURL=" + outBaseName + ".map";
+ } else {
+ fileContents = optimized;
+ }
+ return fileContents;
+ } else {
+ throw new Error('Cannot closure compile file: ' + fileName + '. Skipping it.');
+ }
+
+ return fileContents;
+ }
+ };
+
+ return optimize;
+});
+}
+
+if(env === 'xpconnect') {
+define('xpconnect/optimize', {});
+}
+/**
+ * @license Copyright (c) 2010-2014, The Dojo Foundation All Rights Reserved.
+ * Available via the MIT or new BSD license.
+ * see: http://github.com/jrburke/requirejs for details
+ */
+
+/*jslint plusplus: true, nomen: true, regexp: true */
+/*global define: false */
+
+define('optimize', [ 'lang', 'logger', 'env!env/optimize', 'env!env/file', 'parse',
+ 'pragma', 'uglifyjs/index', 'uglifyjs2',
+ 'source-map'],
+function (lang, logger, envOptimize, file, parse,
+ pragma, uglify, uglify2,
+ sourceMap) {
+ 'use strict';
+
+ var optimize,
+ cssImportRegExp = /\@import\s+(url\()?\s*([^);]+)\s*(\))?([\w, ]*)(;)?/ig,
+ cssCommentImportRegExp = /\/\*[^\*]*@import[^\*]*\*\//g,
+ cssUrlRegExp = /\url\(\s*([^\)]+)\s*\)?/g,
+ SourceMapGenerator = sourceMap.SourceMapGenerator,
+ SourceMapConsumer =sourceMap.SourceMapConsumer;
+
+ /**
+ * If an URL from a CSS url value contains start/end quotes, remove them.
+ * This is not done in the regexp, since my regexp fu is not that strong,
+ * and the CSS spec allows for ' and " in the URL if they are backslash escaped.
+ * @param {String} url
+ */
+ function cleanCssUrlQuotes(url) {
+ //Make sure we are not ending in whitespace.
+ //Not very confident of the css regexps above that there will not be ending
+ //whitespace.
+ url = url.replace(/\s+$/, "");
+
+ if (url.charAt(0) === "'" || url.charAt(0) === "\"") {
+ url = url.substring(1, url.length - 1);
+ }
+
+ return url;
+ }
+
+ function fixCssUrlPaths(fileName, path, contents, cssPrefix) {
+ return contents.replace(cssUrlRegExp, function (fullMatch, urlMatch) {
+ var colonIndex, firstChar, parts, i,
+ fixedUrlMatch = cleanCssUrlQuotes(urlMatch);
+
+ fixedUrlMatch = fixedUrlMatch.replace(lang.backSlashRegExp, "/");
+
+ //Only do the work for relative URLs. Skip things that start with / or #, or have
+ //a protocol.
+ firstChar = fixedUrlMatch.charAt(0);
+ colonIndex = fixedUrlMatch.indexOf(":");
+ if (firstChar !== "/" && firstChar !== "#" && (colonIndex === -1 || colonIndex > fixedUrlMatch.indexOf("/"))) {
+ //It is a relative URL, tack on the cssPrefix and path prefix
+ urlMatch = cssPrefix + path + fixedUrlMatch;
+
+ } else {
+ logger.trace(fileName + "\n URL not a relative URL, skipping: " + urlMatch);
+ }
+
+ //Collapse .. and .
+ parts = urlMatch.split("/");
+ for (i = parts.length - 1; i > 0; i--) {
+ if (parts[i] === ".") {
+ parts.splice(i, 1);
+ } else if (parts[i] === "..") {
+ if (i !== 0 && parts[i - 1] !== "..") {
+ parts.splice(i - 1, 2);
+ i -= 1;
+ }
+ }
+ }
+
+ return "url(" + parts.join("/") + ")";
+ });
+ }
+
+ /**
+ * Inlines nested stylesheets that have @import calls in them.
+ * @param {String} fileName the file name
+ * @param {String} fileContents the file contents
+ * @param {String} cssImportIgnore comma delimited string of files to ignore
+ * @param {String} cssPrefix string to be prefixed before relative URLs
+ * @param {Object} included an object used to track the files already imported
+ */
+ function flattenCss(fileName, fileContents, cssImportIgnore, cssPrefix, included, topLevel) {
+ //Find the last slash in the name.
+ fileName = fileName.replace(lang.backSlashRegExp, "/");
+ var endIndex = fileName.lastIndexOf("/"),
+ //Make a file path based on the last slash.
+ //If no slash, so must be just a file name. Use empty string then.
+ filePath = (endIndex !== -1) ? fileName.substring(0, endIndex + 1) : "",
+ //store a list of merged files
+ importList = [],
+ skippedList = [];
+
+ //First make a pass by removing any commented out @import calls.
+ fileContents = fileContents.replace(cssCommentImportRegExp, '');
+
+ //Make sure we have a delimited ignore list to make matching faster
+ if (cssImportIgnore && cssImportIgnore.charAt(cssImportIgnore.length - 1) !== ",") {
+ cssImportIgnore += ",";
+ }
+
+ fileContents = fileContents.replace(cssImportRegExp, function (fullMatch, urlStart, importFileName, urlEnd, mediaTypes) {
+ //Only process media type "all" or empty media type rules.
+ if (mediaTypes && ((mediaTypes.replace(/^\s\s*/, '').replace(/\s\s*$/, '')) !== "all")) {
+ skippedList.push(fileName);
+ return fullMatch;
+ }
+
+ importFileName = cleanCssUrlQuotes(importFileName);
+
+ //Ignore the file import if it is part of an ignore list.
+ if (cssImportIgnore && cssImportIgnore.indexOf(importFileName + ",") !== -1) {
+ return fullMatch;
+ }
+
+ //Make sure we have a unix path for the rest of the operation.
+ importFileName = importFileName.replace(lang.backSlashRegExp, "/");
+
+ try {
+ //if a relative path, then tack on the filePath.
+ //If it is not a relative path, then the readFile below will fail,
+ //and we will just skip that import.
+ var fullImportFileName = importFileName.charAt(0) === "/" ? importFileName : filePath + importFileName,
+ importContents = file.readFile(fullImportFileName),
+ importEndIndex, importPath, flat;
+
+ //Skip the file if it has already been included.
+ if (included[fullImportFileName]) {
+ return '';
+ }
+ included[fullImportFileName] = true;
+
+ //Make sure to flatten any nested imports.
+ flat = flattenCss(fullImportFileName, importContents, cssImportIgnore, cssPrefix, included);
+ importContents = flat.fileContents;
+
+ if (flat.importList.length) {
+ importList.push.apply(importList, flat.importList);
+ }
+ if (flat.skippedList.length) {
+ skippedList.push.apply(skippedList, flat.skippedList);
+ }
+
+ //Make the full import path
+ importEndIndex = importFileName.lastIndexOf("/");
+
+ //Make a file path based on the last slash.
+ //If no slash, so must be just a file name. Use empty string then.
+ importPath = (importEndIndex !== -1) ? importFileName.substring(0, importEndIndex + 1) : "";
+
+ //fix url() on relative import (#5)
+ importPath = importPath.replace(/^\.\//, '');
+
+ //Modify URL paths to match the path represented by this file.
+ importContents = fixCssUrlPaths(importFileName, importPath, importContents, cssPrefix);
+
+ importList.push(fullImportFileName);
+ return importContents;
+ } catch (e) {
+ logger.warn(fileName + "\n Cannot inline css import, skipping: " + importFileName);
+ return fullMatch;
+ }
+ });
+
+ if (cssPrefix && topLevel) {
+ //Modify URL paths to match the path represented by this file.
+ fileContents = fixCssUrlPaths(fileName, '', fileContents, cssPrefix);
+ }
+
+ return {
+ importList : importList,
+ skippedList: skippedList,
+ fileContents : fileContents
+ };
+ }
+
+ optimize = {
+ /**
+ * Optimizes a file that contains JavaScript content. Optionally collects
+ * plugin resources mentioned in a file, and then passes the content
+ * through an minifier if one is specified via config.optimize.
+ *
+ * @param {String} fileName the name of the file to optimize
+ * @param {String} fileContents the contents to optimize. If this is
+ * a null value, then fileName will be used to read the fileContents.
+ * @param {String} outFileName the name of the file to use for the
+ * saved optimized content.
+ * @param {Object} config the build config object.
+ * @param {Array} [pluginCollector] storage for any plugin resources
+ * found.
+ */
+ jsFile: function (fileName, fileContents, outFileName, config, pluginCollector) {
+ if (!fileContents) {
+ fileContents = file.readFile(fileName);
+ }
+
+ fileContents = optimize.js(fileName, fileContents, outFileName, config, pluginCollector);
+
+ file.saveUtf8File(outFileName, fileContents);
+ },
+
+ /**
+ * Optimizes a file that contains JavaScript content. Optionally collects
+ * plugin resources mentioned in a file, and then passes the content
+ * through an minifier if one is specified via config.optimize.
+ *
+ * @param {String} fileName the name of the file that matches the
+ * fileContents.
+ * @param {String} fileContents the string of JS to optimize.
+ * @param {Object} [config] the build config object.
+ * @param {Array} [pluginCollector] storage for any plugin resources
+ * found.
+ */
+ js: function (fileName, fileContents, outFileName, config, pluginCollector) {
+ var optFunc, optConfig,
+ parts = (String(config.optimize)).split('.'),
+ optimizerName = parts[0],
+ keepLines = parts[1] === 'keepLines',
+ licenseContents = '';
+
+ config = config || {};
+
+ //Apply pragmas/namespace renaming
+ fileContents = pragma.process(fileName, fileContents, config, 'OnSave', pluginCollector);
+
+ //Optimize the JS files if asked.
+ if (optimizerName && optimizerName !== 'none') {
+ optFunc = envOptimize[optimizerName] || optimize.optimizers[optimizerName];
+ if (!optFunc) {
+ throw new Error('optimizer with name of "' +
+ optimizerName +
+ '" not found for this environment');
+ }
+
+ optConfig = config[optimizerName] || {};
+ if (config.generateSourceMaps) {
+ optConfig.generateSourceMaps = !!config.generateSourceMaps;
+ optConfig._buildSourceMap = config._buildSourceMap;
+ }
+
+ try {
+ if (config.preserveLicenseComments) {
+ //Pull out any license comments for prepending after optimization.
+ try {
+ licenseContents = parse.getLicenseComments(fileName, fileContents);
+ } catch (e) {
+ throw new Error('Cannot parse file: ' + fileName + ' for comments. Skipping it. Error is:\n' + e.toString());
+ }
+ }
+
+ fileContents = licenseContents + optFunc(fileName,
+ fileContents,
+ outFileName,
+ keepLines,
+ optConfig);
+ if (optConfig._buildSourceMap && optConfig._buildSourceMap !== config._buildSourceMap) {
+ config._buildSourceMap = optConfig._buildSourceMap;
+ }
+ } catch (e) {
+ if (config.throwWhen && config.throwWhen.optimize) {
+ throw e;
+ } else {
+ logger.error(e);
+ }
+ }
+ } else {
+ if (config._buildSourceMap) {
+ config._buildSourceMap = null;
+ }
+ }
+
+ return fileContents;
+ },
+
+ /**
+ * Optimizes one CSS file, inlining @import calls, stripping comments, and
+ * optionally removes line returns.
+ * @param {String} fileName the path to the CSS file to optimize
+ * @param {String} outFileName the path to save the optimized file.
+ * @param {Object} config the config object with the optimizeCss and
+ * cssImportIgnore options.
+ */
+ cssFile: function (fileName, outFileName, config) {
+
+ //Read in the file. Make sure we have a JS string.
+ var originalFileContents = file.readFile(fileName),
+ flat = flattenCss(fileName, originalFileContents, config.cssImportIgnore, config.cssPrefix, {}, true),
+ //Do not use the flattened CSS if there was one that was skipped.
+ fileContents = flat.skippedList.length ? originalFileContents : flat.fileContents,
+ startIndex, endIndex, buildText, comment;
+
+ if (flat.skippedList.length) {
+ logger.warn('Cannot inline @imports for ' + fileName +
+ ',\nthe following files had media queries in them:\n' +
+ flat.skippedList.join('\n'));
+ }
+
+ //Do comment removal.
+ try {
+ if (config.optimizeCss.indexOf(".keepComments") === -1) {
+ startIndex = 0;
+ //Get rid of comments.
+ while ((startIndex = fileContents.indexOf("/*", startIndex)) !== -1) {
+ endIndex = fileContents.indexOf("*/", startIndex + 2);
+ if (endIndex === -1) {
+ throw "Improper comment in CSS file: " + fileName;
+ }
+ comment = fileContents.substring(startIndex, endIndex);
+
+ if (config.preserveLicenseComments &&
+ (comment.indexOf('license') !== -1 ||
+ comment.indexOf('opyright') !== -1 ||
+ comment.indexOf('(c)') !== -1)) {
+ //Keep the comment, just increment the startIndex
+ startIndex = endIndex;
+ } else {
+ fileContents = fileContents.substring(0, startIndex) + fileContents.substring(endIndex + 2, fileContents.length);
+ startIndex = 0;
+ }
+ }
+ }
+ //Get rid of newlines.
+ if (config.optimizeCss.indexOf(".keepLines") === -1) {
+ fileContents = fileContents.replace(/[\r\n]/g, " ");
+ fileContents = fileContents.replace(/\s+/g, " ");
+ fileContents = fileContents.replace(/\{\s/g, "{");
+ fileContents = fileContents.replace(/\s\}/g, "}");
+ } else {
+ //Remove multiple empty lines.
+ fileContents = fileContents.replace(/(\r\n)+/g, "\r\n");
+ fileContents = fileContents.replace(/(\n)+/g, "\n");
+ }
+ //Remove unnecessary whitespace
+ if (config.optimizeCss.indexOf(".keepWhitespace") === -1) {
+ //Remove leading and trailing whitespace from lines
+ fileContents = fileContents.replace(/^[ \t]+/gm, "");
+ fileContents = fileContents.replace(/[ \t]+$/gm, "");
+ //Remove whitespace after semicolon, colon, curly brackets and commas
+ fileContents = fileContents.replace(/(;|:|\{|}|,)[ \t]+/g, "$1");
+ //Remove whitespace before opening curly brackets
+ fileContents = fileContents.replace(/[ \t]+(\{)/g, "$1");
+ //Truncate double whitespace
+ fileContents = fileContents.replace(/([ \t])+/g, "$1");
+ //Remove empty lines
+ fileContents = fileContents.replace(/^[ \t]*[\r\n]/gm,'');
+ }
+ } catch (e) {
+ fileContents = originalFileContents;
+ logger.error("Could not optimized CSS file: " + fileName + ", error: " + e);
+ }
+
+ file.saveUtf8File(outFileName, fileContents);
+
+ //text output to stdout and/or written to build.txt file
+ buildText = "\n"+ outFileName.replace(config.dir, "") +"\n----------------\n";
+ flat.importList.push(fileName);
+ buildText += flat.importList.map(function(path){
+ return path.replace(config.dir, "");
+ }).join("\n");
+
+ return {
+ importList: flat.importList,
+ buildText: buildText +"\n"
+ };
+ },
+
+ /**
+ * Optimizes CSS files, inlining @import calls, stripping comments, and
+ * optionally removes line returns.
+ * @param {String} startDir the path to the top level directory
+ * @param {Object} config the config object with the optimizeCss and
+ * cssImportIgnore options.
+ */
+ css: function (startDir, config) {
+ var buildText = "",
+ importList = [],
+ shouldRemove = config.dir && config.removeCombined,
+ i, fileName, result, fileList;
+ if (config.optimizeCss.indexOf("standard") !== -1) {
+ fileList = file.getFilteredFileList(startDir, /\.css$/, true);
+ if (fileList) {
+ for (i = 0; i < fileList.length; i++) {
+ fileName = fileList[i];
+ logger.trace("Optimizing (" + config.optimizeCss + ") CSS file: " + fileName);
+ result = optimize.cssFile(fileName, fileName, config);
+ buildText += result.buildText;
+ if (shouldRemove) {
+ result.importList.pop();
+ importList = importList.concat(result.importList);
+ }
+ }
+ }
+
+ if (shouldRemove) {
+ importList.forEach(function (path) {
+ if (file.exists(path)) {
+ file.deleteFile(path);
+ }
+ });
+ }
+ }
+ return buildText;
+ },
+
+ optimizers: {
+ uglify: function (fileName, fileContents, outFileName, keepLines, config) {
+ var parser = uglify.parser,
+ processor = uglify.uglify,
+ ast, errMessage, errMatch;
+
+ config = config || {};
+
+ logger.trace("Uglifying file: " + fileName);
+
+ try {
+ ast = parser.parse(fileContents, config.strict_semicolons);
+ if (config.no_mangle !== true) {
+ ast = processor.ast_mangle(ast, config);
+ }
+ ast = processor.ast_squeeze(ast, config);
+
+ fileContents = processor.gen_code(ast, config);
+
+ if (config.max_line_length) {
+ fileContents = processor.split_lines(fileContents, config.max_line_length);
+ }
+
+ //Add trailing semicolon to match uglifyjs command line version
+ fileContents += ';';
+ } catch (e) {
+ errMessage = e.toString();
+ errMatch = /\nError(\r)?\n/.exec(errMessage);
+ if (errMatch) {
+ errMessage = errMessage.substring(0, errMatch.index);
+ }
+ throw new Error('Cannot uglify file: ' + fileName + '. Skipping it. Error is:\n' + errMessage);
+ }
+ return fileContents;
+ },
+ uglify2: function (fileName, fileContents, outFileName, keepLines, config) {
+ var result, existingMap, resultMap, finalMap, sourceIndex,
+ uconfig = {},
+ existingMapPath = outFileName + '.map',
+ baseName = fileName && fileName.split('/').pop();
+
+ config = config || {};
+
+ lang.mixin(uconfig, config, true);
+
+ uconfig.fromString = true;
+
+ if (config.generateSourceMaps && (outFileName || config._buildSourceMap)) {
+ uconfig.outSourceMap = baseName;
+
+ if (config._buildSourceMap) {
+ existingMap = JSON.parse(config._buildSourceMap);
+ uconfig.inSourceMap = existingMap;
+ } else if (file.exists(existingMapPath)) {
+ uconfig.inSourceMap = existingMapPath;
+ existingMap = JSON.parse(file.readFile(existingMapPath));
+ }
+ }
+
+ logger.trace("Uglify2 file: " + fileName);
+
+ try {
+ //var tempContents = fileContents.replace(/\/\/\# sourceMappingURL=.*$/, '');
+ result = uglify2.minify(fileContents, uconfig, baseName + '.src.js');
+ if (uconfig.outSourceMap && result.map) {
+ resultMap = result.map;
+ if (existingMap) {
+ resultMap = JSON.parse(resultMap);
+ finalMap = SourceMapGenerator.fromSourceMap(new SourceMapConsumer(resultMap));
+ finalMap.applySourceMap(new SourceMapConsumer(existingMap));
+ resultMap = finalMap.toString();
+ } else if (!config._buildSourceMap) {
+ file.saveFile(outFileName + '.src.js', fileContents);
+ }
+
+ fileContents = result.code;
+
+ if (config._buildSourceMap) {
+ config._buildSourceMap = resultMap;
+ } else {
+ file.saveFile(outFileName + '.map', resultMap);
+ fileContents += "\n//# sourceMappingURL=" + baseName + ".map";
+ }
+ } else {
+ fileContents = result.code;
+ }
+ } catch (e) {
+ throw new Error('Cannot uglify2 file: ' + fileName + '. Skipping it. Error is:\n' + e.toString());
+ }
+ return fileContents;
+ }
+ }
+ };
+
+ return optimize;
+});
+/**
+ * @license RequireJS Copyright (c) 2010-2014, The Dojo Foundation All Rights Reserved.
+ * Available via the MIT or new BSD license.
+ * see: http://github.com/jrburke/requirejs for details
+ */
+/*
+ * This file patches require.js to communicate with the build system.
+ */
+
+//Using sloppy since this uses eval for some code like plugins,
+//which may not be strict mode compliant. So if use strict is used
+//below they will have strict rules applied and may cause an error.
+/*jslint sloppy: true, nomen: true, plusplus: true, regexp: true */
+/*global require, define: true */
+
+//NOT asking for require as a dependency since the goal is to modify the
+//global require below
+define('requirePatch', [ 'env!env/file', 'pragma', 'parse', 'lang', 'logger', 'commonJs', 'prim'], function (
+ file,
+ pragma,
+ parse,
+ lang,
+ logger,
+ commonJs,
+ prim
+) {
+
+ var allowRun = true,
+ hasProp = lang.hasProp,
+ falseProp = lang.falseProp,
+ getOwn = lang.getOwn;
+
+ //This method should be called when the patches to require should take hold.
+ return function () {
+ if (!allowRun) {
+ return;
+ }
+ allowRun = false;
+
+ var layer,
+ pluginBuilderRegExp = /(["']?)pluginBuilder(["']?)\s*[=\:]\s*["']([^'"\s]+)["']/,
+ oldNewContext = require.s.newContext,
+ oldDef,
+
+ //create local undefined values for module and exports,
+ //so that when files are evaled in this function they do not
+ //see the node values used for r.js
+ exports,
+ module;
+
+ /**
+ * Reset "global" build caches that are kept around between
+ * build layer builds. Useful to do when there are multiple
+ * top level requirejs.optimize() calls.
+ */
+ require._cacheReset = function () {
+ //Stored raw text caches, used by browser use.
+ require._cachedRawText = {};
+ //Stored cached file contents for reuse in other layers.
+ require._cachedFileContents = {};
+ //Store which cached files contain a require definition.
+ require._cachedDefinesRequireUrls = {};
+ };
+ require._cacheReset();
+
+ /**
+ * Makes sure the URL is something that can be supported by the
+ * optimization tool.
+ * @param {String} url
+ * @returns {Boolean}
+ */
+ require._isSupportedBuildUrl = function (url) {
+ //Ignore URLs with protocols, hosts or question marks, means either network
+ //access is needed to fetch it or it is too dynamic. Note that
+ //on Windows, full paths are used for some urls, which include
+ //the drive, like c:/something, so need to test for something other
+ //than just a colon.
+ if (url.indexOf("://") === -1 && url.indexOf("?") === -1 &&
+ url.indexOf('empty:') !== 0 && url.indexOf('//') !== 0) {
+ return true;
+ } else {
+ if (!layer.ignoredUrls[url]) {
+ if (url.indexOf('empty:') === -1) {
+ logger.info('Cannot optimize network URL, skipping: ' + url);
+ }
+ layer.ignoredUrls[url] = true;
+ }
+ return false;
+ }
+ };
+
+ function normalizeUrlWithBase(context, moduleName, url) {
+ //Adjust the URL if it was not transformed to use baseUrl.
+ if (require.jsExtRegExp.test(moduleName)) {
+ url = (context.config.dir || context.config.dirBaseUrl) + url;
+ }
+ return url;
+ }
+
+ //Overrides the new context call to add existing tracking features.
+ require.s.newContext = function (name) {
+ var context = oldNewContext(name),
+ oldEnable = context.enable,
+ moduleProto = context.Module.prototype,
+ oldInit = moduleProto.init,
+ oldCallPlugin = moduleProto.callPlugin;
+
+ //Only do this for the context used for building.
+ if (name === '_') {
+ //For build contexts, do everything sync
+ context.nextTick = function (fn) {
+ fn();
+ };
+
+ context.needFullExec = {};
+ context.fullExec = {};
+ context.plugins = {};
+ context.buildShimExports = {};
+
+ //Override the shim exports function generator to just
+ //spit out strings that can be used in the stringified
+ //build output.
+ context.makeShimExports = function (value) {
+ var fn;
+ if (context.config.wrapShim) {
+ fn = function () {
+ var str = 'return ';
+ // If specifies an export that is just a global
+ // name, no dot for a `this.` and such, then also
+ // attach to the global, for `var a = {}` files
+ // where the function closure would hide that from
+ // the global object.
+ if (value.exports && value.exports.indexOf('.') === -1) {
+ str += 'root.' + value.exports + ' = ';
+ }
+
+ if (value.init) {
+ str += '(' + value.init.toString() + '.apply(this, arguments))';
+ }
+ if (value.init && value.exports) {
+ str += ' || ';
+ }
+ if (value.exports) {
+ str += value.exports;
+ }
+ str += ';';
+ return str;
+ };
+ } else {
+ fn = function () {
+ return '(function (global) {\n' +
+ ' return function () {\n' +
+ ' var ret, fn;\n' +
+ (value.init ?
+ (' fn = ' + value.init.toString() + ';\n' +
+ ' ret = fn.apply(global, arguments);\n') : '') +
+ (value.exports ?
+ ' return ret || global.' + value.exports + ';\n' :
+ ' return ret;\n') +
+ ' };\n' +
+ '}(this))';
+ };
+ }
+
+ return fn;
+ };
+
+ context.enable = function (depMap, parent) {
+ var id = depMap.id,
+ parentId = parent && parent.map.id,
+ needFullExec = context.needFullExec,
+ fullExec = context.fullExec,
+ mod = getOwn(context.registry, id);
+
+ if (mod && !mod.defined) {
+ if (parentId && getOwn(needFullExec, parentId)) {
+ needFullExec[id] = true;
+ }
+
+ } else if ((getOwn(needFullExec, id) && falseProp(fullExec, id)) ||
+ (parentId && getOwn(needFullExec, parentId) &&
+ falseProp(fullExec, id))) {
+ context.require.undef(id);
+ }
+
+ return oldEnable.apply(context, arguments);
+ };
+
+ //Override load so that the file paths can be collected.
+ context.load = function (moduleName, url) {
+ /*jslint evil: true */
+ var contents, pluginBuilderMatch, builderName,
+ shim, shimExports;
+
+ //Do not mark the url as fetched if it is
+ //not an empty: URL, used by the optimizer.
+ //In that case we need to be sure to call
+ //load() for each module that is mapped to
+ //empty: so that dependencies are satisfied
+ //correctly.
+ if (url.indexOf('empty:') === 0) {
+ delete context.urlFetched[url];
+ }
+
+ //Only handle urls that can be inlined, so that means avoiding some
+ //URLs like ones that require network access or may be too dynamic,
+ //like JSONP
+ if (require._isSupportedBuildUrl(url)) {
+ //Adjust the URL if it was not transformed to use baseUrl.
+ url = normalizeUrlWithBase(context, moduleName, url);
+
+ //Save the module name to path and path to module name mappings.
+ layer.buildPathMap[moduleName] = url;
+ layer.buildFileToModule[url] = moduleName;
+
+ if (hasProp(context.plugins, moduleName)) {
+ //plugins need to have their source evaled as-is.
+ context.needFullExec[moduleName] = true;
+ }
+
+ prim().start(function () {
+ if (hasProp(require._cachedFileContents, url) &&
+ (falseProp(context.needFullExec, moduleName) ||
+ getOwn(context.fullExec, moduleName))) {
+ contents = require._cachedFileContents[url];
+
+ //If it defines require, mark it so it can be hoisted.
+ //Done here and in the else below, before the
+ //else block removes code from the contents.
+ //Related to #263
+ if (!layer.existingRequireUrl && require._cachedDefinesRequireUrls[url]) {
+ layer.existingRequireUrl = url;
+ }
+ } else {
+ //Load the file contents, process for conditionals, then
+ //evaluate it.
+ return require._cacheReadAsync(url).then(function (text) {
+ contents = text;
+
+ if (context.config.cjsTranslate &&
+ (!context.config.shim || !lang.hasProp(context.config.shim, moduleName))) {
+ contents = commonJs.convert(url, contents);
+ }
+
+ //If there is a read filter, run it now.
+ if (context.config.onBuildRead) {
+ contents = context.config.onBuildRead(moduleName, url, contents);
+ }
+
+ contents = pragma.process(url, contents, context.config, 'OnExecute');
+
+ //Find out if the file contains a require() definition. Need to know
+ //this so we can inject plugins right after it, but before they are needed,
+ //and to make sure this file is first, so that define calls work.
+ try {
+ if (!layer.existingRequireUrl && parse.definesRequire(url, contents)) {
+ layer.existingRequireUrl = url;
+ require._cachedDefinesRequireUrls[url] = true;
+ }
+ } catch (e1) {
+ throw new Error('Parse error using esprima ' +
+ 'for file: ' + url + '\n' + e1);
+ }
+ }).then(function () {
+ if (hasProp(context.plugins, moduleName)) {
+ //This is a loader plugin, check to see if it has a build extension,
+ //otherwise the plugin will act as the plugin builder too.
+ pluginBuilderMatch = pluginBuilderRegExp.exec(contents);
+ if (pluginBuilderMatch) {
+ //Load the plugin builder for the plugin contents.
+ builderName = context.makeModuleMap(pluginBuilderMatch[3],
+ context.makeModuleMap(moduleName),
+ null,
+ true).id;
+ return require._cacheReadAsync(context.nameToUrl(builderName));
+ }
+ }
+ return contents;
+ }).then(function (text) {
+ contents = text;
+
+ //Parse out the require and define calls.
+ //Do this even for plugins in case they have their own
+ //dependencies that may be separate to how the pluginBuilder works.
+ try {
+ if (falseProp(context.needFullExec, moduleName)) {
+ contents = parse(moduleName, url, contents, {
+ insertNeedsDefine: true,
+ has: context.config.has,
+ findNestedDependencies: context.config.findNestedDependencies
+ });
+ }
+ } catch (e2) {
+ throw new Error('Parse error using esprima ' +
+ 'for file: ' + url + '\n' + e2);
+ }
+
+ require._cachedFileContents[url] = contents;
+ });
+ }
+ }).then(function () {
+ if (contents) {
+ eval(contents);
+ }
+
+ try {
+ //If have a string shim config, and this is
+ //a fully executed module, try to see if
+ //it created a variable in this eval scope
+ if (getOwn(context.needFullExec, moduleName)) {
+ shim = getOwn(context.config.shim, moduleName);
+ if (shim && shim.exports) {
+ shimExports = eval(shim.exports);
+ if (typeof shimExports !== 'undefined') {
+ context.buildShimExports[moduleName] = shimExports;
+ }
+ }
+ }
+
+ //Need to close out completion of this module
+ //so that listeners will get notified that it is available.
+ context.completeLoad(moduleName);
+ } catch (e) {
+ //Track which module could not complete loading.
+ if (!e.moduleTree) {
+ e.moduleTree = [];
+ }
+ e.moduleTree.push(moduleName);
+ throw e;
+ }
+ }).then(null, function (eOuter) {
+
+ if (!eOuter.fileName) {
+ eOuter.fileName = url;
+ }
+ throw eOuter;
+ }).end();
+ } else {
+ //With unsupported URLs still need to call completeLoad to
+ //finish loading.
+ context.completeLoad(moduleName);
+ }
+ };
+
+ //Marks module has having a name, and optionally executes the
+ //callback, but only if it meets certain criteria.
+ context.execCb = function (name, cb, args, exports) {
+ var buildShimExports = getOwn(layer.context.buildShimExports, name);
+
+ if (buildShimExports) {
+ return buildShimExports;
+ } else if (cb.__requireJsBuild || getOwn(layer.context.needFullExec, name)) {
+ return cb.apply(exports, args);
+ }
+ return undefined;
+ };
+
+ moduleProto.init = function (depMaps) {
+ if (context.needFullExec[this.map.id]) {
+ lang.each(depMaps, lang.bind(this, function (depMap) {
+ if (typeof depMap === 'string') {
+ depMap = context.makeModuleMap(depMap,
+ (this.map.isDefine ? this.map : this.map.parentMap));
+ }
+
+ if (!context.fullExec[depMap.id]) {
+ context.require.undef(depMap.id);
+ }
+ }));
+ }
+
+ return oldInit.apply(this, arguments);
+ };
+
+ moduleProto.callPlugin = function () {
+ var map = this.map,
+ pluginMap = context.makeModuleMap(map.prefix),
+ pluginId = pluginMap.id,
+ pluginMod = getOwn(context.registry, pluginId);
+
+ context.plugins[pluginId] = true;
+ context.needFullExec[pluginId] = true;
+
+ //If the module is not waiting to finish being defined,
+ //undef it and start over, to get full execution.
+ if (falseProp(context.fullExec, pluginId) && (!pluginMod || pluginMod.defined)) {
+ context.require.undef(pluginMap.id);
+ }
+
+ return oldCallPlugin.apply(this, arguments);
+ };
+ }
+
+ return context;
+ };
+
+ //Clear up the existing context so that the newContext modifications
+ //above will be active.
+ delete require.s.contexts._;
+
+ /** Reset state for each build layer pass. */
+ require._buildReset = function () {
+ var oldContext = require.s.contexts._;
+
+ //Clear up the existing context.
+ delete require.s.contexts._;
+
+ //Set up new context, so the layer object can hold onto it.
+ require({});
+
+ layer = require._layer = {
+ buildPathMap: {},
+ buildFileToModule: {},
+ buildFilePaths: [],
+ pathAdded: {},
+ modulesWithNames: {},
+ needsDefine: {},
+ existingRequireUrl: "",
+ ignoredUrls: {},
+ context: require.s.contexts._
+ };
+
+ //Return the previous context in case it is needed, like for
+ //the basic config object.
+ return oldContext;
+ };
+
+ require._buildReset();
+
+ //Override define() to catch modules that just define an object, so that
+ //a dummy define call is not put in the build file for them. They do
+ //not end up getting defined via context.execCb, so we need to catch them
+ //at the define call.
+ oldDef = define;
+
+ //This function signature does not have to be exact, just match what we
+ //are looking for.
+ define = function (name) {
+ if (typeof name === "string" && falseProp(layer.needsDefine, name)) {
+ layer.modulesWithNames[name] = true;
+ }
+ return oldDef.apply(require, arguments);
+ };
+
+ define.amd = oldDef.amd;
+
+ //Add some utilities for plugins
+ require._readFile = file.readFile;
+ require._fileExists = function (path) {
+ return file.exists(path);
+ };
+
+ //Called when execManager runs for a dependency. Used to figure out
+ //what order of execution.
+ require.onResourceLoad = function (context, map) {
+ var id = map.id,
+ url;
+
+ //If build needed a full execution, indicate it
+ //has been done now. But only do it if the context is tracking
+ //that. Only valid for the context used in a build, not for
+ //other contexts being run, like for useLib, plain requirejs
+ //use in node/rhino.
+ if (context.needFullExec && getOwn(context.needFullExec, id)) {
+ context.fullExec[id] = true;
+ }
+
+ //A plugin.
+ if (map.prefix) {
+ if (falseProp(layer.pathAdded, id)) {
+ layer.buildFilePaths.push(id);
+ //For plugins the real path is not knowable, use the name
+ //for both module to file and file to module mappings.
+ layer.buildPathMap[id] = id;
+ layer.buildFileToModule[id] = id;
+ layer.modulesWithNames[id] = true;
+ layer.pathAdded[id] = true;
+ }
+ } else if (map.url && require._isSupportedBuildUrl(map.url)) {
+ //If the url has not been added to the layer yet, and it
+ //is from an actual file that was loaded, add it now.
+ url = normalizeUrlWithBase(context, id, map.url);
+ if (!layer.pathAdded[url] && getOwn(layer.buildPathMap, id)) {
+ //Remember the list of dependencies for this layer.
+ layer.buildFilePaths.push(url);
+ layer.pathAdded[url] = true;
+ }
+ }
+ };
+
+ //Called by output of the parse() function, when a file does not
+ //explicitly call define, probably just require, but the parse()
+ //function normalizes on define() for dependency mapping and file
+ //ordering works correctly.
+ require.needsDefine = function (moduleName) {
+ layer.needsDefine[moduleName] = true;
+ };
+ };
+});
+/**
+ * @license RequireJS Copyright (c) 2010-2014, The Dojo Foundation All Rights Reserved.
+ * Available via the MIT or new BSD license.
+ * see: http://github.com/jrburke/requirejs for details
+ */
+
+/*jslint */
+/*global define: false, console: false */
+
+define('commonJs', ['env!env/file', 'parse'], function (file, parse) {
+ 'use strict';
+ var commonJs = {
+ //Set to false if you do not want this file to log. Useful in environments
+ //like node where you want the work to happen without noise.
+ useLog: true,
+
+ convertDir: function (commonJsPath, savePath) {
+ var fileList, i,
+ jsFileRegExp = /\.js$/,
+ fileName, convertedFileName, fileContents;
+
+ //Get list of files to convert.
+ fileList = file.getFilteredFileList(commonJsPath, /\w/, true);
+
+ //Normalize on front slashes and make sure the paths do not end in a slash.
+ commonJsPath = commonJsPath.replace(/\\/g, "/");
+ savePath = savePath.replace(/\\/g, "/");
+ if (commonJsPath.charAt(commonJsPath.length - 1) === "/") {
+ commonJsPath = commonJsPath.substring(0, commonJsPath.length - 1);
+ }
+ if (savePath.charAt(savePath.length - 1) === "/") {
+ savePath = savePath.substring(0, savePath.length - 1);
+ }
+
+ //Cycle through all the JS files and convert them.
+ if (!fileList || !fileList.length) {
+ if (commonJs.useLog) {
+ if (commonJsPath === "convert") {
+ //A request just to convert one file.
+ console.log('\n\n' + commonJs.convert(savePath, file.readFile(savePath)));
+ } else {
+ console.log("No files to convert in directory: " + commonJsPath);
+ }
+ }
+ } else {
+ for (i = 0; i < fileList.length; i++) {
+ fileName = fileList[i];
+ convertedFileName = fileName.replace(commonJsPath, savePath);
+
+ //Handle JS files.
+ if (jsFileRegExp.test(fileName)) {
+ fileContents = file.readFile(fileName);
+ fileContents = commonJs.convert(fileName, fileContents);
+ file.saveUtf8File(convertedFileName, fileContents);
+ } else {
+ //Just copy the file over.
+ file.copyFile(fileName, convertedFileName, true);
+ }
+ }
+ }
+ },
+
+ /**
+ * Does the actual file conversion.
+ *
+ * @param {String} fileName the name of the file.
+ *
+ * @param {String} fileContents the contents of a file :)
+ *
+ * @returns {String} the converted contents
+ */
+ convert: function (fileName, fileContents) {
+ //Strip out comments.
+ try {
+ var preamble = '',
+ commonJsProps = parse.usesCommonJs(fileName, fileContents);
+
+ //First see if the module is not already RequireJS-formatted.
+ if (parse.usesAmdOrRequireJs(fileName, fileContents) || !commonJsProps) {
+ return fileContents;
+ }
+
+ if (commonJsProps.dirname || commonJsProps.filename) {
+ preamble = 'var __filename = module.uri || "", ' +
+ '__dirname = __filename.substring(0, __filename.lastIndexOf("/") + 1); ';
+ }
+
+ //Construct the wrapper boilerplate.
+ fileContents = 'define(function (require, exports, module) {' +
+ preamble +
+ fileContents +
+ '\n});\n';
+
+ } catch (e) {
+ console.log("commonJs.convert: COULD NOT CONVERT: " + fileName + ", so skipping it. Error was: " + e);
+ return fileContents;
+ }
+
+ return fileContents;
+ }
+ };
+
+ return commonJs;
+});
+/**
+ * @license Copyright (c) 2010-2014, The Dojo Foundation All Rights Reserved.
+ * Available via the MIT or new BSD license.
+ * see: http://github.com/jrburke/requirejs for details
+ */
+
+/*jslint plusplus: true, nomen: true, regexp: true */
+/*global define, requirejs */
+
+
+define('build', function (require) {
+ 'use strict';
+
+ var build,
+ lang = require('lang'),
+ prim = require('prim'),
+ logger = require('logger'),
+ file = require('env!env/file'),
+ parse = require('parse'),
+ optimize = require('optimize'),
+ pragma = require('pragma'),
+ transform = require('transform'),
+ requirePatch = require('requirePatch'),
+ env = require('env'),
+ commonJs = require('commonJs'),
+ SourceMapGenerator = require('source-map/source-map-generator'),
+ hasProp = lang.hasProp,
+ getOwn = lang.getOwn,
+ falseProp = lang.falseProp,
+ endsWithSemiColonRegExp = /;\s*$/,
+ endsWithSlashRegExp = /[\/\\]$/,
+ resourceIsModuleIdRegExp = /^[\w\/\\\.]+$/;
+
+ prim.nextTick = function (fn) {
+ fn();
+ };
+
+ //Now map require to the outermost requirejs, now that we have
+ //local dependencies for this module. The rest of the require use is
+ //manipulating the requirejs loader.
+ require = requirejs;
+
+ //Caching function for performance. Attached to
+ //require so it can be reused in requirePatch.js. _cachedRawText
+ //set up by requirePatch.js
+ require._cacheReadAsync = function (path, encoding) {
+ var d;
+
+ if (lang.hasProp(require._cachedRawText, path)) {
+ d = prim();
+ d.resolve(require._cachedRawText[path]);
+ return d.promise;
+ } else {
+ return file.readFileAsync(path, encoding).then(function (text) {
+ require._cachedRawText[path] = text;
+ return text;
+ });
+ }
+ };
+
+ function makeBuildBaseConfig() {
+ return {
+ appDir: "",
+ pragmas: {},
+ paths: {},
+ optimize: "uglify",
+ optimizeCss: "standard.keepLines.keepWhitespace",
+ inlineText: true,
+ isBuild: true,
+ optimizeAllPluginResources: false,
+ findNestedDependencies: false,
+ preserveLicenseComments: true,
+ //By default, all files/directories are copied, unless
+ //they match this regexp, by default just excludes .folders
+ dirExclusionRegExp: file.dirExclusionRegExp,
+ _buildPathToModuleIndex: {}
+ };
+ }
+
+ /**
+ * Some JS may not be valid if concatenated with other JS, in particular
+ * the style of omitting semicolons and rely on ASI. Add a semicolon in
+ * those cases.
+ */
+ function addSemiColon(text, config) {
+ if (config.skipSemiColonInsertion || endsWithSemiColonRegExp.test(text)) {
+ return text;
+ } else {
+ return text + ";";
+ }
+ }
+
+ function endsWithSlash(dirName) {
+ if (dirName.charAt(dirName.length - 1) !== "/") {
+ dirName += "/";
+ }
+ return dirName;
+ }
+
+ //Method used by plugin writeFile calls, defined up here to avoid
+ //jslint warning about "making a function in a loop".
+ function makeWriteFile(namespace, layer) {
+ function writeFile(name, contents) {
+ logger.trace('Saving plugin-optimized file: ' + name);
+ file.saveUtf8File(name, contents);
+ }
+
+ writeFile.asModule = function (moduleName, fileName, contents) {
+ writeFile(fileName,
+ build.toTransport(namespace, moduleName, fileName, contents, layer));
+ };
+
+ return writeFile;
+ }
+
+ /**
+ * Main API entry point into the build. The args argument can either be
+ * an array of arguments (like the onese passed on a command-line),
+ * or it can be a JavaScript object that has the format of a build profile
+ * file.
+ *
+ * If it is an object, then in addition to the normal properties allowed in
+ * a build profile file, the object should contain one other property:
+ *
+ * The object could also contain a "buildFile" property, which is a string
+ * that is the file path to a build profile that contains the rest
+ * of the build profile directives.
+ *
+ * This function does not return a status, it should throw an error if
+ * there is a problem completing the build.
+ */
+ build = function (args) {
+ var buildFile, cmdConfig, errorMsg, errorStack, stackMatch, errorTree,
+ i, j, errorMod,
+ stackRegExp = /( {4}at[^\n]+)\n/,
+ standardIndent = ' ';
+
+ return prim().start(function () {
+ if (!args || lang.isArray(args)) {
+ if (!args || args.length < 1) {
+ logger.error("build.js buildProfile.js\n" +
+ "where buildProfile.js is the name of the build file (see example.build.js for hints on how to make a build file).");
+ return undefined;
+ }
+
+ //Next args can include a build file path as well as other build args.
+ //build file path comes first. If it does not contain an = then it is
+ //a build file path. Otherwise, just all build args.
+ if (args[0].indexOf("=") === -1) {
+ buildFile = args[0];
+ args.splice(0, 1);
+ }
+
+ //Remaining args are options to the build
+ cmdConfig = build.convertArrayToObject(args);
+ cmdConfig.buildFile = buildFile;
+ } else {
+ cmdConfig = args;
+ }
+
+ return build._run(cmdConfig);
+ }).then(null, function (e) {
+ var err;
+
+ errorMsg = e.toString();
+ errorTree = e.moduleTree;
+ stackMatch = stackRegExp.exec(errorMsg);
+
+ if (stackMatch) {
+ errorMsg += errorMsg.substring(0, stackMatch.index + stackMatch[0].length + 1);
+ }
+
+ //If a module tree that shows what module triggered the error,
+ //print it out.
+ if (errorTree && errorTree.length > 0) {
+ errorMsg += '\nIn module tree:\n';
+
+ for (i = errorTree.length - 1; i > -1; i--) {
+ errorMod = errorTree[i];
+ if (errorMod) {
+ for (j = errorTree.length - i; j > -1; j--) {
+ errorMsg += standardIndent;
+ }
+ errorMsg += errorMod + '\n';
+ }
+ }
+
+ logger.error(errorMsg);
+ }
+
+ errorStack = e.stack;
+
+ if (typeof args === 'string' && args.indexOf('stacktrace=true') !== -1) {
+ errorMsg += '\n' + errorStack;
+ } else {
+ if (!stackMatch && errorStack) {
+ //Just trim out the first "at" in the stack.
+ stackMatch = stackRegExp.exec(errorStack);
+ if (stackMatch) {
+ errorMsg += '\n' + stackMatch[0] || '';
+ }
+ }
+ }
+
+ err = new Error(errorMsg);
+ err.originalError = e;
+ throw err;
+ });
+ };
+
+ build._run = function (cmdConfig) {
+ var buildPaths, fileName, fileNames,
+ paths, i,
+ baseConfig, config,
+ modules, srcPath, buildContext,
+ destPath, moduleMap, parentModuleMap, context,
+ resources, resource, plugin, fileContents,
+ pluginProcessed = {},
+ buildFileContents = "",
+ pluginCollector = {};
+
+ return prim().start(function () {
+ var prop;
+
+ //Can now run the patches to require.js to allow it to be used for
+ //build generation. Do it here instead of at the top of the module
+ //because we want normal require behavior to load the build tool
+ //then want to switch to build mode.
+ requirePatch();
+
+ config = build.createConfig(cmdConfig);
+ paths = config.paths;
+
+ //Remove the previous build dir, in case it contains source transforms,
+ //like the ones done with onBuildRead and onBuildWrite.
+ if (config.dir && !config.keepBuildDir && file.exists(config.dir)) {
+ file.deleteFile(config.dir);
+ }
+
+ if (!config.out && !config.cssIn) {
+ //This is not just a one-off file build but a full build profile, with
+ //lots of files to process.
+
+ //First copy all the baseUrl content
+ file.copyDir((config.appDir || config.baseUrl), config.dir, /\w/, true);
+
+ //Adjust baseUrl if config.appDir is in play, and set up build output paths.
+ buildPaths = {};
+ if (config.appDir) {
+ //All the paths should be inside the appDir, so just adjust
+ //the paths to use the dirBaseUrl
+ for (prop in paths) {
+ if (hasProp(paths, prop)) {
+ buildPaths[prop] = paths[prop].replace(config.appDir, config.dir);
+ }
+ }
+ } else {
+ //If no appDir, then make sure to copy the other paths to this directory.
+ for (prop in paths) {
+ if (hasProp(paths, prop)) {
+ //Set up build path for each path prefix, but only do so
+ //if the path falls out of the current baseUrl
+ if (paths[prop].indexOf(config.baseUrl) === 0) {
+ buildPaths[prop] = paths[prop].replace(config.baseUrl, config.dirBaseUrl);
+ } else {
+ buildPaths[prop] = paths[prop] === 'empty:' ? 'empty:' : prop.replace(/\./g, "/");
+
+ //Make sure source path is fully formed with baseUrl,
+ //if it is a relative URL.
+ srcPath = paths[prop];
+ if (srcPath.indexOf('/') !== 0 && srcPath.indexOf(':') === -1) {
+ srcPath = config.baseUrl + srcPath;
+ }
+
+ destPath = config.dirBaseUrl + buildPaths[prop];
+
+ //Skip empty: paths
+ if (srcPath !== 'empty:') {
+ //If the srcPath is a directory, copy the whole directory.
+ if (file.exists(srcPath) && file.isDirectory(srcPath)) {
+ //Copy files to build area. Copy all files (the /\w/ regexp)
+ file.copyDir(srcPath, destPath, /\w/, true);
+ } else {
+ //Try a .js extension
+ srcPath += '.js';
+ destPath += '.js';
+ file.copyFile(srcPath, destPath);
+ }
+ }
+ }
+ }
+ }
+ }
+ }
+
+ //Figure out source file location for each module layer. Do this by seeding require
+ //with source area configuration. This is needed so that later the module layers
+ //can be manually copied over to the source area, since the build may be
+ //require multiple times and the above copyDir call only copies newer files.
+ require({
+ baseUrl: config.baseUrl,
+ paths: paths,
+ packagePaths: config.packagePaths,
+ packages: config.packages
+ });
+ buildContext = require.s.contexts._;
+ modules = config.modules;
+
+ if (modules) {
+ modules.forEach(function (module) {
+ if (module.name) {
+ module._sourcePath = buildContext.nameToUrl(module.name);
+ //If the module does not exist, and this is not a "new" module layer,
+ //as indicated by a true "create" property on the module, and
+ //it is not a plugin-loaded resource, and there is no
+ //'rawText' containing the module's source then throw an error.
+ if (!file.exists(module._sourcePath) && !module.create &&
+ module.name.indexOf('!') === -1 &&
+ (!config.rawText || !lang.hasProp(config.rawText, module.name))) {
+ throw new Error("ERROR: module path does not exist: " +
+ module._sourcePath + " for module named: " + module.name +
+ ". Path is relative to: " + file.absPath('.'));
+ }
+ }
+ });
+ }
+
+ if (config.out) {
+ //Just set up the _buildPath for the module layer.
+ require(config);
+ if (!config.cssIn) {
+ config.modules[0]._buildPath = typeof config.out === 'function' ?
+ 'FUNCTION' : config.out;
+ }
+ } else if (!config.cssIn) {
+ //Now set up the config for require to use the build area, and calculate the
+ //build file locations. Pass along any config info too.
+ baseConfig = {
+ baseUrl: config.dirBaseUrl,
+ paths: buildPaths
+ };
+
+ lang.mixin(baseConfig, config);
+ require(baseConfig);
+
+ if (modules) {
+ modules.forEach(function (module) {
+ if (module.name) {
+ module._buildPath = buildContext.nameToUrl(module.name, null);
+
+ //If buildPath and sourcePath are the same, throw since this
+ //would result in modifying source. This condition can happen
+ //with some more tricky paths: config and appDir/baseUrl
+ //setting, which is a sign of incorrect config.
+ if (module._buildPath === module._sourcePath) {
+ throw new Error('Module ID \'' + module.name +
+ '\' has a source path that is same as output path: ' +
+ module._sourcePath +
+ '. Stopping, config is malformed.');
+ }
+
+ if (!module.create) {
+ file.copyFile(module._sourcePath, module._buildPath);
+ }
+ }
+ });
+ }
+ }
+
+ //Run CSS optimizations before doing JS module tracing, to allow
+ //things like text loader plugins loading CSS to get the optimized
+ //CSS.
+ if (config.optimizeCss && config.optimizeCss !== "none" && config.dir) {
+ buildFileContents += optimize.css(config.dir, config);
+ }
+ }).then(function() {
+ baseConfig = lang.deeplikeCopy(require.s.contexts._.config);
+ }).then(function () {
+ var actions = [];
+
+ if (modules) {
+ actions = modules.map(function (module, i) {
+ return function () {
+ //Save off buildPath to module index in a hash for quicker
+ //lookup later.
+ config._buildPathToModuleIndex[file.normalize(module._buildPath)] = i;
+
+ //Call require to calculate dependencies.
+ return build.traceDependencies(module, config, baseConfig)
+ .then(function (layer) {
+ module.layer = layer;
+ });
+ };
+ });
+
+ return prim.serial(actions);
+ }
+ }).then(function () {
+ var actions;
+
+ if (modules) {
+ //Now build up shadow layers for anything that should be excluded.
+ //Do this after tracing dependencies for each module, in case one
+ //of those modules end up being one of the excluded values.
+ actions = modules.map(function (module) {
+ return function () {
+ if (module.exclude) {
+ module.excludeLayers = [];
+ return prim.serial(module.exclude.map(function (exclude, i) {
+ return function () {
+ //See if it is already in the list of modules.
+ //If not trace dependencies for it.
+ var found = build.findBuildModule(exclude, modules);
+ if (found) {
+ module.excludeLayers[i] = found;
+ } else {
+ return build.traceDependencies({name: exclude}, config, baseConfig)
+ .then(function (layer) {
+ module.excludeLayers[i] = { layer: layer };
+ });
+ }
+ };
+ }));
+ }
+ };
+ });
+
+ return prim.serial(actions);
+ }
+ }).then(function () {
+ if (modules) {
+ return prim.serial(modules.map(function (module) {
+ return function () {
+ if (module.exclude) {
+ //module.exclude is an array of module names. For each one,
+ //get the nested dependencies for it via a matching entry
+ //in the module.excludeLayers array.
+ module.exclude.forEach(function (excludeModule, i) {
+ var excludeLayer = module.excludeLayers[i].layer,
+ map = excludeLayer.buildFileToModule;
+ excludeLayer.buildFilePaths.forEach(function(filePath){
+ build.removeModulePath(map[filePath], filePath, module.layer);
+ });
+ });
+ }
+ if (module.excludeShallow) {
+ //module.excludeShallow is an array of module names.
+ //shallow exclusions are just that module itself, and not
+ //its nested dependencies.
+ module.excludeShallow.forEach(function (excludeShallowModule) {
+ var path = getOwn(module.layer.buildPathMap, excludeShallowModule);
+ if (path) {
+ build.removeModulePath(excludeShallowModule, path, module.layer);
+ }
+ });
+ }
+
+ //Flatten them and collect the build output for each module.
+ return build.flattenModule(module, module.layer, config).then(function (builtModule) {
+ var finalText, baseName;
+ //Save it to a temp file for now, in case there are other layers that
+ //contain optimized content that should not be included in later
+ //layer optimizations. See issue #56.
+ if (module._buildPath === 'FUNCTION') {
+ module._buildText = builtModule.text;
+ module._buildSourceMap = builtModule.sourceMap;
+ } else {
+ finalText = builtModule.text;
+ if (builtModule.sourceMap) {
+ baseName = module._buildPath.split('/');
+ baseName = baseName.pop();
+ finalText += '\n//# sourceMappingURL=' + baseName + '.map';
+ file.saveUtf8File(module._buildPath + '.map', builtModule.sourceMap);
+ }
+ file.saveUtf8File(module._buildPath + '-temp', finalText);
+
+ }
+ buildFileContents += builtModule.buildText;
+ });
+ };
+ }));
+ }
+ }).then(function () {
+ var moduleName, outOrigSourceMap;
+ if (modules) {
+ //Now move the build layers to their final position.
+ modules.forEach(function (module) {
+ var finalPath = module._buildPath;
+ if (finalPath !== 'FUNCTION') {
+ if (file.exists(finalPath)) {
+ file.deleteFile(finalPath);
+ }
+ file.renameFile(finalPath + '-temp', finalPath);
+
+ //And finally, if removeCombined is specified, remove
+ //any of the files that were used in this layer.
+ //Be sure not to remove other build layers.
+ if (config.removeCombined && !config.out) {
+ module.layer.buildFilePaths.forEach(function (path) {
+ var isLayer = modules.some(function (mod) {
+ return mod._buildPath === path;
+ }),
+ relPath = build.makeRelativeFilePath(config.dir, path);
+
+ if (file.exists(path) &&
+ // not a build layer target
+ !isLayer &&
+ // not outside the build directory
+ relPath.indexOf('..') !== 0) {
+ file.deleteFile(path);
+ }
+ });
+ }
+ }
+
+ //Signal layer is done
+ if (config.onModuleBundleComplete) {
+ config.onModuleBundleComplete(module.onCompleteData);
+ }
+ });
+ }
+
+ //If removeCombined in play, remove any empty directories that
+ //may now exist because of its use
+ if (config.removeCombined && !config.out && config.dir) {
+ file.deleteEmptyDirs(config.dir);
+ }
+
+ //Do other optimizations.
+ if (config.out && !config.cssIn) {
+ //Just need to worry about one JS file.
+ fileName = config.modules[0]._buildPath;
+ if (fileName === 'FUNCTION') {
+ outOrigSourceMap = config.modules[0]._buildSourceMap;
+ config._buildSourceMap = outOrigSourceMap;
+ config.modules[0]._buildText = optimize.js((config.modules[0].name ||
+ config.modules[0].include[0] ||
+ fileName) + '.build.js',
+ config.modules[0]._buildText,
+ null,
+ config);
+ if (config._buildSourceMap && config._buildSourceMap !== outOrigSourceMap) {
+ config.modules[0]._buildSourceMap = config._buildSourceMap;
+ config._buildSourceMap = null;
+ }
+ } else {
+ optimize.jsFile(fileName, null, fileName, config);
+ }
+ } else if (!config.cssIn) {
+ //Normal optimizations across modules.
+
+ //JS optimizations.
+ fileNames = file.getFilteredFileList(config.dir, /\.js$/, true);
+ fileNames.forEach(function (fileName) {
+ var cfg, override, moduleIndex;
+
+ //Generate the module name from the config.dir root.
+ moduleName = fileName.replace(config.dir, '');
+ //Get rid of the extension
+ moduleName = moduleName.substring(0, moduleName.length - 3);
+
+ //If there is an override for a specific layer build module,
+ //and this file is that module, mix in the override for use
+ //by optimize.jsFile.
+ moduleIndex = getOwn(config._buildPathToModuleIndex, fileName);
+ //Normalize, since getOwn could have returned undefined
+ moduleIndex = moduleIndex === 0 || moduleIndex > 0 ? moduleIndex : -1;
+
+ //Try to avoid extra work if the other files do not need to
+ //be read. Build layers should be processed at the very
+ //least for optimization.
+ if (moduleIndex > -1 || !config.skipDirOptimize ||
+ config.normalizeDirDefines === "all" ||
+ config.cjsTranslate) {
+ //Convert the file to transport format, but without a name
+ //inserted (by passing null for moduleName) since the files are
+ //standalone, one module per file.
+ fileContents = file.readFile(fileName);
+
+
+ //For builds, if wanting cjs translation, do it now, so that
+ //the individual modules can be loaded cross domain via
+ //plain script tags.
+ if (config.cjsTranslate &&
+ (!config.shim || !lang.hasProp(config.shim, moduleName))) {
+ fileContents = commonJs.convert(fileName, fileContents);
+ }
+
+ if (moduleIndex === -1) {
+ if (config.onBuildRead) {
+ fileContents = config.onBuildRead(moduleName,
+ fileName,
+ fileContents);
+ }
+
+ //Only do transport normalization if this is not a build
+ //layer (since it was already normalized) and if
+ //normalizeDirDefines indicated all should be done.
+ if (config.normalizeDirDefines === "all") {
+ fileContents = build.toTransport(config.namespace,
+ null,
+ fileName,
+ fileContents);
+ }
+
+ if (config.onBuildWrite) {
+ fileContents = config.onBuildWrite(moduleName,
+ fileName,
+ fileContents);
+ }
+ }
+
+ override = moduleIndex > -1 ?
+ config.modules[moduleIndex].override : null;
+ if (override) {
+ cfg = build.createOverrideConfig(config, override);
+ } else {
+ cfg = config;
+ }
+
+ if (moduleIndex > -1 || !config.skipDirOptimize) {
+ optimize.jsFile(fileName, fileContents, fileName, cfg, pluginCollector);
+ }
+ }
+ });
+
+ //Normalize all the plugin resources.
+ context = require.s.contexts._;
+
+ for (moduleName in pluginCollector) {
+ if (hasProp(pluginCollector, moduleName)) {
+ parentModuleMap = context.makeModuleMap(moduleName);
+ resources = pluginCollector[moduleName];
+ for (i = 0; i < resources.length; i++) {
+ resource = resources[i];
+ moduleMap = context.makeModuleMap(resource, parentModuleMap);
+ if (falseProp(context.plugins, moduleMap.prefix)) {
+ //Set the value in context.plugins so it
+ //will be evaluated as a full plugin.
+ context.plugins[moduleMap.prefix] = true;
+
+ //Do not bother if the plugin is not available.
+ if (!file.exists(require.toUrl(moduleMap.prefix + '.js'))) {
+ continue;
+ }
+
+ //Rely on the require in the build environment
+ //to be synchronous
+ context.require([moduleMap.prefix]);
+
+ //Now that the plugin is loaded, redo the moduleMap
+ //since the plugin will need to normalize part of the path.
+ moduleMap = context.makeModuleMap(resource, parentModuleMap);
+ }
+
+ //Only bother with plugin resources that can be handled
+ //processed by the plugin, via support of the writeFile
+ //method.
+ if (falseProp(pluginProcessed, moduleMap.id)) {
+ //Only do the work if the plugin was really loaded.
+ //Using an internal access because the file may
+ //not really be loaded.
+ plugin = getOwn(context.defined, moduleMap.prefix);
+ if (plugin && plugin.writeFile) {
+ plugin.writeFile(
+ moduleMap.prefix,
+ moduleMap.name,
+ require,
+ makeWriteFile(
+ config.namespace
+ ),
+ context.config
+ );
+ }
+
+ pluginProcessed[moduleMap.id] = true;
+ }
+ }
+
+ }
+ }
+
+ //console.log('PLUGIN COLLECTOR: ' + JSON.stringify(pluginCollector, null, " "));
+
+
+ //All module layers are done, write out the build.txt file.
+ file.saveUtf8File(config.dir + "build.txt", buildFileContents);
+ }
+
+ //If just have one CSS file to optimize, do that here.
+ if (config.cssIn) {
+ buildFileContents += optimize.cssFile(config.cssIn, config.out, config).buildText;
+ }
+
+ if (typeof config.out === 'function') {
+ config.out(config.modules[0]._buildText, config.modules[0]._buildSourceMap);
+ }
+
+ //Print out what was built into which layers.
+ if (buildFileContents) {
+ logger.info(buildFileContents);
+ return buildFileContents;
+ }
+
+ return '';
+ });
+ };
+
+ /**
+ * Converts command line args like "paths.foo=../some/path"
+ * result.paths = { foo: '../some/path' } where prop = paths,
+ * name = paths.foo and value = ../some/path, so it assumes the
+ * name=value splitting has already happened.
+ */
+ function stringDotToObj(result, name, value) {
+ var parts = name.split('.');
+
+ parts.forEach(function (prop, i) {
+ if (i === parts.length - 1) {
+ result[prop] = value;
+ } else {
+ if (falseProp(result, prop)) {
+ result[prop] = {};
+ }
+ result = result[prop];
+ }
+
+ });
+ }
+
+ build.objProps = {
+ paths: true,
+ wrap: true,
+ pragmas: true,
+ pragmasOnSave: true,
+ has: true,
+ hasOnSave: true,
+ uglify: true,
+ uglify2: true,
+ closure: true,
+ map: true,
+ throwWhen: true
+ };
+
+ build.hasDotPropMatch = function (prop) {
+ var dotProp,
+ index = prop.indexOf('.');
+
+ if (index !== -1) {
+ dotProp = prop.substring(0, index);
+ return hasProp(build.objProps, dotProp);
+ }
+ return false;
+ };
+
+ /**
+ * Converts an array that has String members of "name=value"
+ * into an object, where the properties on the object are the names in the array.
+ * Also converts the strings "true" and "false" to booleans for the values.
+ * member name/value pairs, and converts some comma-separated lists into
+ * arrays.
+ * @param {Array} ary
+ */
+ build.convertArrayToObject = function (ary) {
+ var result = {}, i, separatorIndex, prop, value,
+ needArray = {
+ "include": true,
+ "exclude": true,
+ "excludeShallow": true,
+ "insertRequire": true,
+ "stubModules": true,
+ "deps": true
+ };
+
+ for (i = 0; i < ary.length; i++) {
+ separatorIndex = ary[i].indexOf("=");
+ if (separatorIndex === -1) {
+ throw "Malformed name/value pair: [" + ary[i] + "]. Format should be name=value";
+ }
+
+ value = ary[i].substring(separatorIndex + 1, ary[i].length);
+ if (value === "true") {
+ value = true;
+ } else if (value === "false") {
+ value = false;
+ }
+
+ prop = ary[i].substring(0, separatorIndex);
+
+ //Convert to array if necessary
+ if (getOwn(needArray, prop)) {
+ value = value.split(",");
+ }
+
+ if (build.hasDotPropMatch(prop)) {
+ stringDotToObj(result, prop, value);
+ } else {
+ result[prop] = value;
+ }
+ }
+ return result; //Object
+ };
+
+ build.makeAbsPath = function (path, absFilePath) {
+ if (!absFilePath) {
+ return path;
+ }
+
+ //Add abspath if necessary. If path starts with a slash or has a colon,
+ //then already is an abolute path.
+ if (path.indexOf('/') !== 0 && path.indexOf(':') === -1) {
+ path = absFilePath +
+ (absFilePath.charAt(absFilePath.length - 1) === '/' ? '' : '/') +
+ path;
+ path = file.normalize(path);
+ }
+ return path.replace(lang.backSlashRegExp, '/');
+ };
+
+ build.makeAbsObject = function (props, obj, absFilePath) {
+ var i, prop;
+ if (obj) {
+ for (i = 0; i < props.length; i++) {
+ prop = props[i];
+ if (hasProp(obj, prop) && typeof obj[prop] === 'string') {
+ obj[prop] = build.makeAbsPath(obj[prop], absFilePath);
+ }
+ }
+ }
+ };
+
+ /**
+ * For any path in a possible config, make it absolute relative
+ * to the absFilePath passed in.
+ */
+ build.makeAbsConfig = function (config, absFilePath) {
+ var props, prop, i;
+
+ props = ["appDir", "dir", "baseUrl"];
+ for (i = 0; i < props.length; i++) {
+ prop = props[i];
+
+ if (getOwn(config, prop)) {
+ //Add abspath if necessary, make sure these paths end in
+ //slashes
+ if (prop === "baseUrl") {
+ config.originalBaseUrl = config.baseUrl;
+ if (config.appDir) {
+ //If baseUrl with an appDir, the baseUrl is relative to
+ //the appDir, *not* the absFilePath. appDir and dir are
+ //made absolute before baseUrl, so this will work.
+ config.baseUrl = build.makeAbsPath(config.originalBaseUrl, config.appDir);
+ } else {
+ //The dir output baseUrl is same as regular baseUrl, both
+ //relative to the absFilePath.
+ config.baseUrl = build.makeAbsPath(config[prop], absFilePath);
+ }
+ } else {
+ config[prop] = build.makeAbsPath(config[prop], absFilePath);
+ }
+
+ config[prop] = endsWithSlash(config[prop]);
+ }
+ }
+
+ build.makeAbsObject(["out", "cssIn"], config, absFilePath);
+ build.makeAbsObject(["startFile", "endFile"], config.wrap, absFilePath);
+ };
+
+ /**
+ * Creates a relative path to targetPath from refPath.
+ * Only deals with file paths, not folders. If folders,
+ * make sure paths end in a trailing '/'.
+ */
+ build.makeRelativeFilePath = function (refPath, targetPath) {
+ var i, dotLength, finalParts, length, targetParts, targetName,
+ refParts = refPath.split('/'),
+ hasEndSlash = endsWithSlashRegExp.test(targetPath),
+ dotParts = [];
+
+ targetPath = file.normalize(targetPath);
+ if (hasEndSlash && !endsWithSlashRegExp.test(targetPath)) {
+ targetPath += '/';
+ }
+ targetParts = targetPath.split('/');
+ //Pull off file name
+ targetName = targetParts.pop();
+
+ //Also pop off the ref file name to make the matches against
+ //targetParts equivalent.
+ refParts.pop();
+
+ length = refParts.length;
+
+ for (i = 0; i < length; i += 1) {
+ if (refParts[i] !== targetParts[i]) {
+ break;
+ }
+ }
+
+ //Now i is the index in which they diverge.
+ finalParts = targetParts.slice(i);
+
+ dotLength = length - i;
+ for (i = 0; i > -1 && i < dotLength; i += 1) {
+ dotParts.push('..');
+ }
+
+ return dotParts.join('/') + (dotParts.length ? '/' : '') +
+ finalParts.join('/') + (finalParts.length ? '/' : '') +
+ targetName;
+ };
+
+ build.nestedMix = {
+ paths: true,
+ has: true,
+ hasOnSave: true,
+ pragmas: true,
+ pragmasOnSave: true
+ };
+
+ /**
+ * Mixes additional source config into target config, and merges some
+ * nested config, like paths, correctly.
+ */
+ function mixConfig(target, source, skipArrays) {
+ var prop, value, isArray, targetValue;
+
+ for (prop in source) {
+ if (hasProp(source, prop)) {
+ //If the value of the property is a plain object, then
+ //allow a one-level-deep mixing of it.
+ value = source[prop];
+ isArray = lang.isArray(value);
+ if (typeof value === 'object' && value &&
+ !isArray && !lang.isFunction(value) &&
+ !lang.isRegExp(value)) {
+ target[prop] = lang.mixin({}, target[prop], value, true);
+ } else if (isArray) {
+ if (!skipArrays) {
+ // Some config, like packages, are arrays. For those,
+ // just merge the results.
+ targetValue = target[prop];
+ if (lang.isArray(targetValue)) {
+ target[prop] = targetValue.concat(value);
+ } else {
+ target[prop] = value;
+ }
+ }
+ } else {
+ target[prop] = value;
+ }
+ }
+ }
+
+ //Set up log level since it can affect if errors are thrown
+ //or caught and passed to errbacks while doing config setup.
+ if (lang.hasProp(target, 'logLevel')) {
+ logger.logLevel(target.logLevel);
+ }
+ }
+
+ /**
+ * Converts a wrap.startFile or endFile to be start/end as a string.
+ * the startFile/endFile values can be arrays.
+ */
+ function flattenWrapFile(wrap, keyName, absFilePath) {
+ var keyFileName = keyName + 'File';
+
+ if (typeof wrap[keyName] !== 'string' && wrap[keyFileName]) {
+ wrap[keyName] = '';
+ if (typeof wrap[keyFileName] === 'string') {
+ wrap[keyFileName] = [wrap[keyFileName]];
+ }
+ wrap[keyFileName].forEach(function (fileName) {
+ wrap[keyName] += (wrap[keyName] ? '\n' : '') +
+ file.readFile(build.makeAbsPath(fileName, absFilePath));
+ });
+ } else if (wrap[keyName] === null || wrap[keyName] === undefined) {
+ //Allow missing one, just set to empty string.
+ wrap[keyName] = '';
+ } else if (typeof wrap[keyName] !== 'string') {
+ throw new Error('wrap.' + keyName + ' or wrap.' + keyFileName + ' malformed');
+ }
+ }
+
+ function normalizeWrapConfig(config, absFilePath) {
+ //Get any wrap text.
+ try {
+ if (config.wrap) {
+ if (config.wrap === true) {
+ //Use default values.
+ config.wrap = {
+ start: '(function () {',
+ end: '}());'
+ };
+ } else {
+ flattenWrapFile(config.wrap, 'start', absFilePath);
+ flattenWrapFile(config.wrap, 'end', absFilePath);
+ }
+ }
+ } catch (wrapError) {
+ throw new Error('Malformed wrap config: ' + wrapError.toString());
+ }
+ }
+
+ /**
+ * Creates a config object for an optimization build.
+ * It will also read the build profile if it is available, to create
+ * the configuration.
+ *
+ * @param {Object} cfg config options that take priority
+ * over defaults and ones in the build file. These options could
+ * be from a command line, for instance.
+ *
+ * @param {Object} the created config object.
+ */
+ build.createConfig = function (cfg) {
+ /*jslint evil: true */
+ var buildFileContents, buildFileConfig, mainConfig,
+ mainConfigFile, mainConfigPath, buildFile, absFilePath,
+ config = {},
+ buildBaseConfig = makeBuildBaseConfig();
+
+ //Make sure all paths are relative to current directory.
+ absFilePath = file.absPath('.');
+ build.makeAbsConfig(cfg, absFilePath);
+ build.makeAbsConfig(buildBaseConfig, absFilePath);
+
+ lang.mixin(config, buildBaseConfig);
+ lang.mixin(config, cfg, true);
+
+ //Set up log level early since it can affect if errors are thrown
+ //or caught and passed to errbacks, even while constructing config.
+ if (lang.hasProp(config, 'logLevel')) {
+ logger.logLevel(config.logLevel);
+ }
+
+ if (config.buildFile) {
+ //A build file exists, load it to get more config.
+ buildFile = file.absPath(config.buildFile);
+
+ //Find the build file, and make sure it exists, if this is a build
+ //that has a build profile, and not just command line args with an in=path
+ if (!file.exists(buildFile)) {
+ throw new Error("ERROR: build file does not exist: " + buildFile);
+ }
+
+ absFilePath = config.baseUrl = file.absPath(file.parent(buildFile));
+
+ //Load build file options.
+ buildFileContents = file.readFile(buildFile);
+ try {
+ buildFileConfig = eval("(" + buildFileContents + ")");
+ build.makeAbsConfig(buildFileConfig, absFilePath);
+
+ //Mix in the config now so that items in mainConfigFile can
+ //be resolved relative to them if necessary, like if appDir
+ //is set here, but the baseUrl is in mainConfigFile. Will
+ //re-mix in the same build config later after mainConfigFile
+ //is processed, since build config should take priority.
+ mixConfig(config, buildFileConfig);
+ } catch (e) {
+ throw new Error("Build file " + buildFile + " is malformed: " + e);
+ }
+ }
+
+ mainConfigFile = config.mainConfigFile || (buildFileConfig && buildFileConfig.mainConfigFile);
+ if (mainConfigFile) {
+ if (typeof mainConfigFile === 'string') {
+ mainConfigFile = [mainConfigFile];
+ }
+
+ mainConfigFile.forEach(function (configFile) {
+ configFile = build.makeAbsPath(configFile, absFilePath);
+ if (!file.exists(configFile)) {
+ throw new Error(configFile + ' does not exist.');
+ }
+ try {
+ mainConfig = parse.findConfig(file.readFile(configFile)).config;
+ } catch (configError) {
+ throw new Error('The config in mainConfigFile ' +
+ configFile +
+ ' cannot be used because it cannot be evaluated' +
+ ' correctly while running in the optimizer. Try only' +
+ ' using a config that is also valid JSON, or do not use' +
+ ' mainConfigFile and instead copy the config values needed' +
+ ' into a build file or command line arguments given to the optimizer.\n' +
+ 'Source error from parsing: ' + configFile + ': ' + configError);
+ }
+ if (mainConfig) {
+ mainConfigPath = configFile.substring(0, configFile.lastIndexOf('/'));
+
+ //Add in some existing config, like appDir, since they can be
+ //used inside the configFile -- paths and baseUrl are
+ //relative to them.
+ if (config.appDir && !mainConfig.appDir) {
+ mainConfig.appDir = config.appDir;
+ }
+
+ //If no baseUrl, then use the directory holding the main config.
+ if (!mainConfig.baseUrl) {
+ mainConfig.baseUrl = mainConfigPath;
+ }
+
+ build.makeAbsConfig(mainConfig, mainConfigPath);
+ mixConfig(config, mainConfig);
+ }
+ });
+ }
+
+ //Mix in build file config, but only after mainConfig has been mixed in.
+ //Since this is a re-application, skip array merging.
+ if (buildFileConfig) {
+ mixConfig(config, buildFileConfig, true);
+ }
+
+ //Re-apply the override config values. Command line
+ //args should take precedence over build file values.
+ //Since this is a re-application, skip array merging.
+ mixConfig(config, cfg, true);
+
+ //Fix paths to full paths so that they can be adjusted consistently
+ //lately to be in the output area.
+ lang.eachProp(config.paths, function (value, prop) {
+ if (lang.isArray(value)) {
+ throw new Error('paths fallback not supported in optimizer. ' +
+ 'Please provide a build config path override ' +
+ 'for ' + prop);
+ }
+ config.paths[prop] = build.makeAbsPath(value, config.baseUrl);
+ });
+
+ //Set final output dir
+ if (hasProp(config, "baseUrl")) {
+ if (config.appDir) {
+ if (!config.originalBaseUrl) {
+ throw new Error('Please set a baseUrl in the build config');
+ }
+ config.dirBaseUrl = build.makeAbsPath(config.originalBaseUrl, config.dir);
+ } else {
+ config.dirBaseUrl = config.dir || config.baseUrl;
+ }
+ //Make sure dirBaseUrl ends in a slash, since it is
+ //concatenated with other strings.
+ config.dirBaseUrl = endsWithSlash(config.dirBaseUrl);
+ }
+
+ //Check for errors in config
+ if (config.main) {
+ throw new Error('"main" passed as an option, but the ' +
+ 'supported option is called "name".');
+ }
+ if (config.out && !config.name && !config.modules && !config.include &&
+ !config.cssIn) {
+ throw new Error('Missing either a "name", "include" or "modules" ' +
+ 'option');
+ }
+ if (config.cssIn) {
+ if (config.dir || config.appDir) {
+ throw new Error('cssIn is only for the output of single file ' +
+ 'CSS optimizations and is not compatible with "dir" or "appDir" configuration.');
+ }
+ if (!config.out) {
+ throw new Error('"out" option missing.');
+ }
+ }
+ if (!config.cssIn && !config.baseUrl) {
+ //Just use the current directory as the baseUrl
+ config.baseUrl = './';
+ }
+ if (!config.out && !config.dir) {
+ throw new Error('Missing either an "out" or "dir" config value. ' +
+ 'If using "appDir" for a full project optimization, ' +
+ 'use "dir". If you want to optimize to one file, ' +
+ 'use "out".');
+ }
+ if (config.appDir && config.out) {
+ throw new Error('"appDir" is not compatible with "out". Use "dir" ' +
+ 'instead. appDir is used to copy whole projects, ' +
+ 'where "out" with "baseUrl" is used to just ' +
+ 'optimize to one file.');
+ }
+ if (config.out && config.dir) {
+ throw new Error('The "out" and "dir" options are incompatible.' +
+ ' Use "out" if you are targeting a single file for' +
+ ' for optimization, and "dir" if you want the appDir' +
+ ' or baseUrl directories optimized.');
+ }
+
+ if (config.dir) {
+ // Make sure the output dir is not set to a parent of the
+ // source dir or the same dir, as it will result in source
+ // code deletion.
+ if (!config.allowSourceOverwrites && (config.dir === config.baseUrl ||
+ config.dir === config.appDir ||
+ (config.baseUrl && build.makeRelativeFilePath(config.dir,
+ config.baseUrl).indexOf('..') !== 0) ||
+ (config.appDir &&
+ build.makeRelativeFilePath(config.dir, config.appDir).indexOf('..') !== 0))) {
+ throw new Error('"dir" is set to a parent or same directory as' +
+ ' "appDir" or "baseUrl". This can result in' +
+ ' the deletion of source code. Stopping. If' +
+ ' you want to allow possible overwriting of' +
+ ' source code, set "allowSourceOverwrites"' +
+ ' to true in the build config, but do so at' +
+ ' your own risk. In that case, you may want' +
+ ' to also set "keepBuildDir" to true.');
+ }
+ }
+
+ if (config.insertRequire && !lang.isArray(config.insertRequire)) {
+ throw new Error('insertRequire should be a list of module IDs' +
+ ' to insert in to a require([]) call.');
+ }
+
+ if (config.generateSourceMaps) {
+ if (config.preserveLicenseComments && config.optimize !== 'none') {
+ throw new Error('Cannot use preserveLicenseComments and ' +
+ 'generateSourceMaps together. Either explcitly set ' +
+ 'preserveLicenseComments to false (default is true) or ' +
+ 'turn off generateSourceMaps. If you want source maps with ' +
+ 'license comments, see: ' +
+ 'http://requirejs.org/docs/errors.html#sourcemapcomments');
+ } else if (config.optimize !== 'none' &&
+ config.optimize !== 'closure' &&
+ config.optimize !== 'uglify2') {
+ //Allow optimize: none to pass, since it is useful when toggling
+ //minification on and off to debug something, and it implicitly
+ //works, since it does not need a source map.
+ throw new Error('optimize: "' + config.optimize +
+ '" does not support generateSourceMaps.');
+ }
+ }
+
+ if ((config.name || config.include) && !config.modules) {
+ //Just need to build one file, but may be part of a whole appDir/
+ //baseUrl copy, but specified on the command line, so cannot do
+ //the modules array setup. So create a modules section in that
+ //case.
+ config.modules = [
+ {
+ name: config.name,
+ out: config.out,
+ create: config.create,
+ include: config.include,
+ exclude: config.exclude,
+ excludeShallow: config.excludeShallow,
+ insertRequire: config.insertRequire,
+ stubModules: config.stubModules
+ }
+ ];
+ delete config.stubModules;
+ } else if (config.modules && config.out) {
+ throw new Error('If the "modules" option is used, then there ' +
+ 'should be a "dir" option set and "out" should ' +
+ 'not be used since "out" is only for single file ' +
+ 'optimization output.');
+ } else if (config.modules && config.name) {
+ throw new Error('"name" and "modules" options are incompatible. ' +
+ 'Either use "name" if doing a single file ' +
+ 'optimization, or "modules" if you want to target ' +
+ 'more than one file for optimization.');
+ }
+
+ if (config.out && !config.cssIn) {
+ //Just one file to optimize.
+
+ //Does not have a build file, so set up some defaults.
+ //Optimizing CSS should not be allowed, unless explicitly
+ //asked for on command line. In that case the only task is
+ //to optimize a CSS file.
+ if (!cfg.optimizeCss) {
+ config.optimizeCss = "none";
+ }
+ }
+
+ //Normalize cssPrefix
+ if (config.cssPrefix) {
+ //Make sure cssPrefix ends in a slash
+ config.cssPrefix = endsWithSlash(config.cssPrefix);
+ } else {
+ config.cssPrefix = '';
+ }
+
+ //Cycle through modules and combine any local stubModules with
+ //global values.
+ if (config.modules && config.modules.length) {
+ config.modules.forEach(function (mod) {
+ if (config.stubModules) {
+ mod.stubModules = config.stubModules.concat(mod.stubModules || []);
+ }
+
+ //Create a hash lookup for the stubModules config to make lookup
+ //cheaper later.
+ if (mod.stubModules) {
+ mod.stubModules._byName = {};
+ mod.stubModules.forEach(function (id) {
+ mod.stubModules._byName[id] = true;
+ });
+ }
+
+ //Allow wrap config in overrides, but normalize it.
+ if (mod.override) {
+ normalizeWrapConfig(mod.override, absFilePath);
+ }
+ });
+ }
+
+ normalizeWrapConfig(config, absFilePath);
+
+ //Do final input verification
+ if (config.context) {
+ throw new Error('The build argument "context" is not supported' +
+ ' in a build. It should only be used in web' +
+ ' pages.');
+ }
+
+ //Set up normalizeDirDefines. If not explicitly set, if optimize "none",
+ //set to "skip" otherwise set to "all".
+ if (!hasProp(config, 'normalizeDirDefines')) {
+ if (config.optimize === 'none' || config.skipDirOptimize) {
+ config.normalizeDirDefines = 'skip';
+ } else {
+ config.normalizeDirDefines = 'all';
+ }
+ }
+
+ //Set file.fileExclusionRegExp if desired
+ if (hasProp(config, 'fileExclusionRegExp')) {
+ if (typeof config.fileExclusionRegExp === "string") {
+ file.exclusionRegExp = new RegExp(config.fileExclusionRegExp);
+ } else {
+ file.exclusionRegExp = config.fileExclusionRegExp;
+ }
+ } else if (hasProp(config, 'dirExclusionRegExp')) {
+ //Set file.dirExclusionRegExp if desired, this is the old
+ //name for fileExclusionRegExp before 1.0.2. Support for backwards
+ //compatibility
+ file.exclusionRegExp = config.dirExclusionRegExp;
+ }
+
+ //Remove things that may cause problems in the build.
+ delete config.jQuery;
+ delete config.enforceDefine;
+ delete config.urlArgs;
+
+ return config;
+ };
+
+ /**
+ * finds the module being built/optimized with the given moduleName,
+ * or returns null.
+ * @param {String} moduleName
+ * @param {Array} modules
+ * @returns {Object} the module object from the build profile, or null.
+ */
+ build.findBuildModule = function (moduleName, modules) {
+ var i, module;
+ for (i = 0; i < modules.length; i++) {
+ module = modules[i];
+ if (module.name === moduleName) {
+ return module;
+ }
+ }
+ return null;
+ };
+
+ /**
+ * Removes a module name and path from a layer, if it is supposed to be
+ * excluded from the layer.
+ * @param {String} moduleName the name of the module
+ * @param {String} path the file path for the module
+ * @param {Object} layer the layer to remove the module/path from
+ */
+ build.removeModulePath = function (module, path, layer) {
+ var index = layer.buildFilePaths.indexOf(path);
+ if (index !== -1) {
+ layer.buildFilePaths.splice(index, 1);
+ }
+ };
+
+ /**
+ * Uses the module build config object to trace the dependencies for the
+ * given module.
+ *
+ * @param {Object} module the module object from the build config info.
+ * @param {Object} config the build config object.
+ * @param {Object} [baseLoaderConfig] the base loader config to use for env resets.
+ *
+ * @returns {Object} layer information about what paths and modules should
+ * be in the flattened module.
+ */
+ build.traceDependencies = function (module, config, baseLoaderConfig) {
+ var include, override, layer, context, oldContext,
+ rawTextByIds,
+ syncChecks = {
+ rhino: true,
+ node: true,
+ xpconnect: true
+ },
+ deferred = prim();
+
+ //Reset some state set up in requirePatch.js, and clean up require's
+ //current context.
+ oldContext = require._buildReset();
+
+ //Grab the reset layer and context after the reset, but keep the
+ //old config to reuse in the new context.
+ layer = require._layer;
+ context = layer.context;
+
+ //Put back basic config, use a fresh object for it.
+ if (baseLoaderConfig) {
+ require(lang.deeplikeCopy(baseLoaderConfig));
+ }
+
+ logger.trace("\nTracing dependencies for: " + (module.name ||
+ (typeof module.out === 'function' ? 'FUNCTION' : module.out)));
+ include = module.name && !module.create ? [module.name] : [];
+ if (module.include) {
+ include = include.concat(module.include);
+ }
+
+ //If there are overrides to basic config, set that up now.;
+ if (module.override) {
+ if (baseLoaderConfig) {
+ override = build.createOverrideConfig(baseLoaderConfig, module.override);
+ } else {
+ override = lang.deeplikeCopy(module.override);
+ }
+ require(override);
+ }
+
+ //Now, populate the rawText cache with any values explicitly passed in
+ //via config.
+ rawTextByIds = require.s.contexts._.config.rawText;
+ if (rawTextByIds) {
+ lang.eachProp(rawTextByIds, function (contents, id) {
+ var url = require.toUrl(id) + '.js';
+ require._cachedRawText[url] = contents;
+ });
+ }
+
+
+ //Configure the callbacks to be called.
+ deferred.reject.__requireJsBuild = true;
+
+ //Use a wrapping function so can check for errors.
+ function includeFinished(value) {
+ //If a sync build environment, check for errors here, instead of
+ //in the then callback below, since some errors, like two IDs pointed
+ //to same URL but only one anon ID will leave the loader in an
+ //unresolved state since a setTimeout cannot be used to check for
+ //timeout.
+ var hasError = false;
+ if (syncChecks[env.get()]) {
+ try {
+ build.checkForErrors(context);
+ } catch (e) {
+ hasError = true;
+ deferred.reject(e);
+ }
+ }
+
+ if (!hasError) {
+ deferred.resolve(value);
+ }
+ }
+ includeFinished.__requireJsBuild = true;
+
+ //Figure out module layer dependencies by calling require to do the work.
+ require(include, includeFinished, deferred.reject);
+
+ // If a sync env, then with the "two IDs to same anon module path"
+ // issue, the require never completes, need to check for errors
+ // here.
+ if (syncChecks[env.get()]) {
+ build.checkForErrors(context);
+ }
+
+ return deferred.promise.then(function () {
+ //Reset config
+ if (module.override && baseLoaderConfig) {
+ require(lang.deeplikeCopy(baseLoaderConfig));
+ }
+
+ build.checkForErrors(context);
+
+ return layer;
+ });
+ };
+
+ build.checkForErrors = function (context) {
+ //Check to see if it all loaded. If not, then throw, and give
+ //a message on what is left.
+ var id, prop, mod, idParts, pluginId, pluginResources,
+ errMessage = '',
+ failedPluginMap = {},
+ failedPluginIds = [],
+ errIds = [],
+ errUrlMap = {},
+ errUrlConflicts = {},
+ hasErrUrl = false,
+ hasUndefined = false,
+ defined = context.defined,
+ registry = context.registry;
+
+ function populateErrUrlMap(id, errUrl, skipNew) {
+ // Loader plugins do not have an errUrl, so skip them.
+ if (!errUrl) {
+ return;
+ }
+
+ if (!skipNew) {
+ errIds.push(id);
+ }
+
+ if (errUrlMap[errUrl]) {
+ hasErrUrl = true;
+ //This error module has the same URL as another
+ //error module, could be misconfiguration.
+ if (!errUrlConflicts[errUrl]) {
+ errUrlConflicts[errUrl] = [];
+ //Store the original module that had the same URL.
+ errUrlConflicts[errUrl].push(errUrlMap[errUrl]);
+ }
+ errUrlConflicts[errUrl].push(id);
+ } else if (!skipNew) {
+ errUrlMap[errUrl] = id;
+ }
+ }
+
+ for (id in registry) {
+ if (hasProp(registry, id) && id.indexOf('_@r') !== 0) {
+ hasUndefined = true;
+ mod = getOwn(registry, id);
+ idParts = id.split('!');
+ pluginId = idParts[0];
+
+ if (id.indexOf('_unnormalized') === -1 && mod && mod.enabled) {
+ populateErrUrlMap(id, mod.map.url);
+ }
+
+ //Look for plugins that did not call load()
+
+ if (idParts.length > 1) {
+ if (falseProp(failedPluginMap, pluginId)) {
+ failedPluginIds.push(pluginId);
+ }
+ pluginResources = failedPluginMap[pluginId];
+ if (!pluginResources) {
+ pluginResources = failedPluginMap[pluginId] = [];
+ }
+ pluginResources.push(id + (mod.error ? ': ' + mod.error : ''));
+ }
+ }
+ }
+
+ // If have some modules that are not defined/stuck in the registry,
+ // then check defined modules for URL overlap.
+ if (hasUndefined) {
+ for (id in defined) {
+ if (hasProp(defined, id) && id.indexOf('!') === -1) {
+ populateErrUrlMap(id, require.toUrl(id) + '.js', true);
+ }
+ }
+ }
+
+ if (errIds.length || failedPluginIds.length) {
+ if (failedPluginIds.length) {
+ errMessage += 'Loader plugin' +
+ (failedPluginIds.length === 1 ? '' : 's') +
+ ' did not call ' +
+ 'the load callback in the build:\n' +
+ failedPluginIds.map(function (pluginId) {
+ var pluginResources = failedPluginMap[pluginId];
+ return pluginId + ':\n ' + pluginResources.join('\n ');
+ }).join('\n') + '\n';
+ }
+ errMessage += 'Module loading did not complete for: ' + errIds.join(', ');
+
+ if (hasErrUrl) {
+ errMessage += '\nThe following modules share the same URL. This ' +
+ 'could be a misconfiguration if that URL only has ' +
+ 'one anonymous module in it:';
+ for (prop in errUrlConflicts) {
+ if (hasProp(errUrlConflicts, prop)) {
+ errMessage += '\n' + prop + ': ' +
+ errUrlConflicts[prop].join(', ');
+ }
+ }
+ }
+ throw new Error(errMessage);
+ }
+ };
+
+ build.createOverrideConfig = function (config, override) {
+ var cfg = lang.deeplikeCopy(config),
+ oride = lang.deeplikeCopy(override);
+
+ lang.eachProp(oride, function (value, prop) {
+ if (hasProp(build.objProps, prop)) {
+ //An object property, merge keys. Start a new object
+ //so that source object in config does not get modified.
+ cfg[prop] = {};
+ lang.mixin(cfg[prop], config[prop], true);
+ lang.mixin(cfg[prop], override[prop], true);
+ } else {
+ cfg[prop] = override[prop];
+ }
+ });
+
+ return cfg;
+ };
+
+ /**
+ * Uses the module build config object to create an flattened version
+ * of the module, with deep dependencies included.
+ *
+ * @param {Object} module the module object from the build config info.
+ *
+ * @param {Object} layer the layer object returned from build.traceDependencies.
+ *
+ * @param {Object} the build config object.
+ *
+ * @returns {Object} with two properties: "text", the text of the flattened
+ * module, and "buildText", a string of text representing which files were
+ * included in the flattened module text.
+ */
+ build.flattenModule = function (module, layer, config) {
+ var fileContents, sourceMapGenerator,
+ sourceMapBase,
+ buildFileContents = '';
+
+ return prim().start(function () {
+ var reqIndex, currContents, fileForSourceMap,
+ moduleName, shim, packageMain, packageName,
+ parts, builder, writeApi,
+ namespace, namespaceWithDot, stubModulesByName,
+ context = layer.context,
+ onLayerEnds = [],
+ onLayerEndAdded = {};
+
+ //Use override settings, particularly for pragmas
+ //Do this before the var readings since it reads config values.
+ if (module.override) {
+ config = build.createOverrideConfig(config, module.override);
+ }
+
+ namespace = config.namespace || '';
+ namespaceWithDot = namespace ? namespace + '.' : '';
+ stubModulesByName = (module.stubModules && module.stubModules._byName) || {};
+
+ //Start build output for the module.
+ module.onCompleteData = {
+ name: module.name,
+ path: (config.dir ? module._buildPath.replace(config.dir, "") : module._buildPath),
+ included: []
+ };
+
+ buildFileContents += "\n" +
+ module.onCompleteData.path +
+ "\n----------------\n";
+
+ //If there was an existing file with require in it, hoist to the top.
+ if (layer.existingRequireUrl) {
+ reqIndex = layer.buildFilePaths.indexOf(layer.existingRequireUrl);
+ if (reqIndex !== -1) {
+ layer.buildFilePaths.splice(reqIndex, 1);
+ layer.buildFilePaths.unshift(layer.existingRequireUrl);
+ }
+ }
+
+ if (config.generateSourceMaps) {
+ sourceMapBase = config.dir || config.baseUrl;
+ fileForSourceMap = module._buildPath === 'FUNCTION' ?
+ (module.name || module.include[0] || 'FUNCTION') + '.build.js' :
+ module._buildPath.replace(sourceMapBase, '');
+ sourceMapGenerator = new SourceMapGenerator.SourceMapGenerator({
+ file: fileForSourceMap
+ });
+ }
+
+ //Write the built module to disk, and build up the build output.
+ fileContents = "";
+ return prim.serial(layer.buildFilePaths.map(function (path) {
+ return function () {
+ var lineCount,
+ singleContents = '';
+
+ moduleName = layer.buildFileToModule[path];
+ packageName = moduleName.split('/').shift();
+
+ //If the moduleName is for a package main, then update it to the
+ //real main value.
+ packageMain = layer.context.config.pkgs &&
+ getOwn(layer.context.config.pkgs, packageName);
+ if (packageMain !== moduleName) {
+ // Not a match, clear packageMain
+ packageMain = undefined;
+ }
+
+ return prim().start(function () {
+ //Figure out if the module is a result of a build plugin, and if so,
+ //then delegate to that plugin.
+ parts = context.makeModuleMap(moduleName);
+ builder = parts.prefix && getOwn(context.defined, parts.prefix);
+ if (builder) {
+ if (builder.onLayerEnd && falseProp(onLayerEndAdded, parts.prefix)) {
+ onLayerEnds.push(builder);
+ onLayerEndAdded[parts.prefix] = true;
+ }
+
+ if (builder.write) {
+ writeApi = function (input) {
+ singleContents += "\n" + addSemiColon(input, config);
+ if (config.onBuildWrite) {
+ singleContents = config.onBuildWrite(moduleName, path, singleContents);
+ }
+ };
+ writeApi.asModule = function (moduleName, input) {
+ singleContents += "\n" +
+ addSemiColon(build.toTransport(namespace, moduleName, path, input, layer, {
+ useSourceUrl: layer.context.config.useSourceUrl
+ }), config);
+ if (config.onBuildWrite) {
+ singleContents = config.onBuildWrite(moduleName, path, singleContents);
+ }
+ };
+ builder.write(parts.prefix, parts.name, writeApi);
+ }
+ return;
+ } else {
+ return prim().start(function () {
+ if (hasProp(stubModulesByName, moduleName)) {
+ //Just want to insert a simple module definition instead
+ //of the source module. Useful for plugins that inline
+ //all their resources.
+ if (hasProp(layer.context.plugins, moduleName)) {
+ //Slightly different content for plugins, to indicate
+ //that dynamic loading will not work.
+ return 'define({load: function(id){throw new Error("Dynamic load not allowed: " + id);}});';
+ } else {
+ return 'define({});';
+ }
+ } else {
+ return require._cacheReadAsync(path);
+ }
+ }).then(function (text) {
+ var hasPackageName;
+
+ currContents = text;
+
+ if (config.cjsTranslate &&
+ (!config.shim || !lang.hasProp(config.shim, moduleName))) {
+ currContents = commonJs.convert(path, currContents);
+ }
+
+ if (config.onBuildRead) {
+ currContents = config.onBuildRead(moduleName, path, currContents);
+ }
+
+ if (packageMain) {
+ hasPackageName = (packageName === parse.getNamedDefine(currContents));
+ }
+
+ if (namespace) {
+ currContents = pragma.namespace(currContents, namespace);
+ }
+
+ currContents = build.toTransport(namespace, moduleName, path, currContents, layer, {
+ useSourceUrl: config.useSourceUrl
+ });
+
+ if (packageMain && !hasPackageName) {
+ currContents = addSemiColon(currContents, config) + '\n';
+ currContents += namespaceWithDot + "define('" +
+ packageName + "', ['" + moduleName +
+ "'], function (main) { return main; });\n";
+ }
+
+ if (config.onBuildWrite) {
+ currContents = config.onBuildWrite(moduleName, path, currContents);
+ }
+
+ //Semicolon is for files that are not well formed when
+ //concatenated with other content.
+ singleContents += addSemiColon(currContents, config);
+ });
+ }
+ }).then(function () {
+ var refPath, pluginId, resourcePath,
+ sourceMapPath, sourceMapLineNumber,
+ shortPath = path.replace(config.dir, "");
+
+ module.onCompleteData.included.push(shortPath);
+ buildFileContents += shortPath + "\n";
+
+ //Some files may not have declared a require module, and if so,
+ //put in a placeholder call so the require does not try to load them
+ //after the module is processed.
+ //If we have a name, but no defined module, then add in the placeholder.
+ if (moduleName && falseProp(layer.modulesWithNames, moduleName) && !config.skipModuleInsertion) {
+ shim = config.shim && (getOwn(config.shim, moduleName) || (packageMain && getOwn(config.shim, moduleName) || getOwn(config.shim, packageName)));
+ if (shim) {
+ if (config.wrapShim) {
+ singleContents = '(function(root) {' +
+ '\n' + namespaceWithDot + 'define("' + moduleName + '", ' +
+ (shim.deps && shim.deps.length ?
+ build.makeJsArrayString(shim.deps) + ', ' : '[], ') +
+ 'function() {\n' +
+ ' return (function() {\n' +
+ singleContents +
+ (shim.exportsFn ? shim.exportsFn() : '') +
+ ' }).apply(root, arguments);\n' +
+ ' });\n' +
+ '}(this));\n';
+ } else {
+ singleContents += '\n' + namespaceWithDot + 'define("' + moduleName + '", ' +
+ (shim.deps && shim.deps.length ?
+ build.makeJsArrayString(shim.deps) + ', ' : '') +
+ (shim.exportsFn ? shim.exportsFn() : 'function(){}') +
+ ');\n';
+ }
+ } else {
+ singleContents += '\n' + namespaceWithDot + 'define("' + moduleName + '", function(){});\n';
+ }
+ }
+
+ //Add line break at end of file, instead of at beginning,
+ //so source map line numbers stay correct, but still allow
+ //for some space separation between files in case ASI issues
+ //for concatenation would cause an error otherwise.
+ singleContents += '\n';
+
+ //Add to the source map
+ if (sourceMapGenerator) {
+ refPath = config.out ? config.baseUrl : module._buildPath;
+ parts = path.split('!');
+ if (parts.length === 1) {
+ //Not a plugin resource, fix the path
+ sourceMapPath = build.makeRelativeFilePath(refPath, path);
+ } else {
+ //Plugin resource. If it looks like just a plugin
+ //followed by a module ID, pull off the plugin
+ //and put it at the end of the name, otherwise
+ //just leave it alone.
+ pluginId = parts.shift();
+ resourcePath = parts.join('!');
+ if (resourceIsModuleIdRegExp.test(resourcePath)) {
+ sourceMapPath = build.makeRelativeFilePath(refPath, require.toUrl(resourcePath)) +
+ '!' + pluginId;
+ } else {
+ sourceMapPath = path;
+ }
+ }
+
+ sourceMapLineNumber = fileContents.split('\n').length - 1;
+ lineCount = singleContents.split('\n').length;
+ for (var i = 1; i <= lineCount; i += 1) {
+ sourceMapGenerator.addMapping({
+ generated: {
+ line: sourceMapLineNumber + i,
+ column: 0
+ },
+ original: {
+ line: i,
+ column: 0
+ },
+ source: sourceMapPath
+ });
+ }
+
+ //Store the content of the original in the source
+ //map since other transforms later like minification
+ //can mess up translating back to the original
+ //source.
+ sourceMapGenerator.setSourceContent(sourceMapPath, singleContents);
+ }
+
+ //Add the file to the final contents
+ fileContents += singleContents;
+ });
+ };
+ })).then(function () {
+ if (onLayerEnds.length) {
+ onLayerEnds.forEach(function (builder) {
+ var path;
+ if (typeof module.out === 'string') {
+ path = module.out;
+ } else if (typeof module._buildPath === 'string') {
+ path = module._buildPath;
+ }
+ builder.onLayerEnd(function (input) {
+ fileContents += "\n" + addSemiColon(input, config);
+ }, {
+ name: module.name,
+ path: path
+ });
+ });
+ }
+
+ if (module.create) {
+ //The ID is for a created layer. Write out
+ //a module definition for it in case the
+ //built file is used with enforceDefine
+ //(#432)
+ fileContents += '\n' + namespaceWithDot + 'define("' + module.name + '", function(){});\n';
+ }
+
+ //Add a require at the end to kick start module execution, if that
+ //was desired. Usually this is only specified when using small shim
+ //loaders like almond.
+ if (module.insertRequire) {
+ fileContents += '\n' + namespaceWithDot + 'require(["' + module.insertRequire.join('", "') + '"]);\n';
+ }
+ });
+ }).then(function () {
+ return {
+ text: config.wrap ?
+ config.wrap.start + fileContents + config.wrap.end :
+ fileContents,
+ buildText: buildFileContents,
+ sourceMap: sourceMapGenerator ?
+ JSON.stringify(sourceMapGenerator.toJSON(), null, ' ') :
+ undefined
+ };
+ });
+ };
+
+ //Converts an JS array of strings to a string representation.
+ //Not using JSON.stringify() for Rhino's sake.
+ build.makeJsArrayString = function (ary) {
+ return '["' + ary.map(function (item) {
+ //Escape any double quotes, backslashes
+ return lang.jsEscape(item);
+ }).join('","') + '"]';
+ };
+
+ build.toTransport = function (namespace, moduleName, path, contents, layer, options) {
+ var baseUrl = layer && layer.context.config.baseUrl;
+
+ function onFound(info) {
+ //Only mark this module as having a name if not a named module,
+ //or if a named module and the name matches expectations.
+ if (layer && (info.needsId || info.foundId === moduleName)) {
+ layer.modulesWithNames[moduleName] = true;
+ }
+ }
+
+ //Convert path to be a local one to the baseUrl, useful for
+ //useSourceUrl.
+ if (baseUrl) {
+ path = path.replace(baseUrl, '');
+ }
+
+ return transform.toTransport(namespace, moduleName, path, contents, onFound, options);
+ };
+
+ return build;
+});
+
+ }
+
+
+ /**
+ * Sets the default baseUrl for requirejs to be directory of top level
+ * script.
+ */
+ function setBaseUrl(fileName) {
+ //Use the file name's directory as the baseUrl if available.
+ dir = fileName.replace(/\\/g, '/');
+ if (dir.indexOf('/') !== -1) {
+ dir = dir.split('/');
+ dir.pop();
+ dir = dir.join('/');
+ //Make sure dir is JS-escaped, since it will be part of a JS string.
+ exec("require({baseUrl: '" + dir.replace(/[\\"']/g, '\\$&') + "'});");
+ }
+ }
+
+ function createRjsApi() {
+ //Create a method that will run the optimzer given an object
+ //config.
+ requirejs.optimize = function (config, callback, errback) {
+ if (!loadedOptimizedLib) {
+ loadLib();
+ loadedOptimizedLib = true;
+ }
+
+ //Create the function that will be called once build modules
+ //have been loaded.
+ var runBuild = function (build, logger, quit) {
+ //Make sure config has a log level, and if not,
+ //make it "silent" by default.
+ config.logLevel = config.hasOwnProperty('logLevel') ?
+ config.logLevel : logger.SILENT;
+
+ //Reset build internals first in case this is part
+ //of a long-running server process that could have
+ //exceptioned out in a bad state. It is only defined
+ //after the first call though.
+ if (requirejs._buildReset) {
+ requirejs._buildReset();
+ requirejs._cacheReset();
+ }
+
+ function done(result) {
+ //And clean up, in case something else triggers
+ //a build in another pathway.
+ if (requirejs._buildReset) {
+ requirejs._buildReset();
+ requirejs._cacheReset();
+ }
+
+ // Ensure errors get propagated to the errback
+ if (result instanceof Error) {
+ throw result;
+ }
+
+ return result;
+ }
+
+ errback = errback || function (err) {
+ // Using console here since logger may have
+ // turned off error logging. Since quit is
+ // called want to be sure a message is printed.
+ console.log(err);
+ quit(1);
+ };
+
+ build(config).then(done, done).then(callback, errback);
+ };
+
+ requirejs({
+ context: 'build'
+ }, ['build', 'logger', 'env!env/quit'], runBuild);
+ };
+
+ requirejs.tools = {
+ useLib: function (contextName, callback) {
+ if (!callback) {
+ callback = contextName;
+ contextName = 'uselib';
+ }
+
+ if (!useLibLoaded[contextName]) {
+ loadLib();
+ useLibLoaded[contextName] = true;
+ }
+
+ var req = requirejs({
+ context: contextName
+ });
+
+ req(['build'], function () {
+ callback(req);
+ });
+ }
+ };
+
+ requirejs.define = define;
+ }
+
+ //If in Node, and included via a require('requirejs'), just export and
+ //THROW IT ON THE GROUND!
+ if (env === 'node' && reqMain !== module) {
+ setBaseUrl(path.resolve(reqMain ? reqMain.filename : '.'));
+
+ createRjsApi();
+
+ module.exports = requirejs;
+ return;
+ } else if (env === 'browser') {
+ //Only option is to use the API.
+ setBaseUrl(location.href);
+ createRjsApi();
+ return;
+ } else if ((env === 'rhino' || env === 'xpconnect') &&
+ //User sets up requirejsAsLib variable to indicate it is loaded
+ //via load() to be used as a library.
+ typeof requirejsAsLib !== 'undefined' && requirejsAsLib) {
+ //This script is loaded via rhino's load() method, expose the
+ //API and get out.
+ setBaseUrl(fileName);
+ createRjsApi();
+ return;
+ }
+
+ if (commandOption === 'o') {
+ //Do the optimizer work.
+ loadLib();
+
+ /**
+ * @license Copyright (c) 2010-2014, The Dojo Foundation All Rights Reserved.
+ * Available via the MIT or new BSD license.
+ * see: http://github.com/jrburke/requirejs for details
+ */
+
+/*
+ * Create a build.js file that has the build options you want and pass that
+ * build file to this file to do the build. See example.build.js for more information.
+ */
+
+/*jslint strict: false, nomen: false */
+/*global require: false */
+
+require({
+ baseUrl: require.s.contexts._.config.baseUrl,
+ //Use a separate context than the default context so that the
+ //build can use the default context.
+ context: 'build',
+ catchError: {
+ define: true
+ }
+}, ['env!env/args', 'env!env/quit', 'logger', 'build'],
+function (args, quit, logger, build) {
+ build(args).then(function () {}, function (err) {
+ logger.error(err);
+ quit(1);
+ });
+});
+
+
+ } else if (commandOption === 'v') {
+ console.log('r.js: ' + version +
+ ', RequireJS: ' + this.requirejsVars.require.version +
+ ', UglifyJS2: 2.4.12, UglifyJS: 1.3.4');
+ } else if (commandOption === 'convert') {
+ loadLib();
+
+ this.requirejsVars.require(['env!env/args', 'commonJs', 'env!env/print'],
+ function (args, commonJs, print) {
+
+ var srcDir, outDir;
+ srcDir = args[0];
+ outDir = args[1];
+
+ if (!srcDir || !outDir) {
+ print('Usage: path/to/commonjs/modules output/dir');
+ return;
+ }
+
+ commonJs.convertDir(args[0], args[1]);
+ });
+ } else {
+ //Just run an app
+
+ //Load the bundled libraries for use in the app.
+ if (commandOption === 'lib') {
+ loadLib();
+ }
+
+ setBaseUrl(fileName);
+
+ if (exists(fileName)) {
+ exec(readFile(fileName), fileName);
+ } else {
+ showHelp();
+ }
+ }
+
+}((typeof console !== 'undefined' ? console : undefined),
+ (typeof Packages !== 'undefined' || (typeof window === 'undefined' &&
+ typeof Components !== 'undefined' && Components.interfaces) ?
+ Array.prototype.slice.call(arguments, 0) : []),
+ (typeof readFile !== 'undefined' ? readFile : undefined)));
--- /dev/null
+(function(){function o(e){var i=function(e,t){return r("",e,t)},s=t;e&&(t[e]||(t[e]={}),s=t[e]);if(!s.define||!s.define.packaged)n.original=s.define,s.define=n,s.define.packaged=!0;if(!s.require||!s.require.packaged)r.original=s.require,s.require=i,s.require.packaged=!0}var e="",t=function(){return this}();if(!e&&typeof requirejs!="undefined")return;var n=function(e,t,r){if(typeof e!="string"){n.original?n.original.apply(window,arguments):(console.error("dropping module because define wasn't a string."),console.trace());return}arguments.length==2&&(r=t),n.modules||(n.modules={},n.payloads={}),n.payloads[e]=r,n.modules[e]=null},r=function(e,t,n){if(Object.prototype.toString.call(t)==="[object Array]"){var i=[];for(var o=0,u=t.length;o<u;++o){var a=s(e,t[o]);if(!a&&r.original)return r.original.apply(window,arguments);i.push(a)}n&&n.apply(null,i)}else{if(typeof t=="string"){var f=s(e,t);return!f&&r.original?r.original.apply(window,arguments):(n&&n(),f)}if(r.original)return r.original.apply(window,arguments)}},i=function(e,t){if(t.indexOf("!")!==-1){var n=t.split("!");return i(e,n[0])+"!"+i(e,n[1])}if(t.charAt(0)=="."){var r=e.split("/").slice(0,-1).join("/");t=r+"/"+t;while(t.indexOf(".")!==-1&&s!=t){var s=t;t=t.replace(/\/\.\//,"/").replace(/[^\/]+\/\.\.\//,"")}}return t},s=function(e,t){t=i(e,t);var s=n.modules[t];if(!s){s=n.payloads[t];if(typeof s=="function"){var o={},u={id:t,uri:"",exports:o,packaged:!0},a=function(e,n){return r(t,e,n)},f=s(a,o,u);o=f||u.exports,n.modules[t]=o,delete n.payloads[t]}s=n.modules[t]=o||s}return s};o(e)})(),define("ace/ace",["require","exports","module","ace/lib/fixoldbrowsers","ace/lib/dom","ace/lib/event","ace/editor","ace/edit_session","ace/undomanager","ace/virtual_renderer","ace/multi_select","ace/worker/worker_client","ace/keyboard/hash_handler","ace/placeholder","ace/mode/folding/fold_mode","ace/theme/textmate","ace/ext/error_marker","ace/config"],function(e,t,n){e("./lib/fixoldbrowsers");var r=e("./lib/dom"),i=e("./lib/event"),s=e("./editor").Editor,o=e("./edit_session").EditSession,u=e("./undomanager").UndoManager,a=e("./virtual_renderer").VirtualRenderer,f=e("./multi_select").MultiSelect;e("./worker/worker_client"),e("./keyboard/hash_handler"),e("./placeholder"),e("./mode/folding/fold_mode"),e("./theme/textmate"),e("./ext/error_marker"),t.config=e("./config"),t.require=e,t.edit=function(e){if(typeof e=="string"){var n=e,e=document.getElementById(n);if(!e)throw new Error("ace.edit can't find div #"+n)}if(e.env&&e.env.editor instanceof s)return e.env.editor;var o=t.createEditSession(r.getInnerText(e));e.innerHTML="";var u=new s(new a(e));new f(u),u.setSession(o);var l={document:o,editor:u,onResize:u.resize.bind(u,null)};return i.addListener(window,"resize",l.onResize),u.on("destroy",function(){i.removeListener(window,"resize",l.onResize)}),e.env=u.env=l,u},t.createEditSession=function(e,t){var n=new o(e,t);return n.setUndoManager(new u),n},t.EditSession=o,t.UndoManager=u}),define("ace/mode/behaviour",["require","exports","module"],function(e,t,n){var r=function(){this.$behaviours={}};(function(){this.add=function(e,t,n){switch(undefined){case this.$behaviours:this.$behaviours={};case this.$behaviours[e]:this.$behaviours[e]={}}this.$behaviours[e][t]=n},this.addBehaviours=function(e){for(var t in e)for(var n in e[t])this.add(t,n,e[t][n])},this.remove=function(e){this.$behaviours&&this.$behaviours[e]&&delete this.$behaviours[e]},this.inherit=function(e,t){if(typeof e=="function")var n=(new e).getBehaviours(t);else var n=e.getBehaviours(t);this.addBehaviours(n)},this.getBehaviours=function(e){if(!e)return this.$behaviours;var t={};for(var n=0;n<e.length;n++)this.$behaviours[e[n]]&&(t[e[n]]=this.$behaviours[e[n]]);return t}}).call(r.prototype),t.Behaviour=r}),define("ace/unicode",["require","exports","module"],function(e,t,n){function r(e){var n=/\w{4}/g;for(var r in e)t.packages[r]=e[r].replace(n,"\\u$&")}t.packages={},r({L:"0041-005A0061-007A00AA00B500BA00C0-00D600D8-00F600F8-02C102C6-02D102E0-02E402EC02EE0370-037403760377037A-037D03860388-038A038C038E-03A103A3-03F503F7-0481048A-05250531-055605590561-058705D0-05EA05F0-05F20621-064A066E066F0671-06D306D506E506E606EE06EF06FA-06FC06FF07100712-072F074D-07A507B107CA-07EA07F407F507FA0800-0815081A082408280904-0939093D09500958-0961097109720979-097F0985-098C098F09900993-09A809AA-09B009B209B6-09B909BD09CE09DC09DD09DF-09E109F009F10A05-0A0A0A0F0A100A13-0A280A2A-0A300A320A330A350A360A380A390A59-0A5C0A5E0A72-0A740A85-0A8D0A8F-0A910A93-0AA80AAA-0AB00AB20AB30AB5-0AB90ABD0AD00AE00AE10B05-0B0C0B0F0B100B13-0B280B2A-0B300B320B330B35-0B390B3D0B5C0B5D0B5F-0B610B710B830B85-0B8A0B8E-0B900B92-0B950B990B9A0B9C0B9E0B9F0BA30BA40BA8-0BAA0BAE-0BB90BD00C05-0C0C0C0E-0C100C12-0C280C2A-0C330C35-0C390C3D0C580C590C600C610C85-0C8C0C8E-0C900C92-0CA80CAA-0CB30CB5-0CB90CBD0CDE0CE00CE10D05-0D0C0D0E-0D100D12-0D280D2A-0D390D3D0D600D610D7A-0D7F0D85-0D960D9A-0DB10DB3-0DBB0DBD0DC0-0DC60E01-0E300E320E330E40-0E460E810E820E840E870E880E8A0E8D0E94-0E970E99-0E9F0EA1-0EA30EA50EA70EAA0EAB0EAD-0EB00EB20EB30EBD0EC0-0EC40EC60EDC0EDD0F000F40-0F470F49-0F6C0F88-0F8B1000-102A103F1050-1055105A-105D106110651066106E-10701075-1081108E10A0-10C510D0-10FA10FC1100-1248124A-124D1250-12561258125A-125D1260-1288128A-128D1290-12B012B2-12B512B8-12BE12C012C2-12C512C8-12D612D8-13101312-13151318-135A1380-138F13A0-13F41401-166C166F-167F1681-169A16A0-16EA1700-170C170E-17111720-17311740-17511760-176C176E-17701780-17B317D717DC1820-18771880-18A818AA18B0-18F51900-191C1950-196D1970-19741980-19AB19C1-19C71A00-1A161A20-1A541AA71B05-1B331B45-1B4B1B83-1BA01BAE1BAF1C00-1C231C4D-1C4F1C5A-1C7D1CE9-1CEC1CEE-1CF11D00-1DBF1E00-1F151F18-1F1D1F20-1F451F48-1F4D1F50-1F571F591F5B1F5D1F5F-1F7D1F80-1FB41FB6-1FBC1FBE1FC2-1FC41FC6-1FCC1FD0-1FD31FD6-1FDB1FE0-1FEC1FF2-1FF41FF6-1FFC2071207F2090-209421022107210A-211321152119-211D212421262128212A-212D212F-2139213C-213F2145-2149214E218321842C00-2C2E2C30-2C5E2C60-2CE42CEB-2CEE2D00-2D252D30-2D652D6F2D80-2D962DA0-2DA62DA8-2DAE2DB0-2DB62DB8-2DBE2DC0-2DC62DC8-2DCE2DD0-2DD62DD8-2DDE2E2F300530063031-3035303B303C3041-3096309D-309F30A1-30FA30FC-30FF3105-312D3131-318E31A0-31B731F0-31FF3400-4DB54E00-9FCBA000-A48CA4D0-A4FDA500-A60CA610-A61FA62AA62BA640-A65FA662-A66EA67F-A697A6A0-A6E5A717-A71FA722-A788A78BA78CA7FB-A801A803-A805A807-A80AA80C-A822A840-A873A882-A8B3A8F2-A8F7A8FBA90A-A925A930-A946A960-A97CA984-A9B2A9CFAA00-AA28AA40-AA42AA44-AA4BAA60-AA76AA7AAA80-AAAFAAB1AAB5AAB6AAB9-AABDAAC0AAC2AADB-AADDABC0-ABE2AC00-D7A3D7B0-D7C6D7CB-D7FBF900-FA2DFA30-FA6DFA70-FAD9FB00-FB06FB13-FB17FB1DFB1F-FB28FB2A-FB36FB38-FB3CFB3EFB40FB41FB43FB44FB46-FBB1FBD3-FD3DFD50-FD8FFD92-FDC7FDF0-FDFBFE70-FE74FE76-FEFCFF21-FF3AFF41-FF5AFF66-FFBEFFC2-FFC7FFCA-FFCFFFD2-FFD7FFDA-FFDC",Ll:"0061-007A00AA00B500BA00DF-00F600F8-00FF01010103010501070109010B010D010F01110113011501170119011B011D011F01210123012501270129012B012D012F01310133013501370138013A013C013E014001420144014601480149014B014D014F01510153015501570159015B015D015F01610163016501670169016B016D016F0171017301750177017A017C017E-0180018301850188018C018D019201950199-019B019E01A101A301A501A801AA01AB01AD01B001B401B601B901BA01BD-01BF01C601C901CC01CE01D001D201D401D601D801DA01DC01DD01DF01E101E301E501E701E901EB01ED01EF01F001F301F501F901FB01FD01FF02010203020502070209020B020D020F02110213021502170219021B021D021F02210223022502270229022B022D022F02310233-0239023C023F0240024202470249024B024D024F-02930295-02AF037103730377037B-037D039003AC-03CE03D003D103D5-03D703D903DB03DD03DF03E103E303E503E703E903EB03ED03EF-03F303F503F803FB03FC0430-045F04610463046504670469046B046D046F04710473047504770479047B047D047F0481048B048D048F04910493049504970499049B049D049F04A104A304A504A704A904AB04AD04AF04B104B304B504B704B904BB04BD04BF04C204C404C604C804CA04CC04CE04CF04D104D304D504D704D904DB04DD04DF04E104E304E504E704E904EB04ED04EF04F104F304F504F704F904FB04FD04FF05010503050505070509050B050D050F05110513051505170519051B051D051F0521052305250561-05871D00-1D2B1D62-1D771D79-1D9A1E011E031E051E071E091E0B1E0D1E0F1E111E131E151E171E191E1B1E1D1E1F1E211E231E251E271E291E2B1E2D1E2F1E311E331E351E371E391E3B1E3D1E3F1E411E431E451E471E491E4B1E4D1E4F1E511E531E551E571E591E5B1E5D1E5F1E611E631E651E671E691E6B1E6D1E6F1E711E731E751E771E791E7B1E7D1E7F1E811E831E851E871E891E8B1E8D1E8F1E911E931E95-1E9D1E9F1EA11EA31EA51EA71EA91EAB1EAD1EAF1EB11EB31EB51EB71EB91EBB1EBD1EBF1EC11EC31EC51EC71EC91ECB1ECD1ECF1ED11ED31ED51ED71ED91EDB1EDD1EDF1EE11EE31EE51EE71EE91EEB1EED1EEF1EF11EF31EF51EF71EF91EFB1EFD1EFF-1F071F10-1F151F20-1F271F30-1F371F40-1F451F50-1F571F60-1F671F70-1F7D1F80-1F871F90-1F971FA0-1FA71FB0-1FB41FB61FB71FBE1FC2-1FC41FC61FC71FD0-1FD31FD61FD71FE0-1FE71FF2-1FF41FF61FF7210A210E210F2113212F21342139213C213D2146-2149214E21842C30-2C5E2C612C652C662C682C6A2C6C2C712C732C742C76-2C7C2C812C832C852C872C892C8B2C8D2C8F2C912C932C952C972C992C9B2C9D2C9F2CA12CA32CA52CA72CA92CAB2CAD2CAF2CB12CB32CB52CB72CB92CBB2CBD2CBF2CC12CC32CC52CC72CC92CCB2CCD2CCF2CD12CD32CD52CD72CD92CDB2CDD2CDF2CE12CE32CE42CEC2CEE2D00-2D25A641A643A645A647A649A64BA64DA64FA651A653A655A657A659A65BA65DA65FA663A665A667A669A66BA66DA681A683A685A687A689A68BA68DA68FA691A693A695A697A723A725A727A729A72BA72DA72F-A731A733A735A737A739A73BA73DA73FA741A743A745A747A749A74BA74DA74FA751A753A755A757A759A75BA75DA75FA761A763A765A767A769A76BA76DA76FA771-A778A77AA77CA77FA781A783A785A787A78CFB00-FB06FB13-FB17FF41-FF5A",Lu:"0041-005A00C0-00D600D8-00DE01000102010401060108010A010C010E01100112011401160118011A011C011E01200122012401260128012A012C012E01300132013401360139013B013D013F0141014301450147014A014C014E01500152015401560158015A015C015E01600162016401660168016A016C016E017001720174017601780179017B017D018101820184018601870189-018B018E-0191019301940196-0198019C019D019F01A001A201A401A601A701A901AC01AE01AF01B1-01B301B501B701B801BC01C401C701CA01CD01CF01D101D301D501D701D901DB01DE01E001E201E401E601E801EA01EC01EE01F101F401F6-01F801FA01FC01FE02000202020402060208020A020C020E02100212021402160218021A021C021E02200222022402260228022A022C022E02300232023A023B023D023E02410243-02460248024A024C024E03700372037603860388-038A038C038E038F0391-03A103A3-03AB03CF03D2-03D403D803DA03DC03DE03E003E203E403E603E803EA03EC03EE03F403F703F903FA03FD-042F04600462046404660468046A046C046E04700472047404760478047A047C047E0480048A048C048E04900492049404960498049A049C049E04A004A204A404A604A804AA04AC04AE04B004B204B404B604B804BA04BC04BE04C004C104C304C504C704C904CB04CD04D004D204D404D604D804DA04DC04DE04E004E204E404E604E804EA04EC04EE04F004F204F404F604F804FA04FC04FE05000502050405060508050A050C050E05100512051405160518051A051C051E0520052205240531-055610A0-10C51E001E021E041E061E081E0A1E0C1E0E1E101E121E141E161E181E1A1E1C1E1E1E201E221E241E261E281E2A1E2C1E2E1E301E321E341E361E381E3A1E3C1E3E1E401E421E441E461E481E4A1E4C1E4E1E501E521E541E561E581E5A1E5C1E5E1E601E621E641E661E681E6A1E6C1E6E1E701E721E741E761E781E7A1E7C1E7E1E801E821E841E861E881E8A1E8C1E8E1E901E921E941E9E1EA01EA21EA41EA61EA81EAA1EAC1EAE1EB01EB21EB41EB61EB81EBA1EBC1EBE1EC01EC21EC41EC61EC81ECA1ECC1ECE1ED01ED21ED41ED61ED81EDA1EDC1EDE1EE01EE21EE41EE61EE81EEA1EEC1EEE1EF01EF21EF41EF61EF81EFA1EFC1EFE1F08-1F0F1F18-1F1D1F28-1F2F1F38-1F3F1F48-1F4D1F591F5B1F5D1F5F1F68-1F6F1FB8-1FBB1FC8-1FCB1FD8-1FDB1FE8-1FEC1FF8-1FFB21022107210B-210D2110-211221152119-211D212421262128212A-212D2130-2133213E213F214521832C00-2C2E2C602C62-2C642C672C692C6B2C6D-2C702C722C752C7E-2C802C822C842C862C882C8A2C8C2C8E2C902C922C942C962C982C9A2C9C2C9E2CA02CA22CA42CA62CA82CAA2CAC2CAE2CB02CB22CB42CB62CB82CBA2CBC2CBE2CC02CC22CC42CC62CC82CCA2CCC2CCE2CD02CD22CD42CD62CD82CDA2CDC2CDE2CE02CE22CEB2CEDA640A642A644A646A648A64AA64CA64EA650A652A654A656A658A65AA65CA65EA662A664A666A668A66AA66CA680A682A684A686A688A68AA68CA68EA690A692A694A696A722A724A726A728A72AA72CA72EA732A734A736A738A73AA73CA73EA740A742A744A746A748A74AA74CA74EA750A752A754A756A758A75AA75CA75EA760A762A764A766A768A76AA76CA76EA779A77BA77DA77EA780A782A784A786A78BFF21-FF3A",Lt:"01C501C801CB01F21F88-1F8F1F98-1F9F1FA8-1FAF1FBC1FCC1FFC",Lm:"02B0-02C102C6-02D102E0-02E402EC02EE0374037A0559064006E506E607F407F507FA081A0824082809710E460EC610FC17D718431AA71C78-1C7D1D2C-1D611D781D9B-1DBF2071207F2090-20942C7D2D6F2E2F30053031-3035303B309D309E30FC-30FEA015A4F8-A4FDA60CA67FA717-A71FA770A788A9CFAA70AADDFF70FF9EFF9F",Lo:"01BB01C0-01C3029405D0-05EA05F0-05F20621-063F0641-064A066E066F0671-06D306D506EE06EF06FA-06FC06FF07100712-072F074D-07A507B107CA-07EA0800-08150904-0939093D09500958-096109720979-097F0985-098C098F09900993-09A809AA-09B009B209B6-09B909BD09CE09DC09DD09DF-09E109F009F10A05-0A0A0A0F0A100A13-0A280A2A-0A300A320A330A350A360A380A390A59-0A5C0A5E0A72-0A740A85-0A8D0A8F-0A910A93-0AA80AAA-0AB00AB20AB30AB5-0AB90ABD0AD00AE00AE10B05-0B0C0B0F0B100B13-0B280B2A-0B300B320B330B35-0B390B3D0B5C0B5D0B5F-0B610B710B830B85-0B8A0B8E-0B900B92-0B950B990B9A0B9C0B9E0B9F0BA30BA40BA8-0BAA0BAE-0BB90BD00C05-0C0C0C0E-0C100C12-0C280C2A-0C330C35-0C390C3D0C580C590C600C610C85-0C8C0C8E-0C900C92-0CA80CAA-0CB30CB5-0CB90CBD0CDE0CE00CE10D05-0D0C0D0E-0D100D12-0D280D2A-0D390D3D0D600D610D7A-0D7F0D85-0D960D9A-0DB10DB3-0DBB0DBD0DC0-0DC60E01-0E300E320E330E40-0E450E810E820E840E870E880E8A0E8D0E94-0E970E99-0E9F0EA1-0EA30EA50EA70EAA0EAB0EAD-0EB00EB20EB30EBD0EC0-0EC40EDC0EDD0F000F40-0F470F49-0F6C0F88-0F8B1000-102A103F1050-1055105A-105D106110651066106E-10701075-1081108E10D0-10FA1100-1248124A-124D1250-12561258125A-125D1260-1288128A-128D1290-12B012B2-12B512B8-12BE12C012C2-12C512C8-12D612D8-13101312-13151318-135A1380-138F13A0-13F41401-166C166F-167F1681-169A16A0-16EA1700-170C170E-17111720-17311740-17511760-176C176E-17701780-17B317DC1820-18421844-18771880-18A818AA18B0-18F51900-191C1950-196D1970-19741980-19AB19C1-19C71A00-1A161A20-1A541B05-1B331B45-1B4B1B83-1BA01BAE1BAF1C00-1C231C4D-1C4F1C5A-1C771CE9-1CEC1CEE-1CF12135-21382D30-2D652D80-2D962DA0-2DA62DA8-2DAE2DB0-2DB62DB8-2DBE2DC0-2DC62DC8-2DCE2DD0-2DD62DD8-2DDE3006303C3041-3096309F30A1-30FA30FF3105-312D3131-318E31A0-31B731F0-31FF3400-4DB54E00-9FCBA000-A014A016-A48CA4D0-A4F7A500-A60BA610-A61FA62AA62BA66EA6A0-A6E5A7FB-A801A803-A805A807-A80AA80C-A822A840-A873A882-A8B3A8F2-A8F7A8FBA90A-A925A930-A946A960-A97CA984-A9B2AA00-AA28AA40-AA42AA44-AA4BAA60-AA6FAA71-AA76AA7AAA80-AAAFAAB1AAB5AAB6AAB9-AABDAAC0AAC2AADBAADCABC0-ABE2AC00-D7A3D7B0-D7C6D7CB-D7FBF900-FA2DFA30-FA6DFA70-FAD9FB1DFB1F-FB28FB2A-FB36FB38-FB3CFB3EFB40FB41FB43FB44FB46-FBB1FBD3-FD3DFD50-FD8FFD92-FDC7FDF0-FDFBFE70-FE74FE76-FEFCFF66-FF6FFF71-FF9DFFA0-FFBEFFC2-FFC7FFCA-FFCFFFD2-FFD7FFDA-FFDC",M:"0300-036F0483-04890591-05BD05BF05C105C205C405C505C70610-061A064B-065E067006D6-06DC06DE-06E406E706E806EA-06ED07110730-074A07A6-07B007EB-07F30816-0819081B-08230825-08270829-082D0900-0903093C093E-094E0951-0955096209630981-098309BC09BE-09C409C709C809CB-09CD09D709E209E30A01-0A030A3C0A3E-0A420A470A480A4B-0A4D0A510A700A710A750A81-0A830ABC0ABE-0AC50AC7-0AC90ACB-0ACD0AE20AE30B01-0B030B3C0B3E-0B440B470B480B4B-0B4D0B560B570B620B630B820BBE-0BC20BC6-0BC80BCA-0BCD0BD70C01-0C030C3E-0C440C46-0C480C4A-0C4D0C550C560C620C630C820C830CBC0CBE-0CC40CC6-0CC80CCA-0CCD0CD50CD60CE20CE30D020D030D3E-0D440D46-0D480D4A-0D4D0D570D620D630D820D830DCA0DCF-0DD40DD60DD8-0DDF0DF20DF30E310E34-0E3A0E47-0E4E0EB10EB4-0EB90EBB0EBC0EC8-0ECD0F180F190F350F370F390F3E0F3F0F71-0F840F860F870F90-0F970F99-0FBC0FC6102B-103E1056-1059105E-10601062-10641067-106D1071-10741082-108D108F109A-109D135F1712-17141732-1734175217531772177317B6-17D317DD180B-180D18A91920-192B1930-193B19B0-19C019C819C91A17-1A1B1A55-1A5E1A60-1A7C1A7F1B00-1B041B34-1B441B6B-1B731B80-1B821BA1-1BAA1C24-1C371CD0-1CD21CD4-1CE81CED1CF21DC0-1DE61DFD-1DFF20D0-20F02CEF-2CF12DE0-2DFF302A-302F3099309AA66F-A672A67CA67DA6F0A6F1A802A806A80BA823-A827A880A881A8B4-A8C4A8E0-A8F1A926-A92DA947-A953A980-A983A9B3-A9C0AA29-AA36AA43AA4CAA4DAA7BAAB0AAB2-AAB4AAB7AAB8AABEAABFAAC1ABE3-ABEAABECABEDFB1EFE00-FE0FFE20-FE26",Mn:"0300-036F0483-04870591-05BD05BF05C105C205C405C505C70610-061A064B-065E067006D6-06DC06DF-06E406E706E806EA-06ED07110730-074A07A6-07B007EB-07F30816-0819081B-08230825-08270829-082D0900-0902093C0941-0948094D0951-095509620963098109BC09C1-09C409CD09E209E30A010A020A3C0A410A420A470A480A4B-0A4D0A510A700A710A750A810A820ABC0AC1-0AC50AC70AC80ACD0AE20AE30B010B3C0B3F0B41-0B440B4D0B560B620B630B820BC00BCD0C3E-0C400C46-0C480C4A-0C4D0C550C560C620C630CBC0CBF0CC60CCC0CCD0CE20CE30D41-0D440D4D0D620D630DCA0DD2-0DD40DD60E310E34-0E3A0E47-0E4E0EB10EB4-0EB90EBB0EBC0EC8-0ECD0F180F190F350F370F390F71-0F7E0F80-0F840F860F870F90-0F970F99-0FBC0FC6102D-10301032-10371039103A103D103E10581059105E-10601071-1074108210851086108D109D135F1712-17141732-1734175217531772177317B7-17BD17C617C9-17D317DD180B-180D18A91920-19221927192819321939-193B1A171A181A561A58-1A5E1A601A621A65-1A6C1A73-1A7C1A7F1B00-1B031B341B36-1B3A1B3C1B421B6B-1B731B801B811BA2-1BA51BA81BA91C2C-1C331C361C371CD0-1CD21CD4-1CE01CE2-1CE81CED1DC0-1DE61DFD-1DFF20D0-20DC20E120E5-20F02CEF-2CF12DE0-2DFF302A-302F3099309AA66FA67CA67DA6F0A6F1A802A806A80BA825A826A8C4A8E0-A8F1A926-A92DA947-A951A980-A982A9B3A9B6-A9B9A9BCAA29-AA2EAA31AA32AA35AA36AA43AA4CAAB0AAB2-AAB4AAB7AAB8AABEAABFAAC1ABE5ABE8ABEDFB1EFE00-FE0FFE20-FE26",Mc:"0903093E-09400949-094C094E0982098309BE-09C009C709C809CB09CC09D70A030A3E-0A400A830ABE-0AC00AC90ACB0ACC0B020B030B3E0B400B470B480B4B0B4C0B570BBE0BBF0BC10BC20BC6-0BC80BCA-0BCC0BD70C01-0C030C41-0C440C820C830CBE0CC0-0CC40CC70CC80CCA0CCB0CD50CD60D020D030D3E-0D400D46-0D480D4A-0D4C0D570D820D830DCF-0DD10DD8-0DDF0DF20DF30F3E0F3F0F7F102B102C10311038103B103C105610571062-10641067-106D108310841087-108C108F109A-109C17B617BE-17C517C717C81923-19261929-192B193019311933-193819B0-19C019C819C91A19-1A1B1A551A571A611A631A641A6D-1A721B041B351B3B1B3D-1B411B431B441B821BA11BA61BA71BAA1C24-1C2B1C341C351CE11CF2A823A824A827A880A881A8B4-A8C3A952A953A983A9B4A9B5A9BAA9BBA9BD-A9C0AA2FAA30AA33AA34AA4DAA7BABE3ABE4ABE6ABE7ABE9ABEAABEC",Me:"0488048906DE20DD-20E020E2-20E4A670-A672",N:"0030-003900B200B300B900BC-00BE0660-066906F0-06F907C0-07C90966-096F09E6-09EF09F4-09F90A66-0A6F0AE6-0AEF0B66-0B6F0BE6-0BF20C66-0C6F0C78-0C7E0CE6-0CEF0D66-0D750E50-0E590ED0-0ED90F20-0F331040-10491090-10991369-137C16EE-16F017E0-17E917F0-17F91810-18191946-194F19D0-19DA1A80-1A891A90-1A991B50-1B591BB0-1BB91C40-1C491C50-1C5920702074-20792080-20892150-21822185-21892460-249B24EA-24FF2776-27932CFD30073021-30293038-303A3192-31953220-32293251-325F3280-328932B1-32BFA620-A629A6E6-A6EFA830-A835A8D0-A8D9A900-A909A9D0-A9D9AA50-AA59ABF0-ABF9FF10-FF19",Nd:"0030-00390660-066906F0-06F907C0-07C90966-096F09E6-09EF0A66-0A6F0AE6-0AEF0B66-0B6F0BE6-0BEF0C66-0C6F0CE6-0CEF0D66-0D6F0E50-0E590ED0-0ED90F20-0F291040-10491090-109917E0-17E91810-18191946-194F19D0-19DA1A80-1A891A90-1A991B50-1B591BB0-1BB91C40-1C491C50-1C59A620-A629A8D0-A8D9A900-A909A9D0-A9D9AA50-AA59ABF0-ABF9FF10-FF19",Nl:"16EE-16F02160-21822185-218830073021-30293038-303AA6E6-A6EF",No:"00B200B300B900BC-00BE09F4-09F90BF0-0BF20C78-0C7E0D70-0D750F2A-0F331369-137C17F0-17F920702074-20792080-20892150-215F21892460-249B24EA-24FF2776-27932CFD3192-31953220-32293251-325F3280-328932B1-32BFA830-A835",P:"0021-00230025-002A002C-002F003A003B003F0040005B-005D005F007B007D00A100AB00B700BB00BF037E0387055A-055F0589058A05BE05C005C305C605F305F40609060A060C060D061B061E061F066A-066D06D40700-070D07F7-07F90830-083E0964096509700DF40E4F0E5A0E5B0F04-0F120F3A-0F3D0F850FD0-0FD4104A-104F10FB1361-13681400166D166E169B169C16EB-16ED1735173617D4-17D617D8-17DA1800-180A1944194519DE19DF1A1E1A1F1AA0-1AA61AA8-1AAD1B5A-1B601C3B-1C3F1C7E1C7F1CD32010-20272030-20432045-20512053-205E207D207E208D208E2329232A2768-277527C527C627E6-27EF2983-299829D8-29DB29FC29FD2CF9-2CFC2CFE2CFF2E00-2E2E2E302E313001-30033008-30113014-301F3030303D30A030FBA4FEA4FFA60D-A60FA673A67EA6F2-A6F7A874-A877A8CEA8CFA8F8-A8FAA92EA92FA95FA9C1-A9CDA9DEA9DFAA5C-AA5FAADEAADFABEBFD3EFD3FFE10-FE19FE30-FE52FE54-FE61FE63FE68FE6AFE6BFF01-FF03FF05-FF0AFF0C-FF0FFF1AFF1BFF1FFF20FF3B-FF3DFF3FFF5BFF5DFF5F-FF65",Pd:"002D058A05BE140018062010-20152E172E1A301C303030A0FE31FE32FE58FE63FF0D",Ps:"0028005B007B0F3A0F3C169B201A201E2045207D208D23292768276A276C276E27702772277427C527E627E827EA27EC27EE2983298529872989298B298D298F299129932995299729D829DA29FC2E222E242E262E283008300A300C300E3010301430163018301A301DFD3EFE17FE35FE37FE39FE3BFE3DFE3FFE41FE43FE47FE59FE5BFE5DFF08FF3BFF5BFF5FFF62",Pe:"0029005D007D0F3B0F3D169C2046207E208E232A2769276B276D276F27712773277527C627E727E927EB27ED27EF298429862988298A298C298E2990299229942996299829D929DB29FD2E232E252E272E293009300B300D300F3011301530173019301B301E301FFD3FFE18FE36FE38FE3AFE3CFE3EFE40FE42FE44FE48FE5AFE5CFE5EFF09FF3DFF5DFF60FF63",Pi:"00AB2018201B201C201F20392E022E042E092E0C2E1C2E20",Pf:"00BB2019201D203A2E032E052E0A2E0D2E1D2E21",Pc:"005F203F20402054FE33FE34FE4D-FE4FFF3F",Po:"0021-00230025-0027002A002C002E002F003A003B003F0040005C00A100B700BF037E0387055A-055F058905C005C305C605F305F40609060A060C060D061B061E061F066A-066D06D40700-070D07F7-07F90830-083E0964096509700DF40E4F0E5A0E5B0F04-0F120F850FD0-0FD4104A-104F10FB1361-1368166D166E16EB-16ED1735173617D4-17D617D8-17DA1800-18051807-180A1944194519DE19DF1A1E1A1F1AA0-1AA61AA8-1AAD1B5A-1B601C3B-1C3F1C7E1C7F1CD3201620172020-20272030-2038203B-203E2041-20432047-205120532055-205E2CF9-2CFC2CFE2CFF2E002E012E06-2E082E0B2E0E-2E162E182E192E1B2E1E2E1F2E2A-2E2E2E302E313001-3003303D30FBA4FEA4FFA60D-A60FA673A67EA6F2-A6F7A874-A877A8CEA8CFA8F8-A8FAA92EA92FA95FA9C1-A9CDA9DEA9DFAA5C-AA5FAADEAADFABEBFE10-FE16FE19FE30FE45FE46FE49-FE4CFE50-FE52FE54-FE57FE5F-FE61FE68FE6AFE6BFF01-FF03FF05-FF07FF0AFF0CFF0EFF0FFF1AFF1BFF1FFF20FF3CFF61FF64FF65",S:"0024002B003C-003E005E0060007C007E00A2-00A900AC00AE-00B100B400B600B800D700F702C2-02C502D2-02DF02E5-02EB02ED02EF-02FF03750384038503F604820606-0608060B060E060F06E906FD06FE07F609F209F309FA09FB0AF10B700BF3-0BFA0C7F0CF10CF20D790E3F0F01-0F030F13-0F170F1A-0F1F0F340F360F380FBE-0FC50FC7-0FCC0FCE0FCF0FD5-0FD8109E109F13601390-139917DB194019E0-19FF1B61-1B6A1B74-1B7C1FBD1FBF-1FC11FCD-1FCF1FDD-1FDF1FED-1FEF1FFD1FFE20442052207A-207C208A-208C20A0-20B8210021012103-21062108210921142116-2118211E-2123212521272129212E213A213B2140-2144214A-214D214F2190-2328232B-23E82400-24262440-244A249C-24E92500-26CD26CF-26E126E326E8-26FF2701-27042706-2709270C-27272729-274B274D274F-27522756-275E2761-276727942798-27AF27B1-27BE27C0-27C427C7-27CA27CC27D0-27E527F0-29822999-29D729DC-29FB29FE-2B4C2B50-2B592CE5-2CEA2E80-2E992E9B-2EF32F00-2FD52FF0-2FFB300430123013302030363037303E303F309B309C319031913196-319F31C0-31E33200-321E322A-32503260-327F328A-32B032C0-32FE3300-33FF4DC0-4DFFA490-A4C6A700-A716A720A721A789A78AA828-A82BA836-A839AA77-AA79FB29FDFCFDFDFE62FE64-FE66FE69FF04FF0BFF1C-FF1EFF3EFF40FF5CFF5EFFE0-FFE6FFE8-FFEEFFFCFFFD",Sm:"002B003C-003E007C007E00AC00B100D700F703F60606-060820442052207A-207C208A-208C2140-2144214B2190-2194219A219B21A021A321A621AE21CE21CF21D221D421F4-22FF2308-230B23202321237C239B-23B323DC-23E125B725C125F8-25FF266F27C0-27C427C7-27CA27CC27D0-27E527F0-27FF2900-29822999-29D729DC-29FB29FE-2AFF2B30-2B442B47-2B4CFB29FE62FE64-FE66FF0BFF1C-FF1EFF5CFF5EFFE2FFE9-FFEC",Sc:"002400A2-00A5060B09F209F309FB0AF10BF90E3F17DB20A0-20B8A838FDFCFE69FF04FFE0FFE1FFE5FFE6",Sk:"005E006000A800AF00B400B802C2-02C502D2-02DF02E5-02EB02ED02EF-02FF0375038403851FBD1FBF-1FC11FCD-1FCF1FDD-1FDF1FED-1FEF1FFD1FFE309B309CA700-A716A720A721A789A78AFF3EFF40FFE3",So:"00A600A700A900AE00B000B60482060E060F06E906FD06FE07F609FA0B700BF3-0BF80BFA0C7F0CF10CF20D790F01-0F030F13-0F170F1A-0F1F0F340F360F380FBE-0FC50FC7-0FCC0FCE0FCF0FD5-0FD8109E109F13601390-1399194019E0-19FF1B61-1B6A1B74-1B7C210021012103-21062108210921142116-2118211E-2123212521272129212E213A213B214A214C214D214F2195-2199219C-219F21A121A221A421A521A7-21AD21AF-21CD21D021D121D321D5-21F32300-2307230C-231F2322-2328232B-237B237D-239A23B4-23DB23E2-23E82400-24262440-244A249C-24E92500-25B625B8-25C025C2-25F72600-266E2670-26CD26CF-26E126E326E8-26FF2701-27042706-2709270C-27272729-274B274D274F-27522756-275E2761-276727942798-27AF27B1-27BE2800-28FF2B00-2B2F2B452B462B50-2B592CE5-2CEA2E80-2E992E9B-2EF32F00-2FD52FF0-2FFB300430123013302030363037303E303F319031913196-319F31C0-31E33200-321E322A-32503260-327F328A-32B032C0-32FE3300-33FF4DC0-4DFFA490-A4C6A828-A82BA836A837A839AA77-AA79FDFDFFE4FFE8FFEDFFEEFFFCFFFD",Z:"002000A01680180E2000-200A20282029202F205F3000",Zs:"002000A01680180E2000-200A202F205F3000",Zl:"2028",Zp:"2029",C:"0000-001F007F-009F00AD03780379037F-0383038B038D03A20526-05300557055805600588058B-059005C8-05CF05EB-05EF05F5-0605061C061D0620065F06DD070E070F074B074C07B2-07BF07FB-07FF082E082F083F-08FF093A093B094F095609570973-097809800984098D098E0991099209A909B109B3-09B509BA09BB09C509C609C909CA09CF-09D609D8-09DB09DE09E409E509FC-0A000A040A0B-0A0E0A110A120A290A310A340A370A3A0A3B0A3D0A43-0A460A490A4A0A4E-0A500A52-0A580A5D0A5F-0A650A76-0A800A840A8E0A920AA90AB10AB40ABA0ABB0AC60ACA0ACE0ACF0AD1-0ADF0AE40AE50AF00AF2-0B000B040B0D0B0E0B110B120B290B310B340B3A0B3B0B450B460B490B4A0B4E-0B550B58-0B5B0B5E0B640B650B72-0B810B840B8B-0B8D0B910B96-0B980B9B0B9D0BA0-0BA20BA5-0BA70BAB-0BAD0BBA-0BBD0BC3-0BC50BC90BCE0BCF0BD1-0BD60BD8-0BE50BFB-0C000C040C0D0C110C290C340C3A-0C3C0C450C490C4E-0C540C570C5A-0C5F0C640C650C70-0C770C800C810C840C8D0C910CA90CB40CBA0CBB0CC50CC90CCE-0CD40CD7-0CDD0CDF0CE40CE50CF00CF3-0D010D040D0D0D110D290D3A-0D3C0D450D490D4E-0D560D58-0D5F0D640D650D76-0D780D800D810D840D97-0D990DB20DBC0DBE0DBF0DC7-0DC90DCB-0DCE0DD50DD70DE0-0DF10DF5-0E000E3B-0E3E0E5C-0E800E830E850E860E890E8B0E8C0E8E-0E930E980EA00EA40EA60EA80EA90EAC0EBA0EBE0EBF0EC50EC70ECE0ECF0EDA0EDB0EDE-0EFF0F480F6D-0F700F8C-0F8F0F980FBD0FCD0FD9-0FFF10C6-10CF10FD-10FF1249124E124F12571259125E125F1289128E128F12B112B612B712BF12C112C612C712D7131113161317135B-135E137D-137F139A-139F13F5-13FF169D-169F16F1-16FF170D1715-171F1737-173F1754-175F176D17711774-177F17B417B517DE17DF17EA-17EF17FA-17FF180F181A-181F1878-187F18AB-18AF18F6-18FF191D-191F192C-192F193C-193F1941-1943196E196F1975-197F19AC-19AF19CA-19CF19DB-19DD1A1C1A1D1A5F1A7D1A7E1A8A-1A8F1A9A-1A9F1AAE-1AFF1B4C-1B4F1B7D-1B7F1BAB-1BAD1BBA-1BFF1C38-1C3A1C4A-1C4C1C80-1CCF1CF3-1CFF1DE7-1DFC1F161F171F1E1F1F1F461F471F4E1F4F1F581F5A1F5C1F5E1F7E1F7F1FB51FC51FD41FD51FDC1FF01FF11FF51FFF200B-200F202A-202E2060-206F20722073208F2095-209F20B9-20CF20F1-20FF218A-218F23E9-23FF2427-243F244B-245F26CE26E226E4-26E727002705270A270B2728274C274E2753-2755275F27602795-279727B027BF27CB27CD-27CF2B4D-2B4F2B5A-2BFF2C2F2C5F2CF2-2CF82D26-2D2F2D66-2D6E2D70-2D7F2D97-2D9F2DA72DAF2DB72DBF2DC72DCF2DD72DDF2E32-2E7F2E9A2EF4-2EFF2FD6-2FEF2FFC-2FFF3040309730983100-3104312E-3130318F31B8-31BF31E4-31EF321F32FF4DB6-4DBF9FCC-9FFFA48D-A48FA4C7-A4CFA62C-A63FA660A661A674-A67BA698-A69FA6F8-A6FFA78D-A7FAA82C-A82FA83A-A83FA878-A87FA8C5-A8CDA8DA-A8DFA8FC-A8FFA954-A95EA97D-A97FA9CEA9DA-A9DDA9E0-A9FFAA37-AA3FAA4EAA4FAA5AAA5BAA7C-AA7FAAC3-AADAAAE0-ABBFABEEABEFABFA-ABFFD7A4-D7AFD7C7-D7CAD7FC-F8FFFA2EFA2FFA6EFA6FFADA-FAFFFB07-FB12FB18-FB1CFB37FB3DFB3FFB42FB45FBB2-FBD2FD40-FD4FFD90FD91FDC8-FDEFFDFEFDFFFE1A-FE1FFE27-FE2FFE53FE67FE6C-FE6FFE75FEFD-FF00FFBF-FFC1FFC8FFC9FFD0FFD1FFD8FFD9FFDD-FFDFFFE7FFEF-FFFBFFFEFFFF",Cc:"0000-001F007F-009F",Cf:"00AD0600-060306DD070F17B417B5200B-200F202A-202E2060-2064206A-206FFEFFFFF9-FFFB",Co:"E000-F8FF",Cs:"D800-DFFF",Cn:"03780379037F-0383038B038D03A20526-05300557055805600588058B-059005C8-05CF05EB-05EF05F5-05FF06040605061C061D0620065F070E074B074C07B2-07BF07FB-07FF082E082F083F-08FF093A093B094F095609570973-097809800984098D098E0991099209A909B109B3-09B509BA09BB09C509C609C909CA09CF-09D609D8-09DB09DE09E409E509FC-0A000A040A0B-0A0E0A110A120A290A310A340A370A3A0A3B0A3D0A43-0A460A490A4A0A4E-0A500A52-0A580A5D0A5F-0A650A76-0A800A840A8E0A920AA90AB10AB40ABA0ABB0AC60ACA0ACE0ACF0AD1-0ADF0AE40AE50AF00AF2-0B000B040B0D0B0E0B110B120B290B310B340B3A0B3B0B450B460B490B4A0B4E-0B550B58-0B5B0B5E0B640B650B72-0B810B840B8B-0B8D0B910B96-0B980B9B0B9D0BA0-0BA20BA5-0BA70BAB-0BAD0BBA-0BBD0BC3-0BC50BC90BCE0BCF0BD1-0BD60BD8-0BE50BFB-0C000C040C0D0C110C290C340C3A-0C3C0C450C490C4E-0C540C570C5A-0C5F0C640C650C70-0C770C800C810C840C8D0C910CA90CB40CBA0CBB0CC50CC90CCE-0CD40CD7-0CDD0CDF0CE40CE50CF00CF3-0D010D040D0D0D110D290D3A-0D3C0D450D490D4E-0D560D58-0D5F0D640D650D76-0D780D800D810D840D97-0D990DB20DBC0DBE0DBF0DC7-0DC90DCB-0DCE0DD50DD70DE0-0DF10DF5-0E000E3B-0E3E0E5C-0E800E830E850E860E890E8B0E8C0E8E-0E930E980EA00EA40EA60EA80EA90EAC0EBA0EBE0EBF0EC50EC70ECE0ECF0EDA0EDB0EDE-0EFF0F480F6D-0F700F8C-0F8F0F980FBD0FCD0FD9-0FFF10C6-10CF10FD-10FF1249124E124F12571259125E125F1289128E128F12B112B612B712BF12C112C612C712D7131113161317135B-135E137D-137F139A-139F13F5-13FF169D-169F16F1-16FF170D1715-171F1737-173F1754-175F176D17711774-177F17DE17DF17EA-17EF17FA-17FF180F181A-181F1878-187F18AB-18AF18F6-18FF191D-191F192C-192F193C-193F1941-1943196E196F1975-197F19AC-19AF19CA-19CF19DB-19DD1A1C1A1D1A5F1A7D1A7E1A8A-1A8F1A9A-1A9F1AAE-1AFF1B4C-1B4F1B7D-1B7F1BAB-1BAD1BBA-1BFF1C38-1C3A1C4A-1C4C1C80-1CCF1CF3-1CFF1DE7-1DFC1F161F171F1E1F1F1F461F471F4E1F4F1F581F5A1F5C1F5E1F7E1F7F1FB51FC51FD41FD51FDC1FF01FF11FF51FFF2065-206920722073208F2095-209F20B9-20CF20F1-20FF218A-218F23E9-23FF2427-243F244B-245F26CE26E226E4-26E727002705270A270B2728274C274E2753-2755275F27602795-279727B027BF27CB27CD-27CF2B4D-2B4F2B5A-2BFF2C2F2C5F2CF2-2CF82D26-2D2F2D66-2D6E2D70-2D7F2D97-2D9F2DA72DAF2DB72DBF2DC72DCF2DD72DDF2E32-2E7F2E9A2EF4-2EFF2FD6-2FEF2FFC-2FFF3040309730983100-3104312E-3130318F31B8-31BF31E4-31EF321F32FF4DB6-4DBF9FCC-9FFFA48D-A48FA4C7-A4CFA62C-A63FA660A661A674-A67BA698-A69FA6F8-A6FFA78D-A7FAA82C-A82FA83A-A83FA878-A87FA8C5-A8CDA8DA-A8DFA8FC-A8FFA954-A95EA97D-A97FA9CEA9DA-A9DDA9E0-A9FFAA37-AA3FAA4EAA4FAA5AAA5BAA7C-AA7FAAC3-AADAAAE0-ABBFABEEABEFABFA-ABFFD7A4-D7AFD7C7-D7CAD7FC-D7FFFA2EFA2FFA6EFA6FFADA-FAFFFB07-FB12FB18-FB1CFB37FB3DFB3FFB42FB45FBB2-FBD2FD40-FD4FFD90FD91FDC8-FDEFFDFEFDFFFE1A-FE1FFE27-FE2FFE53FE67FE6C-FE6FFE75FEFDFEFEFF00FFBF-FFC1FFC8FFC9FFD0FFD1FFD8FFD9FFDD-FFDFFFE7FFEF-FFF8FFFEFFFF"})}),define("ace/token_iterator",["require","exports","module"],function(e,t,n){var r=function(e,t,n){this.$session=e,this.$row=t,this.$rowTokens=e.getTokens(t);var r=e.getTokenAt(t,n);this.$tokenIndex=r?r.index:-1};(function(){this.stepBackward=function(){this.$tokenIndex-=1;while(this.$tokenIndex<0){this.$row-=1;if(this.$row<0)return this.$row=0,null;this.$rowTokens=this.$session.getTokens(this.$row),this.$tokenIndex=this.$rowTokens.length-1}return this.$rowTokens[this.$tokenIndex]},this.stepForward=function(){this.$tokenIndex+=1;var e;while(this.$tokenIndex>=this.$rowTokens.length){this.$row+=1,e||(e=this.$session.getLength());if(this.$row>=e)return this.$row=e-1,null;this.$rowTokens=this.$session.getTokens(this.$row),this.$tokenIndex=0}return this.$rowTokens[this.$tokenIndex]},this.getCurrentToken=function(){return this.$rowTokens[this.$tokenIndex]},this.getCurrentTokenRow=function(){return this.$row},this.getCurrentTokenColumn=function(){var e=this.$rowTokens,t=this.$tokenIndex,n=e[t].start;if(n!==undefined)return n;n=0;while(t>0)t-=1,n+=e[t].value.length;return n}}).call(r.prototype),t.TokenIterator=r}),define("ace/mode/text_highlight_rules",["require","exports","module","ace/lib/lang"],function(e,t,n){var r=e("../lib/lang"),i=function(){this.$rules={start:[{token:"empty_line",regex:"^$"},{defaultToken:"text"}]}};(function(){this.addRules=function(e,t){if(!t){for(var n in e)this.$rules[n]=e[n];return}for(var n in e){var r=e[n];for(var i=0;i<r.length;i++){var s=r[i];s.next&&(typeof s.next!="string"?s.nextState&&s.nextState.indexOf(t)!==0&&(s.nextState=t+s.nextState):s.next.indexOf(t)!==0&&(s.next=t+s.next))}this.$rules[t+n]=r}},this.getRules=function(){return this.$rules},this.embedRules=function(e,t,n,i,s){var o=typeof e=="function"?(new e).getRules():e;if(i)for(var u=0;u<i.length;u++)i[u]=t+i[u];else{i=[];for(var a in o)i.push(t+a)}this.addRules(o,t);if(n){var f=Array.prototype[s?"push":"unshift"];for(var u=0;u<i.length;u++)f.apply(this.$rules[i[u]],r.deepCopy(n))}this.$embeds||(this.$embeds=[]),this.$embeds.push(t)},this.getEmbeds=function(){return this.$embeds};var e=function(e,t){return(e!="start"||t.length)&&t.unshift(this.nextState,e),this.nextState},t=function(e,t){return t.shift(),t.shift()||"start"};this.normalizeRules=function(){function i(s){var o=r[s];o.processed=!0;for(var u=0;u<o.length;u++){var a=o[u];!a.regex&&a.start&&(a.regex=a.start,a.next||(a.next=[]),a.next.push({defaultToken:a.token},{token:a.token+".end",regex:a.end||a.start,next:"pop"}),a.token=a.token+".start",a.push=!0);var f=a.next||a.push;if(f&&Array.isArray(f)){var l=a.stateName;l||(l=a.token,typeof l!="string"&&(l=l[0]||""),r[l]&&(l+=n++)),r[l]=f,a.next=l,i(l)}else f=="pop"&&(a.next=t);a.push&&(a.nextState=a.next||a.push,a.next=e,delete a.push);if(a.rules)for(var c in a.rules)r[c]?r[c].push&&r[c].push.apply(r[c],a.rules[c]):r[c]=a.rules[c];if(a.include||typeof a=="string")var h=a.include||a,p=r[h];else Array.isArray(a)&&(p=a);if(p){var d=[u,1].concat(p);a.noEscape&&(d=d.filter(function(e){return!e.next})),o.splice.apply(o,d),u--,p=null}a.keywordMap&&(a.token=this.createKeywordMapper(a.keywordMap,a.defaultToken||"text",a.caseInsensitive),delete a.defaultToken)}}var n=0,r=this.$rules;Object.keys(r).forEach(i,this)},this.createKeywordMapper=function(e,t,n,r){var i=Object.create(null);return Object.keys(e).forEach(function(t){var s=e[t];n&&(s=s.toLowerCase());var o=s.split(r||"|");for(var u=o.length;u--;)i[o[u]]=t}),Object.getPrototypeOf(i)&&(i.__proto__=null),this.$keywordList=Object.keys(i),e=null,n?function(e){return i[e.toLowerCase()]||t}:function(e){return i[e]||t}},this.getKeywords=function(){return this.$keywords}}).call(i.prototype),t.TextHighlightRules=i}),define("ace/anchor",["require","exports","module","ace/lib/oop","ace/lib/event_emitter"],function(e,t,n){var r=e("./lib/oop"),i=e("./lib/event_emitter").EventEmitter,s=t.Anchor=function(e,t,n){this.$onChange=this.onChange.bind(this),this.attach(e),typeof n=="undefined"?this.setPosition(t.row,t.column):this.setPosition(t,n)};(function(){r.implement(this,i),this.getPosition=function(){return this.$clipPositionToDocument(this.row,this.column)},this.getDocument=function(){return this.document},this.$insertRight=!1,this.onChange=function(e){var t=e.data,n=t.range;if(n.start.row==n.end.row&&n.start.row!=this.row)return;if(n.start.row>this.row)return;if(n.start.row==this.row&&n.start.column>this.column)return;var r=this.row,i=this.column,s=n.start,o=n.end;if(t.action==="insertText")if(s.row===r&&s.column<=i){if(s.column!==i||!this.$insertRight)s.row===o.row?i+=o.column-s.column:(i-=s.column,r+=o.row-s.row)}else s.row!==o.row&&s.row<r&&(r+=o.row-s.row);else t.action==="insertLines"?s.row<=r&&(r+=o.row-s.row):t.action==="removeText"?s.row===r&&s.column<i?o.column>=i?i=s.column:i=Math.max(0,i-(o.column-s.column)):s.row!==o.row&&s.row<r?(o.row===r&&(i=Math.max(0,i-o.column)+s.column),r-=o.row-s.row):o.row===r&&(r-=o.row-s.row,i=Math.max(0,i-o.column)+s.column):t.action=="removeLines"&&s.row<=r&&(o.row<=r?r-=o.row-s.row:(r=s.row,i=0));this.setPosition(r,i,!0)},this.setPosition=function(e,t,n){var r;n?r={row:e,column:t}:r=this.$clipPositionToDocument(e,t);if(this.row==r.row&&this.column==r.column)return;var i={row:this.row,column:this.column};this.row=r.row,this.column=r.column,this._signal("change",{old:i,value:r})},this.detach=function(){this.document.removeEventListener("change",this.$onChange)},this.attach=function(e){this.document=e||this.document,this.document.on("change",this.$onChange)},this.$clipPositionToDocument=function(e,t){var n={};return e>=this.document.getLength()?(n.row=Math.max(0,this.document.getLength()-1),n.column=this.document.getLine(n.row).length):e<0?(n.row=0,n.column=0):(n.row=e,n.column=Math.min(this.document.getLine(n.row).length,Math.max(0,t))),t<0&&(n.column=0),n}}).call(s.prototype)}),define("ace/background_tokenizer",["require","exports","module","ace/lib/oop","ace/lib/event_emitter"],function(e,t,n){var r=e("./lib/oop"),i=e("./lib/event_emitter").EventEmitter,s=function(e,t){this.running=!1,this.lines=[],this.states=[],this.currentLine=0,this.tokenizer=e;var n=this;this.$worker=function(){if(!n.running)return;var e=new Date,t=n.currentLine,r=-1,i=n.doc;while(n.lines[t])t++;var s=t,o=i.getLength(),u=0;n.running=!1;while(t<o){n.$tokenizeRow(t),r=t;do t++;while(n.lines[t]);u++;if(u%5==0&&new Date-e>20){n.running=setTimeout(n.$worker,20),n.currentLine=t;return}}n.currentLine=t,s<=r&&n.fireUpdateEvent(s,r)}};(function(){r.implement(this,i),this.setTokenizer=function(e){this.tokenizer=e,this.lines=[],this.states=[],this.start(0)},this.setDocument=function(e){this.doc=e,this.lines=[],this.states=[],this.stop()},this.fireUpdateEvent=function(e,t){var n={first:e,last:t};this._signal("update",{data:n})},this.start=function(e){this.currentLine=Math.min(e||0,this.currentLine,this.doc.getLength()),this.lines.splice(this.currentLine,this.lines.length),this.states.splice(this.currentLine,this.states.length),this.stop(),this.running=setTimeout(this.$worker,700)},this.scheduleStart=function(){this.running||(this.running=setTimeout(this.$worker,700))},this.$updateOnChange=function(e){var t=e.range,n=t.start.row,r=t.end.row-n;if(r===0)this.lines[n]=null;else if(e.action=="removeText"||e.action=="removeLines")this.lines.splice(n,r+1,null),this.states.splice(n,r+1,null);else{var i=Array(r+1);i.unshift(n,1),this.lines.splice.apply(this.lines,i),this.states.splice.apply(this.states,i)}this.currentLine=Math.min(n,this.currentLine,this.doc.getLength()),this.stop()},this.stop=function(){this.running&&clearTimeout(this.running),this.running=!1},this.getTokens=function(e){return this.lines[e]||this.$tokenizeRow(e)},this.getState=function(e){return this.currentLine==e&&this.$tokenizeRow(e),this.states[e]||"start"},this.$tokenizeRow=function(e){var t=this.doc.getLine(e),n=this.states[e-1],r=this.tokenizer.getLineTokens(t,n,e);return this.states[e]+""!=r.state+""?(this.states[e]=r.state,this.lines[e+1]=null,this.currentLine>e+1&&(this.currentLine=e+1)):this.currentLine==e&&(this.currentLine=e+1),this.lines[e]=r.tokens}}).call(s.prototype),t.BackgroundTokenizer=s}),define("ace/search_highlight",["require","exports","module","ace/lib/lang","ace/lib/oop","ace/range"],function(e,t,n){var r=e("./lib/lang"),i=e("./lib/oop"),s=e("./range").Range,o=function(e,t,n){this.setRegexp(e),this.clazz=t,this.type=n||"text"};(function(){this.MAX_RANGES=500,this.setRegexp=function(e){if(this.regExp+""==e+"")return;this.regExp=e,this.cache=[]},this.update=function(e,t,n,i){if(!this.regExp)return;var o=i.firstRow,u=i.lastRow;for(var a=o;a<=u;a++){var f=this.cache[a];f==null&&(f=r.getMatchOffsets(n.getLine(a),this.regExp),f.length>this.MAX_RANGES&&(f=f.slice(0,this.MAX_RANGES)),f=f.map(function(e){return new s(a,e.offset,a,e.offset+e.length)}),this.cache[a]=f.length?f:"");for(var l=f.length;l--;)t.drawSingleLineMarker(e,f[l].toScreenRange(n),this.clazz,i)}}}).call(o.prototype),t.SearchHighlight=o}),define("ace/edit_session/folding",["require","exports","module","ace/range","ace/edit_session/fold_line","ace/edit_session/fold","ace/token_iterator"],function(e,t,n){function u(){this.getFoldAt=function(e,t,n){var r=this.getFoldLine(e);if(!r)return null;var i=r.folds;for(var s=0;s<i.length;s++){var o=i[s];if(o.range.contains(e,t)){if(n==1&&o.range.isEnd(e,t))continue;if(n==-1&&o.range.isStart(e,t))continue;return o}}},this.getFoldsInRange=function(e){var t=e.start,n=e.end,r=this.$foldData,i=[];t.column+=1,n.column-=1;for(var s=0;s<r.length;s++){var o=r[s].range.compareRange(e);if(o==2)continue;if(o==-2)break;var u=r[s].folds;for(var a=0;a<u.length;a++){var f=u[a];o=f.range.compareRange(e);if(o==-2)break;if(o==2)continue;if(o==42)break;i.push(f)}}return t.column-=1,n.column+=1,i},this.getFoldsInRangeList=function(e){if(Array.isArray(e)){var t=[];e.forEach(function(e){t=t.concat(this.getFoldsInRange(e))},this)}else var t=this.getFoldsInRange(e);return t},this.getAllFolds=function(){var e=[],t=this.$foldData;for(var n=0;n<t.length;n++)for(var r=0;r<t[n].folds.length;r++)e.push(t[n].folds[r]);return e},this.getFoldStringAt=function(e,t,n,r){r=r||this.getFoldLine(e);if(!r)return null;var i={end:{column:0}},s,o;for(var u=0;u<r.folds.length;u++){o=r.folds[u];var a=o.range.compareEnd(e,t);if(a==-1){s=this.getLine(o.start.row).substring(i.end.column,o.start.column);break}if(a===0)return null;i=o}return s||(s=this.getLine(o.start.row).substring(i.end.column)),n==-1?s.substring(0,t-i.end.column):n==1?s.substring(t-i.end.column):s},this.getFoldLine=function(e,t){var n=this.$foldData,r=0;t&&(r=n.indexOf(t)),r==-1&&(r=0);for(r;r<n.length;r++){var i=n[r];if(i.start.row<=e&&i.end.row>=e)return i;if(i.end.row>e)return null}return null},this.getNextFoldLine=function(e,t){var n=this.$foldData,r=0;t&&(r=n.indexOf(t)),r==-1&&(r=0);for(r;r<n.length;r++){var i=n[r];if(i.end.row>=e)return i}return null},this.getFoldedRowCount=function(e,t){var n=this.$foldData,r=t-e+1;for(var i=0;i<n.length;i++){var s=n[i],o=s.end.row,u=s.start.row;if(o>=t){u<t&&(u>=e?r-=t-u:r=0);break}o>=e&&(u>=e?r-=o-u:r-=o-e+1)}return r},this.$addFoldLine=function(e){return this.$foldData.push(e),this.$foldData.sort(function(e,t){return e.start.row-t.start.row}),e},this.addFold=function(e,t){var n=this.$foldData,r=!1,o;e instanceof s?o=e:(o=new s(t,e),o.collapseChildren=t.collapseChildren),this.$clipRangeToDocument(o.range);var u=o.start.row,a=o.start.column,f=o.end.row,l=o.end.column;if(u<f||u==f&&a<=l-2){var c=this.getFoldAt(u,a,1),h=this.getFoldAt(f,l,-1);if(c&&h==c)return c.addSubFold(o);if(c&&!c.range.isStart(u,a)||h&&!h.range.isEnd(f,l))throw new Error("A fold can't intersect already existing fold"+o.range+c.range);var p=this.getFoldsInRange(o.range);p.length>0&&(this.removeFolds(p),p.forEach(function(e){o.addSubFold(e)}));for(var d=0;d<n.length;d++){var v=n[d];if(f==v.start.row){v.addFold(o),r=!0;break}if(u==v.end.row){v.addFold(o),r=!0;if(!o.sameRow){var m=n[d+1];if(m&&m.start.row==f){v.merge(m);break}}break}if(f<=v.start.row)break}return r||(v=this.$addFoldLine(new i(this.$foldData,o))),this.$useWrapMode?this.$updateWrapData(v.start.row,v.start.row):this.$updateRowLengthCache(v.start.row,v.start.row),this.$modified=!0,this._emit("changeFold",{data:o,action:"add"}),o}throw new Error("The range has to be at least 2 characters width")},this.addFolds=function(e){e.forEach(function(e){this.addFold(e)},this)},this.removeFold=function(e){var t=e.foldLine,n=t.start.row,r=t.end.row,i=this.$foldData,s=t.folds;if(s.length==1)i.splice(i.indexOf(t),1);else if(t.range.isEnd(e.end.row,e.end.column))s.pop(),t.end.row=s[s.length-1].end.row,t.end.column=s[s.length-1].end.column;else if(t.range.isStart(e.start.row,e.start.column))s.shift(),t.start.row=s[0].start.row,t.start.column=s[0].start.column;else if(e.sameRow)s.splice(s.indexOf(e),1);else{var o=t.split(e.start.row,e.start.column);s=o.folds,s.shift(),o.start.row=s[0].start.row,o.start.column=s[0].start.column}this.$updating||(this.$useWrapMode?this.$updateWrapData(n,r):this.$updateRowLengthCache(n,r)),this.$modified=!0,this._emit("changeFold",{data:e,action:"remove"})},this.removeFolds=function(e){var t=[];for(var n=0;n<e.length;n++)t.push(e[n]);t.forEach(function(e){this.removeFold(e)},this),this.$modified=!0},this.expandFold=function(e){this.removeFold(e),e.subFolds.forEach(function(t){e.restoreRange(t),this.addFold(t)},this),e.collapseChildren>0&&this.foldAll(e.start.row+1,e.end.row,e.collapseChildren-1),e.subFolds=[]},this.expandFolds=function(e){e.forEach(function(e){this.expandFold(e)},this)},this.unfold=function(e,t){var n,i;e==null?(n=new r(0,0,this.getLength(),0),t=!0):typeof e=="number"?n=new r(e,0,e,this.getLine(e).length):"row"in e?n=r.fromPoints(e,e):n=e,i=this.getFoldsInRangeList(n);if(t)this.removeFolds(i);else{var s=i;while(s.length)this.expandFolds(s),s=this.getFoldsInRangeList(n)}if(i.length)return i},this.isRowFolded=function(e,t){return!!this.getFoldLine(e,t)},this.getRowFoldEnd=function(e,t){var n=this.getFoldLine(e,t);return n?n.end.row:e},this.getRowFoldStart=function(e,t){var n=this.getFoldLine(e,t);return n?n.start.row:e},this.getFoldDisplayLine=function(e,t,n,r,i){r==null&&(r=e.start.row,i=0),t==null&&(t=e.end.row,n=this.getLine(t).length);var s=this.doc,o="";return e.walk(function(e,t,n,u){if(t<r)return;if(t==r){if(n<i)return;u=Math.max(i,u)}e!=null?o+=e:o+=s.getLine(t).substring(u,n)},t,n),o},this.getDisplayLine=function(e,t,n,r){var i=this.getFoldLine(e);if(!i){var s;return s=this.doc.getLine(e),s.substring(r||0,t||s.length)}return this.getFoldDisplayLine(i,e,t,n,r)},this.$cloneFoldData=function(){var e=[];return e=this.$foldData.map(function(t){var n=t.folds.map(function(e){return e.clone()});return new i(e,n)}),e},this.toggleFold=function(e){var t=this.selection,n=t.getRange(),r,i;if(n.isEmpty()){var s=n.start;r=this.getFoldAt(s.row,s.column);if(r){this.expandFold(r);return}(i=this.findMatchingBracket(s))?n.comparePoint(i)==1?n.end=i:(n.start=i,n.start.column++,n.end.column--):(i=this.findMatchingBracket({row:s.row,column:s.column+1}))?(n.comparePoint(i)==1?n.end=i:n.start=i,n.start.column++):n=this.getCommentFoldRange(s.row,s.column)||n}else{var o=this.getFoldsInRange(n);if(e&&o.length){this.expandFolds(o);return}o.length==1&&(r=o[0])}r||(r=this.getFoldAt(n.start.row,n.start.column));if(r&&r.range.toString()==n.toString()){this.expandFold(r);return}var u="...";if(!n.isMultiLine()){u=this.getTextRange(n);if(u.length<4)return;u=u.trim().substring(0,2)+".."}this.addFold(u,n)},this.getCommentFoldRange=function(e,t,n){var i=new o(this,e,t),s=i.getCurrentToken();if(s&&/^comment|string/.test(s.type)){var u=new r,a=new RegExp(s.type.replace(/\..*/,"\\."));if(n!=1){do s=i.stepBackward();while(s&&a.test(s.type));i.stepForward()}u.start.row=i.getCurrentTokenRow(),u.start.column=i.getCurrentTokenColumn()+2,i=new o(this,e,t);if(n!=-1){do s=i.stepForward();while(s&&a.test(s.type));s=i.stepBackward()}else s=i.getCurrentToken();return u.end.row=i.getCurrentTokenRow(),u.end.column=i.getCurrentTokenColumn()+s.value.length-2,u}},this.foldAll=function(e,t,n){n==undefined&&(n=1e5);var r=this.foldWidgets;if(!r)return;t=t||this.getLength(),e=e||0;for(var i=e;i<t;i++){r[i]==null&&(r[i]=this.getFoldWidget(i));if(r[i]!="start")continue;var s=this.getFoldWidgetRange(i);if(s&&s.isMultiLine()&&s.end.row<=t&&s.start.row>=e){i=s.end.row;try{var o=this.addFold("...",s);o&&(o.collapseChildren=n)}catch(u){}}}},this.$foldStyles={manual:1,markbegin:1,markbeginend:1},this.$foldStyle="markbegin",this.setFoldStyle=function(e){if(!this.$foldStyles[e])throw new Error("invalid fold style: "+e+"["+Object.keys(this.$foldStyles).join(", ")+"]");if(this.$foldStyle==e)return;this.$foldStyle=e,e=="manual"&&this.unfold();var t=this.$foldMode;this.$setFolding(null),this.$setFolding(t)},this.$setFolding=function(e){if(this.$foldMode==e)return;this.$foldMode=e,this.removeListener("change",this.$updateFoldWidgets),this._emit("changeAnnotation");if(!e||this.$foldStyle=="manual"){this.foldWidgets=null;return}this.foldWidgets=[],this.getFoldWidget=e.getFoldWidget.bind(e,this,this.$foldStyle),this.getFoldWidgetRange=e.getFoldWidgetRange.bind(e,this,this.$foldStyle),this.$updateFoldWidgets=this.updateFoldWidgets.bind(this),this.on("change",this.$updateFoldWidgets)},this.getParentFoldRangeData=function(e,t){var n=this.foldWidgets;if(!n||t&&n[e])return{};var r=e-1,i;while(r>=0){var s=n[r];s==null&&(s=n[r]=this.getFoldWidget(r));if(s=="start"){var o=this.getFoldWidgetRange(r);i||(i=o);if(o&&o.end.row>=e)break}r--}return{range:r!==-1&&o,firstRange:i}},this.onFoldWidgetClick=function(e,t){t=t.domEvent;var n={children:t.shiftKey,all:t.ctrlKey||t.metaKey,siblings:t.altKey},r=this.$toggleFoldWidget(e,n);if(!r){var i=t.target||t.srcElement;i&&/ace_fold-widget/.test(i.className)&&(i.className+=" ace_invalid")}},this.$toggleFoldWidget=function(e,t){if(!this.getFoldWidget)return;var n=this.getFoldWidget(e),r=this.getLine(e),i=n==="end"?-1:1,s=this.getFoldAt(e,i===-1?0:r.length,i);if(s){t.children||t.all?this.removeFold(s):this.expandFold(s);return}var o=this.getFoldWidgetRange(e,!0);if(o&&!o.isMultiLine()){s=this.getFoldAt(o.start.row,o.start.column,1);if(s&&o.isEqual(s.range)){this.removeFold(s);return}}if(t.siblings){var u=this.getParentFoldRangeData(e);if(u.range)var a=u.range.start.row+1,f=u.range.end.row;this.foldAll(a,f,t.all?1e4:0)}else t.children?(f=o?o.end.row:this.getLength(),this.foldAll(e+1,o.end.row,t.all?1e4:0)):o&&(t.all&&(o.collapseChildren=1e4),this.addFold("...",o));return o},this.toggleFoldWidget=function(e){var t=this.selection.getCursor().row;t=this.getRowFoldStart(t);var n=this.$toggleFoldWidget(t,{});if(n)return;var r=this.getParentFoldRangeData(t,!0);n=r.range||r.firstRange;if(n){t=n.start.row;var i=this.getFoldAt(t,this.getLine(t).length,1);i?this.removeFold(i):this.addFold("...",n)}},this.updateFoldWidgets=function(e){var t=e.data,n=t.range,r=n.start.row,i=n.end.row-r;if(i===0)this.foldWidgets[r]=null;else if(t.action=="removeText"||t.action=="removeLines")this.foldWidgets.splice(r,i+1,null);else{var s=Array(i+1);s.unshift(r,1),this.foldWidgets.splice.apply(this.foldWidgets,s)}}}var r=e("../range").Range,i=e("./fold_line").FoldLine,s=e("./fold").Fold,o=e("../token_iterator").TokenIterator;t.Folding=u}),define("ace/edit_session/fold_line",["require","exports","module","ace/range"],function(e,t,n){function i(e,t){this.foldData=e,Array.isArray(t)?this.folds=t:t=this.folds=[t];var n=t[t.length-1];this.range=new r(t[0].start.row,t[0].start.column,n.end.row,n.end.column),this.start=this.range.start,this.end=this.range.end,this.folds.forEach(function(e){e.setFoldLine(this)},this)}var r=e("../range").Range;(function(){this.shiftRow=function(e){this.start.row+=e,this.end.row+=e,this.folds.forEach(function(t){t.start.row+=e,t.end.row+=e})},this.addFold=function(e){if(e.sameRow){if(e.start.row<this.startRow||e.endRow>this.endRow)throw new Error("Can't add a fold to this FoldLine as it has no connection");this.folds.push(e),this.folds.sort(function(e,t){return-e.range.compareEnd(t.start.row,t.start.column)}),this.range.compareEnd(e.start.row,e.start.column)>0?(this.end.row=e.end.row,this.end.column=e.end.column):this.range.compareStart(e.end.row,e.end.column)<0&&(this.start.row=e.start.row,this.start.column=e.start.column)}else if(e.start.row==this.end.row)this.folds.push(e),this.end.row=e.end.row,this.end.column=e.end.column;else{if(e.end.row!=this.start.row)throw new Error("Trying to add fold to FoldRow that doesn't have a matching row");this.folds.unshift(e),this.start.row=e.start.row,this.start.column=e.start.column}e.foldLine=this},this.containsRow=function(e){return e>=this.start.row&&e<=this.end.row},this.walk=function(e,t,n){var r=0,i=this.folds,s,o,u,a=!0;t==null&&(t=this.end.row,n=this.end.column);for(var f=0;f<i.length;f++){s=i[f],o=s.range.compareStart(t,n);if(o==-1){e(null,t,n,r,a);return}u=e(null,s.start.row,s.start.column,r,a),u=!u&&e(s.placeholder,s.start.row,s.start.column,r);if(u||o==0)return;a=!s.sameRow,r=s.end.column}e(null,t,n,r,a)},this.getNextFoldTo=function(e,t){var n,r;for(var i=0;i<this.folds.length;i++){n=this.folds[i],r=n.range.compareEnd(e,t);if(r==-1)return{fold:n,kind:"after"};if(r==0)return{fold:n,kind:"inside"}}return null},this.addRemoveChars=function(e,t,n){var r=this.getNextFoldTo(e,t),i,s;if(r){i=r.fold;if(r.kind=="inside"&&i.start.column!=t&&i.start.row!=e)window.console&&window.console.log(e,t,i);else if(i.start.row==e){s=this.folds;var o=s.indexOf(i);o==0&&(this.start.column+=n);for(o;o<s.length;o++){i=s[o],i.start.column+=n;if(!i.sameRow)return;i.end.column+=n}this.end.column+=n}}},this.split=function(e,t){var n=this.getNextFoldTo(e,t).fold,r=this.folds,s=this.foldData;if(!n)return null;var o=r.indexOf(n),u=r[o-1];this.end.row=u.end.row,this.end.column=u.end.column,r=r.splice(o,r.length-o);var a=new i(s,r);return s.splice(s.indexOf(this)+1,0,a),a},this.merge=function(e){var t=e.folds;for(var n=0;n<t.length;n++)this.addFold(t[n]);var r=this.foldData;r.splice(r.indexOf(e),1)},this.toString=function(){var e=[this.range.toString()+": ["];return this.folds.forEach(function(t){e.push(" "+t.toString())}),e.push("]"),e.join("\n")},this.idxToPosition=function(e){var t=0,n;for(var r=0;r<this.folds.length;r++){var n=this.folds[r];e-=n.start.column-t;if(e<0)return{row:n.start.row,column:n.start.column+e};e-=n.placeholder.length;if(e<0)return n.start;t=n.end.column}return{row:this.end.row,column:this.end.column+e}}}).call(i.prototype),t.FoldLine=i}),define("ace/tokenizer",["require","exports","module"],function(e,t,n){var r=1e3,i=function(e){this.states=e,this.regExps={},this.matchMappings={};for(var t in this.states){var n=this.states[t],r=[],i=0,s=this.matchMappings[t]={defaultToken:"text"},o="g",u=[];for(var a=0;a<n.length;a++){var f=n[a];f.defaultToken&&(s.defaultToken=f.defaultToken),f.caseInsensitive&&(o="gi");if(f.regex==null)continue;f.regex instanceof RegExp&&(f.regex=f.regex.toString().slice(1,-1));var l=f.regex,c=(new RegExp("(?:("+l+")|(.))")).exec("a").length-2;if(Array.isArray(f.token))if(f.token.length==1||c==1)f.token=f.token[0];else{if(c-1!=f.token.length)throw new Error("number of classes and regexp groups in '"+f.token+"'\n'"+f.regex+"' doesn't match\n"+(c-1)+"!="+f.token.length);f.tokenArray=f.token,f.token=null,f.onMatch=this.$arrayTokens}else typeof f.token=="function"&&!f.onMatch&&(c>1?f.onMatch=this.$applyToken:f.onMatch=f.token);c>1&&(/\\\d/.test(f.regex)?l=f.regex.replace(/\\([0-9]+)/g,function(e,t){return"\\"+(parseInt(t,10)+i+1)}):(c=1,l=this.removeCapturingGroups(f.regex)),!f.splitRegex&&typeof f.token!="string"&&u.push(f)),s[i]=a,i+=c,r.push(l),f.onMatch||(f.onMatch=null),f.__proto__=null}u.forEach(function(e){e.splitRegex=this.createSplitterRegexp(e.regex,o)},this),this.regExps[t]=new RegExp("("+r.join(")|(")+")|($)",o)}};(function(){this.$setMaxTokenCount=function(e){r=e|0},this.$applyToken=function(e){var t=this.splitRegex.exec(e).slice(1),n=this.token.apply(this,t);if(typeof n=="string")return[{type:n,value:e}];var r=[];for(var i=0,s=n.length;i<s;i++)t[i]&&(r[r.length]={type:n[i],value:t[i]});return r},this.$arrayTokens=function(e){if(!e)return[];var t=this.splitRegex.exec(e);if(!t)return"text";var n=[],r=this.tokenArray;for(var i=0,s=r.length;i<s;i++)t[i+1]&&(n[n.length]={type:r[i],value:t[i+1]});return n},this.removeCapturingGroups=function(e){var t=e.replace(/\[(?:\\.|[^\]])*?\]|\\.|\(\?[:=!]|(\()/g,function(e,t){return t?"(?:":e});return t},this.createSplitterRegexp=function(e,t){if(e.indexOf("(?=")!=-1){var n=0,r=!1,i={};e.replace(/(\\.)|(\((?:\?[=!])?)|(\))|([\[\]])/g,function(e,t,s,o,u,a){return r?r=u!="]":u?r=!0:o?(n==i.stack&&(i.end=a+1,i.stack=-1),n--):s&&(n++,s.length!=1&&(i.stack=n,i.start=a)),e}),i.end!=null&&/^\)*$/.test(e.substr(i.end))&&(e=e.substring(0,i.start)+e.substr(i.end))}return new RegExp(e,(t||"").replace("g",""))},this.getLineTokens=function(e,t){if(t&&typeof t!="string"){var n=t.slice(0);t=n[0]}else var n=[];var i=t||"start",s=this.states[i];s||(i="start",s=this.states[i]);var o=this.matchMappings[i],u=this.regExps[i];u.lastIndex=0;var a,f=[],l=0,c={type:null,value:""};while(a=u.exec(e)){var h=o.defaultToken,p=null,d=a[0],v=u.lastIndex;if(v-d.length>l){var m=e.substring(l,v-d.length);c.type==h?c.value+=m:(c.type&&f.push(c),c={type:h,value:m})}for(var g=0;g<a.length-2;g++){if(a[g+1]===undefined)continue;p=s[o[g]],p.onMatch?h=p.onMatch(d,i,n):h=p.token,p.next&&(typeof p.next=="string"?i=p.next:i=p.next(i,n),s=this.states[i],s||(window.console&&console.error&&console.error(i,"doesn't exist"),i="start",s=this.states[i]),o=this.matchMappings[i],l=v,u=this.regExps[i],u.lastIndex=v);break}if(d)if(typeof h=="string")!!p&&p.merge===!1||c.type!==h?(c.type&&f.push(c),c={type:h,value:d}):c.value+=d;else if(h){c.type&&f.push(c),c={type:null,value:""};for(var g=0;g<h.length;g++)f.push(h[g])}if(l==e.length)break;l=v;if(f.length>r){while(l<e.length)c.type&&f.push(c),c={value:e.substring(l,l+=2e3),type:"overflow"};i="start",n=[];break}}return c.type&&f.push(c),n.length>1&&n[0]!==i&&n.unshift(i),{tokens:f,state:n.length?n:i}}}).call(i.prototype),t.Tokenizer=i}),define("ace/edit_session/fold",["require","exports","module","ace/range","ace/range_list","ace/lib/oop"],function(e,t,n){function u(e,t){e.row-=t.row,e.row==0&&(e.column-=t.column)}function a(e,t){u(e.start,t),u(e.end,t)}function f(e,t){e.row==0&&(e.column+=t.column),e.row+=t.row}function l(e,t){f(e.start,t),f(e.end,t)}var r=e("../range").Range,i=e("../range_list").RangeList,s=e("../lib/oop"),o=t.Fold=function(e,t){this.foldLine=null,this.placeholder=t,this.range=e,this.start=e.start,this.end=e.end,this.sameRow=e.start.row==e.end.row,this.subFolds=this.ranges=[]};s.inherits(o,i),function(){this.toString=function(){return'"'+this.placeholder+'" '+this.range.toString()},this.setFoldLine=function(e){this.foldLine=e,this.subFolds.forEach(function(t){t.setFoldLine(e)})},this.clone=function(){var e=this.range.clone(),t=new o(e,this.placeholder);return this.subFolds.forEach(function(e){t.subFolds.push(e.clone())}),t.collapseChildren=this.collapseChildren,t},this.addSubFold=function(e){if(this.range.isEqual(e))return;if(!this.range.containsRange(e))throw new Error("A fold can't intersect already existing fold"+e.range+this.range);a(e,this.start);var t=e.start.row,n=e.start.column;for(var r=0,i=-1;r<this.subFolds.length;r++){i=this.subFolds[r].range.compare(t,n);if(i!=1)break}var s=this.subFolds[r];if(i==0)return s.addSubFold(e);var t=e.range.end.row,n=e.range.end.column;for(var o=r,i=-1;o<this.subFolds.length;o++){i=this.subFolds[o].range.compare(t,n);if(i!=1)break}var u=this.subFolds[o];if(i==0)throw new Error("A fold can't intersect already existing fold"+e.range+this.range);var f=this.subFolds.splice(r,o-r,e);return e.setFoldLine(this.foldLine),e},this.restoreRange=function(e){return l(e,this.start)}}.call(o.prototype)}),define("ace/mode/text",["require","exports","module","ace/tokenizer","ace/mode/text_highlight_rules","ace/mode/behaviour","ace/unicode","ace/lib/lang","ace/token_iterator","ace/range"],function(e,t,n){var r=e("../tokenizer").Tokenizer,i=e("./text_highlight_rules").TextHighlightRules,s=e("./behaviour").Behaviour,o=e("../unicode"),u=e("../lib/lang"),a=e("../token_iterator").TokenIterator,f=e("../range").Range,l=function(){this.HighlightRules=i,this.$behaviour=new s};(function(){this.tokenRe=new RegExp("^["+o.packages.L+o.packages.Mn+o.packages.Mc+o.packages.Nd+o.packages.Pc+"\\$_]+","g"),this.nonTokenRe=new RegExp("^(?:[^"+o.packages.L+o.packages.Mn+o.packages.Mc+o.packages.Nd+o.packages.Pc+"\\$_]|\\s])+","g"),this.getTokenizer=function(){return this.$tokenizer||(this.$highlightRules=new this.HighlightRules,this.$tokenizer=new r(this.$highlightRules.getRules())),this.$tokenizer},this.lineCommentStart="",this.blockComment="",this.toggleCommentLines=function(e,t,n,r){function w(e){for(var t=n;t<=r;t++)e(i.getLine(t),t)}var i=t.doc,s=!0,o=!0,a=Infinity,f=t.getTabSize(),l=!1;if(!this.lineCommentStart){if(!this.blockComment)return!1;var c=this.blockComment.start,h=this.blockComment.end,p=new RegExp("^(\\s*)(?:"+u.escapeRegExp(c)+")"),d=new RegExp("(?:"+u.escapeRegExp(h)+")\\s*$"),v=function(e,t){if(g(e,t))return;if(!s||/\S/.test(e))i.insertInLine({row:t,column:e.length},h),i.insertInLine({row:t,column:a},c)},m=function(e,t){var n;(n=e.match(d))&&i.removeInLine(t,e.length-n[0].length,e.length),(n=e.match(p))&&i.removeInLine(t,n[1].length,n[0].length)},g=function(e,n){if(p.test(e))return!0;var r=t.getTokens(n);for(var i=0;i<r.length;i++)if(r[i].type==="comment")return!0}}else{if(Array.isArray(this.lineCommentStart))var p=this.lineCommentStart.map(u.escapeRegExp).join("|"),c=this.lineCommentStart[0];else var p=u.escapeRegExp(this.lineCommentStart),c=this.lineCommentStart;p=new RegExp("^(\\s*)(?:"+p+") ?"),l=t.getUseSoftTabs();var m=function(e,t){var n=e.match(p);if(!n)return;var r=n[1].length,s=n[0].length;!b(e,r,s)&&n[0][s-1]==" "&&s--,i.removeInLine(t,r,s)},y=c+" ",v=function(e,t){if(!s||/\S/.test(e))b(e,a,a)?i.insertInLine({row:t,column:a},y):i.insertInLine({row:t,column:a},c)},g=function(e,t){return p.test(e)},b=function(e,t,n){var r=0;while(t--&&e.charAt(t)==" ")r++;if(r%f!=0)return!1;var r=0;while(e.charAt(n++)==" ")r++;return f>2?r%f!=f-1:r%f==0}}var E=Infinity;w(function(e,t){var n=e.search(/\S/);n!==-1?(n<a&&(a=n),o&&!g(e,t)&&(o=!1)):E>e.length&&(E=e.length)}),a==Infinity&&(a=E,s=!1,o=!1),l&&a%f!=0&&(a=Math.floor(a/f)*f),w(o?m:v)},this.toggleBlockComment=function(e,t,n,r){var i=this.blockComment;if(!i)return;!i.start&&i[0]&&(i=i[0]);var s=new a(t,r.row,r.column),o=s.getCurrentToken(),u=t.selection,l=t.selection.toOrientedRange(),c,h;if(o&&/comment/.test(o.type)){var p,d;while(o&&/comment/.test(o.type)){var v=o.value.indexOf(i.start);if(v!=-1){var m=s.getCurrentTokenRow(),g=s.getCurrentTokenColumn()+v;p=new f(m,g,m,g+i.start.length);break}o=s.stepBackward()}var s=new a(t,r.row,r.column),o=s.getCurrentToken();while(o&&/comment/.test(o.type)){var v=o.value.indexOf(i.end);if(v!=-1){var m=s.getCurrentTokenRow(),g=s.getCurrentTokenColumn()+v;d=new f(m,g,m,g+i.end.length);break}o=s.stepForward()}d&&t.remove(d),p&&(t.remove(p),c=p.start.row,h=-i.start.length)}else h=i.start.length,c=n.start.row,t.insert(n.end,i.end),t.insert(n.start,i.start);l.start.row==c&&(l.start.column+=h),l.end.row==c&&(l.end.column+=h),t.selection.fromOrientedRange(l)},this.getNextLineIndent=function(e,t,n){return this.$getIndent(t)},this.checkOutdent=function(e,t,n){return!1},this.autoOutdent=function(e,t,n){},this.$getIndent=function(e){return e.match(/^\s*/)[0]},this.createWorker=function(e){return null},this.createModeDelegates=function(e){this.$embeds=[],this.$modes={};for(var t in e)e[t]&&(this.$embeds.push(t),this.$modes[t]=new e[t]);var n=["toggleBlockComment","toggleCommentLines","getNextLineIndent","checkOutdent","autoOutdent","transformAction","getCompletions"];for(var t=0;t<n.length;t++)(function(e){var r=n[t],i=e[r];e[n[t]]=function(){return this.$delegator(r,arguments,i)}})(this)},this.$delegator=function(e,t,n){var r=t[0];typeof r!="string"&&(r=r[0]);for(var i=0;i<this.$embeds.length;i++){if(!this.$modes[this.$embeds[i]])continue;var s=r.split(this.$embeds[i]);if(!s[0]&&s[1]){t[0]=s[1];var o=this.$modes[this.$embeds[i]];return o[e].apply(o,t)}}var u=n.apply(this,t);return n?u:undefined},this.transformAction=function(e,t,n,r,i){if(this.$behaviour){var s=this.$behaviour.getBehaviours();for(var o in s)if(s[o][t]){var u=s[o][t].apply(this,arguments);if(u)return u}}},this.getKeywords=function(e){if(!this.completionKeywords){var t=this.$tokenizer.rules,n=[];for(var r in t){var i=t[r];for(var s=0,o=i.length;s<o;s++)if(typeof i[s].token=="string")/keyword|support|storage/.test(i[s].token)&&n.push(i[s].regex);else if(typeof i[s].token=="object")for(var u=0,a=i[s].token.length;u<a;u++)if(/keyword|support|storage/.test(i[s].token[u])){var r=i[s].regex.match(/\(.+?\)/g)[u];n.push(r.substr(1,r.length-2))}}this.completionKeywords=n}return e?n.concat(this.$keywordList||[]):this.$keywordList},this.$createKeywordList=function(){return this.$highlightRules||this.getTokenizer(),this.$keywordList=this.$highlightRules.$keywordList||[]},this.getCompletions=function(e,t,n,r){var i=this.$keywordList||this.$createKeywordList();return i.map(function(e){return{name:e,value:e,score:0,meta:"keyword"}})},this.$id="ace/mode/text"}).call(l.prototype),t.Mode=l}),define("ace/range_list",["require","exports","module","ace/range"],function(e,t,n){var r=e("./range").Range,i=r.comparePoints,s=function(){this.ranges=[]};(function(){this.comparePoints=i,this.pointIndex=function(e,t,n){var r=this.ranges;for(var s=n||0;s<r.length;s++){var o=r[s],u=i(e,o.end);if(u>0)continue;var a=i(e,o.start);return u===0?t&&a!==0?-s-2:s:a>0||a===0&&!t?s:-s-1}return-s-1},this.add=function(e){var t=!e.isEmpty(),n=this.pointIndex(e.start,t);n<0&&(n=-n-1);var r=this.pointIndex(e.end,t,n);return r<0?r=-r-1:r++,this.ranges.splice(n,r-n,e)},this.addList=function(e){var t=[];for(var n=e.length;n--;)t.push.call(t,this.add(e[n]));return t},this.substractPoint=function(e){var t=this.pointIndex(e);if(t>=0)return this.ranges.splice(t,1)},this.merge=function(){var e=[],t=this.ranges;t=t.sort(function(e,t){return i(e.start,t.start)});var n=t[0],r;for(var s=1;s<t.length;s++){r=n,n=t[s];var o=i(r.end,n.start);if(o<0)continue;if(o==0&&!r.isEmpty()&&!n.isEmpty())continue;i(r.end,n.end)<0&&(r.end.row=n.end.row,r.end.column=n.end.column),t.splice(s,1),e.push(n),n=r,s--}return this.ranges=t,e},this.contains=function(e,t){return this.pointIndex({row:e,column:t})>=0},this.containsPoint=function(e){return this.pointIndex(e)>=0},this.rangeAtPoint=function(e){var t=this.pointIndex(e);if(t>=0)return this.ranges[t]},this.clipRows=function(e,t){var n=this.ranges;if(n[0].start.row>t||n[n.length-1].start.row<e)return[];var r=this.pointIndex({row:e,column:0});r<0&&(r=-r-1);var i=this.pointIndex({row:t,column:0},r);i<0&&(i=-i-1);var s=[];for(var o=r;o<i;o++)s.push(n[o]);return s},this.removeAll=function(){return this.ranges.splice(0,this.ranges.length)},this.attach=function(e){this.session&&this.detach(),this.session=e,this.onChange=this.$onChange.bind(this),this.session.on("change",this.onChange)},this.detach=function(){if(!this.session)return;this.session.removeListener("change",this.onChange),this.session=null},this.$onChange=function(e){var t=e.data.range;if(e.data.action[0]=="i")var n=t.start,r=t.end;else var r=t.start,n=t.end;var i=n.row,s=r.row,o=s-i,u=-n.column+r.column,a=this.ranges;for(var f=0,l=a.length;f<l;f++){var c=a[f];if(c.end.row<i)continue;if(c.start.row>i)break;c.start.row==i&&c.start.column>=n.column&&(c.start.column!=n.column||!this.$insertRight)&&(c.start.column+=u,c.start.row+=o);if(c.end.row==i&&c.end.column>=n.column){if(c.end.column==n.column&&this.$insertRight)continue;c.end.column==n.column&&u>0&&f<l-1&&c.end.column>c.start.column&&c.end.column==a[f+1].start.column&&(c.end.column-=u),c.end.column+=u,c.end.row+=o}}if(o!=0&&f<l)for(;f<l;f++){var c=a[f];c.start.row+=o,c.end.row+=o}}}).call(s.prototype),t.RangeList=s}),define("ace/range",["require","exports","module"],function(e,t,n){var r=function(e,t){return e.row-t.row||e.column-t.column},i=function(e,t,n,r){this.start={row:e,column:t},this.end={row:n,column:r}};(function(){this.isEqual=function(e){return this.start.row===e.start.row&&this.end.row===e.end.row&&this.start.column===e.start.column&&this.end.column===e.end.column},this.toString=function(){return"Range: ["+this.start.row+"/"+this.start.column+"] -> ["+this.end.row+"/"+this.end.column+"]"},this.contains=function(e,t){return this.compare(e,t)==0},this.compareRange=function(e){var t,n=e.end,r=e.start;return t=this.compare(n.row,n.column),t==1?(t=this.compare(r.row,r.column),t==1?2:t==0?1:0):t==-1?-2:(t=this.compare(r.row,r.column),t==-1?-1:t==1?42:0)},this.comparePoint=function(e){return this.compare(e.row,e.column)},this.containsRange=function(e){return this.comparePoint(e.start)==0&&this.comparePoint(e.end)==0},this.intersects=function(e){var t=this.compareRange(e);return t==-1||t==0||t==1},this.isEnd=function(e,t){return this.end.row==e&&this.end.column==t},this.isStart=function(e,t){return this.start.row==e&&this.start.column==t},this.setStart=function(e,t){typeof e=="object"?(this.start.column=e.column,this.start.row=e.row):(this.start.row=e,this.start.column=t)},this.setEnd=function(e,t){typeof e=="object"?(this.end.column=e.column,this.end.row=e.row):(this.end.row=e,this.end.column=t)},this.inside=function(e,t){return this.compare(e,t)==0?this.isEnd(e,t)||this.isStart(e,t)?!1:!0:!1},this.insideStart=function(e,t){return this.compare(e,t)==0?this.isEnd(e,t)?!1:!0:!1},this.insideEnd=function(e,t){return this.compare(e,t)==0?this.isStart(e,t)?!1:!0:!1},this.compare=function(e,t){return!this.isMultiLine()&&e===this.start.row?t<this.start.column?-1:t>this.end.column?1:0:e<this.start.row?-1:e>this.end.row?1:this.start.row===e?t>=this.start.column?0:-1:this.end.row===e?t<=this.end.column?0:1:0},this.compareStart=function(e,t){return this.start.row==e&&this.start.column==t?-1:this.compare(e,t)},this.compareEnd=function(e,t){return this.end.row==e&&this.end.column==t?1:this.compare(e,t)},this.compareInside=function(e,t){return this.end.row==e&&this.end.column==t?1:this.start.row==e&&this.start.column==t?-1:this.compare(e,t)},this.clipRows=function(e,t){if(this.end.row>t)var n={row:t+1,column:0};else if(this.end.row<e)var n={row:e,column:0};if(this.start.row>t)var r={row:t+1,column:0};else if(this.start.row<e)var r={row:e,column:0};return i.fromPoints(r||this.start,n||this.end)},this.extend=function(e,t){var n=this.compare(e,t);if(n==0)return this;if(n==-1)var r={row:e,column:t};else var s={row:e,column:t};return i.fromPoints(r||this.start,s||this.end)},this.isEmpty=function(){return this.start.row===this.end.row&&this.start.column===this.end.column},this.isMultiLine=function(){return this.start.row!==this.end.row},this.clone=function(){return i.fromPoints(this.start,this.end)},this.collapseRows=function(){return this.end.column==0?new i(this.start.row,0,Math.max(this.start.row,this.end.row-1),0):new i(this.start.row,0,this.end.row,0)},this.toScreenRange=function(e){var t=e.documentToScreenPosition(this.start),n=e.documentToScreenPosition(this.end);return new i(t.row,t.column,n.row,n.column)},this.moveBy=function(e,t){this.start.row+=e,this.start.column+=t,this.end.row+=e,this.end.column+=t}}).call(i.prototype),i.fromPoints=function(e,t){return new i(e.row,e.column,t.row,t.column)},i.comparePoints=r,i.comparePoints=function(e,t){return e.row-t.row||e.column-t.column},t.Range=i}),define("ace/edit_session/bracket_match",["require","exports","module","ace/token_iterator","ace/range"],function(e,t,n){function s(){this.findMatchingBracket=function(e,t){if(e.column==0)return null;var n=t||this.getLine(e.row).charAt(e.column-1);if(n=="")return null;var r=n.match(/([\(\[\{])|([\)\]\}])/);return r?r[1]?this.$findClosingBracket(r[1],e):this.$findOpeningBracket(r[2],e):null},this.getBracketRange=function(e){var t=this.getLine(e.row),n=!0,r,s=t.charAt(e.column-1),o=s&&s.match(/([\(\[\{])|([\)\]\}])/);o||(s=t.charAt(e.column),e={row:e.row,column:e.column+1},o=s&&s.match(/([\(\[\{])|([\)\]\}])/),n=!1);if(!o)return null;if(o[1]){var u=this.$findClosingBracket(o[1],e);if(!u)return null;r=i.fromPoints(e,u),n||(r.end.column++,r.start.column--),r.cursor=r.end}else{var u=this.$findOpeningBracket(o[2],e);if(!u)return null;r=i.fromPoints(u,e),n||(r.start.column++,r.end.column--),r.cursor=r.start}return r},this.$brackets={")":"(","(":")","]":"[","[":"]","{":"}","}":"{"},this.$findOpeningBracket=function(e,t,n){var i=this.$brackets[e],s=1,o=new r(this,t.row,t.column),u=o.getCurrentToken();u||(u=o.stepForward());if(!u)return;n||(n=new RegExp("(\\.?"+u.type.replace(".","\\.").replace("rparen",".paren")+")+"));var a=t.column-o.getCurrentTokenColumn()-2,f=u.value;for(;;){while(a>=0){var l=f.charAt(a);if(l==i){s-=1;if(s==0)return{row:o.getCurrentTokenRow(),column:a+o.getCurrentTokenColumn()}}else l==e&&(s+=1);a-=1}do u=o.stepBackward();while(u&&!n.test(u.type));if(u==null)break;f=u.value,a=f.length-1}return null},this.$findClosingBracket=function(e,t,n){var i=this.$brackets[e],s=1,o=new r(this,t.row,t.column),u=o.getCurrentToken();u||(u=o.stepForward());if(!u)return;n||(n=new RegExp("(\\.?"+u.type.replace(".","\\.").replace("lparen",".paren")+")+"));var a=t.column-o.getCurrentTokenColumn();for(;;){var f=u.value,l=f.length;while(a<l){var c=f.charAt(a);if(c==i){s-=1;if(s==0)return{row:o.getCurrentTokenRow(),column:a+o.getCurrentTokenColumn()}}else c==e&&(s+=1);a+=1}do u=o.stepForward();while(u&&!n.test(u.type));if(u==null)break;a=0}return null}}var r=e("../token_iterator").TokenIterator,i=e("../range").Range;t.BracketMatch=s}),define("ace/selection",["require","exports","module","ace/lib/oop","ace/lib/lang","ace/lib/event_emitter","ace/range"],function(e,t,n){var r=e("./lib/oop"),i=e("./lib/lang"),s=e("./lib/event_emitter").EventEmitter,o=e("./range").Range,u=function(e){this.session=e,this.doc=e.getDocument(),this.clearSelection(),this.lead=this.selectionLead=this.doc.createAnchor(0,0),this.anchor=this.selectionAnchor=this.doc.createAnchor(0,0);var t=this;this.lead.on("change",function(e){t._emit("changeCursor"),t.$isEmpty||t._emit("changeSelection"),!t.$keepDesiredColumnOnChange&&e.old.column!=e.value.column&&(t.$desiredColumn=null)}),this.selectionAnchor.on("change",function(){t.$isEmpty||t._emit("changeSelection")})};(function(){r.implement(this,s),this.isEmpty=function(){return this.$isEmpty||this.anchor.row==this.lead.row&&this.anchor.column==this.lead.column},this.isMultiLine=function(){return this.isEmpty()?!1:this.getRange().isMultiLine()},this.getCursor=function(){return this.lead.getPosition()},this.setSelectionAnchor=function(e,t){this.anchor.setPosition(e,t),this.$isEmpty&&(this.$isEmpty=!1,this._emit("changeSelection"))},this.getSelectionAnchor=function(){return this.$isEmpty?this.getSelectionLead():this.anchor.getPosition()},this.getSelectionLead=function(){return this.lead.getPosition()},this.shiftSelection=function(e){if(this.$isEmpty){this.moveCursorTo(this.lead.row,this.lead.column+e);return}var t=this.getSelectionAnchor(),n=this.getSelectionLead(),r=this.isBackwards();(!r||t.column!==0)&&this.setSelectionAnchor(t.row,t.column+e),(r||n.column!==0)&&this.$moveSelection(function(){this.moveCursorTo(n.row,n.column+e)})},this.isBackwards=function(){var e=this.anchor,t=this.lead;return e.row>t.row||e.row==t.row&&e.column>t.column},this.getRange=function(){var e=this.anchor,t=this.lead;return this.isEmpty()?o.fromPoints(t,t):this.isBackwards()?o.fromPoints(t,e):o.fromPoints(e,t)},this.clearSelection=function(){this.$isEmpty||(this.$isEmpty=!0,this._emit("changeSelection"))},this.selectAll=function(){var e=this.doc.getLength()-1;this.setSelectionAnchor(0,0),this.moveCursorTo(e,this.doc.getLine(e).length)},this.setRange=this.setSelectionRange=function(e,t){t?(this.setSelectionAnchor(e.end.row,e.end.column),this.selectTo(e.start.row,e.start.column)):(this.setSelectionAnchor(e.start.row,e.start.column),this.selectTo(e.end.row,e.end.column)),this.getRange().isEmpty()&&(this.$isEmpty=!0),this.$desiredColumn=null},this.$moveSelection=function(e){var t=this.lead;this.$isEmpty&&this.setSelectionAnchor(t.row,t.column),e.call(this)},this.selectTo=function(e,t){this.$moveSelection(function(){this.moveCursorTo(e,t)})},this.selectToPosition=function(e){this.$moveSelection(function(){this.moveCursorToPosition(e)})},this.moveTo=function(e,t){this.clearSelection(),this.moveCursorTo(e,t)},this.moveToPosition=function(e){this.clearSelection(),this.moveCursorToPosition(e)},this.selectUp=function(){this.$moveSelection(this.moveCursorUp)},this.selectDown=function(){this.$moveSelection(this.moveCursorDown)},this.selectRight=function(){this.$moveSelection(this.moveCursorRight)},this.selectLeft=function(){this.$moveSelection(this.moveCursorLeft)},this.selectLineStart=function(){this.$moveSelection(this.moveCursorLineStart)},this.selectLineEnd=function(){this.$moveSelection(this.moveCursorLineEnd)},this.selectFileEnd=function(){this.$moveSelection(this.moveCursorFileEnd)},this.selectFileStart=function(){this.$moveSelection(this.moveCursorFileStart)},this.selectWordRight=function(){this.$moveSelection(this.moveCursorWordRight)},this.selectWordLeft=function(){this.$moveSelection(this.moveCursorWordLeft)},this.getWordRange=function(e,t){if(typeof t=="undefined"){var n=e||this.lead;e=n.row,t=n.column}return this.session.getWordRange(e,t)},this.selectWord=function(){this.setSelectionRange(this.getWordRange())},this.selectAWord=function(){var e=this.getCursor(),t=this.session.getAWordRange(e.row,e.column);this.setSelectionRange(t)},this.getLineRange=function(e,t){var n=typeof e=="number"?e:this.lead.row,r,i=this.session.getFoldLine(n);return i?(n=i.start.row,r=i.end.row):r=n,t===!0?new o(n,0,r,this.session.getLine(r).length):new o(n,0,r+1,0)},this.selectLine=function(){this.setSelectionRange(this.getLineRange())},this.moveCursorUp=function(){this.moveCursorBy(-1,0)},this.moveCursorDown=function(){this.moveCursorBy(1,0)},this.moveCursorLeft=function(){var e=this.lead.getPosition(),t;if(t=this.session.getFoldAt(e.row,e.column,-1))this.moveCursorTo(t.start.row,t.start.column);else if(e.column==0)e.row>0&&this.moveCursorTo(e.row-1,this.doc.getLine(e.row-1).length);else{var n=this.session.getTabSize();this.session.isTabStop(e)&&this.doc.getLine(e.row).slice(e.column-n,e.column).split(" ").length-1==n?this.moveCursorBy(0,-n):this.moveCursorBy(0,-1)}},this.moveCursorRight=function(){var e=this.lead.getPosition(),t;if(t=this.session.getFoldAt(e.row,e.column,1))this.moveCursorTo(t.end.row,t.end.column);else if(this.lead.column==this.doc.getLine(this.lead.row).length)this.lead.row<this.doc.getLength()-1&&this.moveCursorTo(this.lead.row+1,0);else{var n=this.session.getTabSize(),e=this.lead;this.session.isTabStop(e)&&this.doc.getLine(e.row).slice(e.column,e.column+n).split(" ").length-1==n?this.moveCursorBy(0,n):this.moveCursorBy(0,1)}},this.moveCursorLineStart=function(){var e=this.lead.row,t=this.lead.column,n=this.session.documentToScreenRow(e,t),r=this.session.screenToDocumentPosition(n,0),i=this.session.getDisplayLine(e,null,r.row,r.column),s=i.match(/^\s*/);s[0].length!=t&&!this.session.$useEmacsStyleLineStart&&(r.column+=s[0].length),this.moveCursorToPosition(r)},this.moveCursorLineEnd=function(){var e=this.lead,t=this.session.getDocumentLastRowColumnPosition(e.row,e.column);if(this.lead.column==t.column){var n=this.session.getLine(t.row);if(t.column==n.length){var r=n.search(/\s+$/);r>0&&(t.column=r)}}this.moveCursorTo(t.row,t.column)},this.moveCursorFileEnd=function(){var e=this.doc.getLength()-1,t=this.doc.getLine(e).length;this.moveCursorTo(e,t)},this.moveCursorFileStart=function(){this.moveCursorTo(0,0)},this.moveCursorLongWordRight=function(){var e=this.lead.row,t=this.lead.column,n=this.doc.getLine(e),r=n.substring(t),i;this.session.nonTokenRe.lastIndex=0,this.session.tokenRe.lastIndex=0;var s=this.session.getFoldAt(e,t,1);if(s){this.moveCursorTo(s.end.row,s.end.column);return}if(i=this.session.nonTokenRe.exec(r))t+=this.session.nonTokenRe.lastIndex,this.session.nonTokenRe.lastIndex=0,r=n.substring(t);if(t>=n.length){this.moveCursorTo(e,n.length),this.moveCursorRight(),e<this.doc.getLength()-1&&this.moveCursorWordRight();return}if(i=this.session.tokenRe.exec(r))t+=this.session.tokenRe.lastIndex,this.session.tokenRe.lastIndex=0;this.moveCursorTo(e,t)},this.moveCursorLongWordLeft=function(){var e=this.lead.row,t=this.lead.column,n;if(n=this.session.getFoldAt(e,t,-1)){this.moveCursorTo(n.start.row,n.start.column);return}var r=this.session.getFoldStringAt(e,t,-1);r==null&&(r=this.doc.getLine(e).substring(0,t));var s=i.stringReverse(r),o;this.session.nonTokenRe.lastIndex=0,this.session.tokenRe.lastIndex=0;if(o=this.session.nonTokenRe.exec(s))t-=this.session.nonTokenRe.lastIndex,s=s.slice(this.session.nonTokenRe.lastIndex),this.session.nonTokenRe.lastIndex=0;if(t<=0){this.moveCursorTo(e,0),this.moveCursorLeft(),e>0&&this.moveCursorWordLeft();return}if(o=this.session.tokenRe.exec(s))t-=this.session.tokenRe.lastIndex,this.session.tokenRe.lastIndex=0;this.moveCursorTo(e,t)},this.$shortWordEndIndex=function(e){var t,n=0,r,i=/\s/,s=this.session.tokenRe;s.lastIndex=0;if(t=this.session.tokenRe.exec(e))n=this.session.tokenRe.lastIndex;else{while((r=e[n])&&i.test(r))n++;if(n<1){s.lastIndex=0;while((r=e[n])&&!s.test(r)){s.lastIndex=0,n++;if(i.test(r)){if(n>2){n--;break}while((r=e[n])&&i.test(r))n++;if(n>2)break}}}}return s.lastIndex=0,n},this.moveCursorShortWordRight=function(){var e=this.lead.row,t=this.lead.column,n=this.doc.getLine(e),r=n.substring(t),i=this.session.getFoldAt(e,t,1);if(i)return this.moveCursorTo(i.end.row,i.end.column);if(t==n.length){var s=this.doc.getLength();do e++,r=this.doc.getLine(e);while(e<s&&/^\s*$/.test(r));/^\s+/.test(r)||(r=""),t=0}var o=this.$shortWordEndIndex(r);this.moveCursorTo(e,t+o)},this.moveCursorShortWordLeft=function(){var e=this.lead.row,t=this.lead.column,n;if(n=this.session.getFoldAt(e,t,-1))return this.moveCursorTo(n.start.row,n.start.column);var r=this.session.getLine(e).substring(0,t);if(t==0){do e--,r=this.doc.getLine(e);while(e>0&&/^\s*$/.test(r));t=r.length,/\s+$/.test(r)||(r="")}var s=i.stringReverse(r),o=this.$shortWordEndIndex(s);return this.moveCursorTo(e,t-o)},this.moveCursorWordRight=function(){this.session.$selectLongWords?this.moveCursorLongWordRight():this.moveCursorShortWordRight()},this.moveCursorWordLeft=function(){this.session.$selectLongWords?this.moveCursorLongWordLeft():this.moveCursorShortWordLeft()},this.moveCursorBy=function(e,t){var n=this.session.documentToScreenPosition(this.lead.row,this.lead.column);t===0&&(this.$desiredColumn?n.column=this.$desiredColumn:this.$desiredColumn=n.column);var r=this.session.screenToDocumentPosition(n.row+e,n.column);e!==0&&t===0&&r.row===this.lead.row&&r.column===this.lead.column&&this.session.lineWidgets&&this.session.lineWidgets[r.row]&&r.row++,this.moveCursorTo(r.row,r.column+t,t===0)},this.moveCursorToPosition=function(e){this.moveCursorTo(e.row,e.column)},this.moveCursorTo=function(e,t,n){var r=this.session.getFoldAt(e,t,1);r&&(e=r.start.row,t=r.start.column),this.$keepDesiredColumnOnChange=!0,this.lead.setPosition(e,t),this.$keepDesiredColumnOnChange=!1,n||(this.$desiredColumn=null)},this.moveCursorToScreen=function(e,t,n){var r=this.session.screenToDocumentPosition(e,t);this.moveCursorTo(r.row,r.column,n)},this.detach=function(){this.lead.detach(),this.anchor.detach(),this.session=this.doc=null},this.fromOrientedRange=function(e){this.setSelectionRange(e,e.cursor==e.start),this.$desiredColumn=e.desiredColumn||this.$desiredColumn},this.toOrientedRange=function(e){var t=this.getRange();return e?(e.start.column=t.start.column,e.start.row=t.start.row,e.end.column=t.end.column,e.end.row=t.end.row):e=t,e.cursor=this.isBackwards()?e.start:e.end,e.desiredColumn=this.$desiredColumn,e},this.toJSON=function(){if(this.rangeCount)var e=this.ranges.map(function(e){var t=e.clone();return t.isBackwards=e.cursor==e.start,t});else{var e=this.getRange();e.isBackwards=this.isBackwards()}return e},this.fromJSON=function(e){if(e.start==undefined){if(this.rangeList){this.toSingleRange(e[0]);for(var t=e.length;t--;){var n=o.fromPoints(e[t].start,e[t].end);e.isBackwards&&(n.cursor=n.start),this.addRange(n,!0)}return}e=e[0]}this.rangeList&&this.toSingleRange(e),this.setSelectionRange(e,e.isBackwards)},this.isEqual=function(e){if((e.length||this.rangeCount)&&e.length!=this.rangeCount)return!1;if(!e.length||!this.ranges)return this.getRange().isEqual(e);for(var t=this.ranges.length;t--;)if(!this.ranges[t].isEqual(e[t]))return!1;return!0}}).call(u.prototype),t.Selection=u}),define("ace/search",["require","exports","module","ace/lib/lang","ace/lib/oop","ace/range"],function(e,t,n){var r=e("./lib/lang"),i=e("./lib/oop"),s=e("./range").Range,o=function(){this.$options={}};(function(){this.set=function(e){return i.mixin(this.$options,e),this},this.getOptions=function(){return r.copyObject(this.$options)},this.setOptions=function(e){this.$options=e},this.find=function(e){var t=this.$matchIterator(e,this.$options);if(!t)return!1;var n=null;return t.forEach(function(e,t,r){if(!e.start){var i=e.offset+(r||0);n=new s(t,i,t,i+e.length)}else n=e;return!0}),n},this.findAll=function(e){var t=this.$options;if(!t.needle)return[];this.$assembleRegExp(t);var n=t.range,i=n?e.getLines(n.start.row,n.end.row):e.doc.getAllLines(),o=[],u=t.re;if(t.$isMultiLine){var a=u.length,f=i.length-a,l;e:for(var c=u.offset||0;c<=f;c++){for(var h=0;h<a;h++)if(i[c+h].search(u[h])==-1)continue e;var p=i[c],d=i[c+a-1],v=p.length-p.match(u[0])[0].length,m=d.match(u[a-1])[0].length;if(l&&l.end.row===c&&l.end.column>v)continue;o.push(l=new s(c,v,c+a-1,m)),a>2&&(c=c+a-2)}}else for(var g=0;g<i.length;g++){var y=r.getMatchOffsets(i[g],u);for(var h=0;h<y.length;h++){var b=y[h];o.push(new s(g,b.offset,g,b.offset+b.length))}}if(n){var w=n.start.column,E=n.start.column,g=0,h=o.length-1;while(g<h&&o[g].start.column<w&&o[g].start.row==n.start.row)g++;while(g<h&&o[h].end.column>E&&o[h].end.row==n.end.row)h--;o=o.slice(g,h+1);for(g=0,h=o.length;g<h;g++)o[g].start.row+=n.start.row,o[g].end.row+=n.start.row}return o},this.replace=function(e,t){var n=this.$options,r=this.$assembleRegExp(n);if(n.$isMultiLine)return t;if(!r)return;var i=r.exec(e);if(!i||i[0].length!=e.length)return null;t=e.replace(r,t);if(n.preserveCase){t=t.split("");for(var s=Math.min(e.length,e.length);s--;){var o=e[s];o&&o.toLowerCase()!=o?t[s]=t[s].toUpperCase():t[s]=t[s].toLowerCase()}t=t.join("")}return t},this.$matchIterator=function(e,t){var n=this.$assembleRegExp(t);if(!n)return!1;var i=this,o,u=t.backwards;if(t.$isMultiLine)var a=n.length,f=function(t,r,i){var u=t.search(n[0]);if(u==-1)return;for(var f=1;f<a;f++){t=e.getLine(r+f);if(t.search(n[f])==-1)return}var l=t.match(n[a-1])[0].length,c=new s(r,u,r+a-1,l);n.offset==1?(c.start.row--,c.start.column=Number.MAX_VALUE):i&&(c.start.column+=i);if(o(c))return!0};else if(u)var f=function(e,t,i){var s=r.getMatchOffsets(e,n);for(var u=s.length-1;u>=0;u--)if(o(s[u],t,i))return!0};else var f=function(e,t,i){var s=r.getMatchOffsets(e,n);for(var u=0;u<s.length;u++)if(o(s[u],t,i))return!0};return{forEach:function(n){o=n,i.$lineIterator(e,t).forEach(f)}}},this.$assembleRegExp=function(e,t){if(e.needle instanceof RegExp)return e.re=e.needle;var n=e.needle;if(!e.needle)return e.re=!1;e.regExp||(n=r.escapeRegExp(n)),e.wholeWord&&(n="\\b"+n+"\\b");var i=e.caseSensitive?"g":"gi";e.$isMultiLine=!t&&/[\n\r]/.test(n);if(e.$isMultiLine)return e.re=this.$assembleMultilineRegExp(n,i);try{var s=new RegExp(n,i)}catch(o){s=!1}return e.re=s},this.$assembleMultilineRegExp=function(e,t){var n=e.replace(/\r\n|\r|\n/g,"$\n^").split("\n"),r=[];for(var i=0;i<n.length;i++)try{r.push(new RegExp(n[i],t))}catch(s){return!1}return n[0]==""?(r.shift(),r.offset=1):r.offset=0,r},this.$lineIterator=function(e,t){var n=t.backwards==1,r=t.skipCurrent!=0,i=t.range,s=t.start;s||(s=i?i[n?"end":"start"]:e.selection.getRange()),s.start&&(s=s[r!=n?"end":"start"]);var o=i?i.start.row:0,u=i?i.end.row:e.getLength()-1,a=n?function(n){var r=s.row,i=e.getLine(r).substring(0,s.column);if(n(i,r))return;for(r--;r>=o;r--)if(n(e.getLine(r),r))return;if(t.wrap==0)return;for(r=u,o=s.row;r>=o;r--)if(n(e.getLine(r),r))return}:function(n){var r=s.row,i=e.getLine(r).substr(s.column);if(n(i,r,s.column))return;for(r+=1;r<=u;r++)if(n(e.getLine(r),r))return;if(t.wrap==0)return;for(r=o,u=s.row;r<=u;r++)if(n(e.getLine(r),r))return};return{forEach:a}}}).call(o.prototype),t.Search=o}),define("ace/edit_session",["require","exports","module","ace/lib/oop","ace/lib/lang","ace/config","ace/lib/event_emitter","ace/selection","ace/mode/text","ace/range","ace/document","ace/background_tokenizer","ace/search_highlight","ace/edit_session/folding","ace/edit_session/bracket_match"],function(e,t,n){var r=e("./lib/oop"),i=e("./lib/lang"),s=e("./config"),o=e("./lib/event_emitter").EventEmitter,u=e("./selection").Selection,a=e("./mode/text").Mode,f=e("./range").Range,l=e("./document").Document,c=e("./background_tokenizer").BackgroundTokenizer,h=e("./search_highlight").SearchHighlight,p=function(e,t){this.$breakpoints=[],this.$decorations=[],this.$frontMarkers={},this.$backMarkers={},this.$markerId=1,this.$undoSelect=!0,this.$foldData=[],this.$foldData.toString=function(){return this.join("\n")},this.on("changeFold",this.onChangeFold.bind(this)),this.$onChange=this.onChange.bind(this);if(typeof e!="object"||!e.getLine)e=new l(e);this.setDocument(e),this.selection=new u(this),s.resetOptions(this),this.setMode(t),s._signal("session",this)};(function(){function g(e){return e<4352?!1:e>=4352&&e<=4447||e>=4515&&e<=4519||e>=4602&&e<=4607||e>=9001&&e<=9002||e>=11904&&e<=11929||e>=11931&&e<=12019||e>=12032&&e<=12245||e>=12272&&e<=12283||e>=12288&&e<=12350||e>=12353&&e<=12438||e>=12441&&e<=12543||e>=12549&&e<=12589||e>=12593&&e<=12686||e>=12688&&e<=12730||e>=12736&&e<=12771||e>=12784&&e<=12830||e>=12832&&e<=12871||e>=12880&&e<=13054||e>=13056&&e<=19903||e>=19968&&e<=42124||e>=42128&&e<=42182||e>=43360&&e<=43388||e>=44032&&e<=55203||e>=55216&&e<=55238||e>=55243&&e<=55291||e>=63744&&e<=64255||e>=65040&&e<=65049||e>=65072&&e<=65106||e>=65108&&e<=65126||e>=65128&&e<=65131||e>=65281&&e<=65376||e>=65504&&e<=65510}r.implement(this,o),this.setDocument=function(e){this.doc&&this.doc.removeListener("change",this.$onChange),this.doc=e,e.on("change",this.$onChange),this.bgTokenizer&&this.bgTokenizer.setDocument(this.getDocument()),this.resetCaches()},this.getDocument=function(){return this.doc},this.$resetRowCache=function(e){if(!e){this.$docRowCache=[],this.$screenRowCache=[];return}var t=this.$docRowCache.length,n=this.$getRowCacheIndex(this.$docRowCache,e)+1;t>n&&(this.$docRowCache.splice(n,t),this.$screenRowCache.splice(n,t))},this.$getRowCacheIndex=function(e,t){var n=0,r=e.length-1;while(n<=r){var i=n+r>>1,s=e[i];if(t>s)n=i+1;else{if(!(t<s))return i;r=i-1}}return n-1},this.resetCaches=function(){this.$modified=!0,this.$wrapData=[],this.$rowLengthCache=[],this.$resetRowCache(0),this.bgTokenizer&&this.bgTokenizer.start(0)},this.onChangeFold=function(e){var t=e.data;this.$resetRowCache(t.start.row)},this.onChange=function(e){var t=e.data;this.$modified=!0,this.$resetRowCache(t.range.start.row);var n=this.$updateInternalDataOnChange(e);!this.$fromUndo&&this.$undoManager&&!t.ignore&&(this.$deltasDoc.push(t),n&&n.length!=0&&this.$deltasFold.push({action:"removeFolds",folds:n}),this.$informUndoManager.schedule()),this.bgTokenizer.$updateOnChange(t),this._signal("change",e)},this.setValue=function(e){this.doc.setValue(e),this.selection.moveTo(0,0),this.$resetRowCache(0),this.$deltas=[],this.$deltasDoc=[],this.$deltasFold=[],this.setUndoManager(this.$undoManager),this.getUndoManager().reset()},this.getValue=this.toString=function(){return this.doc.getValue()},this.getSelection=function(){return this.selection},this.getState=function(e){return this.bgTokenizer.getState(e)},this.getTokens=function(e){return this.bgTokenizer.getTokens(e)},this.getTokenAt=function(e,t){var n=this.bgTokenizer.getTokens(e),r,i=0;if(t==null)s=n.length-1,i=this.getLine(e).length;else for(var s=0;s<n.length;s++){i+=n[s].value.length;if(i>=t)break}return r=n[s],r?(r.index=s,r.start=i-r.value.length,r):null},this.setUndoManager=function(e){this.$undoManager=e,this.$deltas=[],this.$deltasDoc=[],this.$deltasFold=[],this.$informUndoManager&&this.$informUndoManager.cancel();if(e){var t=this;this.$syncInformUndoManager=function(){t.$informUndoManager.cancel(),t.$deltasFold.length&&(t.$deltas.push({group:"fold",deltas:t.$deltasFold}),t.$deltasFold=[]),t.$deltasDoc.length&&(t.$deltas.push({group:"doc",deltas:t.$deltasDoc}),t.$deltasDoc=[]),t.$deltas.length>0&&e.execute({action:"aceupdate",args:[t.$deltas,t],merge:t.mergeUndoDeltas}),t.mergeUndoDeltas=!1,t.$deltas=[]},this.$informUndoManager=i.delayedCall(this.$syncInformUndoManager)}},this.markUndoGroup=function(){this.$syncInformUndoManager&&this.$syncInformUndoManager()},this.$defaultUndoManager={undo:function(){},redo:function(){},reset:function(){}},this.getUndoManager=function(){return this.$undoManager||this.$defaultUndoManager},this.getTabString=function(){return this.getUseSoftTabs()?i.stringRepeat(" ",this.getTabSize()):" "},this.setUseSoftTabs=function(e){this.setOption("useSoftTabs",e)},this.getUseSoftTabs=function(){return this.$useSoftTabs&&!this.$mode.$indentWithTabs},this.setTabSize=function(e){this.setOption("tabSize",e)},this.getTabSize=function(){return this.$tabSize},this.isTabStop=function(e){return this.$useSoftTabs&&e.column%this.$tabSize===0},this.$overwrite=!1,this.setOverwrite=function(e){this.setOption("overwrite",e)},this.getOverwrite=function(){return this.$overwrite},this.toggleOverwrite=function(){this.setOverwrite(!this.$overwrite)},this.addGutterDecoration=function(e,t){this.$decorations[e]||(this.$decorations[e]=""),this.$decorations[e]+=" "+t,this._signal("changeBreakpoint",{})},this.removeGutterDecoration=function(e,t){this.$decorations[e]=(this.$decorations[e]||"").replace(" "+t,""),this._signal("changeBreakpoint",{})},this.getBreakpoints=function(){return this.$breakpoints},this.setBreakpoints=function(e){this.$breakpoints=[];for(var t=0;t<e.length;t++)this.$breakpoints[e[t]]="ace_breakpoint";this._signal("changeBreakpoint",{})},this.clearBreakpoints=function(){this.$breakpoints=[],this._signal("changeBreakpoint",{})},this.setBreakpoint=function(e,t){t===undefined&&(t="ace_breakpoint"),t?this.$breakpoints[e]=t:delete this.$breakpoints[e],this._signal("changeBreakpoint",{})},this.clearBreakpoint=function(e){delete this.$breakpoints[e],this._signal("changeBreakpoint",{})},this.addMarker=function(e,t,n,r){var i=this.$markerId++,s={range:e,type:n||"line",renderer:typeof n=="function"?n:null,clazz:t,inFront:!!r,id:i};return r?(this.$frontMarkers[i]=s,this._signal("changeFrontMarker")):(this.$backMarkers[i]=s,this._signal("changeBackMarker")),i},this.addDynamicMarker=function(e,t){if(!e.update)return;var n=this.$markerId++;return e.id=n,e.inFront=!!t,t?(this.$frontMarkers[n]=e,this._signal("changeFrontMarker")):(this.$backMarkers[n]=e,this._signal("changeBackMarker")),e},this.removeMarker=function(e){var t=this.$frontMarkers[e]||this.$backMarkers[e];if(!t)return;var n=t.inFront?this.$frontMarkers:this.$backMarkers;t&&(delete n[e],this._signal(t.inFront?"changeFrontMarker":"changeBackMarker"))},this.getMarkers=function(e){return e?this.$frontMarkers:this.$backMarkers},this.highlight=function(e){if(!this.$searchHighlight){var t=new h(null,"ace_selected-word","text");this.$searchHighlight=this.addDynamicMarker(t)}this.$searchHighlight.setRegexp(e)},this.highlightLines=function(e,t,n,r){typeof t!="number"&&(n=t,t=e),n||(n="ace_step");var i=new f(e,0,t,Infinity);return i.id=this.addMarker(i,n,"fullLine",r),i},this.setAnnotations=function(e){this.$annotations=e,this._signal("changeAnnotation",{})},this.getAnnotations=function(){return this.$annotations||[]},this.clearAnnotations=function(){this.setAnnotations([])},this.$detectNewLine=function(e){var t=e.match(/^.*?(\r?\n)/m);t?this.$autoNewLine=t[1]:this.$autoNewLine="\n"},this.getWordRange=function(e,t){var n=this.getLine(e),r=!1;t>0&&(r=!!n.charAt(t-1).match(this.tokenRe)),r||(r=!!n.charAt(t).match(this.tokenRe));if(r)var i=this.tokenRe;else if(/^\s+$/.test(n.slice(t-1,t+1)))var i=/\s/;else var i=this.nonTokenRe;var s=t;if(s>0){do s--;while(s>=0&&n.charAt(s).match(i));s++}var o=t;while(o<n.length&&n.charAt(o).match(i))o++;return new f(e,s,e,o)},this.getAWordRange=function(e,t){var n=this.getWordRange(e,t),r=this.getLine(n.end.row);while(r.charAt(n.end.column).match(/[ \t]/))n.end.column+=1;return n},this.setNewLineMode=function(e){this.doc.setNewLineMode(e)},this.getNewLineMode=function(){return this.doc.getNewLineMode()},this.setUseWorker=function(e){this.setOption("useWorker",e)},this.getUseWorker=function(){return this.$useWorker},this.onReloadTokenizer=function(e){var t=e.data;this.bgTokenizer.start(t.first),this._signal("tokenizerUpdate",e)},this.$modes={},this.$mode=null,this.$modeId=null,this.setMode=function(e,t){if(e&&typeof e=="object"){if(e.getTokenizer)return this.$onChangeMode(e);var n=e,r=n.path}else r=e||"ace/mode/text";this.$modes["ace/mode/text"]||(this.$modes["ace/mode/text"]=new a);if(this.$modes[r]&&!n){this.$onChangeMode(this.$modes[r]),t&&t();return}this.$modeId=r,s.loadModule(["mode",r],function(e){if(this.$modeId!==r)return t&&t();if(this.$modes[r]&&!n)return this.$onChangeMode(this.$modes[r]);e&&e.Mode&&(e=new e.Mode(n),n||(this.$modes[r]=e,e.$id=r),this.$onChangeMode(e),t&&t())}.bind(this)),this.$mode||this.$onChangeMode(this.$modes["ace/mode/text"],!0)},this.$onChangeMode=function(e,t){t||(this.$modeId=e.$id);if(this.$mode===e)return;this.$mode=e,this.$stopWorker(),this.$useWorker&&this.$startWorker();var n=e.getTokenizer();if(n.addEventListener!==undefined){var r=this.onReloadTokenizer.bind(this);n.addEventListener("update",r)}if(!this.bgTokenizer){this.bgTokenizer=new c(n);var i=this;this.bgTokenizer.addEventListener("update",function(e){i._signal("tokenizerUpdate",e)})}else this.bgTokenizer.setTokenizer(n);this.bgTokenizer.setDocument(this.getDocument()),this.tokenRe=e.tokenRe,this.nonTokenRe=e.nonTokenRe,t||(this.$options.wrapMethod.set.call(this,this.$wrapMethod),this.$setFolding(e.foldingRules),this.bgTokenizer.start(0),this._emit("changeMode"))},this.$stopWorker=function(){this.$worker&&this.$worker.terminate(),this.$worker=null},this.$startWorker=function(){if(typeof Worker!="undefined"&&!e.noWorker)try{this.$worker=this.$mode.createWorker(this)}catch(t){console.log("Could not load worker"),console.log(t),this.$worker=null}else this.$worker=null},this.getMode=function(){return this.$mode},this.$scrollTop=0,this.setScrollTop=function(e){if(this.$scrollTop===e||isNaN(e))return;this.$scrollTop=e,this._signal("changeScrollTop",e)},this.getScrollTop=function(){return this.$scrollTop},this.$scrollLeft=0,this.setScrollLeft=function(e){if(this.$scrollLeft===e||isNaN(e))return;this.$scrollLeft=e,this._signal("changeScrollLeft",e)},this.getScrollLeft=function(){return this.$scrollLeft},this.getScreenWidth=function(){return this.$computeWidth(),this.lineWidgets?Math.max(this.getLineWidgetMaxWidth(),this.screenWidth):this.screenWidth},this.getLineWidgetMaxWidth=function(){if(this.lineWidgetsWidth!=null)return this.lineWidgetsWidth;var e=0;return this.lineWidgets.forEach(function(t){t&&t.screenWidth>e&&(e=t.screenWidth)}),this.lineWidgetWidth=e},this.$computeWidth=function(e){if(this.$modified||e){this.$modified=!1;if(this.$useWrapMode)return this.screenWidth=this.$wrapLimit;var t=this.doc.getAllLines(),n=this.$rowLengthCache,r=0,i=0,s=this.$foldData[i],o=s?s.start.row:Infinity,u=t.length;for(var a=0;a<u;a++){if(a>o){a=s.end.row+1;if(a>=u)break;s=this.$foldData[i++],o=s?s.start.row:Infinity}n[a]==null&&(n[a]=this.$getStringScreenWidth(t[a])[0]),n[a]>r&&(r=n[a])}this.screenWidth=r}},this.getLine=function(e){return this.doc.getLine(e)},this.getLines=function(e,t){return this.doc.getLines(e,t)},this.getLength=function(){return this.doc.getLength()},this.getTextRange=function(e){return this.doc.getTextRange(e||this.selection.getRange())},this.insert=function(e,t){return this.doc.insert(e,t)},this.remove=function(e){return this.doc.remove(e)},this.undoChanges=function(e,t){if(!e.length)return;this.$fromUndo=!0;var n=null;for(var r=e.length-1;r!=-1;r--){var i=e[r];i.group=="doc"?(this.doc.revertDeltas(i.deltas),n=this.$getUndoSelection(i.deltas,!0,n)):i.deltas.forEach(function(e){this.addFolds(e.folds)},this)}return this.$fromUndo=!1,n&&this.$undoSelect&&!t&&this.selection.setSelectionRange(n),n},this.redoChanges=function(e,t){if(!e.length)return;this.$fromUndo=!0;var n=null;for(var r=0;r<e.length;r++){var i=e[r];i.group=="doc"&&(this.doc.applyDeltas(i.deltas),n=this.$getUndoSelection(i.deltas,!1,n))}return this.$fromUndo=!1,n&&this.$undoSelect&&!t&&this.selection.setSelectionRange(n),n},this.setUndoSelect=function(e){this.$undoSelect=e},this.$getUndoSelection=function(e,t,n){function r(e){var n=e.action==="insertText"||e.action==="insertLines";return t?!n:n}var i=e[0],s,o,u=!1;r(i)?(s=f.fromPoints(i.range.start,i.range.end),u=!0):(s=f.fromPoints(i.range.start,i.range.start),u=!1);for(var a=1;a<e.length;a++)i=e[a],r(i)?(o=i.range.start,s.compare(o.row,o.column)==-1&&s.setStart(i.range.start),o=i.range.end,s.compare(o.row,o.column)==1&&s.setEnd(i.range.end),u=!0):(o=i.range.start,s.compare(o.row,o.column)==-1&&(s=f.fromPoints(i.range.start,i.range.start)),u=!1);if(n!=null){f.comparePoints(n.start,s.start)===0&&(n.start.column+=s.end.column-s.start.column,n.end.column+=s.end.column-s.start.column);var l=n.compareRange(s);l==1?s.setStart(n.start):l==-1&&s.setEnd(n.end)}return s},this.replace=function(e,t){return this.doc.replace(e,t)},this.moveText=function(e,t,n){var r=this.getTextRange(e),i=this.getFoldsInRange(e),s=f.fromPoints(t,t);if(!n){this.remove(e);var o=e.start.row-e.end.row,u=o?-e.end.column:e.start.column-e.end.column;u&&(s.start.row==e.end.row&&s.start.column>e.end.column&&(s.start.column+=u),s.end.row==e.end.row&&s.end.column>e.end.column&&(s.end.column+=u)),o&&s.start.row>=e.end.row&&(s.start.row+=o,s.end.row+=o)}s.end=this.insert(s.start,r);if(i.length){var a=e.start,l=s.start,o=l.row-a.row,u=l.column-a.column;this.addFolds(i.map(function(e){return e=e.clone(),e.start.row==a.row&&(e.start.column+=u),e.end.row==a.row&&(e.end.column+=u),e.start.row+=o,e.end.row+=o,e}))}return s},this.indentRows=function(e,t,n){n=n.replace(/\t/g,this.getTabString());for(var r=e;r<=t;r++)this.insert({row:r,column:0},n)},this.outdentRows=function(e){var t=e.collapseRows(),n=new f(0,0,0,0),r=this.getTabSize();for(var i=t.start.row;i<=t.end.row;++i){var s=this.getLine(i);n.start.row=i,n.end.row=i;for(var o=0;o<r;++o)if(s.charAt(o)!=" ")break;o<r&&s.charAt(o)==" "?(n.start.column=o,n.end.column=o+1):(n.start.column=0,n.end.column=o),this.remove(n)}},this.$moveLines=function(e,t,n){e=this.getRowFoldStart(e),t=this.getRowFoldEnd(t);if(n<0){var r=this.getRowFoldStart(e+n);if(r<0)return 0;var i=r-e}else if(n>0){var r=this.getRowFoldEnd(t+n);if(r>this.doc.getLength()-1)return 0;var i=r-t}else{e=this.$clipRowToDocument(e),t=this.$clipRowToDocument(t);var i=t-e+1}var s=new f(e,0,t,Number.MAX_VALUE),o=this.getFoldsInRange(s).map(function(e){return e=e.clone(),e.start.row+=i,e.end.row+=i,e}),u=n==0?this.doc.getLines(e,t):this.doc.removeLines(e,t);return this.doc.insertLines(e+i,u),o.length&&this.addFolds(o),i},this.moveLinesUp=function(e,t){return this.$moveLines(e,t,-1)},this.moveLinesDown=function(e,t){return this.$moveLines(e,t,1)},this.duplicateLines=function(e,t){return this.$moveLines(e,t,0)},this.$clipRowToDocument=function(e){return Math.max(0,Math.min(e,this.doc.getLength()-1))},this.$clipColumnToRow=function(e,t){return t<0?0:Math.min(this.doc.getLine(e).length,t)},this.$clipPositionToDocument=function(e,t){t=Math.max(0,t);if(e<0)e=0,t=0;else{var n=this.doc.getLength();e>=n?(e=n-1,t=this.doc.getLine(n-1).length):t=Math.min(this.doc.getLine(e).length,t)}return{row:e,column:t}},this.$clipRangeToDocument=function(e){e.start.row<0?(e.start.row=0,e.start.column=0):e.start.column=this.$clipColumnToRow(e.start.row,e.start.column);var t=this.doc.getLength()-1;return e.end.row>t?(e.end.row=t,e.end.column=this.doc.getLine(t).length):e.end.column=this.$clipColumnToRow(e.end.row,e.end.column),e},this.$wrapLimit=80,this.$useWrapMode=!1,this.$wrapLimitRange={min:null,max:null},this.setUseWrapMode=function(e){if(e!=this.$useWrapMode){this.$useWrapMode=e,this.$modified=!0,this.$resetRowCache(0);if(e){var t=this.getLength();this.$wrapData=Array(t),this.$updateWrapData(0,t-1)}this._signal("changeWrapMode")}},this.getUseWrapMode=function(){return this.$useWrapMode},this.setWrapLimitRange=function(e,t){if(this.$wrapLimitRange.min!==e||this.$wrapLimitRange.max!==t)this.$wrapLimitRange={min:e,max:t},this.$modified=!0,this._signal("changeWrapMode")},this.adjustWrapLimit=function(e,t){var n=this.$wrapLimitRange;n.max<0&&(n={min:t,max:t});var r=this.$constrainWrapLimit(e,n.min,n.max);return r!=this.$wrapLimit&&r>1?(this.$wrapLimit=r,this.$modified=!0,this.$useWrapMode&&(this.$updateWrapData(0,this.getLength()-1),this.$resetRowCache(0),this._signal("changeWrapLimit")),!0):!1},this.$constrainWrapLimit=function(e,t,n){return t&&(e=Math.max(t,e)),n&&(e=Math.min(n,e)),e},this.getWrapLimit=function(){return this.$wrapLimit},this.setWrapLimit=function(e){this.setWrapLimitRange(e,e)},this.getWrapLimitRange=function(){return{min:this.$wrapLimitRange.min,max:this.$wrapLimitRange.max}},this.$updateInternalDataOnChange=function(e){var t=this.$useWrapMode,n,r=e.data.action,i=e.data.range.start.row,s=e.data.range.end.row,o=e.data.range.start,u=e.data.range.end,a=null;r.indexOf("Lines")!=-1?(r=="insertLines"?s=i+e.data.lines.length:s=i,n=e.data.lines?e.data.lines.length:s-i):n=s-i,this.$updating=!0;if(n!=0)if(r.indexOf("remove")!=-1){this[t?"$wrapData":"$rowLengthCache"].splice(i,n);var f=this.$foldData;a=this.getFoldsInRange(e.data.range),this.removeFolds(a);var l=this.getFoldLine(u.row),c=0;if(l){l.addRemoveChars(u.row,u.column,o.column-u.column),l.shiftRow(-n);var h=this.getFoldLine(i);h&&h!==l&&(h.merge(l),l=h),c=f.indexOf(l)+1}for(c;c<f.length;c++){var l=f[c];l.start.row>=u.row&&l.shiftRow(-n)}s=i}else{var p=Array(n);p.unshift(i,0);var d=t?this.$wrapData:this.$rowLengthCache;d.splice.apply(d,p);var f=this.$foldData,l=this.getFoldLine(i),c=0;if(l){var v=l.range.compareInside(o.row,o.column);v==0?(l=l.split(o.row,o.column),l.shiftRow(n),l.addRemoveChars(s,0,u.column-o.column)):v==-1&&(l.addRemoveChars(i,0,u.column-o.column),l.shiftRow(n)),c=f.indexOf(l)+1}for(c;c<f.length;c++){var l=f[c];l.start.row>=i&&l.shiftRow(n)}}else{n=Math.abs(e.data.range.start.column-e.data.range.end.column),r.indexOf("remove")!=-1&&(a=this.getFoldsInRange(e.data.range),this.removeFolds(a),n=-n);var l=this.getFoldLine(i);l&&l.addRemoveChars(i,o.column,n)}return t&&this.$wrapData.length!=this.doc.getLength()&&console.error("doc.getLength() and $wrapData.length have to be the same!"),this.$updating=!1,t?this.$updateWrapData(i,s):this.$updateRowLengthCache(i,s),a},this.$updateRowLengthCache=function(e,t,n){this.$rowLengthCache[e]=null,this.$rowLengthCache[t]=null},this.$updateWrapData=function(e,t){var n=this.doc.getAllLines(),r=this.getTabSize(),i=this.$wrapData,s=this.$wrapLimit,o,a,f=e;t=Math.min(t,n.length-1);while(f<=t)a=this.getFoldLine(f,a),a?(o=[],a.walk(function(e,t,r,i){var s;if(e!=null){s=this.$getDisplayTokens(e,o.length),s[0]=u;for(var a=1;a<s.length;a++)s[a]=l}else s=this.$getDisplayTokens(n[t].substring(i,r),o.length);o=o.concat(s)}.bind(this),a.end.row,n[a.end.row].length+1),i[a.start.row]=this.$computeWrapSplits(o,s,r),f=a.end.row+1):(o=this.$getDisplayTokens(n[f]),i[f]=this.$computeWrapSplits(o,s,r),f++)};var t=1,n=2,u=3,l=4,p=9,d=10,v=11,m=12;this.$computeWrapSplits=function(e,t){function a(t){var r=e.slice(i,t),o=r.length;r.join("").replace(/12/g,function(){o-=1}).replace(/2/g,function(){o-=1}),s+=o,n.push(s),i=t}if(e.length==0)return[];var n=[],r=e.length,i=0,s=0,o=this.$wrapAsCode;while(r-i>t){var f=i+t;if(e[f-1]>=d&&e[f]>=d){a(f);continue}if(e[f]==u||e[f]==l){for(f;f!=i-1;f--)if(e[f]==u)break;if(f>i){a(f);continue}f=i+t;for(f;f<e.length;f++)if(e[f]!=l)break;if(f==e.length)break;a(f);continue}var c=Math.max(f-(o?10:t-(t>>2)),i-1);while(f>c&&e[f]<u)f--;if(o){while(f>c&&e[f]<u)f--;while(f>c&&e[f]==p)f--}else while(f>c&&e[f]<d)f--;if(f>c){a(++f);continue}f=i+t,a(f)}return n},this.$getDisplayTokens=function(e,r){var i=[],s;r=r||0;for(var o=0;o<e.length;o++){var u=e.charCodeAt(o);if(u==9){s=this.getScreenTabSize(i.length+r),i.push(v);for(var a=1;a<s;a++)i.push(m)}else u==32?i.push(d):u>39&&u<48||u>57&&u<64?i.push(p):u>=4352&&g(u)?i.push(t,n):i.push(t)}return i},this.$getStringScreenWidth=function(e,t,n){if(t==0)return[0,0];t==null&&(t=Infinity),n=n||0;var r,i;for(i=0;i<e.length;i++){r=e.charCodeAt(i),r==9?n+=this.getScreenTabSize(n):r>=4352&&g(r)?n+=2:n+=1;if(n>t)break}return[n,i]},this.lineWidgets=null,this.getRowLength=function(e){if(this.lineWidgets)var t=this.lineWidgets[e]&&this.lineWidgets[e].rowCount||0;else t=0;return!this.$useWrapMode||!this.$wrapData[e]?1+t:this.$wrapData[e].length+1+t},this.getRowLineCount=function(e){return!this.$useWrapMode||!this.$wrapData[e]?1:this.$wrapData[e].length+1},this.getScreenLastRowColumn=function(e){var t=this.screenToDocumentPosition(e,Number.MAX_VALUE);return this.documentToScreenColumn(t.row,t.column)},this.getDocumentLastRowColumn=function(e,t){var n=this.documentToScreenRow(e,t);return this.getScreenLastRowColumn(n)},this.getDocumentLastRowColumnPosition=function(e,t){var n=this.documentToScreenRow(e,t);return this.screenToDocumentPosition(n,Number.MAX_VALUE/10)},this.getRowSplitData=function(e){return this.$useWrapMode?this.$wrapData[e]:undefined},this.getScreenTabSize=function(e){return this.$tabSize-e%this.$tabSize},this.screenToDocumentRow=function(e,t){return this.screenToDocumentPosition(e,t).row},this.screenToDocumentColumn=function(e,t){return this.screenToDocumentPosition(e,t).column},this.screenToDocumentPosition=function(e,t){if(e<0)return{row:0,column:0};var n,r=0,i=0,s,o=0,u=0,a=this.$screenRowCache,f=this.$getRowCacheIndex(a,e),l=a.length;if(l&&f>=0)var o=a[f],r=this.$docRowCache[f],c=e>a[l-1];else var c=!l;var h=this.getLength()-1,p=this.getNextFoldLine(r),d=p?p.start.row:Infinity;while(o<=e){u=this.getRowLength(r);if(o+u>e||r>=h)break;o+=u,r++,r>d&&(r=p.end.row+1,p=this.getNextFoldLine(r,p),d=p?p.start.row:Infinity),c&&(this.$docRowCache.push(r),this.$screenRowCache.push(o))}if(p&&p.start.row<=r)n=this.getFoldDisplayLine(p),r=p.start.row;else{if(o+u<=e||r>h)return{row:h,column:this.getLine(h).length};n=this.getLine(r),p=null}if(this.$useWrapMode){var v=this.$wrapData[r];if(v){var m=Math.floor(e-o);s=v[m],m>0&&v.length&&(i=v[m-1]||v[v.length-1],n=n.substring(i))}}return i+=this.$getStringScreenWidth(n,t)[1],this.$useWrapMode&&i>=s&&(i=s-1),p?p.idxToPosition(i):{row:r,column:i}},this.documentToScreenPosition=function(e,t){if(typeof t=="undefined")var n=this.$clipPositionToDocument(e.row,e.column);else n=this.$clipPositionToDocument(e,t);e=n.row,t=n.column;var r=0,i=null,s=null;s=this.getFoldAt(e,t,1),s&&(e=s.start.row,t=s.start.column);var o,u=0,a=this.$docRowCache,f=this.$getRowCacheIndex(a,e),l=a.length;if(l&&f>=0)var u=a[f],r=this.$screenRowCache[f],c=e>a[l-1];else var c=!l;var h=this.getNextFoldLine(u),p=h?h.start.row:Infinity;while(u<e){if(u>=p){o=h.end.row+1;if(o>e)break;h=this.getNextFoldLine(o,h),p=h?h.start.row:Infinity}else o=u+1;r+=this.getRowLength(u),u=o,c&&(this.$docRowCache.push(u),this.$screenRowCache.push(r))}var d="";h&&u>=p?(d=this.getFoldDisplayLine(h,e,t),i=h.start.row):(d=this.getLine(e).substring(0,t),i=e);if(this.$useWrapMode){var v=this.$wrapData[i];if(v){var m=0;while(d.length>=v[m])r++,m++;d=d.substring(v[m-1]||0,d.length)}}return{row:r,column:this.$getStringScreenWidth(d)[0]}},this.documentToScreenColumn=function(e,t){return this.documentToScreenPosition(e,t).column},this.documentToScreenRow=function(e,t){return this.documentToScreenPosition(e,t).row},this.getScreenLength=function(){var e=0,t=null;if(!this.$useWrapMode){e=this.getLength();var n=this.$foldData;for(var r=0;r<n.length;r++)t=n[r],e-=t.end.row-t.start.row}else{var i=this.$wrapData.length,s=0,r=0,t=this.$foldData[r++],o=t?t.start.row:Infinity;while(s<i){var u=this.$wrapData[s];e+=u?u.length+1:1,s++,s>o&&(s=t.end.row+1,t=this.$foldData[r++],o=t?t.start.row:Infinity)}}return this.lineWidgets&&(e+=this.$getWidgetScreenLength()),e},this.$setFontMetrics=function(e){}}).call(p.prototype),e("./edit_session/folding").Folding.call(p.prototype),e("./edit_session/bracket_match").BracketMatch.call(p.prototype),s.defineOptions(p.prototype,"session",{wrap:{set:function(e){!e||e=="off"?e=!1:e=="free"?e=!0:e=="printMargin"?e=-1:typeof e=="string"&&(e=parseInt(e,10)||!1);if(this.$wrap==e)return;if(!e)this.setUseWrapMode(!1);else{var t=typeof e=="number"?e:null;this.setWrapLimitRange(t,t),this.setUseWrapMode(!0)}this.$wrap=e},get:function(){return this.getUseWrapMode()?this.$wrap==-1?"printMargin":this.getWrapLimitRange().min?this.$wrap:"free":"off"},handlesSet:!0},wrapMethod:{set:function(e){e=e=="auto"?this.$mode.type!="text":e!="text",e!=this.$wrapAsCode&&(this.$wrapAsCode=e,this.$useWrapMode&&(this.$modified=!0,this.$resetRowCache(0),this.$updateWrapData(0,this.getLength()-1)))},initialValue:"auto"},firstLineNumber:{set:function(){this._signal("changeBreakpoint")},initialValue:1},useWorker:{set:function(e){this.$useWorker=e,this.$stopWorker(),e&&this.$startWorker()},initialValue:!0},useSoftTabs:{initialValue:!0},tabSize:{set:function(e){if(isNaN(e)||this.$tabSize===e)return;this.$modified=!0,this.$rowLengthCache=[],this.$tabSize=e,this._signal("changeTabSize")},initialValue:4,handlesSet:!0},overwrite:{set:function(e){this._signal("changeOverwrite")},initialValue:!1},newLineMode:{set:function(e){this.doc.setNewLineMode(e)},get:function(){return this.doc.getNewLineMode()},handlesSet:!0},mode:{set:function(e){this.setMode(e)},get:function(){return this.$modeId}}}),t.EditSession=p}),define("ace/commands/command_manager",["require","exports","module","ace/lib/oop","ace/keyboard/hash_handler","ace/lib/event_emitter"],function(e,t,n){var r=e("../lib/oop"),i=e("../keyboard/hash_handler").HashHandler,s=e("../lib/event_emitter").EventEmitter,o=function(e,t){i.call(this,t,e),this.byName=this.commands,this.setDefaultHandler("exec",function(e){return e.command.exec(e.editor,e.args||{})})};r.inherits(o,i),function(){r.implement(this,s),this.exec=function(e,t,n){typeof e=="string"&&(e=this.commands[e]);if(!e)return!1;if(t&&t.$readOnly&&!e.readOnly)return!1;var r={editor:t,command:e,args:n},i=this._emit("exec",r);return this._signal("afterExec",r),i===!1?!1:!0},this.toggleRecording=function(e){if(this.$inReplay)return;return e&&e._emit("changeStatus"),this.recording?(this.macro.pop(),this.removeEventListener("exec",this.$addCommandToMacro),this.macro.length||(this.macro=this.oldMacro),this.recording=!1):(this.$addCommandToMacro||(this.$addCommandToMacro=function(e){this.macro.push([e.command,e.args])}.bind(this)),this.oldMacro=this.macro,this.macro=[],this.on("exec",this.$addCommandToMacro),this.recording=!0)},this.replay=function(e){if(this.$inReplay||!this.macro)return;if(this.recording)return this.toggleRecording(e);try{this.$inReplay=!0,this.macro.forEach(function(t){typeof t=="string"?this.exec(t,e):this.exec(t[0],e,t[1])},this)}finally{this.$inReplay=!1}},this.trimMacro=function(e){return e.map(function(e){return typeof e[0]!="string"&&(e[0]=e[0].name),e[1]||(e=e[0]),e})}}.call(o.prototype),t.CommandManager=o}),define("ace/keyboard/keybinding",["require","exports","module","ace/lib/keys","ace/lib/event"],function(e,t,n){var r=e("../lib/keys"),i=e("../lib/event"),s=function(e){this.$editor=e,this.$data={},this.$handlers=[],this.setDefaultHandler(e.commands)};(function(){this.setDefaultHandler=function(e){this.removeKeyboardHandler(this.$defaultHandler),this.$defaultHandler=e,this.addKeyboardHandler(e,0),this.$data={editor:this.$editor}},this.setKeyboardHandler=function(e){var t=this.$handlers;if(t[t.length-1]==e)return;while(t[t.length-1]&&t[t.length-1]!=this.$defaultHandler)this.removeKeyboardHandler(t[t.length-1]);this.addKeyboardHandler(e,1)},this.addKeyboardHandler=function(e,t){if(!e)return;typeof e=="function"&&!e.handleKeyboard&&(e.handleKeyboard=e);var n=this.$handlers.indexOf(e);n!=-1&&this.$handlers.splice(n,1),t==undefined?this.$handlers.push(e):this.$handlers.splice(t,0,e),n==-1&&e.attach&&e.attach(this.$editor)},this.removeKeyboardHandler=function(e){var t=this.$handlers.indexOf(e);return t==-1?!1:(this.$handlers.splice(t,1),e.detach&&e.detach(this.$editor),!0)},this.getKeyboardHandler=function(){return this.$handlers[this.$handlers.length-1]},this.$callKeyboardHandlers=function(e,t,n,r){var s,o=!1,u=this.$editor.commands;for(var a=this.$handlers.length;a--;){s=this.$handlers[a].handleKeyboard(this.$data,e,t,n,r);if(!s||!s.command)continue;s.command=="null"?o=!0:o=u.exec(s.command,this.$editor,s.args,r),o&&r&&e!=-1&&s.passEvent!=1&&s.command.passEvent!=1&&i.stopEvent(r);if(o)break}return o},this.onCommandKey=function(e,t,n){var i=r.keyCodeToString(n);this.$callKeyboardHandlers(t,i,n,e)},this.onTextInput=function(e){var t=this.$callKeyboardHandlers(-1,e);t||this.$editor.commands.exec("insertstring",this.$editor,e)}}).call(s.prototype),t.KeyBinding=s}),define("ace/keyboard/hash_handler",["require","exports","module","ace/lib/keys","ace/lib/useragent"],function(e,t,n){function s(e,t){this.platform=t||(i.isMac?"mac":"win"),this.commands={},this.commandKeyBinding={};if(this.__defineGetter__&&this.__defineSetter__&&typeof console!="undefined"&&console.error){var n=!1,r=function(){n||(n=!0,console.error("commmandKeyBinding has too many m's. use commandKeyBinding"))};this.__defineGetter__("commmandKeyBinding",function(){return r(),this.commandKeyBinding}),this.__defineSetter__("commmandKeyBinding",function(e){return r(),this.commandKeyBinding=e})}else this.commmandKeyBinding=this.commandKeyBinding;this.addCommands(e)}var r=e("../lib/keys"),i=e("../lib/useragent");(function(){this.addCommand=function(e){this.commands[e.name]&&this.removeCommand(e),this.commands[e.name]=e,e.bindKey&&this._buildKeyHash(e)},this.removeCommand=function(e){var t=typeof e=="string"?e:e.name;e=this.commands[t],delete this.commands[t];var n=this.commandKeyBinding;for(var r in n)for(var i in n[r])n[r][i]==e&&delete n[r][i]},this.bindKey=function(e,t){if(!e)return;if(typeof t=="function"){this.addCommand({exec:t,bindKey:e,name:t.name||e});return}var n=this.commandKeyBinding;e.split("|").forEach(function(e){var r=this.parseKeys(e,t),i=r.hashId;(n[i]||(n[i]={}))[r.key]=t},this)},this.addCommands=function(e){e&&Object.keys(e).forEach(function(t){var n=e[t];if(!n)return;if(typeof n=="string")return this.bindKey(n,t);typeof n=="function"&&(n={exec:n});if(typeof n!="object")return;n.name||(n.name=t),this.addCommand(n)},this)},this.removeCommands=function(e){Object.keys(e).forEach(function(t){this.removeCommand(e[t])},this)},this.bindKeys=function(e){Object.keys(e).forEach(function(t){this.bindKey(t,e[t])},this)},this._buildKeyHash=function(e){var t=e.bindKey;if(!t)return;var n=typeof t=="string"?t:t[this.platform];this.bindKey(n,e)},this.parseKeys=function(e){e.indexOf(" ")!=-1&&(e=e.split(/\s+/).pop());var t=e.toLowerCase().split(/[\-\+]([\-\+])?/).filter(function(e){return e}),n=t.pop(),i=r[n];if(r.FUNCTION_KEYS[i])n=r.FUNCTION_KEYS[i].toLowerCase();else{if(!t.length)return{key:n,hashId:-1};if(t.length==1&&t[0]=="shift")return{key:n.toUpperCase(),hashId:-1}}var s=0;for(var o=t.length;o--;){var u=r.KEY_MODS[t[o]];if(u==null)return typeof console!="undefined"&&console.error("invalid modifier "+t[o]+" in "+e),!1;s|=u}return{key:n,hashId:s}},this.findKeyCommand=function(t,n){var r=this.commandKeyBinding;return r[t]&&r[t][n]},this.handleKeyboard=function(e,t,n,r){return{command:this.findKeyCommand(t,n)}}}).call(s.prototype),t.HashHandler=s}),define("ace/mouse/fold_handler",["require","exports","module"],function(e,t,n){function r(e){e.on("click",function(t){var n=t.getDocumentPosition(),r=e.session,i=r.getFoldAt(n.row,n.column,1);i&&(t.getAccelKey()?r.removeFold(i):r.expandFold(i),t.stop())}),e.on("gutterclick",function(t){var n=e.renderer.$gutterLayer.getRegion(t);if(n=="foldWidgets"){var r=t.getDocumentPosition().row,i=e.session;i.foldWidgets&&i.foldWidgets[r]&&e.session.onFoldWidgetClick(r,t),e.isFocused()||e.focus(),t.stop()}}),e.on("gutterdblclick",function(t){var n=e.renderer.$gutterLayer.getRegion(t);if(n=="foldWidgets"){var r=t.getDocumentPosition().row,i=e.session,s=i.getParentFoldRangeData(r,!0),o=s.range||s.firstRange;if(o){r=o.start.row;var u=i.getFoldAt(r,i.getLine(r).length,1);u?i.removeFold(u):(i.addFold("...",o),e.renderer.scrollCursorIntoView({row:o.start.row,column:0}))}t.stop()}})}t.FoldHandler=r}),define("ace/commands/default_commands",["require","exports","module","ace/lib/lang","ace/config"],function(e,t,n){function s(e,t){return{win:e,mac:t}}var r=e("../lib/lang"),i=e("../config");t.commands=[{name:"showSettingsMenu",bindKey:s("Ctrl-,","Command-,"),exec:function(e){i.loadModule("ace/ext/settings_menu",function(t){t.init(e),e.showSettingsMenu()})},readOnly:!0},{name:"goToNextError",bindKey:s("Alt-E","Ctrl-E"),exec:function(e){i.loadModule("ace/ext/error_marker",function(t){t.showErrorMarker(e,1)})},scrollIntoView:"animate",readOnly:!0},{name:"goToPreviousError",bindKey:s("Alt-Shift-E","Ctrl-Shift-E"),exec:function(e){i.loadModule("ace/ext/error_marker",function(t){t.showErrorMarker(e,-1)})},scrollIntoView:"animate",readOnly:!0},{name:"selectall",bindKey:s("Ctrl-A","Command-A"),exec:function(e){e.selectAll()},readOnly:!0},{name:"centerselection",bindKey:s(null,"Ctrl-L"),exec:function(e){e.centerSelection()},readOnly:!0},{name:"gotoline",bindKey:s("Ctrl-L","Command-L"),exec:function(e){var t=parseInt(prompt("Enter line number:"),10);isNaN(t)||e.gotoLine(t)},readOnly:!0},{name:"fold",bindKey:s("Alt-L|Ctrl-F1","Command-Alt-L|Command-F1"),exec:function(e){e.session.toggleFold(!1)},scrollIntoView:"center",readOnly:!0},{name:"unfold",bindKey:s("Alt-Shift-L|Ctrl-Shift-F1","Command-Alt-Shift-L|Command-Shift-F1"),exec:function(e){e.session.toggleFold(!0)},scrollIntoView:"center",readOnly:!0},{name:"toggleFoldWidget",bindKey:s("F2","F2"),exec:function(e){e.session.toggleFoldWidget()},scrollIntoView:"center",readOnly:!0},{name:"toggleParentFoldWidget",bindKey:s("Alt-F2","Alt-F2"),exec:function(e){e.session.toggleFoldWidget(!0)},scrollIntoView:"center",readOnly:!0},{name:"foldall",bindKey:s("Ctrl-Alt-0","Ctrl-Command-Option-0"),exec:function(e){e.session.foldAll()},scrollIntoView:"center",readOnly:!0},{name:"foldOther",bindKey:s("Alt-0","Command-Option-0"),exec:function(e){e.session.foldAll(),e.session.unfold(e.selection.getAllRanges())},scrollIntoView:"center",readOnly:!0},{name:"unfoldall",bindKey:s("Alt-Shift-0","Command-Option-Shift-0"),exec:function(e){e.session.unfold()},scrollIntoView:"center",readOnly:!0},{name:"findnext",bindKey:s("Ctrl-K","Command-G"),exec:function(e){e.findNext()},readOnly:!0},{name:"findprevious",bindKey:s("Ctrl-Shift-K","Command-Shift-G"),exec:function(e){e.findPrevious()},readOnly:!0},{name:"selectOrFindNext",bindKey:s("ALt-K","Ctrl-G"),exec:function(e){e.selection.isEmpty()?e.selection.selectWord():e.findNext()},readOnly:!0},{name:"selectOrFindPrevious",bindKey:s("Alt-Shift-K","Ctrl-Shift-G"),exec:function(e){e.selection.isEmpty()?e.selection.selectWord():e.findPrevious()},readOnly:!0},{name:"find",bindKey:s("Ctrl-F","Command-F"),exec:function(e){i.loadModule("ace/ext/searchbox",function(t){t.Search(e)})},readOnly:!0},{name:"overwrite",bindKey:"Insert",exec:function(e){e.toggleOverwrite()},readOnly:!0},{name:"selecttostart",bindKey:s("Ctrl-Shift-Home","Command-Shift-Up"),exec:function(e){e.getSelection().selectFileStart()},multiSelectAction:"forEach",readOnly:!0,scrollIntoView:"animate",aceCommandGroup:"fileJump"},{name:"gotostart",bindKey:s("Ctrl-Home","Command-Home|Command-Up"),exec:function(e){e.navigateFileStart()},multiSelectAction:"forEach",readOnly:!0,scrollIntoView:"animate",aceCommandGroup:"fileJump"},{name:"selectup",bindKey:s("Shift-Up","Shift-Up"),exec:function(e){e.getSelection().selectUp()},multiSelectAction:"forEach",readOnly:!0},{name:"golineup",bindKey:s("Up","Up|Ctrl-P"),exec:function(e,t){e.navigateUp(t.times)},multiSelectAction:"forEach",readOnly:!0},{name:"selecttoend",bindKey:s("Ctrl-Shift-End","Command-Shift-Down"),exec:function(e){e.getSelection().selectFileEnd()},multiSelectAction:"forEach",readOnly:!0,scrollIntoView:"animate",aceCommandGroup:"fileJump"},{name:"gotoend",bindKey:s("Ctrl-End","Command-End|Command-Down"),exec:function(e){e.navigateFileEnd()},multiSelectAction:"forEach",readOnly:!0,scrollIntoView:"animate",aceCommandGroup:"fileJump"},{name:"selectdown",bindKey:s("Shift-Down","Shift-Down"),exec:function(e){e.getSelection().selectDown()},multiSelectAction:"forEach",scrollIntoView:"cursor",readOnly:!0},{name:"golinedown",bindKey:s("Down","Down|Ctrl-N"),exec:function(e,t){e.navigateDown(t.times)},multiSelectAction:"forEach",scrollIntoView:"cursor",readOnly:!0},{name:"selectwordleft",bindKey:s("Ctrl-Shift-Left","Option-Shift-Left"),exec:function(e){e.getSelection().selectWordLeft()},multiSelectAction:"forEach",scrollIntoView:"cursor",readOnly:!0},{name:"gotowordleft",bindKey:s("Ctrl-Left","Option-Left"),exec:function(e){e.navigateWordLeft()},multiSelectAction:"forEach",scrollIntoView:"cursor",readOnly:!0},{name:"selecttolinestart",bindKey:s("Alt-Shift-Left","Command-Shift-Left"),exec:function(e){e.getSelection().selectLineStart()},multiSelectAction:"forEach",scrollIntoView:"cursor",readOnly:!0},{name:"gotolinestart",bindKey:s("Alt-Left|Home","Command-Left|Home|Ctrl-A"),exec:function(e){e.navigateLineStart()},multiSelectAction:"forEach",scrollIntoView:"cursor",readOnly:!0},{name:"selectleft",bindKey:s("Shift-Left","Shift-Left"),exec:function(e){e.getSelection().selectLeft()},multiSelectAction:"forEach",scrollIntoView:"cursor",readOnly:!0},{name:"gotoleft",bindKey:s("Left","Left|Ctrl-B"),exec:function(e,t){e.navigateLeft(t.times)},multiSelectAction:"forEach",scrollIntoView:"cursor",readOnly:!0},{name:"selectwordright",bindKey:s("Ctrl-Shift-Right","Option-Shift-Right"),exec:function(e){e.getSelection().selectWordRight()},multiSelectAction:"forEach",scrollIntoView:"cursor",readOnly:!0},{name:"gotowordright",bindKey:s("Ctrl-Right","Option-Right"),exec:function(e){e.navigateWordRight()},multiSelectAction:"forEach",scrollIntoView:"cursor",readOnly:!0},{name:"selecttolineend",bindKey:s("Alt-Shift-Right","Command-Shift-Right"),exec:function(e){e.getSelection().selectLineEnd()},multiSelectAction:"forEach",scrollIntoView:"cursor",readOnly:!0},{name:"gotolineend",bindKey:s("Alt-Right|End","Command-Right|End|Ctrl-E"),exec:function(e){e.navigateLineEnd()},multiSelectAction:"forEach",scrollIntoView:"cursor",readOnly:!0},{name:"selectright",bindKey:s("Shift-Right","Shift-Right"),exec:function(e){e.getSelection().selectRight()},multiSelectAction:"forEach",scrollIntoView:"cursor",readOnly:!0},{name:"gotoright",bindKey:s("Right","Right|Ctrl-F"),exec:function(e,t){e.navigateRight(t.times)},multiSelectAction:"forEach",scrollIntoView:"cursor",readOnly:!0},{name:"selectpagedown",bindKey:"Shift-PageDown",exec:function(e){e.selectPageDown()},readOnly:!0},{name:"pagedown",bindKey:s(null,"Option-PageDown"),exec:function(e){e.scrollPageDown()},readOnly:!0},{name:"gotopagedown",bindKey:s("PageDown","PageDown|Ctrl-V"),exec:function(e){e.gotoPageDown()},readOnly:!0},{name:"selectpageup",bindKey:"Shift-PageUp",exec:function(e){e.selectPageUp()},readOnly:!0},{name:"pageup",bindKey:s(null,"Option-PageUp"),exec:function(e){e.scrollPageUp()},readOnly:!0},{name:"gotopageup",bindKey:"PageUp",exec:function(e){e.gotoPageUp()},readOnly:!0},{name:"scrollup",bindKey:s("Ctrl-Up",null),exec:function(e){e.renderer.scrollBy(0,-2*e.renderer.layerConfig.lineHeight)},readOnly:!0},{name:"scrolldown",bindKey:s("Ctrl-Down",null),exec:function(e){e.renderer.scrollBy(0,2*e.renderer.layerConfig.lineHeight)},readOnly:!0},{name:"selectlinestart",bindKey:"Shift-Home",exec:function(e){e.getSelection().selectLineStart()},multiSelectAction:"forEach",scrollIntoView:"cursor",readOnly:!0},{name:"selectlineend",bindKey:"Shift-End",exec:function(e){e.getSelection().selectLineEnd()},multiSelectAction:"forEach",scrollIntoView:"cursor",readOnly:!0},{name:"togglerecording",bindKey:s("Ctrl-Alt-E","Command-Option-E"),exec:function(e){e.commands.toggleRecording(e)},readOnly:!0},{name:"replaymacro",bindKey:s("Ctrl-Shift-E","Command-Shift-E"),exec:function(e){e.commands.replay(e)},readOnly:!0},{name:"jumptomatching",bindKey:s("Ctrl-P","Ctrl-Shift-P"),exec:function(e){e.jumpToMatching()},multiSelectAction:"forEach",readOnly:!0},{name:"selecttomatching",bindKey:s("Ctrl-Shift-P",null),exec:function(e){e.jumpToMatching(!0)},multiSelectAction:"forEach",readOnly:!0},{name:"cut",exec:function(e){var t=e.getSelectionRange();e._emit("cut",t),e.selection.isEmpty()||(e.session.remove(t),e.clearSelection())},scrollIntoView:"cursor",multiSelectAction:"forEach"},{name:"removeline",bindKey:s("Ctrl-D","Command-D"),exec:function(e){e.removeLines()},scrollIntoView:"cursor",multiSelectAction:"forEachLine"},{name:"duplicateSelection",bindKey:s("Ctrl-Shift-D","Command-Shift-D"),exec:function(e){e.duplicateSelection()},scrollIntoView:"cursor",multiSelectAction:"forEach"},{name:"sortlines",bindKey:s("Ctrl-Alt-S","Command-Alt-S"),exec:function(e){e.sortLines()},scrollIntoView:"selection",multiSelectAction:"forEachLine"},{name:"togglecomment",bindKey:s("Ctrl-/","Command-/"),exec:function(e){e.toggleCommentLines()},multiSelectAction:"forEachLine",scrollIntoView:"selectionPart"},{name:"toggleBlockComment",bindKey:s("Ctrl-Shift-/","Command-Shift-/"),exec:function(e){e.toggleBlockComment()},multiSelectAction:"forEach",scrollIntoView:"selectionPart"},{name:"modifyNumberUp",bindKey:s("Ctrl-Shift-Up","Alt-Shift-Up"),exec:function(e){e.modifyNumber(1)},multiSelectAction:"forEach"},{name:"modifyNumberDown",bindKey:s("Ctrl-Shift-Down","Alt-Shift-Down"),exec:function(e){e.modifyNumber(-1)},multiSelectAction:"forEach"},{name:"replace",bindKey:s("Ctrl-H","Command-Option-F"),exec:function(e){i.loadModule("ace/ext/searchbox",function(t){t.Search(e,!0)})}},{name:"undo",bindKey:s("Ctrl-Z","Command-Z"),exec:function(e){e.undo()}},{name:"redo",bindKey:s("Ctrl-Shift-Z|Ctrl-Y","Command-Shift-Z|Command-Y"),exec:function(e){e.redo()}},{name:"copylinesup",bindKey:s("Alt-Shift-Up","Command-Option-Up"),exec:function(e){e.copyLinesUp()},scrollIntoView:"cursor"},{name:"movelinesup",bindKey:s("Alt-Up","Option-Up"),exec:function(e){e.moveLinesUp()},scrollIntoView:"cursor"},{name:"copylinesdown",bindKey:s("Alt-Shift-Down","Command-Option-Down"),exec:function(e){e.copyLinesDown()},scrollIntoView:"cursor"},{name:"movelinesdown",bindKey:s("Alt-Down","Option-Down"),exec:function(e){e.moveLinesDown()},scrollIntoView:"cursor"},{name:"del",bindKey:s("Delete","Delete|Ctrl-D|Shift-Delete"),exec:function(e){e.remove("right")},multiSelectAction:"forEach",scrollIntoView:"cursor"},{name:"backspace",bindKey:s("Shift-Backspace|Backspace","Ctrl-Backspace|Shift-Backspace|Backspace|Ctrl-H"),exec:function(e){e.remove("left")},multiSelectAction:"forEach",scrollIntoView:"cursor"},{name:"cut_or_delete",bindKey:s("Shift-Delete",null),exec:function(e){if(!e.selection.isEmpty())return!1;e.remove("left")},multiSelectAction:"forEach",scrollIntoView:"cursor"},{name:"removetolinestart",bindKey:s("Alt-Backspace","Command-Backspace"),exec:function(e){e.removeToLineStart()},multiSelectAction:"forEach",scrollIntoView:"cursor"},{name:"removetolineend",bindKey:s("Alt-Delete","Ctrl-K"),exec:function(e){e.removeToLineEnd()},multiSelectAction:"forEach",scrollIntoView:"cursor"},{name:"removewordleft",bindKey:s("Ctrl-Backspace","Alt-Backspace|Ctrl-Alt-Backspace"),exec:function(e){e.removeWordLeft()},multiSelectAction:"forEach",scrollIntoView:"cursor"},{name:"removewordright",bindKey:s("Ctrl-Delete","Alt-Delete"),exec:function(e){e.removeWordRight()},multiSelectAction:"forEach",scrollIntoView:"cursor"},{name:"outdent",bindKey:s("Shift-Tab","Shift-Tab"),exec:function(e){e.blockOutdent()},multiSelectAction:"forEach",scrollIntoView:"selectionPart"},{name:"indent",bindKey:s("Tab","Tab"),exec:function(e){e.indent()},multiSelectAction:"forEach",scrollIntoView:"selectionPart"},{name:"blockoutdent",bindKey:s("Ctrl-[","Ctrl-["),exec:function(e){e.blockOutdent()},multiSelectAction:"forEachLine",scrollIntoView:"selectionPart"},{name:"blockindent",bindKey:s("Ctrl-]","Ctrl-]"),exec:function(e){e.blockIndent()},multiSelectAction:"forEachLine",scrollIntoView:"selectionPart"},{name:"insertstring",exec:function(e,t){e.insert(t)},multiSelectAction:"forEach",scrollIntoView:"cursor"},{name:"inserttext",exec:function(e,t){e.insert(r.stringRepeat(t.text||"",t.times||1))},multiSelectAction:"forEach",scrollIntoView:"cursor"},{name:"splitline",bindKey:s(null,"Ctrl-O"),exec:function(e){e.splitLine()},multiSelectAction:"forEach",scrollIntoView:"cursor"},{name:"transposeletters",bindKey:s("Ctrl-T","Ctrl-T"),exec:function(e){e.transposeLetters()},multiSelectAction:function(e){e.transposeSelections(1)},scrollIntoView:"cursor"},{name:"touppercase",bindKey:s("Ctrl-U","Ctrl-U"),exec:function(e){e.toUpperCase()},multiSelectAction:"forEach",scrollIntoView:"cursor"},{name:"tolowercase",bindKey:s("Ctrl-Shift-U","Ctrl-Shift-U"),exec:function(e){e.toLowerCase()},multiSelectAction:"forEach",scrollIntoView:"cursor"}]}),define("ace/lib/event_emitter",["require","exports","module"],function(e,t,n){var r={},i=function(){this.propagationStopped=!0},s=function(){this.defaultPrevented=!0};r._emit=r._dispatchEvent=function(e,t){this._eventRegistry||(this._eventRegistry={}),this._defaultHandlers||(this._defaultHandlers={});var n=this._eventRegistry[e]||[],r=this._defaultHandlers[e];if(!n.length&&!r)return;if(typeof t!="object"||!t)t={};t.type||(t.type=e),t.stopPropagation||(t.stopPropagation=i),t.preventDefault||(t.preventDefault=s),n=n.slice();for(var o=0;o<n.length;o++){n[o](t,this);if(t.propagationStopped)break}if(r&&!t.defaultPrevented)return r(t,this)},r._signal=function(e,t){var n=(this._eventRegistry||{})[e];if(!n)return;n=n.slice();for(var r=0;r<n.length;r++)n[r](t,this)},r.once=function(e,t){var n=this;t&&this.addEventListener(e,function r(){n.removeEventListener(e,r),t.apply(null,arguments)})},r.setDefaultHandler=function(e,t){var n=this._defaultHandlers;n||(n=this._defaultHandlers={_disabled_:{}});if(n[e]){var r=n[e],i=n._disabled_[e];i||(n._disabled_[e]=i=[]),i.push(r);var s=i.indexOf(t);s!=-1&&i.splice(s,1)}n[e]=t},r.removeDefaultHandler=function(e,t){var n=this._defaultHandlers;if(!n)return;var r=n._disabled_[e];if(n[e]==t){var i=n[e];r&&this.setDefaultHandler(e,r.pop())}else if(r){var s=r.indexOf(t);s!=-1&&r.splice(s,1)}},r.on=r.addEventListener=function(e,t,n){this._eventRegistry=this._eventRegistry||{};var r=this._eventRegistry[e];return r||(r=this._eventRegistry[e]=[]),r.indexOf(t)==-1&&r[n?"unshift":"push"](t),t},r.off=r.removeListener=r.removeEventListener=function(e,t){this._eventRegistry=this._eventRegistry||{};var n=this._eventRegistry[e];if(!n)return;var r=n.indexOf(t);r!==-1&&n.splice(r,1)},r.removeAllListeners=function(e){this._eventRegistry&&(this._eventRegistry[e]=[])},t.EventEmitter=r}),define("ace/undomanager",["require","exports","module"],function(e,t,n){var r=function(){this.reset()};(function(){this.execute=function(e){var t=e.args[0];this.$doc=e.args[1],e.merge&&this.hasUndo()&&(this.dirtyCounter--,t=this.$undoStack.pop().concat(t)),this.$undoStack.push(t),this.$redoStack=[],this.dirtyCounter<0&&(this.dirtyCounter=NaN),this.dirtyCounter++},this.undo=function(e){var t=this.$undoStack.pop(),n=null;return t&&(n=this.$doc.undoChanges(t,e),this.$redoStack.push(t),this.dirtyCounter--),n},this.redo=function(e){var t=this.$redoStack.pop(),n=null;return t&&(n=this.$doc.redoChanges(t,e),this.$undoStack.push(t),this.dirtyCounter++),n},this.reset=function(){this.$undoStack=[],this.$redoStack=[],this.dirtyCounter=0},this.hasUndo=function(){return this.$undoStack.length>0},this.hasRedo=function(){return this.$redoStack.length>0},this.markClean=function(){this.dirtyCounter=0},this.isClean=function(){return this.dirtyCounter===0}}).call(r.prototype),t.UndoManager=r}),define("ace/lib/net",["require","exports","module","ace/lib/dom"],function(e,t,n){var r=e("./dom");t.get=function(e,t){var n=new XMLHttpRequest;n.open("GET",e,!0),n.onreadystatechange=function(){n.readyState===4&&t(n.responseText)},n.send(null)},t.loadScript=function(e,t){var n=r.getDocumentHead(),i=document.createElement("script");i.src=e,n.appendChild(i),i.onload=i.onreadystatechange=function(e,n){if(n||!i.readyState||i.readyState=="loaded"||i.readyState=="complete")i=i.onload=i.onreadystatechange=null,n||t()}}}),define("ace/virtual_renderer",["require","exports","module","ace/lib/oop","ace/lib/dom","ace/config","ace/layer/gutter","ace/layer/marker","ace/layer/text","ace/layer/cursor","ace/scrollbar","ace/renderloop","ace/layer/font_metrics","ace/lib/event_emitter"],function(e,t,n){var r=e("./lib/oop"),i=e("./lib/dom"),s=e("./config"),o=e("./layer/gutter").Gutter,u=e("./layer/marker").Marker,a=e("./layer/text").Text,f=e("./layer/cursor").Cursor,l=e("./scrollbar").HScrollBar,c=e("./scrollbar").VScrollBar,h=e("./renderloop").RenderLoop,p=e("./layer/font_metrics").FontMetrics,d=e("./lib/event_emitter").EventEmitter,v='.ace_editor {position: relative;overflow: hidden;font-family: \'Monaco\', \'Menlo\', \'Ubuntu Mono\', \'Consolas\', \'source-code-pro\', monospace;font-size: 12px;line-height: normal;direction: ltr;}.ace_scroller {position: absolute;overflow: hidden;top: 0;bottom: 0;background-color: inherit;-ms-user-select: none;-moz-user-select: none;-webkit-user-select: none;user-select: none;}.ace_content {position: absolute;-moz-box-sizing: border-box;-webkit-box-sizing: border-box;box-sizing: border-box;cursor: text;min-width: 100%;}.ace_dragging, .ace_dragging * {cursor: move !important;}.ace_dragging .ace_scroller:before{position: absolute;top: 0;left: 0;right: 0;bottom: 0;content: \'\';background: rgba(250, 250, 250, 0.01);z-index: 1000;}.ace_dragging.ace_dark .ace_scroller:before{background: rgba(0, 0, 0, 0.01);}.ace_selecting, .ace_selecting * {cursor: text !important;}.ace_gutter {position: absolute;overflow : hidden;width: auto;top: 0;bottom: 0;left: 0;cursor: default;z-index: 4;-ms-user-select: none;-moz-user-select: none;-webkit-user-select: none;user-select: none;}.ace_gutter-active-line {position: absolute;left: 0;right: 0;}.ace_scroller.ace_scroll-left {box-shadow: 17px 0 16px -16px rgba(0, 0, 0, 0.4) inset;}.ace_gutter-cell {padding-left: 19px;padding-right: 6px;background-repeat: no-repeat;}.ace_gutter-cell.ace_error {background-image: url("data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAMAAAAoLQ9TAAABOFBMVEX/////////QRswFAb/Ui4wFAYwFAYwFAaWGAfDRymzOSH/PxswFAb/SiUwFAYwFAbUPRvjQiDllog5HhHdRybsTi3/Tyv9Tir+Syj/UC3////XurebMBIwFAb/RSHbPx/gUzfdwL3kzMivKBAwFAbbvbnhPx66NhowFAYwFAaZJg8wFAaxKBDZurf/RB6mMxb/SCMwFAYwFAbxQB3+RB4wFAb/Qhy4Oh+4QifbNRcwFAYwFAYwFAb/QRzdNhgwFAYwFAbav7v/Uy7oaE68MBK5LxLewr/r2NXewLswFAaxJw4wFAbkPRy2PyYwFAaxKhLm1tMwFAazPiQwFAaUGAb/QBrfOx3bvrv/VC/maE4wFAbRPBq6MRO8Qynew8Dp2tjfwb0wFAbx6eju5+by6uns4uH9/f36+vr/GkHjAAAAYnRSTlMAGt+64rnWu/bo8eAA4InH3+DwoN7j4eLi4xP99Nfg4+b+/u9B/eDs1MD1mO7+4PHg2MXa347g7vDizMLN4eG+Pv7i5evs/v79yu7S3/DV7/498Yv24eH+4ufQ3Ozu/v7+y13sRqwAAADLSURBVHjaZc/XDsFgGIBhtDrshlitmk2IrbHFqL2pvXf/+78DPokj7+Fz9qpU/9UXJIlhmPaTaQ6QPaz0mm+5gwkgovcV6GZzd5JtCQwgsxoHOvJO15kleRLAnMgHFIESUEPmawB9ngmelTtipwwfASilxOLyiV5UVUyVAfbG0cCPHig+GBkzAENHS0AstVF6bacZIOzgLmxsHbt2OecNgJC83JERmePUYq8ARGkJx6XtFsdddBQgZE2nPR6CICZhawjA4Fb/chv+399kfR+MMMDGOQAAAABJRU5ErkJggg==");background-repeat: no-repeat;background-position: 2px center;}.ace_gutter-cell.ace_warning {background-image: url("data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAMAAAAoLQ9TAAAAmVBMVEX///8AAAD///8AAAAAAABPSzb/5sAAAAB/blH/73z/ulkAAAAAAAD85pkAAAAAAAACAgP/vGz/rkDerGbGrV7/pkQICAf////e0IsAAAD/oED/qTvhrnUAAAD/yHD/njcAAADuv2r/nz//oTj/p064oGf/zHAAAAA9Nir/tFIAAAD/tlTiuWf/tkIAAACynXEAAAAAAAAtIRW7zBpBAAAAM3RSTlMAABR1m7RXO8Ln31Z36zT+neXe5OzooRDfn+TZ4p3h2hTf4t3k3ucyrN1K5+Xaks52Sfs9CXgrAAAAjklEQVR42o3PbQ+CIBQFYEwboPhSYgoYunIqqLn6/z8uYdH8Vmdnu9vz4WwXgN/xTPRD2+sgOcZjsge/whXZgUaYYvT8QnuJaUrjrHUQreGczuEafQCO/SJTufTbroWsPgsllVhq3wJEk2jUSzX3CUEDJC84707djRc5MTAQxoLgupWRwW6UB5fS++NV8AbOZgnsC7BpEAAAAABJRU5ErkJggg==");background-position: 2px center;}.ace_gutter-cell.ace_info {background-image: url("data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAAAAAA6mKC9AAAAGXRFWHRTb2Z0d2FyZQBBZG9iZSBJbWFnZVJlYWR5ccllPAAAAAJ0Uk5TAAB2k804AAAAPklEQVQY02NgIB68QuO3tiLznjAwpKTgNyDbMegwisCHZUETUZV0ZqOquBpXj2rtnpSJT1AEnnRmL2OgGgAAIKkRQap2htgAAAAASUVORK5CYII=");background-position: 2px center;}.ace_dark .ace_gutter-cell.ace_info {background-image: url("data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABAAAAAQBAMAAADt3eJSAAAAJFBMVEUAAAChoaGAgIAqKiq+vr6tra1ZWVmUlJSbm5s8PDxubm56enrdgzg3AAAAAXRSTlMAQObYZgAAAClJREFUeNpjYMAPdsMYHegyJZFQBlsUlMFVCWUYKkAZMxZAGdxlDMQBAG+TBP4B6RyJAAAAAElFTkSuQmCC");}.ace_scrollbar {position: absolute;right: 0;bottom: 0;z-index: 6;}.ace_scrollbar-inner {position: absolute;cursor: text;left: 0;top: 0;}.ace_scrollbar-v{overflow-x: hidden;overflow-y: scroll;top: 0;}.ace_scrollbar-h {overflow-x: scroll;overflow-y: hidden;left: 0;}.ace_print-margin {position: absolute;height: 100%;}.ace_text-input {position: absolute;z-index: 0;width: 0.5em;height: 1em;opacity: 0;background: transparent;-moz-appearance: none;appearance: none;border: none;resize: none;outline: none;overflow: hidden;font: inherit;padding: 0 1px;margin: 0 -1px;text-indent: -1em;-ms-user-select: text;-moz-user-select: text;-webkit-user-select: text;user-select: text;}.ace_text-input.ace_composition {background: #f8f8f8;color: #111;z-index: 1000;opacity: 1;text-indent: 0;}.ace_layer {z-index: 1;position: absolute;overflow: hidden;white-space: pre;height: 100%;width: 100%;-moz-box-sizing: border-box;-webkit-box-sizing: border-box;box-sizing: border-box;/* setting pointer-events: auto; on node under the mouse, which changesduring scroll, will break mouse wheel scrolling in Safari */pointer-events: none;}.ace_gutter-layer {position: relative;width: auto;text-align: right;pointer-events: auto;}.ace_text-layer {font: inherit !important;}.ace_cjk {display: inline-block;text-align: center;}.ace_cursor-layer {z-index: 4;}.ace_cursor {z-index: 4;position: absolute;-moz-box-sizing: border-box;-webkit-box-sizing: border-box;box-sizing: border-box;border-left: 2px solid}.ace_slim-cursors .ace_cursor {border-left-width: 1px;}.ace_overwrite-cursors .ace_cursor {border-left-width: 0px;border-bottom: 1px solid;}.ace_hidden-cursors .ace_cursor {opacity: 0.2;}.ace_smooth-blinking .ace_cursor {-moz-transition: opacity 0.18s;-webkit-transition: opacity 0.18s;-o-transition: opacity 0.18s;-ms-transition: opacity 0.18s;transition: opacity 0.18s;}.ace_editor.ace_multiselect .ace_cursor {border-left-width: 1px;}.ace_marker-layer .ace_step, .ace_marker-layer .ace_stack {position: absolute;z-index: 3;}.ace_marker-layer .ace_selection {position: absolute;z-index: 5;}.ace_marker-layer .ace_bracket {position: absolute;z-index: 6;}.ace_marker-layer .ace_active-line {position: absolute;z-index: 2;}.ace_marker-layer .ace_selected-word {position: absolute;z-index: 4;-moz-box-sizing: border-box;-webkit-box-sizing: border-box;box-sizing: border-box;}.ace_line .ace_fold {-moz-box-sizing: border-box;-webkit-box-sizing: border-box;box-sizing: border-box;display: inline-block;height: 11px;margin-top: -2px;vertical-align: middle;background-image:url("data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABEAAAAJCAYAAADU6McMAAAAGXRFWHRTb2Z0d2FyZQBBZG9iZSBJbWFnZVJlYWR5ccllPAAAAJpJREFUeNpi/P//PwOlgAXGYGRklAVSokD8GmjwY1wasKljQpYACtpCFeADcHVQfQyMQAwzwAZI3wJKvCLkfKBaMSClBlR7BOQikCFGQEErIH0VqkabiGCAqwUadAzZJRxQr/0gwiXIal8zQQPnNVTgJ1TdawL0T5gBIP1MUJNhBv2HKoQHHjqNrA4WO4zY0glyNKLT2KIfIMAAQsdgGiXvgnYAAAAASUVORK5CYII="),url("data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAA3CAYAAADNNiA5AAAAGXRFWHRTb2Z0d2FyZQBBZG9iZSBJbWFnZVJlYWR5ccllPAAAACJJREFUeNpi+P//fxgTAwPDBxDxD078RSX+YeEyDFMCIMAAI3INmXiwf2YAAAAASUVORK5CYII=");background-repeat: no-repeat, repeat-x;background-position: center center, top left;color: transparent;border: 1px solid black;-moz-border-radius: 2px;-webkit-border-radius: 2px;border-radius: 2px;cursor: pointer;pointer-events: auto;}.ace_dark .ace_fold {}.ace_fold:hover{background-image:url("data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABEAAAAJCAYAAADU6McMAAAAGXRFWHRTb2Z0d2FyZQBBZG9iZSBJbWFnZVJlYWR5ccllPAAAAJpJREFUeNpi/P//PwOlgAXGYGRklAVSokD8GmjwY1wasKljQpYACtpCFeADcHVQfQyMQAwzwAZI3wJKvCLkfKBaMSClBlR7BOQikCFGQEErIH0VqkabiGCAqwUadAzZJRxQr/0gwiXIal8zQQPnNVTgJ1TdawL0T5gBIP1MUJNhBv2HKoQHHjqNrA4WO4zY0glyNKLT2KIfIMAAQsdgGiXvgnYAAAAASUVORK5CYII="),url("data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAA3CAYAAADNNiA5AAAAGXRFWHRTb2Z0d2FyZQBBZG9iZSBJbWFnZVJlYWR5ccllPAAAACBJREFUeNpi+P//fz4TAwPDZxDxD5X4i5fLMEwJgAADAEPVDbjNw87ZAAAAAElFTkSuQmCC");}.ace_tooltip {background-color: #FFF;background-image: -webkit-linear-gradient(top, transparent, rgba(0, 0, 0, 0.1));background-image: linear-gradient(to bottom, transparent, rgba(0, 0, 0, 0.1));border: 1px solid gray;border-radius: 1px;box-shadow: 0 1px 2px rgba(0, 0, 0, 0.3);color: black;display: block;max-width: 100%;padding: 3px 4px;position: fixed;z-index: 999999;-moz-box-sizing: border-box;-webkit-box-sizing: border-box;box-sizing: border-box;cursor: default;white-space: pre;word-wrap: break-word;line-height: normal;font-style: normal;font-weight: normal;letter-spacing: normal;pointer-events: none;}.ace_folding-enabled > .ace_gutter-cell {padding-right: 13px;}.ace_fold-widget {-moz-box-sizing: border-box;-webkit-box-sizing: border-box;box-sizing: border-box;margin: 0 -12px 0 1px;display: none;width: 11px;vertical-align: top;background-image: url("data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAUAAAAFCAYAAACNbyblAAAANElEQVR42mWKsQ0AMAzC8ixLlrzQjzmBiEjp0A6WwBCSPgKAXoLkqSot7nN3yMwR7pZ32NzpKkVoDBUxKAAAAABJRU5ErkJggg==");background-repeat: no-repeat;background-position: center;border-radius: 3px;border: 1px solid transparent;cursor: pointer;}.ace_folding-enabled .ace_fold-widget {display: inline-block; }.ace_fold-widget.ace_end {background-image: url("data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAUAAAAFCAYAAACNbyblAAAANElEQVR42m3HwQkAMAhD0YzsRchFKI7sAikeWkrxwScEB0nh5e7KTPWimZki4tYfVbX+MNl4pyZXejUO1QAAAABJRU5ErkJggg==");}.ace_fold-widget.ace_closed {background-image: url("data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAMAAAAGCAYAAAAG5SQMAAAAOUlEQVR42jXKwQkAMAgDwKwqKD4EwQ26sSOkVWjgIIHAzPiCgaqiqnJHZnKICBERHN194O5b9vbLuAVRL+l0YWnZAAAAAElFTkSuQmCCXA==");}.ace_fold-widget:hover {border: 1px solid rgba(0, 0, 0, 0.3);background-color: rgba(255, 255, 255, 0.2);-moz-box-shadow: 0 1px 1px rgba(255, 255, 255, 0.7);-webkit-box-shadow: 0 1px 1px rgba(255, 255, 255, 0.7);box-shadow: 0 1px 1px rgba(255, 255, 255, 0.7);}.ace_fold-widget:active {border: 1px solid rgba(0, 0, 0, 0.4);background-color: rgba(0, 0, 0, 0.05);-moz-box-shadow: 0 1px 1px rgba(255, 255, 255, 0.8);-webkit-box-shadow: 0 1px 1px rgba(255, 255, 255, 0.8);box-shadow: 0 1px 1px rgba(255, 255, 255, 0.8);}/*** Dark version for fold widgets*/.ace_dark .ace_fold-widget {background-image: url("data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAUAAAAFCAYAAACNbyblAAAAHklEQVQIW2P4//8/AzoGEQ7oGCaLLAhWiSwB146BAQCSTPYocqT0AAAAAElFTkSuQmCC");}.ace_dark .ace_fold-widget.ace_end {background-image: url("data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAUAAAAFCAYAAACNbyblAAAAH0lEQVQIW2P4//8/AxQ7wNjIAjDMgC4AxjCVKBirIAAF0kz2rlhxpAAAAABJRU5ErkJggg==");}.ace_dark .ace_fold-widget.ace_closed {background-image: url("data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAMAAAAFCAYAAACAcVaiAAAAHElEQVQIW2P4//+/AxAzgDADlOOAznHAKgPWAwARji8UIDTfQQAAAABJRU5ErkJggg==");}.ace_dark .ace_fold-widget:hover {box-shadow: 0 1px 1px rgba(255, 255, 255, 0.2);background-color: rgba(255, 255, 255, 0.1);}.ace_dark .ace_fold-widget:active {-moz-box-shadow: 0 1px 1px rgba(255, 255, 255, 0.2);-webkit-box-shadow: 0 1px 1px rgba(255, 255, 255, 0.2);box-shadow: 0 1px 1px rgba(255, 255, 255, 0.2);}.ace_fold-widget.ace_invalid {background-color: #FFB4B4;border-color: #DE5555;}.ace_fade-fold-widgets .ace_fold-widget {-moz-transition: opacity 0.4s ease 0.05s;-webkit-transition: opacity 0.4s ease 0.05s;-o-transition: opacity 0.4s ease 0.05s;-ms-transition: opacity 0.4s ease 0.05s;transition: opacity 0.4s ease 0.05s;opacity: 0;}.ace_fade-fold-widgets:hover .ace_fold-widget {-moz-transition: opacity 0.05s ease 0.05s;-webkit-transition: opacity 0.05s ease 0.05s;-o-transition: opacity 0.05s ease 0.05s;-ms-transition: opacity 0.05s ease 0.05s;transition: opacity 0.05s ease 0.05s;opacity:1;}.ace_underline {text-decoration: underline;}.ace_bold {font-weight: bold;}.ace_nobold .ace_bold {font-weight: normal;}.ace_italic {font-style: italic;}.ace_error-marker {background-color: rgba(255, 0, 0,0.2);position: absolute;z-index: 9;}.ace_highlight-marker {background-color: rgba(255, 255, 0,0.2);position: absolute;z-index: 8;}';i.importCssString(v,"ace_editor");var m=function(e,t){var n=this;this.container=e||i.createElement("div"),this.$keepTextAreaAtCursor=!0,i.addCssClass(this.container,"ace_editor"),this.setTheme(t),this.$gutter=i.createElement("div"),this.$gutter.className="ace_gutter",this.container.appendChild(this.$gutter),this.scroller=i.createElement("div"),this.scroller.className="ace_scroller",this.container.appendChild(this.scroller),this.content=i.createElement("div"),this.content.className="ace_content",this.scroller.appendChild(this.content),this.$gutterLayer=new o(this.$gutter),this.$gutterLayer.on("changeGutterWidth",this.onGutterResize.bind(this)),this.$markerBack=new u(this.content);var r=this.$textLayer=new a(this.content);this.canvas=r.element,this.$markerFront=new u(this.content),this.$cursorLayer=new f(this.content),this.$horizScroll=!1,this.$vScroll=!1,this.scrollBar=this.scrollBarV=new c(this.container,this),this.scrollBarH=new l(this.container,this),this.scrollBarV.addEventListener("scroll",function(e){n.$scrollAnimation||n.session.setScrollTop(e.data-n.scrollMargin.top)}),this.scrollBarH.addEventListener("scroll",function(e){n.$scrollAnimation||n.session.setScrollLeft(e.data-n.scrollMargin.left)}),this.scrollTop=0,this.scrollLeft=0,this.cursorPos={row:0,column:0},this.$fontMetrics=new p(this.container,500),this.$textLayer.$setFontMetrics(this.$fontMetrics),this.$textLayer.addEventListener("changeCharacterSize",function(e){n.updateCharacterSize(),n.onResize(!0,n.gutterWidth,n.$size.width,n.$size.height),n._signal("changeCharacterSize",e)}),this.$size={width:0,height:0,scrollerHeight:0,scrollerWidth:0,$dirty:!0},this.layerConfig={width:1,padding:0,firstRow:0,firstRowScreen:0,lastRow:0,lineHeight:0,characterWidth:0,minHeight:1,maxHeight:1,offset:0,height:1,gutterOffset:1},this.scrollMargin={left:0,right:0,top:0,bottom:0,v:0,h:0},this.$loop=new h(this.$renderChanges.bind(this),this.container.ownerDocument.defaultView),this.$loop.schedule(this.CHANGE_FULL),this.updateCharacterSize(),this.setPadding(4),s.resetOptions(this),s._emit("renderer",this)};(function(){this.CHANGE_CURSOR=1,this.CHANGE_MARKER=2,this.CHANGE_GUTTER=4,this.CHANGE_SCROLL=8,this.CHANGE_LINES=16,this.CHANGE_TEXT=32,this.CHANGE_SIZE=64,this.CHANGE_MARKER_BACK=128,this.CHANGE_MARKER_FRONT=256,this.CHANGE_FULL=512,this.CHANGE_H_SCROLL=1024,r.implement(this,d),this.updateCharacterSize=function(){this.$textLayer.allowBoldFonts!=this.$allowBoldFonts&&(this.$allowBoldFonts=this.$textLayer.allowBoldFonts,this.setStyle("ace_nobold",!this.$allowBoldFonts)),this.layerConfig.characterWidth=this.characterWidth=this.$textLayer.getCharacterWidth(),this.layerConfig.lineHeight=this.lineHeight=this.$textLayer.getLineHeight(),this.$updatePrintMargin()},this.setSession=function(e){this.session&&this.session.doc.off("changeNewLineMode",this.onChangeNewLineMode),this.session=e;if(!e)return;this.scrollMargin.top&&e.getScrollTop()<=0&&e.setScrollTop(-this.scrollMargin.top),this.$cursorLayer.setSession(e),this.$markerBack.setSession(e),this.$markerFront.setSession(e),this.$gutterLayer.setSession(e),this.$textLayer.setSession(e),this.$loop.schedule(this.CHANGE_FULL),this.session.$setFontMetrics(this.$fontMetrics),this.onChangeNewLineMode=this.onChangeNewLineMode.bind(this),this.onChangeNewLineMode(),this.session.doc.on("changeNewLineMode",this.onChangeNewLineMode)},this.updateLines=function(e,t){t===undefined&&(t=Infinity),this.$changedLines?(this.$changedLines.firstRow>e&&(this.$changedLines.firstRow=e),this.$changedLines.lastRow<t&&(this.$changedLines.lastRow=t)):this.$changedLines={firstRow:e,lastRow:t};if(this.$changedLines.firstRow>this.layerConfig.lastRow||this.$changedLines.lastRow<this.layerConfig.firstRow)return;this.$loop.schedule(this.CHANGE_LINES)},this.onChangeNewLineMode=function(){this.$loop.schedule(this.CHANGE_TEXT),this.$textLayer.$updateEolChar()},this.onChangeTabSize=function(){this.$loop.schedule(this.CHANGE_TEXT|this.CHANGE_MARKER),this.$textLayer.onChangeTabSize()},this.updateText=function(){this.$loop.schedule(this.CHANGE_TEXT)},this.updateFull=function(e){e?this.$renderChanges(this.CHANGE_FULL,!0):this.$loop.schedule(this.CHANGE_FULL)},this.updateFontSize=function(){this.$textLayer.checkForSizeChanges()},this.$changes=0,this.$updateSizeAsync=function(){this.$loop.pending?this.$size.$dirty=!0:this.onResize()},this.onResize=function(e,t,n,r){if(this.resizing>2)return;this.resizing>0?this.resizing++:this.resizing=e?1:0;var i=this.container;r||(r=i.clientHeight||i.scrollHeight),n||(n=i.clientWidth||i.scrollWidth);var s=this.$updateCachedSize(e,t,n,r);if(!this.$size.scrollerHeight||!n&&!r)return this.resizing=0;e&&(this.$gutterLayer.$padding=null),e?this.$renderChanges(s|this.$changes,!0):this.$loop.schedule(s|this.$changes),this.resizing&&(this.resizing=0)},this.$updateCachedSize=function(e,t,n,r){r-=this.$extraHeight||0;var i=0,s=this.$size,o={width:s.width,height:s.height,scrollerHeight:s.scrollerHeight,scrollerWidth:s.scrollerWidth};r&&(e||s.height!=r)&&(s.height=r,i|=this.CHANGE_SIZE,s.scrollerHeight=s.height,this.$horizScroll&&(s.scrollerHeight-=this.scrollBarH.getHeight()),this.scrollBarV.element.style.bottom=this.scrollBarH.getHeight()+"px",i|=this.CHANGE_SCROLL);if(n&&(e||s.width!=n)){i|=this.CHANGE_SIZE,s.width=n,t==null&&(t=this.$showGutter?this.$gutter.offsetWidth:0),this.gutterWidth=t,this.scrollBarH.element.style.left=this.scroller.style.left=t+"px",s.scrollerWidth=Math.max(0,n-t-this.scrollBarV.getWidth()),this.scrollBarH.element.style.right=this.scroller.style.right=this.scrollBarV.getWidth()+"px",this.scroller.style.bottom=this.scrollBarH.getHeight()+"px";if(this.session&&this.session.getUseWrapMode()&&this.adjustWrapLimit()||e)i|=this.CHANGE_FULL}return s.$dirty=!n||!r,i&&this._signal("resize",o),i},this.onGutterResize=function(){var e=this.$showGutter?this.$gutter.offsetWidth:0;e!=this.gutterWidth&&(this.$changes|=this.$updateCachedSize(!0,e,this.$size.width,this.$size.height)),this.session.getUseWrapMode()&&this.adjustWrapLimit()?this.$loop.schedule(this.CHANGE_FULL):this.$size.$dirty?this.$loop.schedule(this.CHANGE_FULL):(this.$computeLayerConfig(),this.$loop.schedule(this.CHANGE_MARKER))},this.adjustWrapLimit=function(){var e=this.$size.scrollerWidth-this.$padding*2,t=Math.floor(e/this.characterWidth);return this.session.adjustWrapLimit(t,this.$showPrintMargin&&this.$printMarginColumn)},this.setAnimatedScroll=function(e){this.setOption("animatedScroll",e)},this.getAnimatedScroll=function(){return this.$animatedScroll},this.setShowInvisibles=function(e){this.setOption("showInvisibles",e)},this.getShowInvisibles=function(){return this.getOption("showInvisibles")},this.getDisplayIndentGuides=function(){return this.getOption("displayIndentGuides")},this.setDisplayIndentGuides=function(e){this.setOption("displayIndentGuides",e)},this.setShowPrintMargin=function(e){this.setOption("showPrintMargin",e)},this.getShowPrintMargin=function(){return this.getOption("showPrintMargin")},this.setPrintMarginColumn=function(e){this.setOption("printMarginColumn",e)},this.getPrintMarginColumn=function(){return this.getOption("printMarginColumn")},this.getShowGutter=function(){return this.getOption("showGutter")},this.setShowGutter=function(e){return this.setOption("showGutter",e)},this.getFadeFoldWidgets=function(){return this.getOption("fadeFoldWidgets")},this.setFadeFoldWidgets=function(e){this.setOption("fadeFoldWidgets",e)},this.setHighlightGutterLine=function(e){this.setOption("highlightGutterLine",e)},this.getHighlightGutterLine=function(){return this.getOption("highlightGutterLine")},this.$updateGutterLineHighlight=function(){var e=this.$cursorLayer.$pixelPos,t=this.layerConfig.lineHeight;if(this.session.getUseWrapMode()){var n=this.session.selection.getCursor();n.column=0,e=this.$cursorLayer.getPixelPosition(n,!0),t*=this.session.getRowLength(n.row)}this.$gutterLineHighlight.style.top=e.top-this.layerConfig.offset+"px",this.$gutterLineHighlight.style.height=t+"px"},this.$updatePrintMargin=function(){if(!this.$showPrintMargin&&!this.$printMarginEl)return;if(!this.$printMarginEl){var e=i.createElement("div");e.className="ace_layer ace_print-margin-layer",this.$printMarginEl=i.createElement("div"),this.$printMarginEl.className="ace_print-margin",e.appendChild(this.$printMarginEl),this.content.insertBefore(e,this.content.firstChild)}var t=this.$printMarginEl.style;t.left=this.characterWidth*this.$printMarginColumn+this.$padding+"px",t.visibility=this.$showPrintMargin?"visible":"hidden",this.session&&this.session.$wrap==-1&&this.adjustWrapLimit()},this.getContainerElement=function(){return this.container},this.getMouseEventTarget=function(){return this.content},this.getTextAreaContainer=function(){return this.container},this.$moveTextAreaToCursor=function(){if(!this.$keepTextAreaAtCursor)return;var e=this.layerConfig,t=this.$cursorLayer.$pixelPos.top,n=this.$cursorLayer.$pixelPos.left;t-=e.offset;var r=this.lineHeight;if(t<0||t>e.height-r)return;var i=this.characterWidth;if(this.$composition){var s=this.textarea.value.replace(/^\x01+/,"");i*=this.session.$getStringScreenWidth(s)[0]+2,r+=2,t-=1}n-=this.scrollLeft,n>this.$size.scrollerWidth-i&&(n=this.$size.scrollerWidth-i),n-=this.scrollBar.width,this.textarea.style.height=r+"px",this.textarea.style.width=i+"px",this.textarea.style.right=Math.max(0,this.$size.scrollerWidth-n-i)+"px",this.textarea.style.bottom=Math.max(0,this.$size.height-t-r)+"px"},this.getFirstVisibleRow=function(){return this.layerConfig.firstRow},this.getFirstFullyVisibleRow=function(){return this.layerConfig.firstRow+(this.layerConfig.offset===0?0:1)},this.getLastFullyVisibleRow=function(){var e=Math.floor((this.layerConfig.height+this.layerConfig.offset)/this.layerConfig.lineHeight);return this.layerConfig.firstRow-1+e},this.getLastVisibleRow=function(){return this.layerConfig.lastRow},this.$padding=null,this.setPadding=function(e){this.$padding=e,this.$textLayer.setPadding(e),this.$cursorLayer.setPadding(e),this.$markerFront.setPadding(e),this.$markerBack.setPadding(e),this.$loop.schedule(this.CHANGE_FULL),this.$updatePrintMargin()},this.setScrollMargin=function(e,t,n,r){var i=this.scrollMargin;i.top=e|0,i.bottom=t|0,i.right=r|0,i.left=n|0,i.v=i.top+i.bottom,i.h=i.left+i.right,i.top&&this.scrollTop<=0&&this.session&&this.session.setScrollTop(-i.top),this.updateFull()},this.getHScrollBarAlwaysVisible=function(){return this.$hScrollBarAlwaysVisible},this.setHScrollBarAlwaysVisible=function(e){this.setOption("hScrollBarAlwaysVisible",e)},this.getVScrollBarAlwaysVisible=function(){return this.$hScrollBarAlwaysVisible},this.setVScrollBarAlwaysVisible=function(e){this.setOption("vScrollBarAlwaysVisible",e)},this.$updateScrollBarV=function(){this.scrollBarV.setScrollHeight(this.layerConfig.maxHeight+this.scrollMargin.v),this.scrollBarV.setScrollTop(this.scrollTop+this.scrollMargin.top)},this.$updateScrollBarH=function(){this.scrollBarH.setScrollWidth(this.layerConfig.width+2*this.$padding+this.scrollMargin.h),this.scrollBarH.setScrollLeft(this.scrollLeft+this.scrollMargin.left)},this.$frozen=!1,this.freeze=function(){this.$frozen=!0},this.unfreeze=function(){this.$frozen=!1},this.$renderChanges=function(e,t){this.$changes&&(e|=this.$changes,this.$changes=0);if(!this.session||!this.container.offsetWidth||this.$frozen||!e&&!t){this.$changes|=e;return}if(this.$size.$dirty)return this.$changes|=e,this.onResize(!0);this.lineHeight||this.$textLayer.checkForSizeChanges(),this._signal("beforeRender");var n=this.layerConfig;if(e&this.CHANGE_FULL||e&this.CHANGE_SIZE||e&this.CHANGE_TEXT||e&this.CHANGE_LINES||e&this.CHANGE_SCROLL||e&this.CHANGE_H_SCROLL)e|=this.$computeLayerConfig(),n=this.layerConfig,this.$updateScrollBarV(),e&this.CHANGE_H_SCROLL&&this.$updateScrollBarH(),this.$gutterLayer.element.style.marginTop=-n.offset+"px",this.content.style.marginTop=-n.offset+"px",this.content.style.width=n.width+2*this.$padding+"px",this.content.style.height=n.minHeight+"px";e&this.CHANGE_H_SCROLL&&(this.content.style.marginLeft=-this.scrollLeft+"px",this.scroller.className=this.scrollLeft<=0?"ace_scroller":"ace_scroller ace_scroll-left");if(e&this.CHANGE_FULL){this.$textLayer.update(n),this.$showGutter&&this.$gutterLayer.update(n),this.$markerBack.update(n),this.$markerFront.update(n),this.$cursorLayer.update(n),this.$moveTextAreaToCursor(),this.$highlightGutterLine&&this.$updateGutterLineHighlight(),this._signal("afterRender");return}if(e&this.CHANGE_SCROLL){e&this.CHANGE_TEXT||e&this.CHANGE_LINES?this.$textLayer.update(n):this.$textLayer.scrollLines(n),this.$showGutter&&this.$gutterLayer.update(n),this.$markerBack.update(n),this.$markerFront.update(n),this.$cursorLayer.update(n),this.$highlightGutterLine&&this.$updateGutterLineHighlight(),this.$moveTextAreaToCursor(),this._signal("afterRender");return}e&this.CHANGE_TEXT?(this.$textLayer.update(n),this.$showGutter&&this.$gutterLayer.update(n)):e&this.CHANGE_LINES?(this.$updateLines()||e&this.CHANGE_GUTTER&&this.$showGutter)&&this.$gutterLayer.update(n):(e&this.CHANGE_TEXT||e&this.CHANGE_GUTTER)&&this.$showGutter&&this.$gutterLayer.update(n),e&this.CHANGE_CURSOR&&(this.$cursorLayer.update(n),this.$moveTextAreaToCursor(),this.$highlightGutterLine&&this.$updateGutterLineHighlight()),e&(this.CHANGE_MARKER|this.CHANGE_MARKER_FRONT)&&this.$markerFront.update(n),e&(this.CHANGE_MARKER|this.CHANGE_MARKER_BACK)&&this.$markerBack.update(n),this._signal("afterRender")},this.$autosize=function(){var e=this.session.getScreenLength()*this.lineHeight,t=this.$maxLines*this.lineHeight,n=Math.max((this.$minLines||1)*this.lineHeight,Math.min(t,e))+this.scrollMargin.v+(this.$extraHeight||0),r=e>t;if(n!=this.desiredHeight||this.$size.height!=this.desiredHeight||r!=this.$vScroll){r!=this.$vScroll&&(this.$vScroll=r,this.scrollBarV.setVisible(r));var i=this.container.clientWidth;this.container.style.height=n+"px",this.$updateCachedSize(!0,this.$gutterWidth,i,n),this.desiredHeight=n}},this.$computeLayerConfig=function(){this.$maxLines&&this.lineHeight>1&&this.$autosize();var e=this.session,t=this.$size,n=t.height<=2*this.lineHeight,r=this.session.getScreenLength(),i=r*this.lineHeight,s=this.scrollTop%this.lineHeight,o=t.scrollerHeight+this.lineHeight,u=this.$getLongestLine(),a=!n&&(this.$hScrollBarAlwaysVisible||t.scrollerWidth-u-2*this.$padding<0),f=this.$horizScroll!==a;f&&(this.$horizScroll=a,this.scrollBarH.setVisible(a)),!this.$maxLines&&this.$scrollPastEnd&&this.scrollTop>i-t.scrollerHeight&&(i+=Math.min((t.scrollerHeight-this.lineHeight)*this.$scrollPastEnd,this.scrollTop-i+t.scrollerHeight));var l=!n&&(this.$vScrollBarAlwaysVisible||t.scrollerHeight-i<0),c=this.$vScroll!==l;c&&(this.$vScroll=l,this.scrollBarV.setVisible(l)),this.session.setScrollTop(Math.max(-this.scrollMargin.top,Math.min(this.scrollTop,i-t.scrollerHeight+this.scrollMargin.bottom))),this.session.setScrollLeft(Math.max(-this.scrollMargin.left,Math.min(this.scrollLeft,u+2*this.$padding-t.scrollerWidth+this.scrollMargin.right)));var h=Math.ceil(o/this.lineHeight)-1,p=Math.max(0,Math.round((this.scrollTop-s)/this.lineHeight)),d=p+h,v,m,g=this.lineHeight;p=e.screenToDocumentRow(p,0);var y=e.getFoldLine(p);y&&(p=y.start.row),v=e.documentToScreenRow(p,0),m=e.getRowLength(p)*g,d=Math.min(e.screenToDocumentRow(d,0),e.getLength()-1),o=t.scrollerHeight+e.getRowLength(d)*g+m,s=this.scrollTop-v*g;var b=0;this.layerConfig.width!=u&&(b=this.CHANGE_H_SCROLL);if(f||c)b=this.$updateCachedSize(!0,this.gutterWidth,t.width,t.height),this._signal("scrollbarVisibilityChanged"),c&&(u=this.$getLongestLine());return this.layerConfig={width:u,padding:this.$padding,firstRow:p,firstRowScreen:v,lastRow:d,lineHeight:g,characterWidth:this.characterWidth,minHeight:o,maxHeight:i,offset:s,gutterOffset:Math.max(0,Math.ceil((s+t.height-t.scrollerHeight)/g)),height:this.$size.scrollerHeight},b},this.$updateLines=function(){var e=this.$changedLines.firstRow,t=this.$changedLines.lastRow;this.$changedLines=null;var n=this.layerConfig;if(e>n.lastRow+1)return;if(t<n.firstRow)return;if(t===Infinity){this.$showGutter&&this.$gutterLayer.update(n),this.$textLayer.update(n);return}return this.$textLayer.updateLines(n,e,t),!0},this.$getLongestLine=function(){var e=this.session.getScreenWidth();return this.showInvisibles&&!this.session.$useWrapMode&&(e+=1),Math.max(this.$size.scrollerWidth-2*this.$padding,Math.round(e*this.characterWidth))},this.updateFrontMarkers=function(){this.$markerFront.setMarkers(this.session.getMarkers(!0)),this.$loop.schedule(this.CHANGE_MARKER_FRONT)},this.updateBackMarkers=function(){this.$markerBack.setMarkers(this.session.getMarkers()),this.$loop.schedule(this.CHANGE_MARKER_BACK)},this.addGutterDecoration=function(e,t){this.$gutterLayer.addGutterDecoration(e,t)},this.removeGutterDecoration=function(e,t){this.$gutterLayer.removeGutterDecoration(e,t)},this.updateBreakpoints=function(e){this.$loop.schedule(this.CHANGE_GUTTER)},this.setAnnotations=function(e){this.$gutterLayer.setAnnotations(e),this.$loop.schedule(this.CHANGE_GUTTER)},this.updateCursor=function(){this.$loop.schedule(this.CHANGE_CURSOR)},this.hideCursor=function(){this.$cursorLayer.hideCursor()},this.showCursor=function(){this.$cursorLayer.showCursor()},this.scrollSelectionIntoView=function(e,t,n){this.scrollCursorIntoView(e,n),this.scrollCursorIntoView(t,n)},this.scrollCursorIntoView=function(e,t,n){if(this.$size.scrollerHeight===0)return;var r=this.$cursorLayer.getPixelPosition(e),i=r.left,s=r.top,o=n&&n.top||0,u=n&&n.bottom||0,a=this.$scrollAnimation?this.session.getScrollTop():this.scrollTop;a+o>s?(t&&(s-=t*this.$size.scrollerHeight),s===0&&(s=-this.scrollMargin.top),this.session.setScrollTop(s)):a+this.$size.scrollerHeight-u<s+this.lineHeight&&(t&&(s+=t*this.$size.scrollerHeight),this.session.setScrollTop(s+this.lineHeight-this.$size.scrollerHeight));var f=this.scrollLeft;f>i?(i<this.$padding+2*this.layerConfig.characterWidth&&(i=-this.scrollMargin.left),this.session.setScrollLeft(i)):f+this.$size.scrollerWidth<i+this.characterWidth?this.session.setScrollLeft(Math.round(i+this.characterWidth-this.$size.scrollerWidth)):f<=this.$padding&&i-f<this.characterWidth&&this.session.setScrollLeft(0)},this.getScrollTop=function(){return this.session.getScrollTop()},this.getScrollLeft=function(){return this.session.getScrollLeft()},this.getScrollTopRow=function(){return this.scrollTop/this.lineHeight},this.getScrollBottomRow=function(){return Math.max(0,Math.floor((this.scrollTop+this.$size.scrollerHeight)/this.lineHeight)-1)},this.scrollToRow=function(e){this.session.setScrollTop(e*this.lineHeight)},this.alignCursor=function(e,t){typeof e=="number"&&(e={row:e,column:0});var n=this.$cursorLayer.getPixelPosition(e),r=this.$size.scrollerHeight-this.lineHeight,i=n.top-r*(t||0);return this.session.setScrollTop(i),i},this.STEPS=8,this.$calcSteps=function(e,t){var n=0,r=this.STEPS,i=[],s=function(e,t,n){return n*(Math.pow(e-1,3)+1)+t};for(n=0;n<r;++n)i.push(s(n/this.STEPS,e,t-e));return i},this.scrollToLine=function(e,t,n,r){var i=this.$cursorLayer.getPixelPosition({row:e,column:0}),s=i.top;t&&(s-=this.$size.scrollerHeight/2);var o=this.scrollTop;this.session.setScrollTop(s),n!==!1&&this.animateScrolling(o,r)},this.animateScrolling=function(e,t){var n=this.scrollTop;if(!this.$animatedScroll)return;var r=this;if(e==n)return;if(this.$scrollAnimation){var i=this.$scrollAnimation.steps;if(i.length){e=i[0];if(e==n)return}}var s=r.$calcSteps(e,n);this.$scrollAnimation={from:e,to:n,steps:s},clearInterval(this.$timer),r.session.setScrollTop(s.shift()),r.session.$scrollTop=n,this.$timer=setInterval(function(){s.length?(r.session.setScrollTop(s.shift()),r.session.$scrollTop=n):n!=null?(r.session.$scrollTop=-1,r.session.setScrollTop(n),n=null):(r.$timer=clearInterval(r.$timer),r.$scrollAnimation=null,t&&t())},10)},this.scrollToY=function(e){this.scrollTop!==e&&(this.$loop.schedule(this.CHANGE_SCROLL),this.scrollTop=e)},this.scrollToX=function(e){this.scrollLeft!==e&&(this.scrollLeft=e),this.$loop.schedule(this.CHANGE_H_SCROLL)},this.scrollTo=function(e,t){this.session.setScrollTop(t),this.session.setScrollLeft(t)},this.scrollBy=function(e,t){t&&this.session.setScrollTop(this.session.getScrollTop()+t),e&&this.session.setScrollLeft(this.session.getScrollLeft()+e)},this.isScrollableBy=function(e,t){if(t<0&&this.session.getScrollTop()>=1-this.scrollMargin.top)return!0;if(t>0&&this.session.getScrollTop()+this.$size.scrollerHeight-this.layerConfig.maxHeight-(this.$size.scrollerHeight-this.lineHeight)*this.$scrollPastEnd<-1+this.scrollMargin.bottom)return!0;if(e<0&&this.session.getScrollLeft()>=1-this.scrollMargin.left)return!0;if(e>0&&this.session.getScrollLeft()+this.$size.scrollerWidth-this.layerConfig.width<-1+this.scrollMargin.right)return!0},this.pixelToScreenCoordinates=function(e,t){var n=this.scroller.getBoundingClientRect(),r=(e+this.scrollLeft-n.left-this.$padding)/this.characterWidth,i=Math.floor((t+this.scrollTop-n.top)/this.lineHeight),s=Math.round(r);return{row:i,column:s,side:r-s>0?1:-1}},this.screenToTextCoordinates=function(e,t){var n=this.scroller.getBoundingClientRect(),r=Math.round((e+this.scrollLeft-n.left-this.$padding)/this.characterWidth),i=(t+this.scrollTop-n.top)/this.lineHeight;return this.session.screenToDocumentPosition(i,Math.max(r,0))},this.textToScreenCoordinates=function(e,t){var n=this.scroller.getBoundingClientRect(),r=this.session.documentToScreenPosition(e,t),i=this.$padding+Math.round(r.column*this.characterWidth),s=r.row*this.lineHeight;return{pageX:n.left+i-this.scrollLeft,pageY:n.top+s-this.scrollTop}},this.visualizeFocus=function(){i.addCssClass(this.container,"ace_focus")},this.visualizeBlur=function(){i.removeCssClass(this.container,"ace_focus")},this.showComposition=function(e){this.$composition||(this.$composition={keepTextAreaAtCursor:this.$keepTextAreaAtCursor,cssText:this.textarea.style.cssText}),this.$keepTextAreaAtCursor=!0,i.addCssClass(this.textarea,"ace_composition"),this.textarea.style.cssText="",this.$moveTextAreaToCursor()},this.setCompositionText=function(e){this.$moveTextAreaToCursor()},this.hideComposition=function(){if(!this.$composition)return;i.removeCssClass(this.textarea,"ace_composition"),this.$keepTextAreaAtCursor=this.$composition.keepTextAreaAtCursor,this.textarea.style.cssText=this.$composition.cssText,this.$composition=null},this.setTheme=function(e,t){function o(r){if(n.$themeId!=e)return t&&t();if(!r.cssClass)return;i.importCssString(r.cssText,r.cssClass,n.container.ownerDocument),n.theme&&i.removeCssClass(n.container,n.theme.cssClass);var s="padding"in r?r.padding:"padding"in(n.theme||{})?4:n.$padding;n.$padding&&s!=n.$padding&&n.setPadding(s),n.$theme=r.cssClass,n.theme=r,i.addCssClass(n.container,r.cssClass),i.setCssClass(n.container,"ace_dark",r.isDark),n.$size&&(n.$size.width=0,n.$updateSizeAsync()),n._dispatchEvent("themeLoaded",{theme:r}),t&&t()}var n=this;this.$themeId=e,n._dispatchEvent("themeChange",{theme:e});if(!e||typeof e=="string"){var r=e||this.$options.theme.initialValue;s.loadModule(["theme",r],o)}else o(e)},this.getTheme=function(){return this.$themeId},this.setStyle=function(e,t){i.setCssClass(this.container,e,t!==!1)},this.unsetStyle=function(e){i.removeCssClass(this.container,e)},this.setCursorStyle=function(e){this.content.style.cursor!=e&&(this.content.style.cursor=e)},this.setMouseCursor=function(e){this.content.style.cursor=e},this.destroy=function(){this.$textLayer.destroy(),this.$cursorLayer.destroy()}}).call(m.prototype),s.defineOptions(m.prototype,"renderer",{animatedScroll:{initialValue:!1},showInvisibles:{set:function(e){this.$textLayer.setShowInvisibles(e)&&this.$loop.schedule(this.CHANGE_TEXT)},initialValue:!1},showPrintMargin:{set:function(){this.$updatePrintMargin()},initialValue:!0},printMarginColumn:{set:function(){this.$updatePrintMargin()},initialValue:80},printMargin:{set:function(e){typeof e=="number"&&(this.$printMarginColumn=e),this.$showPrintMargin=!!e,this.$updatePrintMargin()},get:function(){return this.$showPrintMargin&&this.$printMarginColumn}},showGutter:{set:function(e){this.$gutter.style.display=e?"block":"none",this.$loop.schedule(this.CHANGE_FULL),this.onGutterResize()},initialValue:!0},fadeFoldWidgets:{set:function(e){i.setCssClass(this.$gutter,"ace_fade-fold-widgets",e)},initialValue:!1},showFoldWidgets:{set:function(e){this.$gutterLayer.setShowFoldWidgets(e)},initialValue:!0},showLineNumbers:{set:function(e){this.$gutterLayer.setShowLineNumbers(e),this.$loop.schedule(this.CHANGE_GUTTER)},initialValue:!0},displayIndentGuides:{set:function(e){this.$textLayer.setDisplayIndentGuides(e)&&this.$loop.schedule(this.CHANGE_TEXT)},initialValue:!0},highlightGutterLine:{set:function(e){if(!this.$gutterLineHighlight){this.$gutterLineHighlight=i.createElement("div"),this.$gutterLineHighlight.className="ace_gutter-active-line",this.$gutter.appendChild(this.$gutterLineHighlight);return}this.$gutterLineHighlight.style.display=e?"":"none",this.$cursorLayer.$pixelPos&&this.$updateGutterLineHighlight()},initialValue:!1,value:!0},hScrollBarAlwaysVisible:{set:function(e){(!this.$hScrollBarAlwaysVisible||!this.$horizScroll)&&this.$loop.schedule(this.CHANGE_SCROLL)},initialValue:!1},vScrollBarAlwaysVisible:{set:function(e){(!this.$vScrollBarAlwaysVisible||!this.$vScroll)&&this.$loop.schedule(this.CHANGE_SCROLL)},initialValue:!1},fontSize:{set:function(e){typeof e=="number"&&(e+="px"),this.container.style.fontSize=e,this.updateFontSize()},initialValue:12},fontFamily:{set:function(e){this.container.style.fontFamily=e,this.updateFontSize()}},maxLines:{set:function(e){this.updateFull()}},minLines:{set:function(e){this.updateFull()}},scrollPastEnd:{set:function(e){e=+e||0;if(this.$scrollPastEnd==e)return;this.$scrollPastEnd=e,this.$loop.schedule(this.CHANGE_SCROLL)},initialValue:0,handlesSet:!0},fixedWidthGutter:{set:function(e){this.$gutterLayer.$fixedWidth=!!e,this.$loop.schedule(this.CHANGE_GUTTER)}},theme:{set:function(e){this.setTheme(e)},get:function(){return this.$themeId||this.theme},initialValue:"./theme/textmate",handlesSet:!0}}),t.VirtualRenderer=m}),define("ace/config",["require","exports","module","ace/lib/lang","ace/lib/oop","ace/lib/net","ace/lib/event_emitter"],function(e,t,n){"no use strict";function f(r){a.packaged=r||e.packaged||n.packaged||u.define&&define.packaged;if(!u.document)return"";var i={},s="",o=document.getElementsByTagName("script");for(var f=0;f<o.length;f++){var c=o[f],h=c.src||c.getAttribute("src");if(!h)continue;var p=c.attributes;for(var d=0,v=p.length;d<v;d++){var m=p[d];m.name.indexOf("data-ace-")===0&&(i[l(m.name.replace(/^data-ace-/,""))]=m.value)}var g=h.match(/^(.*)\/ace(\-\w+)?\.js(\?|$)/);g&&(s=g[1])}s&&(i.base=i.base||s,i.packaged=!0),i.basePath=i.base,i.workerPath=i.workerPath||i.base,i.modePath=i.modePath||i.base,i.themePath=i.themePath||i.base,delete i.base;for(var y in i)typeof i[y]!="undefined"&&t.set(y,i[y])}function l(e){return e.replace(/-(.)/g,function(e,t){return t.toUpperCase()})}var r=e("./lib/lang"),i=e("./lib/oop"),s=e("./lib/net"),o=e("./lib/event_emitter").EventEmitter,u=function(){return this}(),a={packaged:!1,workerPath:null,modePath:null,themePath:null,basePath:"",suffix:".js",$moduleUrls:{}};t.get=function(e){if(!a.hasOwnProperty(e))throw new Error("Unknown config key: "+e);return a[e]},t.set=function(e,t){if(!a.hasOwnProperty(e))throw new Error("Unknown config key: "+e);a[e]=t},t.all=function(){return r.copyObject(a)},i.implement(t,o),t.moduleUrl=function(e,t){if(a.$moduleUrls[e])return a.$moduleUrls[e];var n=e.split("/");t=t||n[n.length-2]||"";var r=t=="snippets"?"/":"-",i=n[n.length-1];if(r=="-"){var s=new RegExp("^"+t+"[\\-_]|[\\-_]"+t+"$","g");i=i.replace(s,"")}(!i||i==t)&&n.length>1&&(i=n[n.length-2]);var o=a[t+"Path"];return o==null?o=a.basePath:r=="/"&&(t=r=""),o&&o.slice(-1)!="/"&&(o+="/"),o+t+r+i+this.get("suffix")},t.setModuleUrl=function(e,t){return a.$moduleUrls[e]=t},t.$loading={},t.loadModule=function(n,r){var i,o;Array.isArray(n)&&(o=n[0],n=n[1]);try{i=e(n)}catch(u){}if(i&&!t.$loading[n])return r&&r(i);t.$loading[n]||(t.$loading[n]=[]),t.$loading[n].push(r);if(t.$loading[n].length>1)return;var a=function(){e([n],function(e){t._emit("load.module",{name:n,module:e});var r=t.$loading[n];t.$loading[n]=null,r.forEach(function(t){t&&t(e)})})};if(!t.get("packaged"))return a();s.loadScript(t.moduleUrl(n,o),a)},f(!0),t.init=f;var c={setOptions:function(e){Object.keys(e).forEach(function(t){this.setOption(t,e[t])},this)},getOptions:function(e){var t={};return e?Array.isArray(e)||(t=e,e=Object.keys(t)):e=Object.keys(this.$options),e.forEach(function(e){t[e]=this.getOption(e)},this),t},setOption:function(e,t){if(this["$"+e]===t)return;var n=this.$options[e];if(!n)return typeof console!="undefined"&&console.warn&&console.warn('misspelled option "'+e+'"'),undefined;if(n.forwardTo)return this[n.forwardTo]&&this[n.forwardTo].setOption(e,t);n.handlesSet||(this["$"+e]=t),n&&n.set&&n.set.call(this,t)},getOption:function(e){var t=this.$options[e];return t?t.forwardTo?this[t.forwardTo]&&this[t.forwardTo].getOption(e):t&&t.get?t.get.call(this):this["$"+e]:(typeof console!="undefined"&&console.warn&&console.warn('misspelled option "'+e+'"'),undefined)}},h={};t.defineOptions=function(e,t,n){return e.$options||(h[t]=e.$options={}),Object.keys(n).forEach(function(t){var r=n[t];typeof r=="string"&&(r={forwardTo:r}),r.name||(r.name=t),e.$options[r.name]=r,"initialValue"in r&&(e["$"+r.name]=r.initialValue)}),i.implement(e,c),this},t.resetOptions=function(e){Object.keys(e.$options).forEach(function(t){var n=e.$options[t];"value"in n&&e.setOption(t,n.value)})},t.setDefaultValue=function(e,n,r){var i=h[e]||(h[e]={});i[n]&&(i.forwardTo?t.setDefaultValue(i.forwardTo,n,r):i[n].value=r)},t.setDefaultValues=function(e,n){Object.keys(n).forEach(function(r){t.setDefaultValue(e,r,n[r])})}}),define("ace/layer/gutter",["require","exports","module","ace/lib/dom","ace/lib/oop","ace/lib/lang","ace/lib/event_emitter"],function(e,t,n){var r=e("../lib/dom"),i=e("../lib/oop"),s=e("../lib/lang"),o=e("../lib/event_emitter").EventEmitter,u=function(e){this.element=r.createElement("div"),this.element.className="ace_layer ace_gutter-layer",e.appendChild(this.element),this.setShowFoldWidgets(this.$showFoldWidgets),this.gutterWidth=0,this.$annotations=[],this.$updateAnnotations=this.$updateAnnotations.bind(this),this.$cells=[]};(function(){i.implement(this,o),this.setSession=function(e){this.session&&this.session.removeEventListener("change",this.$updateAnnotations),this.session=e,e.on("change",this.$updateAnnotations)},this.addGutterDecoration=function(e,t){window.console&&console.warn&&console.warn("deprecated use session.addGutterDecoration"),this.session.addGutterDecoration(e,t)},this.removeGutterDecoration=function(e,t){window.console&&console.warn&&console.warn("deprecated use session.removeGutterDecoration"),this.session.removeGutterDecoration(e,t)},this.setAnnotations=function(e){this.$annotations=[];for(var t=0;t<e.length;t++){var n=e[t],r=n.row,i=this.$annotations[r];i||(i=this.$annotations[r]={text:[]});var o=n.text;o=o?s.escapeHTML(o):n.html||"",i.text.indexOf(o)===-1&&i.text.push(o);var u=n.type;u=="error"?i.className=" ace_error":u=="warning"&&i.className!=" ace_error"?i.className=" ace_warning":u=="info"&&!i.className&&(i.className=" ace_info")}},this.$updateAnnotations=function(e){if(!this.$annotations.length)return;var t=e.data,n=t.range,r=n.start.row,i=n.end.row-r;if(i!==0)if(t.action=="removeText"||t.action=="removeLines")this.$annotations.splice(r,i+1,null);else{var s=new Array(i+1);s.unshift(r,1),this.$annotations.splice.apply(this.$annotations,s)}},this.update=function(e){var t=this.session,n=e.firstRow,i=Math.min(e.lastRow+e.gutterOffset,t.getLength()-1),s=t.getNextFoldLine(n),o=s?s.start.row:Infinity,u=this.$showFoldWidgets&&t.foldWidgets,a=t.$breakpoints,f=t.$decorations,l=t.$firstLineNumber,c=0,h=t.gutterRenderer||this.$renderer,p=null,d=-1,v=n;for(;;){v>o&&(v=s.end.row+1,s=t.getNextFoldLine(v,s),o=s?s.start.row:Infinity);if(v>i){while(this.$cells.length>d+1)p=this.$cells.pop(),this.element.removeChild(p.element);break}p=this.$cells[++d],p||(p={element:null,textNode:null,foldWidget:null},p.element=r.createElement("div"),p.textNode=document.createTextNode(""),p.element.appendChild(p.textNode),this.element.appendChild(p.element),this.$cells[d]=p);var m="ace_gutter-cell ";a[v]&&(m+=a[v]),f[v]&&(m+=f[v]),this.$annotations[v]&&(m+=this.$annotations[v].className),p.element.className!=m&&(p.element.className=m);var g=t.getRowLength(v)*e.lineHeight+"px";g!=p.element.style.height&&(p.element.style.height=g);if(u){var y=u[v];y==null&&(y=u[v]=t.getFoldWidget(v))}if(y){p.foldWidget||(p.foldWidget=r.createElement("span"),p.element.appendChild(p.foldWidget));var m="ace_fold-widget ace_"+y;y=="start"&&v==o&&v<s.end.row?m+=" ace_closed":m+=" ace_open",p.foldWidget.className!=m&&(p.foldWidget.className=m);var g=e.lineHeight+"px";p.foldWidget.style.height!=g&&(p.foldWidget.style.height=g)}else p.foldWidget&&(p.element.removeChild(p.foldWidget),p.foldWidget=null);var b=c=h?h.getText(t,v):v+l;b!=p.textNode.data&&(p.textNode.data=b),v++}this.element.style.height=e.minHeight+"px";if(this.$fixedWidth||t.$useWrapMode)c=t.getLength()+l;var w=h?h.getWidth(t,c,e):c.toString().length*e.characterWidth,E=this.$padding||this.$computePadding();w+=E.left+E.right,w!==this.gutterWidth&&!isNaN(w)&&(this.gutterWidth=w,this.element.style.width=Math.ceil(this.gutterWidth)+"px",this._emit("changeGutterWidth",w))},this.$fixedWidth=!1,this.$showLineNumbers=!0,this.$renderer="",this.setShowLineNumbers=function(e){this.$renderer=!e&&{getWidth:function(){return""},getText:function(){return""}}},this.getShowLineNumbers=function(){return this.$showLineNumbers},this.$showFoldWidgets=!0,this.setShowFoldWidgets=function(e){e?r.addCssClass(this.element,"ace_folding-enabled"):r.removeCssClass(this.element,"ace_folding-enabled"),this.$showFoldWidgets=e,this.$padding=null},this.getShowFoldWidgets=function(){return this.$showFoldWidgets},this.$computePadding=function(){if(!this.element.firstChild)return{left:0,right:0};var e=r.computedStyle(this.element.firstChild);return this.$padding={},this.$padding.left=parseInt(e.paddingLeft)+1||0,this.$padding.right=parseInt(e.paddingRight)||0,this.$padding},this.getRegion=function(e){var t=this.$padding||this.$computePadding(),n=this.element.getBoundingClientRect();if(e.x<t.left+n.left)return"markers";if(this.$showFoldWidgets&&e.x>n.right-t.right)return"foldWidgets"}}).call(u.prototype),t.Gutter=u}),define("ace/mouse/dragdrop_handler",["require","exports","module","ace/lib/dom","ace/lib/event","ace/lib/useragent"],function(e,t,n){function f(e){function T(e,n){var r=Date.now(),i=!n||e.row!=n.row,s=!n||e.column!=n.column;if(!S||i||s)t.$blockScrolling+=1,t.moveCursorToPosition(e),t.$blockScrolling-=1,S=r,x={x:p,y:d};else{var o=l(x.x,x.y,p,d);o>a?S=null:r-S>=u&&(t.renderer.scrollCursorIntoView(),S=null)}}function N(e,n){var r=Date.now(),i=t.renderer.layerConfig.lineHeight,s=t.renderer.layerConfig.characterWidth,u=t.renderer.scroller.getBoundingClientRect(),a={x:{left:p-u.left,right:u.right-p},y:{top:d-u.top,bottom:u.bottom-d}},f=Math.min(a.x.left,a.x.right),l=Math.min(a.y.top,a.y.bottom),c={row:e.row,column:e.column};f/s<=2&&(c.column+=a.x.left<a.x.right?-3:2),l/i<=1&&(c.row+=a.y.top<a.y.bottom?-1:1);var h=e.row!=c.row,v=e.column!=c.column,m=!n||e.row!=n.row;h||v&&!m?E?r-E>=o&&t.renderer.scrollCursorIntoView(c):E=r:E=null}function C(){var e=g;g=t.renderer.screenToTextCoordinates(p,d),T(g,e),N(g,e)}function k(){m=t.selection.toOrientedRange(),h=t.session.addMarker(m,"ace_selection",t.getSelectionStyle()),t.clearSelection(),t.isFocused()&&t.renderer.$cursorLayer.setBlinking(!1),clearInterval(v),v=setInterval(C,20),y=0,i.addListener(document,"mousemove",O)}function L(){clearInterval(v),t.session.removeMarker(h),h=null,t.$blockScrolling+=1,t.selection.fromOrientedRange(m),t.$blockScrolling-=1,t.isFocused()&&!w&&t.renderer.$cursorLayer.setBlinking(!t.getReadOnly()),m=null,y=0,E=null,S=null,i.removeListener(document,"mousemove",O)}function O(){A==null&&(A=setTimeout(function(){A!=null&&h&&L()},20))}function M(e){var t=e.types;return!t||Array.prototype.some.call(t,function(e){return e=="text/plain"||e=="Text"})}function _(e){var t=["copy","copymove","all","uninitialized"],n=["move","copymove","linkmove","all","uninitialized"],r=s.isMac?e.altKey:e.ctrlKey,i="uninitialized";try{i=e.dataTransfer.effectAllowed.toLowerCase()}catch(e){}var o="none";return r&&t.indexOf(i)>=0?o="copy":n.indexOf(i)>=0?o="move":t.indexOf(i)>=0&&(o="copy"),o}var t=e.editor,n=r.createElement("img");n.src="data:image/gif;base64,R0lGODlhAQABAAAAACH5BAEKAAEALAAAAAABAAEAAAICTAEAOw==",s.isOpera&&(n.style.cssText="width:1px;height:1px;position:fixed;top:0;left:0;z-index:2147483647;opacity:0;");var f=["dragWait","dragWaitEnd","startDrag","dragReadyEnd","onMouseDrag"];f.forEach(function(t){e[t]=this[t]},this),t.addEventListener("mousedown",this.onMouseDown.bind(e));var c=t.container,h,p,d,v,m,g,y=0,b,w,E,S,x;this.onDragStart=function(e){if(this.cancelDrag||!c.draggable){var r=this;return setTimeout(function(){r.startSelect(),r.captureMouse(e)},0),e.preventDefault()}m=t.getSelectionRange();var i=e.dataTransfer;i.effectAllowed=t.getReadOnly()?"copy":"copyMove",s.isOpera&&(t.container.appendChild(n),n._top=n.offsetTop),i.setDragImage&&i.setDragImage(n,0,0),s.isOpera&&t.container.removeChild(n),i.clearData(),i.setData("Text",t.session.getTextRange()),w=!0,this.setState("drag")},this.onDragEnd=function(e){c.draggable=!1,w=!1,this.setState(null);if(!t.getReadOnly()){var n=e.dataTransfer.dropEffect;!b&&n=="move"&&t.session.remove(t.getSelectionRange()),t.renderer.$cursorLayer.setBlinking(!0)}this.editor.unsetStyle("ace_dragging")},this.onDragEnter=function(e){if(t.getReadOnly()||!M(e.dataTransfer))return;return h||k(),y++,e.dataTransfer.dropEffect=b=_(e),i.preventDefault(e)},this.onDragOver=function(e){if(t.getReadOnly()||!M(e.dataTransfer))return;return h||(k(),y++),A!==null&&(A=null),p=e.clientX,d=e.clientY,e.dataTransfer.dropEffect=b=_(e),i.preventDefault(e)},this.onDragLeave=function(e){y--;if(y<=0&&h)return L(),b=null,i.preventDefault(e)},this.onDrop=function(e){if(!h)return;var n=e.dataTransfer;if(w)switch(b){case"move":m.contains(g.row,g.column)?m={start:g,end:g}:m=t.moveText(m,g);break;case"copy":m=t.moveText(m,g,!0)}else{var r=n.getData("Text");m={start:g,end:t.session.insert(g,r)},t.focus(),b=null}return L(),i.preventDefault(e)},i.addListener(c,"dragstart",this.onDragStart.bind(e)),i.addListener(c,"dragend",this.onDragEnd.bind(e)),i.addListener(c,"dragenter",this.onDragEnter.bind(e)),i.addListener(c,"dragover",this.onDragOver.bind(e)),i.addListener(c,"dragleave",this.onDragLeave.bind(e)),i.addListener(c,"drop",this.onDrop.bind(e));var A=null}function l(e,t,n,r){return Math.sqrt(Math.pow(n-e,2)+Math.pow(r-t,2))}var r=e("../lib/dom"),i=e("../lib/event"),s=e("../lib/useragent"),o=200,u=200,a=5;(function(){this.dragWait=function(){var e=Date.now()-this.mousedownEvent.time;e>this.editor.getDragDelay()&&this.startDrag()},this.dragWaitEnd=function(){var e=this.editor.container;e.draggable=!1,this.startSelect(this.mousedownEvent.getDocumentPosition()),this.selectEnd()},this.dragReadyEnd=function(e){this.editor.renderer.$cursorLayer.setBlinking(!this.editor.getReadOnly()),this.editor.unsetStyle("ace_dragging"),this.dragWaitEnd()},this.startDrag=function(){this.cancelDrag=!1;var e=this.editor.container;e.draggable=!0,this.editor.renderer.$cursorLayer.setBlinking(!1),this.editor.setStyle("ace_dragging"),this.setState("dragReady")},this.onMouseDrag=function(e){var t=this.editor.container;if(s.isIE&&this.state=="dragReady"){var n=l(this.mousedownEvent.x,this.mousedownEvent.y,this.x,this.y);n>3&&t.dragDrop()}if(this.state==="dragWait"){var n=l(this.mousedownEvent.x,this.mousedownEvent.y,this.x,this.y);n>0&&(t.draggable=!1,this.startSelect(this.mousedownEvent.getDocumentPosition()))}},this.onMouseDown=function(e){if(!this.$dragEnabled)return;this.mousedownEvent=e;var t=this.editor,n=e.inSelection(),r=e.getButton(),i=e.domEvent.detail||1;if(i===1&&r===0&&n){if(e.editor.inMultiSelectMode&&(e.getAccelKey()||e.getShiftKey()))return;this.mousedownEvent.time=Date.now();var o=e.domEvent.target||e.domEvent.srcElement;"unselectable"in o&&(o.unselectable="on");if(t.getDragDelay()){if(s.isWebKit){this.cancelDrag=!0;var u=t.container;u.draggable=!0}this.setState("dragWait")}else this.startDrag();this.captureMouse(e,this.onMouseDrag.bind(this)),e.defaultPrevented=!0}}}).call(f.prototype),t.DragdropHandler=f}),define("ace/layer/marker",["require","exports","module","ace/range","ace/lib/dom"],function(e,t,n){var r=e("../range").Range,i=e("../lib/dom"),s=function(e){this.element=i.createElement("div"),this.element.className="ace_layer ace_marker-layer",e.appendChild(this.element)};(function(){this.$padding=0,this.setPadding=function(e){this.$padding=e},this.setSession=function(e){this.session=e},this.setMarkers=function(e){this.markers=e},this.update=function(e){var e=e||this.config;if(!e)return;this.config=e;var t=[];for(var n in this.markers){var r=this.markers[n];if(!r.range){r.update(t,this,this.session,e);continue}var s=r.range.clipRows(e.firstRow,e.lastRow);if(s.isEmpty())continue;s=s.toScreenRange(this.session);if(r.renderer){var o=this.$getTop(s.start.row,e),u=this.$padding+s.start.column*e.characterWidth;r.renderer(t,s,u,o,e)}else r.type=="fullLine"?this.drawFullLineMarker(t,s,r.clazz,e):r.type=="screenLine"?this.drawScreenLineMarker(t,s,r.clazz,e):s.isMultiLine()?r.type=="text"?this.drawTextMarker(t,s,r.clazz,e):this.drawMultiLineMarker(t,s,r.clazz,e):this.drawSingleLineMarker(t,s,r.clazz+" ace_start",e)}this.element=i.setInnerHtml(this.element,t.join(""))},this.$getTop=function(e,t){return(e-t.firstRowScreen)*t.lineHeight},this.drawTextMarker=function(e,t,n,i,s){var o=t.start.row,u=new r(o,t.start.column,o,this.session.getScreenLastRowColumn(o));this.drawSingleLineMarker(e,u,n+" ace_start",i,1,s),o=t.end.row,u=new r(o,0,o,t.end.column),this.drawSingleLineMarker(e,u,n,i,0,s);for(o=t.start.row+1;o<t.end.row;o++)u.start.row=o,u.end.row=o,u.end.column=this.session.getScreenLastRowColumn(o),this.drawSingleLineMarker(e,u,n,i,1,s)},this.drawMultiLineMarker=function(e,t,n,r,i){var s=this.$padding,o=r.lineHeight,u=this.$getTop(t.start.row,r),a=s+t.start.column*r.characterWidth;i=i||"",e.push("<div class='",n," ace_start' style='","height:",o,"px;","right:0;","top:",u,"px;","left:",a,"px;",i,"'></div>"),u=this.$getTop(t.end.row,r);var f=t.end.column*r.characterWidth;e.push("<div class='",n,"' style='","height:",o,"px;","width:",f,"px;","top:",u,"px;","left:",s,"px;",i,"'></div>"),o=(t.end.row-t.start.row-1)*r.lineHeight;if(o<0)return;u=this.$getTop(t.start.row+1,r),e.push("<div class='",n,"' style='","height:",o,"px;","right:0;","top:",u,"px;","left:",s,"px;",i,"'></div>")},this.drawSingleLineMarker=function(e,t,n,r,i,s){var o=r.lineHeight,u=(t.end.column+(i||0)-t.start.column)*r.characterWidth,a=this.$getTop(t.start.row,r),f=this.$padding+t.start.column*r.characterWidth;e.push("<div class='",n,"' style='","height:",o,"px;","width:",u,"px;","top:",a,"px;","left:",f,"px;",s||"","'></div>")},this.drawFullLineMarker=function(e,t,n,r,i){var s=this.$getTop(t.start.row,r),o=r.lineHeight;t.start.row!=t.end.row&&(o+=this.$getTop(t.end.row,r)-s),e.push("<div class='",n,"' style='","height:",o,"px;","top:",s,"px;","left:0;right:0;",i||"","'></div>")},this.drawScreenLineMarker=function(e,t,n,r,i){var s=this.$getTop(t.start.row,r),o=r.lineHeight;e.push("<div class='",n,"' style='","height:",o,"px;","top:",s,"px;","left:0;right:0;",i||"","'></div>")}}).call(s.prototype),t.Marker=s}),define("ace/mouse/mouse_event",["require","exports","module","ace/lib/event","ace/lib/useragent"],function(e,t,n){var r=e("../lib/event"),i=e("../lib/useragent"),s=t.MouseEvent=function(e,t){this.domEvent=e,this.editor=t,this.x=this.clientX=e.clientX,this.y=this.clientY=e.clientY,this.$pos=null,this.$inSelection=null,this.propagationStopped=!1,this.defaultPrevented=!1};(function(){this.stopPropagation=function(){r.stopPropagation(this.domEvent),this.propagationStopped=!0},this.preventDefault=function(){r.preventDefault(this.domEvent),this.defaultPrevented=!0},this.stop=function(){this.stopPropagation(),this.preventDefault()},this.getDocumentPosition=function(){return this.$pos?this.$pos:(this.$pos=this.editor.renderer.screenToTextCoordinates(this.clientX,this.clientY),this.$pos)},this.inSelection=function(){if(this.$inSelection!==null)return this.$inSelection;var e=this.editor,t=e.getSelectionRange();if(t.isEmpty())this.$inSelection=!1;else{var n=this.getDocumentPosition();this.$inSelection=t.contains(n.row,n.column)}return this.$inSelection},this.getButton=function(){return r.getButton(this.domEvent)},this.getShiftKey=function(){return this.domEvent.shiftKey},this.getAccelKey=i.isMac?function(){return this.domEvent.metaKey}:function(){return this.domEvent.ctrlKey}}).call(s.prototype)}),define("ace/layer/text",["require","exports","module","ace/lib/oop","ace/lib/dom","ace/lib/lang","ace/lib/useragent","ace/lib/event_emitter"],function(e,t,n){var r=e("../lib/oop"),i=e("../lib/dom"),s=e("../lib/lang"),o=e("../lib/useragent"),u=e("../lib/event_emitter").EventEmitter,a=function(e){this.element=i.createElement("div"),this.element.className="ace_layer ace_text-layer",e.appendChild(this.element),this.$updateEolChar=this.$updateEolChar.bind(this)};(function(){r.implement(this,u),this.EOF_CHAR="\xb6",this.EOL_CHAR_LF="\xac",this.EOL_CHAR_CRLF="\xa4",this.EOL_CHAR=this.EOL_CHAR_LF,this.TAB_CHAR="\u2192",this.SPACE_CHAR="\xb7",this.$padding=0,this.$updateEolChar=function(){var e=this.session.doc.getNewLineCharacter()=="\n"?this.EOL_CHAR_LF:this.EOL_CHAR_CRLF;if(this.EOL_CHAR!=e)return this.EOL_CHAR=e,!0},this.setPadding=function(e){this.$padding=e,this.element.style.padding="0 "+e+"px"},this.getLineHeight=function(){return this.$fontMetrics.$characterSize.height||0},this.getCharacterWidth=function(){return this.$fontMetrics.$characterSize.width||0},this.$setFontMetrics=function(e){this.$fontMetrics=e,this.$fontMetrics.on("changeCharacterSize",function(e){this._signal("changeCharacterSize",e)}.bind(this)),this.$pollSizeChanges()},this.checkForSizeChanges=function(){this.$fontMetrics.checkForSizeChanges()},this.$pollSizeChanges=function(){return this.$pollSizeChangesTimer=this.$fontMetrics.$pollSizeChanges()},this.setSession=function(e){this.session=e,this.$computeTabString()},this.showInvisibles=!1,this.setShowInvisibles=function(e){return this.showInvisibles==e?!1:(this.showInvisibles=e,this.$computeTabString(),!0)},this.displayIndentGuides=!0,this.setDisplayIndentGuides=function(e){return this.displayIndentGuides==e?!1:(this.displayIndentGuides=e,this.$computeTabString(),!0)},this.$tabStrings=[],this.onChangeTabSize=this.$computeTabString=function(){var e=this.session.getTabSize();this.tabSize=e;var t=this.$tabStrings=[0];for(var n=1;n<e+1;n++)this.showInvisibles?t.push("<span class='ace_invisible'>"+this.TAB_CHAR+s.stringRepeat("\xa0",n-1)+"</span>"):t.push(s.stringRepeat("\xa0",n));if(this.displayIndentGuides){this.$indentGuideRe=/\s\S| \t|\t |\s$/;var r="ace_indent-guide";if(this.showInvisibles){r+=" ace_invisible";var i=s.stringRepeat(this.SPACE_CHAR,this.tabSize),o=this.TAB_CHAR+s.stringRepeat("\xa0",this.tabSize-1)}else var i=s.stringRepeat("\xa0",this.tabSize),o=i;this.$tabStrings[" "]="<span class='"+r+"'>"+i+"</span>",this.$tabStrings[" "]="<span class='"+r+"'>"+o+"</span>"}},this.updateLines=function(e,t,n){(this.config.lastRow!=e.lastRow||this.config.firstRow!=e.firstRow)&&this.scrollLines(e),this.config=e;var r=Math.max(t,e.firstRow),s=Math.min(n,e.lastRow),o=this.element.childNodes,u=0;for(var a=e.firstRow;a<r;a++){var f=this.session.getFoldLine(a);if(f){if(f.containsRow(r)){r=f.start.row;break}a=f.end.row}u++}var a=r,f=this.session.getNextFoldLine(a),l=f?f.start.row:Infinity;for(;;){a>l&&(a=f.end.row+1,f=this.session.getNextFoldLine(a,f),l=f?f.start.row:Infinity);if(a>s)break;var c=o[u++];if(c){var h=[];this.$renderLine(h,a,!this.$useLineGroups(),a==l?f:!1),c.style.height=e.lineHeight*this.session.getRowLength(a)+"px",i.setInnerHtml(c,h.join(""))}a++}},this.scrollLines=function(e){var t=this.config;this.config=e;if(!t||t.lastRow<e.firstRow)return this.update(e);if(e.lastRow<t.firstRow)return this.update(e);var n=this.element;if(t.firstRow<e.firstRow)for(var r=this.session.getFoldedRowCount(t.firstRow,e.firstRow-1);r>0;r--)n.removeChild(n.firstChild);if(t.lastRow>e.lastRow)for(var r=this.session.getFoldedRowCount(e.lastRow+1,t.lastRow);r>0;r--)n.removeChild(n.lastChild);if(e.firstRow<t.firstRow){var i=this.$renderLinesFragment(e,e.firstRow,t.firstRow-1);n.firstChild?n.insertBefore(i,n.firstChild):n.appendChild(i)}if(e.lastRow>t.lastRow){var i=this.$renderLinesFragment(e,t.lastRow+1,e.lastRow);n.appendChild(i)}},this.$renderLinesFragment=function(e,t,n){var r=this.element.ownerDocument.createDocumentFragment(),s=t,o=this.session.getNextFoldLine(s),u=o?o.start.row:Infinity;for(;;){s>u&&(s=o.end.row+1,o=this.session.getNextFoldLine(s,o),u=o?o.start.row:Infinity);if(s>n)break;var a=i.createElement("div"),f=[];this.$renderLine(f,s,!1,s==u?o:!1),a.innerHTML=f.join("");if(this.$useLineGroups())a.className="ace_line_group",r.appendChild(a),a.style.height=e.lineHeight*this.session.getRowLength(s)+"px";else while(a.firstChild)r.appendChild(a.firstChild);s++}return r},this.update=function(e){this.config=e;var t=[],n=e.firstRow,r=e.lastRow,s=n,o=this.session.getNextFoldLine(s),u=o?o.start.row:Infinity;for(;;){s>u&&(s=o.end.row+1,o=this.session.getNextFoldLine(s,o),u=o?o.start.row:Infinity);if(s>r)break;this.$useLineGroups()&&t.push("<div class='ace_line_group' style='height:",e.lineHeight*this.session.getRowLength(s),"px'>"),this.$renderLine(t,s,!1,s==u?o:!1),this.$useLineGroups()&&t.push("</div>"),s++}this.element=i.setInnerHtml(this.element,t.join(""))},this.$textToken={text:!0,rparen:!0,lparen:!0},this.$renderToken=function(e,t,n,r){var i=this,o=/\t|&|<|( +)|([\x00-\x1f\x80-\xa0\u1680\u180E\u2000-\u200f\u2028\u2029\u202F\u205F\u3000\uFEFF])|[\u1100-\u115F\u11A3-\u11A7\u11FA-\u11FF\u2329-\u232A\u2E80-\u2E99\u2E9B-\u2EF3\u2F00-\u2FD5\u2FF0-\u2FFB\u3000-\u303E\u3041-\u3096\u3099-\u30FF\u3105-\u312D\u3131-\u318E\u3190-\u31BA\u31C0-\u31E3\u31F0-\u321E\u3220-\u3247\u3250-\u32FE\u3300-\u4DBF\u4E00-\uA48C\uA490-\uA4C6\uA960-\uA97C\uAC00-\uD7A3\uD7B0-\uD7C6\uD7CB-\uD7FB\uF900-\uFAFF\uFE10-\uFE19\uFE30-\uFE52\uFE54-\uFE66\uFE68-\uFE6B\uFF01-\uFF60\uFFE0-\uFFE6]/g,u=function(e,n,r,o,u){if(n)return i.showInvisibles?"<span class='ace_invisible'>"+s.stringRepeat(i.SPACE_CHAR,e.length)+"</span>":s.stringRepeat("\xa0",e.length);if(e=="&")return"&";if(e=="<")return"<";if(e==" "){var a=i.session.getScreenTabSize(t+o);return t+=a-1,i.$tabStrings[a]}if(e=="\u3000"){var f=i.showInvisibles?"ace_cjk ace_invisible":"ace_cjk",l=i.showInvisibles?i.SPACE_CHAR:"";return t+=1,"<span class='"+f+"' style='width:"+i.config.characterWidth*2+"px'>"+l+"</span>"}return r?"<span class='ace_invisible ace_invalid'>"+i.SPACE_CHAR+"</span>":(t+=1,"<span class='ace_cjk' style='width:"+i.config.characterWidth*2+"px'>"+e+"</span>")},a=r.replace(o,u);if(!this.$textToken[n.type]){var f="ace_"+n.type.replace(/\./g," ace_"),l="";n.type=="fold"&&(l=" style='width:"+n.value.length*this.config.characterWidth+"px;' "),e.push("<span class='",f,"'",l,">",a,"</span>")}else e.push(a);return t+r.length},this.renderIndentGuide=function(e,t,n){var r=t.search(this.$indentGuideRe);return r<=0||r>=n?t:t[0]==" "?(r-=r%this.tabSize,e.push(s.stringRepeat(this.$tabStrings[" "],r/this.tabSize)),t.substr(r)):t[0]==" "?(e.push(s.stringRepeat(this.$tabStrings[" "],r)),t.substr(r)):t},this.$renderWrappedLine=function(e,t,n,r){var i=0,s=0,o=n[0],u=0;for(var a=0;a<t.length;a++){var f=t[a],l=f.value;if(a==0&&this.displayIndentGuides){i=l.length,l=this.renderIndentGuide(e,l,o);if(!l)continue;i-=l.length}if(i+l.length<o)u=this.$renderToken(e,u,f,l),i+=l.length;else{while(i+l.length>=o)u=this.$renderToken(e,u,f,l.substring(0,o-i)),l=l.substring(o-i),i=o,r||e.push("</div>","<div class='ace_line' style='height:",this.config.lineHeight,"px'>"),s++,u=0,o=n[s]||Number.MAX_VALUE;l.length!=0&&(i+=l.length,u=this.$renderToken(e,u,f,l))}}},this.$renderSimpleLine=function(e,t){var n=0,r=t[0],i=r.value;this.displayIndentGuides&&(i=this.renderIndentGuide(e,i)),i&&(n=this.$renderToken(e,n,r,i));for(var s=1;s<t.length;s++)r=t[s],i=r.value,n=this.$renderToken(e,n,r,i)},this.$renderLine=function(e,t,n,r){!r&&r!=0&&(r=this.session.getFoldLine(t));if(r)var i=this.$getFoldLineTokens(t,r);else var i=this.session.getTokens(t);n||e.push("<div class='ace_line' style='height:",this.config.lineHeight*(this.$useLineGroups()?1:this.session.getRowLength(t)),"px'>");if(i.length){var s=this.session.getRowSplitData(t);s&&s.length?this.$renderWrappedLine(e,i,s,n):this.$renderSimpleLine(e,i)}this.showInvisibles&&(r&&(t=r.end.row),e.push("<span class='ace_invisible'>",t==this.session.getLength()-1?this.EOF_CHAR:this.EOL_CHAR,"</span>")),n||e.push("</div>")},this.$getFoldLineTokens=function(e,t){function i(e,t,n){var i=0,s=0;while(s+e[i].value.length<t){s+=e[i].value.length,i++;if(i==e.length)return}if(s!=t){var o=e[i].value.substring(t-s);o.length>n-t&&(o=o.substring(0,n-t)),r.push({type:e[i].type,value:o}),s=t+o.length,i+=1}while(s<n&&i<e.length){var o=e[i].value;o.length+s>n?r.push({type:e[i].type,value:o.substring(0,n-s)}):r.push(e[i]),s+=o.length,i+=1}}var n=this.session,r=[],s=n.getTokens(e);return t.walk(function(e,t,o,u,a){e!=null?r.push({type:"fold",value:e}):(a&&(s=n.getTokens(t)),s.length&&i(s,u,o))},t.end.row,this.session.getLine(t.end.row).length),r},this.$useLineGroups=function(){return this.session.getUseWrapMode()},this.destroy=function(){clearInterval(this.$pollSizeChangesTimer),this.$measureNode&&this.$measureNode.parentNode.removeChild(this.$measureNode),delete this.$measureNode}}).call(a.prototype),t.Text=a}),define("ace/tooltip",["require","exports","module","ace/lib/oop","ace/lib/dom"],function(e,t,n){function s(e){this.isOpen=!1,this.$element=null,this.$parentNode=e}var r=e("./lib/oop"),i=e("./lib/dom");(function(){this.$init=function(){return this.$element=i.createElement("div"),this.$element.className="ace_tooltip",this.$element.style.display="none",this.$parentNode.appendChild(this.$element),this.$element},this.getElement=function(){return this.$element||this.$init()},this.setText=function(e){i.setInnerText(this.getElement(),e)},this.setHtml=function(e){this.getElement().innerHTML=e},this.setPosition=function(e,t){this.getElement().style.left=e+"px",this.getElement().style.top=t+"px"},this.setClassName=function(e){i.addCssClass(this.getElement(),e)},this.show=function(e,t,n){e!=null&&this.setText(e),t!=null&&n!=null&&this.setPosition(t,n),this.isOpen||(this.getElement().style.display="block",this.isOpen=!0)},this.hide=function(){this.isOpen&&(this.getElement().style.display="none",this.isOpen=!1)},this.getHeight=function(){return this.getElement().offsetHeight},this.getWidth=function(){return this.getElement().offsetWidth}}).call(s.prototype),t.Tooltip=s}),define("ace/layer/cursor",["require","exports","module","ace/lib/dom"],function(e,t,n){var r=e("../lib/dom"),i,s=function(e){this.element=r.createElement("div"),this.element.className="ace_layer ace_cursor-layer",e.appendChild(this.element),i===undefined&&(i="opacity"in this.element),this.isVisible=!1,this.isBlinking=!0,this.blinkInterval=1e3,this.smoothBlinking=!1,this.cursors=[],this.cursor=this.addCursor(),r.addCssClass(this.element,"ace_hidden-cursors"),this.$updateCursors=this.$updateVisibility.bind(this)};(function(){this.$updateVisibility=function(e){var t=this.cursors;for(var n=t.length;n--;)t[n].style.visibility=e?"":"hidden"},this.$updateOpacity=function(e){var t=this.cursors;for(var n=t.length;n--;)t[n].style.opacity=e?"":"0"},this.$padding=0,this.setPadding=function(e){this.$padding=e},this.setSession=function(e){this.session=e},this.setBlinking=function(e){e!=this.isBlinking&&(this.isBlinking=e,this.restartTimer())},this.setBlinkInterval=function(e){e!=this.blinkInterval&&(this.blinkInterval=e,this.restartTimer())},this.setSmoothBlinking=function(e){e!=this.smoothBlinking&&!i&&(this.smoothBlinking=e,r.setCssClass(this.element,"ace_smooth-blinking",e),this.$updateCursors(!0),this.$updateCursors=(e?this.$updateOpacity:this.$updateVisibility).bind(this),this.restartTimer())},this.addCursor=function(){var e=r.createElement("div");return e.className="ace_cursor",this.element.appendChild(e),this.cursors.push(e),e},this.removeCursor=function(){if(this.cursors.length>1){var e=this.cursors.pop();return e.parentNode.removeChild(e),e}},this.hideCursor=function(){this.isVisible=!1,r.addCssClass(this.element,"ace_hidden-cursors"),this.restartTimer()},this.showCursor=function(){this.isVisible=!0,r.removeCssClass(this.element,"ace_hidden-cursors"),this.restartTimer()},this.restartTimer=function(){var e=this.$updateCursors;clearInterval(this.intervalId),clearTimeout(this.timeoutId),this.smoothBlinking&&r.removeCssClass(this.element,"ace_smooth-blinking"),e(!0);if(!this.isBlinking||!this.blinkInterval||!this.isVisible)return;this.smoothBlinking&&setTimeout(function(){r.addCssClass(this.element,"ace_smooth-blinking")}.bind(this));var t=function(){this.timeoutId=setTimeout(function(){e(!1)},.6*this.blinkInterval)}.bind(this);this.intervalId=setInterval(function(){e(!0),t()},this.blinkInterval),t()},this.getPixelPosition=function(e,t){if(!this.config||!this.session)return{left:0,top:0};e||(e=this.session.selection.getCursor());var n=this.session.documentToScreenPosition(e),r=this.$padding+n.column*this.config.characterWidth,i=(n.row-(t?this.config.firstRowScreen:0))*this.config.lineHeight;return{left:r,top:i}},this.update=function(e){this.config=e;var t=this.session.$selectionMarkers,n=0,r=0;if(t===undefined||t.length===0)t=[{cursor:null}];for(var n=0,i=t.length;n<i;n++){var s=this.getPixelPosition(t[n].cursor,!0);if((s.top>e.height+e.offset||s.top<0)&&n>1)continue;var o=(this.cursors[r++]||this.addCursor()).style;o.left=s.left+"px",o.top=s.top+"px",o.width=e.characterWidth+"px",o.height=e.lineHeight+"px"}while(this.cursors.length>r)this.removeCursor();var u=this.session.getOverwrite();this.$setOverwrite(u),this.$pixelPos=s,this.restartTimer()},this.$setOverwrite=function(e){e!=this.overwrite&&(this.overwrite=e,e?r.addCssClass(this.element,"ace_overwrite-cursors"):r.removeCssClass(this.element,"ace_overwrite-cursors"))},this.destroy=function(){clearInterval(this.intervalId),clearTimeout(this.timeoutId)}}).call(s.prototype),t.Cursor=s}),define("ace/mouse/default_gutter_handler",["require","exports","module","ace/lib/dom","ace/lib/oop","ace/lib/event","ace/tooltip"],function(e,t,n){function u(e){function l(){var r=u.getDocumentPosition().row,s=n.$annotations[r];if(!s)return c();var o=t.session.getLength();if(r==o){var a=t.renderer.pixelToScreenCoordinates(0,u.y).row,l=u.$pos;if(a>t.session.documentToScreenRow(l.row,l.column))return c()}if(f==s)return;f=s.text.join("<br/>"),i.setHtml(f),i.show(),t.on("mousewheel",c);if(e.$tooltipFollowsMouse)h(u);else{var p=n.$cells[r].element,d=p.getBoundingClientRect(),v=i.getElement().style;v.left=d.right+"px",v.top=d.bottom+"px"}}function c(){o&&(o=clearTimeout(o)),f&&(i.hide(),f=null,t.removeEventListener("mousewheel",c))}function h(e){i.setPosition(e.x,e.y)}var t=e.editor,n=t.renderer.$gutterLayer,i=new a(t.container);e.editor.setDefaultHandler("guttermousedown",function(r){if(!t.isFocused()||r.getButton()!=0)return;var i=n.getRegion(r);if(i=="foldWidgets")return;var s=r.getDocumentPosition().row,o=t.session.selection;if(r.getShiftKey())o.selectTo(s,0);else{if(r.domEvent.detail==2)return t.selectAll(),r.preventDefault();e.$clickSelection=t.selection.getLineRange(s)}return e.setState("selectByLines"),e.captureMouse(r),r.preventDefault()});var o,u,f;e.editor.setDefaultHandler("guttermousemove",function(t){var n=t.domEvent.target||t.domEvent.srcElement;if(r.hasCssClass(n,"ace_fold-widget"))return c();f&&e.$tooltipFollowsMouse&&h(t),u=t;if(o)return;o=setTimeout(function(){o=null,u&&!e.isMousePressed?l():c()},50)}),s.addListener(t.renderer.$gutter,"mouseout",function(e){u=null;if(!f||o)return;o=setTimeout(function(){o=null,c()},50)}),t.on("changeSession",c)}function a(e){o.call(this,e)}var r=e("../lib/dom"),i=e("../lib/oop"),s=e("../lib/event"),o=e("../tooltip").Tooltip;i.inherits(a,o),function(){this.setPosition=function(e,t){var n=window.innerWidth||document.documentElement.clientWidth,r=window.innerHeight||document.documentElement.clientHeight,i=this.getWidth(),s=this.getHeight();e+=15,t+=15,e+i>n&&(e-=e+i-n),t+s>r&&(t-=20+s),o.prototype.setPosition.call(this,e,t)}}.call(a.prototype),t.GutterHandler=u}),define("ace/scrollbar",["require","exports","module","ace/lib/oop","ace/lib/dom","ace/lib/event","ace/lib/event_emitter"],function(e,t,n){var r=e("./lib/oop"),i=e("./lib/dom"),s=e("./lib/event"),o=e("./lib/event_emitter").EventEmitter,u=function(e){this.element=i.createElement("div"),this.element.className="ace_scrollbar ace_scrollbar"+this.classSuffix,this.inner=i.createElement("div"),this.inner.className="ace_scrollbar-inner",this.element.appendChild(this.inner),e.appendChild(this.element),this.setVisible(!1),this.skipEvent=!1,s.addListener(this.element,"scroll",this.onScroll.bind(this)),s.addListener(this.element,"mousedown",s.preventDefault)};(function(){r.implement(this,o),this.setVisible=function(e){this.element.style.display=e?"":"none",this.isVisible=e}}).call(u.prototype);var a=function(e,t){u.call(this,e),this.scrollTop=0,t.$scrollbarWidth=this.width=i.scrollbarWidth(e.ownerDocument),this.inner.style.width=this.element.style.width=(this.width||15)+5+"px"};r.inherits(a,u),function(){this.classSuffix="-v",this.onScroll=function(){this.skipEvent||(this.scrollTop=this.element.scrollTop,this._emit("scroll",{data:this.scrollTop})),this.skipEvent=!1},this.getWidth=function(){return this.isVisible?this.width:0},this.setHeight=function(e){this.element.style.height=e+"px"},this.setInnerHeight=function(e){this.inner.style.height=e+"px"},this.setScrollHeight=function(e){this.inner.style.height=e+"px"},this.setScrollTop=function(e){this.scrollTop!=e&&(this.skipEvent=!0,this.scrollTop=this.element.scrollTop=e)}}.call(a.prototype);var f=function(e,t){u.call(this,e),this.scrollLeft=0,this.height=t.$scrollbarWidth,this.inner.style.height=this.element.style.height=(this.height||15)+5+"px"};r.inherits(f,u),function(){this.classSuffix="-h",this.onScroll=function(){this.skipEvent||(this.scrollLeft=this.element.scrollLeft,this._emit("scroll",{data:this.scrollLeft})),this.skipEvent=!1},this.getHeight=function(){return this.isVisible?this.height:0},this.setWidth=function(e){this.element.style.width=e+"px"},this.setInnerWidth=function(e){this.inner.style.width=e+"px"},this.setScrollWidth=function(e){this.inner.style.width=e+"px"},this.setScrollLeft=function(e){this.scrollLeft!=e&&(this.skipEvent=!0,this.scrollLeft=this.element.scrollLeft=e)}}.call(f.prototype),t.ScrollBar=a,t.ScrollBarV=a,t.ScrollBarH=f,t.VScrollBar=a,t.HScrollBar=f}),define("ace/mouse/default_handlers",["require","exports","module","ace/lib/dom","ace/lib/event","ace/lib/useragent"],function(e,t,n){function u(e){e.$clickSelection=null;var t=e.editor;t.setDefaultHandler("mousedown",this.onMouseDown.bind(e)),t.setDefaultHandler("dblclick",this.onDoubleClick.bind(e)),t.setDefaultHandler("tripleclick",this.onTripleClick.bind(e)),t.setDefaultHandler("quadclick",this.onQuadClick.bind(e)),t.setDefaultHandler("mousewheel",this.onMouseWheel.bind(e));var n=["select","startSelect","selectEnd","selectAllEnd","selectByWordsEnd","selectByLinesEnd","dragWait","dragWaitEnd","focusWait"];n.forEach(function(t){e[t]=this[t]},this),e.selectByLines=this.extendSelectionBy.bind(e,"getLineRange"),e.selectByWords=this.extendSelectionBy.bind(e,"getWordRange")}function a(e,t,n,r){return Math.sqrt(Math.pow(n-e,2)+Math.pow(r-t,2))}function f(e,t){if(e.start.row==e.end.row)var n=2*t.column-e.start.column-e.end.column;else if(e.start.row==e.end.row-1&&!e.start.column&&!e.end.column)var n=t.column-4;else var n=2*t.row-e.start.row-e.end.row;return n<0?{cursor:e.start,anchor:e.end}:{cursor:e.end,anchor:e.start}}var r=e("../lib/dom"),i=e("../lib/event"),s=e("../lib/useragent"),o=0;(function(){this.onMouseDown=function(e){var t=e.inSelection(),n=e.getDocumentPosition();this.mousedownEvent=e;var r=this.editor,i=e.getButton();if(i!==0){var s=r.getSelectionRange(),o=s.isEmpty();o&&r.selection.moveToPosition(n),r.textInput.onContextMenu(e.domEvent);return}if(t&&!r.isFocused()){r.focus();if(this.$focusTimout&&!this.$clickSelection&&!r.inMultiSelectMode){this.mousedownEvent.time=Date.now(),this.setState("focusWait"),this.captureMouse(e);return}}return this.captureMouse(e),!t||this.$clickSelection||e.getShiftKey()||r.inMultiSelectMode?this.startSelect(n):t&&(this.mousedownEvent.time=Date.now(),this.startSelect(n)),e.preventDefault()},this.startSelect=function(e){e=e||this.editor.renderer.screenToTextCoordinates(this.x,this.y);var t=this.editor,n=this.mousedownEvent.getShiftKey();n?t.selection.selectToPosition(e):this.$clickSelection||t.selection.moveToPosition(e),t.renderer.scroller.setCapture&&t.renderer.scroller.setCapture(),t.setStyle("ace_selecting"),this.setState("select")},this.select=function(){var e,t=this.editor,n=t.renderer.screenToTextCoordinates(this.x,this.y);if(this.$clickSelection){var r=this.$clickSelection.comparePoint(n);if(r==-1)e=this.$clickSelection.end;else if(r==1)e=this.$clickSelection.start;else{var i=f(this.$clickSelection,n);n=i.cursor,e=i.anchor}t.selection.setSelectionAnchor(e.row,e.column)}t.selection.selectToPosition(n),t.renderer.scrollCursorIntoView()},this.extendSelectionBy=function(e){var t,n=this.editor,r=n.renderer.screenToTextCoordinates(this.x,this.y),i=n.selection[e](r.row,r.column);if(this.$clickSelection){var s=this.$clickSelection.comparePoint(i.start),o=this.$clickSelection.comparePoint(i.end);if(s==-1&&o<=0){t=this.$clickSelection.end;if(i.end.row!=r.row||i.end.column!=r.column)r=i.start}else if(o==1&&s>=0){t=this.$clickSelection.start;if(i.start.row!=r.row||i.start.column!=r.column)r=i.end}else if(s==-1&&o==1)r=i.end,t=i.start;else{var u=f(this.$clickSelection,r);r=u.cursor,t=u.anchor}n.selection.setSelectionAnchor(t.row,t.column)}n.selection.selectToPosition(r),n.renderer.scrollCursorIntoView()},this.selectEnd=this.selectAllEnd=this.selectByWordsEnd=this.selectByLinesEnd=function(){this.editor.unsetStyle("ace_selecting"),this.editor.renderer.scroller.releaseCapture&&this.editor.renderer.scroller.releaseCapture()},this.focusWait=function(){var e=a(this.mousedownEvent.x,this.mousedownEvent.y,this.x,this.y),t=Date.now();(e>o||t-this.mousedownEvent.time>this.$focusTimout)&&this.startSelect(this.mousedownEvent.getDocumentPosition())},this.onDoubleClick=function(e){var t=e.getDocumentPosition(),n=this.editor,r=n.session,i=r.getBracketRange(t);i?(i.isEmpty()&&(i.start.column--,i.end.column++),this.setState("select")):(i=n.selection.getWordRange(t.row,t.column),this.setState("selectByWords")),this.$clickSelection=i,this[this.state]&&this[this.state](e)},this.onTripleClick=function(e){var t=e.getDocumentPosition(),n=this.editor;this.setState("selectByLines"),this.$clickSelection=n.selection.getLineRange(t.row),this[this.state]&&this[this.state](e)},this.onQuadClick=function(e){var t=this.editor;t.selectAll(),this.$clickSelection=t.getSelectionRange(),this.setState("selectAll")},this.onMouseWheel=function(e){if(e.getAccelKey())return;e.getShiftKey()&&e.wheelY&&!e.wheelX&&(e.wheelX=e.wheelY,e.wheelY=0);var t=e.domEvent.timeStamp,n=t-(this.$lastScrollTime||0),r=this.editor,i=r.renderer.isScrollableBy(e.wheelX*e.speed,e.wheelY*e.speed);if(i||n<200)return this.$lastScrollTime=t,r.renderer.scrollBy(e.wheelX*e.speed,e.wheelY*e.speed),e.stop()}}).call(u.prototype),t.DefaultHandlers=u}),define("ace/renderloop",["require","exports","module","ace/lib/event"],function(e,t,n){var r=e("./lib/event"),i=function(e,t){this.onRender=e,this.pending=!1,this.changes=0,this.window=t||window};(function(){this.schedule=function(e){this.changes=this.changes|e;if(!this.pending&&this.changes){this.pending=!0;var t=this;r.nextFrame(function(){t.pending=!1;var e;while(e=t.changes)t.changes=0,t.onRender(e)},this.window)}}}).call(i.prototype),t.RenderLoop=i}),define("ace/mouse/mouse_handler",["require","exports","module","ace/lib/event","ace/lib/useragent","ace/mouse/default_handlers","ace/mouse/default_gutter_handler","ace/mouse/mouse_event","ace/mouse/dragdrop_handler","ace/config"],function(e,t,n){var r=e("../lib/event"),i=e("../lib/useragent"),s=e("./default_handlers").DefaultHandlers,o=e("./default_gutter_handler").GutterHandler,u=e("./mouse_event").MouseEvent,a=e("./dragdrop_handler").DragdropHandler,f=e("../config"),l=function(e){this.editor=e,new s(this),new o(this),new a(this);var t=e.renderer.getMouseEventTarget();r.addListener(t,"click",this.onMouseEvent.bind(this,"click")),r.addListener(t,"mousemove",this.onMouseMove.bind(this,"mousemove")),r.addMultiMouseDownListener(t,[300,300,250],this,"onMouseEvent"),e.renderer.scrollBarV&&(r.addMultiMouseDownListener(e.renderer.scrollBarV.inner,[300,300,250],this,"onMouseEvent"),r.addMultiMouseDownListener(e.renderer.scrollBarH.inner,[300,300,250],this,"onMouseEvent")),r.addMouseWheelListener(e.container,this.onMouseWheel.bind(this,"mousewheel"));var n=e.renderer.$gutter;r.addListener(n,"mousedown",this.onMouseEvent.bind(this,"guttermousedown")),r.addListener(n,"click",this.onMouseEvent.bind(this,"gutterclick")),r.addListener(n,"dblclick",this.onMouseEvent.bind(this,"gutterdblclick")),r.addListener(n,"mousemove",this.onMouseEvent.bind(this,"guttermousemove")),r.addListener(t,"mousedown",function(t){e.focus()}),r.addListener(n,"mousedown",function(t){return e.focus(),r.preventDefault(t)})};(function(){this.onMouseEvent=function(e,t){this.editor._emit(e,new u(t,this.editor))},this.onMouseMove=function(e,t){var n=this.editor._eventRegistry&&this.editor._eventRegistry.mousemove;if(!n||!n.length)return;this.editor._emit(e,new u(t,this.editor))},this.onMouseWheel=function(e,t){var n=new u(t,this.editor);n.speed=this.$scrollSpeed*2,n.wheelX=t.wheelX,n.wheelY=t.wheelY,this.editor._emit(e,n)},this.setState=function(e){this.state=e},this.captureMouse=function(e,t){this.x=e.x,this.y=e.y,this.isMousePressed=!0;var n=this.editor.renderer;n.$keepTextAreaAtCursor&&(n.$keepTextAreaAtCursor=null);var s=this,o=function(e){s.x=e.clientX,s.y=e.clientY,t&&t(e),s.mouseEvent=new u(e,s.editor),s.$mouseMoved=!0},a=function(e){clearInterval(l),f(),s[s.state+"End"]&&s[s.state+"End"](e),s.$clickSelection=null,n.$keepTextAreaAtCursor==null&&(n.$keepTextAreaAtCursor=!0,n.$moveTextAreaToCursor()),s.isMousePressed=!1,s.$onCaptureMouseMove=s.releaseMouse=null,s.onMouseEvent("mouseup",e)},f=function(){s[s.state]&&s[s.state](),s.$mouseMoved=!1};if(i.isOldIE&&e.domEvent.type=="dblclick")return setTimeout(function(){a(e)});s.$onCaptureMouseMove=o,s.releaseMouse=r.capture(this.editor.container,o,a);var l=setInterval(f,20)},this.releaseMouse=null}).call(l.prototype),f.defineOptions(l.prototype,"mouseHandler",{scrollSpeed:{initialValue:2},dragDelay:{initialValue:150},dragEnabled:{initialValue:!0},focusTimout:{initialValue:0},tooltipFollowsMouse:{initialValue:!0}}),t.MouseHandler=l}),define("ace/layer/font_metrics",["require","exports","module","ace/lib/oop","ace/lib/dom","ace/lib/lang","ace/lib/event_emitter"],function(e,t,n){var r=e("../lib/oop"),i=e("../lib/dom"),s=e("../lib/lang"),o=e("../lib/event_emitter").EventEmitter,u=0,a=t.FontMetrics=function(e,t){this.el=i.createElement("div"),this.$setMeasureNodeStyles(this.el.style,!0),this.$main=i.createElement("div"),this.$setMeasureNodeStyles(this.$main.style),this.$measureNode=i.createElement("div"),this.$setMeasureNodeStyles(this.$measureNode.style),this.el.appendChild(this.$main),this.el.appendChild(this.$measureNode),e.appendChild(this.el),u||this.$testFractionalRect(),this.$measureNode.textContent=s.stringRepeat("X",u),this.$characterSize={width:0,height:0},this.checkForSizeChanges()};(function(){r.implement(this,o),this.$characterSize={width:0,height:0},this.$testFractionalRect=function(){var e=i.createElement("div");this.$setMeasureNodeStyles(e.style),e.style.width="0.2px",document.documentElement.appendChild(e);var t=e.getBoundingClientRect().width;t>0&&t<1?u=1:u=100,e.parentNode.removeChild(e)},this.$setMeasureNodeStyles=function(e,t){e.width=e.height="auto",e.left=e.top="-100px",e.visibility="hidden",e.position="fixed",e.whiteSpace="pre",e.font="inherit",e.overflow=t?"hidden":"visible"},this.checkForSizeChanges=function(){var e=this.$measureSizes();if(e&&(this.$characterSize.width!==e.width||this.$characterSize.height!==e.height)){this.$measureNode.style.fontWeight="bold";var t=this.$measureSizes();this.$measureNode.style.fontWeight="",this.$characterSize=e,this.charSizes=Object.create(null),this.allowBoldFonts=t&&t.width===e.width&&t.height===e.height,this._emit("changeCharacterSize",{data:e})}},this.$pollSizeChanges=function(){if(this.$pollSizeChangesTimer)return this.$pollSizeChangesTimer;var e=this;return this.$pollSizeChangesTimer=setInterval(function(){e.checkForSizeChanges()},500)},this.setPolling=function(e){e?this.$pollSizeChanges():this.$pollSizeChangesTimer&&this.$pollSizeChangesTimer},this.$measureSizes=function(){var e=this.$measureNode.getBoundingClientRect(),t={height:e.height,width:e.width/u};return t.width===0||t.height===0?null:t},this.$measureCharWidth=function(e){this.$main.textContent=s.stringRepeat(e,u);var t=this.$main.getBoundingClientRect();return t.width/u},this.getCharacterWidth=function(e){var t=this.charSizes[e];return t===undefined&&(this.charSizes[e]=this.$measureCharWidth(e)/this.$characterSize.width),t},this.destroy=function(){clearInterval(this.$pollSizeChangesTimer),this.el&&this.el.parentNode&&this.el.parentNode.removeChild(this.el)}}).call(a.prototype)}),define("ace/keyboard/textinput",["require","exports","module","ace/lib/event","ace/lib/useragent","ace/lib/dom","ace/lib/lang"],function(e,t,n){var r=e("../lib/event"),i=e("../lib/useragent"),s=e("../lib/dom"),o=e("../lib/lang"),u=i.isChrome<18,a=function(e,t){function b(e){if(h)return;if(k)t=0,r=e?0:n.value.length-1;else var t=e?2:1,r=2;try{n.setSelectionRange(t,r)}catch(i){}}function w(){if(h)return;n.value=a,i.isWebKit&&y.schedule()}function F(){setTimeout(function(){p&&(n.style.cssText=p,p=""),t.renderer.$keepTextAreaAtCursor==null&&(t.renderer.$keepTextAreaAtCursor=!0,t.renderer.$moveTextAreaToCursor())},0)}var n=s.createElement("textarea");n.className="ace_text-input",i.isTouchPad&&n.setAttribute("x-palm-disable-auto-cap",!0),n.wrap="off",n.autocorrect="off",n.autocapitalize="off",n.spellcheck=!1,n.style.opacity="0",e.insertBefore(n,e.firstChild);var a="\x01\x01",f=!1,l=!1,c=!1,h=!1,p="",d=!0;try{var v=document.activeElement===n}catch(m){}r.addListener(n,"blur",function(){t.onBlur(),v=!1}),r.addListener(n,"focus",function(){v=!0,t.onFocus(),b()}),this.focus=function(){n.focus()},this.blur=function(){n.blur()},this.isFocused=function(){return v};var g=o.delayedCall(function(){v&&b(d)}),y=o.delayedCall(function(){h||(n.value=a,v&&b())});i.isWebKit||t.addEventListener("changeSelection",function(){t.selection.isEmpty()!=d&&(d=!d,g.schedule())}),w(),v&&t.onFocus();var E=function(e){return e.selectionStart===0&&e.selectionEnd===e.value.length};!n.setSelectionRange&&n.createTextRange&&(n.setSelectionRange=function(e,t){var n=this.createTextRange();n.collapse(!0),n.moveStart("character",e),n.moveEnd("character",t),n.select()},E=function(e){try{var t=e.ownerDocument.selection.createRange()}catch(n){}return!t||t.parentElement()!=e?!1:t.text==e.value});if(i.isOldIE){var S=!1,x=function(e){if(S)return;var t=n.value;if(h||!t||t==a)return;if(e&&t==a[0])return T.schedule();A(t),S=!0,w(),S=!1},T=o.delayedCall(x);r.addListener(n,"propertychange",x);var N={13:1,27:1};r.addListener(n,"keyup",function(e){h&&(!n.value||N[e.keyCode])&&setTimeout(B,0);if((n.value.charCodeAt(0)||0)<129)return T.call();h?H():P()}),r.addListener(n,"keydown",function(e){T.schedule(50)})}var C=function(e){f?f=!1:l?l=!1:E(n)?(t.selectAll(),b()):k&&b(t.selection.isEmpty())},k=null;this.setInputHandler=function(e){k=e},this.getInputHandler=function(){return k};var L=!1,A=function(e){k&&(e=k(e),k=null),c?(b(),e&&t.onPaste(e),c=!1):e==a.charAt(0)?L?t.execCommand("del",{source:"ace"}):t.execCommand("backspace",{source:"ace"}):(e.substring(0,2)==a?e=e.substr(2):e.charAt(0)==a.charAt(0)?e=e.substr(1):e.charAt(e.length-1)==a.charAt(0)&&(e=e.slice(0,-1)),e.charAt(e.length-1)==a.charAt(0)&&(e=e.slice(0,-1)),e&&t.onTextInput(e)),L&&(L=!1)},O=function(e){if(h)return;var t=n.value;A(t),w()},M=function(e){var i=t.getCopyText();if(!i){r.preventDefault(e);return}var s=e.clipboardData||window.clipboardData;if(s&&!u){var o=s.setData("Text",i);o&&(t.onCut(),r.preventDefault(e))}o||(f=!0,n.value=i,n.select(),setTimeout(function(){f=!1,w(),b(),t.onCut()}))},_=function(e){var i=t.getCopyText();if(!i){r.preventDefault(e);return}var s=e.clipboardData||window.clipboardData;if(s&&!u){var o=s.setData("Text",i);o&&(t.onCopy(),r.preventDefault(e))}o||(l=!0,n.value=i,n.select(),setTimeout(function(){l=!1,w(),b(),t.onCopy()}))},D=function(e){var s=e.clipboardData||window.clipboardData;if(s){var o=s.getData("Text");o&&t.onPaste(o),i.isIE&&setTimeout(b),r.preventDefault(e)}else n.value="",c=!0};r.addCommandKeyListener(n,t.onCommandKey.bind(t)),r.addListener(n,"select",C),r.addListener(n,"input",O),r.addListener(n,"cut",M),r.addListener(n,"copy",_),r.addListener(n,"paste",D),(!("oncut"in n)||!("oncopy"in n)||!("onpaste"in n))&&r.addListener(e,"keydown",function(e){if(i.isMac&&!e.metaKey||!e.ctrlKey)return;switch(e.keyCode){case 67:_(e);break;case 86:D(e);break;case 88:M(e)}});var P=function(e){if(h||!t.onCompositionStart)return;h={},t.onCompositionStart(),setTimeout(H,0),t.on("mousedown",B),t.selection.isEmpty()||(t.insert(""),t.session.markUndoGroup(),t.selection.clearSelection()),t.session.markUndoGroup()},H=function(){if(!h||!t.onCompositionUpdate)return;var e=n.value.replace(/\x01/g,"");if(h.lastValue===e)return;t.onCompositionUpdate(e),h.lastValue&&t.undo(),h.lastValue=e;if(h.lastValue){var r=t.selection.getRange();t.insert(h.lastValue),t.session.markUndoGroup(),h.range=t.selection.getRange(),t.selection.setRange(r),t.selection.clearSelection()}},B=function(e){if(!t.onCompositionEnd)return;var r=h;h=!1;var i=setTimeout(function(){i=null;var e=n.value.replace(/\x01/g,"");if(h)return;e==r.lastValue?w():!r.lastValue&&e&&(w(),A(e))});k=function(n){return i&&clearTimeout(i),n=n.replace(/\x01/g,""),n==r.lastValue?"":(r.lastValue&&i&&t.undo(),n)},t.onCompositionEnd(),t.removeListener("mousedown",B),e.type=="compositionend"&&r.range&&t.selection.setRange(r.range)},j=o.delayedCall(H,50);r.addListener(n,"compositionstart",P),i.isGecko?r.addListener(n,"text",function(){j.schedule()}):(r.addListener(n,"keyup",function(){j.schedule()}),r.addListener(n,"keydown",function(){j.schedule()})),r.addListener(n,"compositionend",B),this.getElement=function(){return n},this.setReadOnly=function(e){n.readOnly=e},this.onContextMenu=function(e){L=!0,p||(p=n.style.cssText),n.style.cssText="z-index:100000;"+(i.isIE?"opacity:0.1;":""),b(t.selection.isEmpty()),t._emit("nativecontextmenu",{target:t,domEvent:e});var o=t.container.getBoundingClientRect(),u=s.computedStyle(t.container),a=o.top+(parseInt(u.borderTopWidth)||0),f=o.left+(parseInt(o.borderLeftWidth)||0),l=o.bottom-a-n.clientHeight,c=function(e){n.style.left=e.clientX-f-2+"px",n.style.top=Math.min(e.clientY-a-2,l)+"px"};c(e);if(e.type!="mousedown")return;t.renderer.$keepTextAreaAtCursor&&(t.renderer.$keepTextAreaAtCursor=null),i.isWin&&r.capture(t.container,c,F)},this.onContextMenuClose=F;if(!i.isGecko||i.isMac){var I=function(e){t.textInput.onContextMenu(e),F()};r.addListener(t.renderer.scroller,"contextmenu",I),r.addListener(n,"contextmenu",I)}};t.TextInput=a}),define("ace/lib/lang",["require","exports","module"],function(e,t,n){t.last=function(e){return e[e.length-1]},t.stringReverse=function(e){return e.split("").reverse().join("")},t.stringRepeat=function(e,t){var n="";while(t>0){t&1&&(n+=e);if(t>>=1)e+=e}return n};var r=/^\s\s*/,i=/\s\s*$/;t.stringTrimLeft=function(e){return e.replace(r,"")},t.stringTrimRight=function(e){return e.replace(i,"")},t.copyObject=function(e){var t={};for(var n in e)t[n]=e[n];return t},t.copyArray=function(e){var t=[];for(var n=0,r=e.length;n<r;n++)e[n]&&typeof e[n]=="object"?t[n]=this.copyObject(e[n]):t[n]=e[n];return t},t.deepCopy=function(e){if(typeof e!="object"||!e)return e;var n=e.constructor;if(n===RegExp)return e;var r=n();for(var i in e)typeof e[i]=="object"?r[i]=t.deepCopy(e[i]):r[i]=e[i];return r},t.arrayToMap=function(e){var t={};for(var n=0;n<e.length;n++)t[e[n]]=1;return t},t.createMap=function(e){var t=Object.create(null);for(var n in e)t[n]=e[n];return t},t.arrayRemove=function(e,t){for(var n=0;n<=e.length;n++)t===e[n]&&e.splice(n,1)},t.escapeRegExp=function(e){return e.replace(/([.*+?^${}()|[\]\/\\])/g,"\\$1")},t.escapeHTML=function(e){return e.replace(/&/g,"&").replace(/"/g,""").replace(/'/g,"'").replace(/</g,"<")},t.getMatchOffsets=function(e,t){var n=[];return e.replace(t,function(e){n.push({offset:arguments[arguments.length-2],length:e.length})}),n},t.deferredCall=function(e){var t=null,n=function(){t=null,e()},r=function(e){return r.cancel(),t=setTimeout(n,e||0),r};return r.schedule=r,r.call=function(){return this.cancel(),e(),r},r.cancel=function(){return clearTimeout(t),t=null,r},r.isPending=function(){return t},r},t.delayedCall=function(e,t){var n=null,r=function(){n=null,e()},i=function(e){n==null&&(n=setTimeout(r,e||t))};return i.delay=function(e){n&&clearTimeout(n),n=setTimeout(r,e||t)},i.schedule=i,i.call=function(){this.cancel(),e()},i.cancel=function(){n&&clearTimeout(n),n=null},i.isPending=function(){return n},i}}),define("ace/multi_select",["require","exports","module","ace/range_list","ace/range","ace/selection","ace/mouse/multi_select_handler","ace/lib/event","ace/lib/lang","ace/commands/multi_select_commands","ace/search","ace/edit_session","ace/editor","ace/config"],function(e,t,n){function h(e,t,n){return c.$options.wrap=!0,c.$options.needle=t,c.$options.backwards=n==-1,c.find(e)}function v(e,t){return e.row==t.row&&e.column==t.column}function m(e){if(e.$multiselectOnSessionChange)return;e.$onAddRange=e.$onAddRange.bind(e),e.$onRemoveRange=e.$onRemoveRange.bind(e),e.$onMultiSelect=e.$onMultiSelect.bind(e),e.$onSingleSelect=e.$onSingleSelect.bind(e),e.$multiselectOnSessionChange=t.onSessionChange.bind(e),e.$multiselectOnSessionChange(e),e.on("changeSession",e.$multiselectOnSessionChange),e.on("mousedown",o),e.commands.addCommands(f.defaultCommands),g(e)}function g(e){function r(t){n&&(e.renderer.setMouseCursor(""),n=!1)}var t=e.textInput.getElement(),n=!1;u.addListener(t,"keydown",function(t){t.keyCode==18&&!(t.ctrlKey||t.shiftKey||t.metaKey)?n||(e.renderer.setMouseCursor("crosshair"),n=!0):n&&r()}),u.addListener(t,"keyup",r),u.addListener(t,"blur",r)}var r=e("./range_list").RangeList,i=e("./range").Range,s=e("./selection").Selection,o=e("./mouse/multi_select_handler").onMouseDown,u=e("./lib/event"),a=e("./lib/lang"),f=e("./commands/multi_select_commands");t.commands=f.defaultCommands.concat(f.multiSelectCommands);var l=e("./search").Search,c=new l,p=e("./edit_session").EditSession;(function(){this.getSelectionMarkers=function(){return this.$selectionMarkers}}).call(p.prototype),function(){this.ranges=null,this.rangeList=null,this.addRange=function(e,t){if(!e)return;if(!this.inMultiSelectMode&&this.rangeCount==0){var n=this.toOrientedRange();this.rangeList.add(n),this.rangeList.add(e);if(this.rangeList.ranges.length!=2)return this.rangeList.removeAll(),t||this.fromOrientedRange(e);this.rangeList.removeAll(),this.rangeList.add(n),this.$onAddRange(n)}e.cursor||(e.cursor=e.end);var r=this.rangeList.add(e);return this.$onAddRange(e),r.length&&this.$onRemoveRange(r),this.rangeCount>1&&!this.inMultiSelectMode&&(this._signal("multiSelect"),this.inMultiSelectMode=!0,this.session.$undoSelect=!1,this.rangeList.attach(this.session)),t||this.fromOrientedRange(e)},this.toSingleRange=function(e){e=e||this.ranges[0];var t=this.rangeList.removeAll();t.length&&this.$onRemoveRange(t),e&&this.fromOrientedRange(e)},this.substractPoint=function(e){var t=this.rangeList.substractPoint(e);if(t)return this.$onRemoveRange(t),t[0]},this.mergeOverlappingRanges=function(){var e=this.rangeList.merge();e.length?this.$onRemoveRange(e):this.ranges[0]&&this.fromOrientedRange(this.ranges[0])},this.$onAddRange=function(e){this.rangeCount=this.rangeList.ranges.length,this.ranges.unshift(e),this._signal("addRange",{range:e})},this.$onRemoveRange=function(e){this.rangeCount=this.rangeList.ranges.length;if(this.rangeCount==1&&this.inMultiSelectMode){var t=this.rangeList.ranges.pop();e.push(t),this.rangeCount=0}for(var n=e.length;n--;){var r=this.ranges.indexOf(e[n]);this.ranges.splice(r,1)}this._signal("removeRange",{ranges:e}),this.rangeCount==0&&this.inMultiSelectMode&&(this.inMultiSelectMode=!1,this._signal("singleSelect"),this.session.$undoSelect=!0,this.rangeList.detach(this.session)),t=t||this.ranges[0],t&&!t.isEqual(this.getRange())&&this.fromOrientedRange(t)},this.$initRangeList=function(){if(this.rangeList)return;this.rangeList=new r,this.ranges=[],this.rangeCount=0},this.getAllRanges=function(){return this.rangeCount?this.rangeList.ranges.concat():[this.getRange()]},this.splitIntoLines=function(){if(this.rangeCount>1){var e=this.rangeList.ranges,t=e[e.length-1],n=i.fromPoints(e[0].start,t.end);this.toSingleRange(),this.setSelectionRange(n,t.cursor==t.start)}else{var n=this.getRange(),r=this.isBackwards(),s=n.start.row,o=n.end.row;if(s==o){if(r)var u=n.end,a=n.start;else var u=n.start,a=n.end;this.addRange(i.fromPoints(a,a)),this.addRange(i.fromPoints(u,u));return}var f=[],l=this.getLineRange(s,!0);l.start.column=n.start.column,f.push(l);for(var c=s+1;c<o;c++)f.push(this.getLineRange(c,!0));l=this.getLineRange(o,!0),l.end.column=n.end.column,f.push(l),f.forEach(this.addRange,this)}},this.toggleBlockSelection=function(){if(this.rangeCount>1){var e=this.rangeList.ranges,t=e[e.length-1],n=i.fromPoints(e[0].start,t.end);this.toSingleRange(),this.setSelectionRange(n,t.cursor==t.start)}else{var r=this.session.documentToScreenPosition(this.selectionLead),s=this.session.documentToScreenPosition(this.selectionAnchor),o=this.rectangularRangeBlock(r,s);o.forEach(this.addRange,this)}},this.rectangularRangeBlock=function(e,t,n){var r=[],s=e.column<t.column;if(s)var o=e.column,u=t.column;else var o=t.column,u=e.column;var a=e.row<t.row;if(a)var f=e.row,l=t.row;else var f=t.row,l=e.row;o<0&&(o=0),f<0&&(f=0),f==l&&(n=!0);for(var c=f;c<=l;c++){var h=i.fromPoints(this.session.screenToDocumentPosition(c,o),this.session.screenToDocumentPosition(c,u));if(h.isEmpty()){if(p&&v(h.end,p))break;var p=h.end}h.cursor=s?h.start:h.end,r.push(h)}a&&r.reverse();if(!n){var d=r.length-1;while(r[d].isEmpty()&&d>0)d--;if(d>0){var m=0;while(r[m].isEmpty())m++}for(var g=d;g>=m;g--)r[g].isEmpty()&&r.splice(g,1)}return r}}.call(s.prototype);var d=e("./editor").Editor;(function(){this.updateSelectionMarkers=function(){this.renderer.updateCursor(),this.renderer.updateBackMarkers()},this.addSelectionMarker=function(e){e.cursor||(e.cursor=e.end);var t=this.getSelectionStyle();return e.marker=this.session.addMarker(e,"ace_selection",t),this.session.$selectionMarkers.push(e),this.session.selectionMarkerCount=this.session.$selectionMarkers.length,e},this.removeSelectionMarker=function(e){if(!e.marker)return;this.session.removeMarker(e.marker);var t=this.session.$selectionMarkers.indexOf(e);t!=-1&&this.session.$selectionMarkers.splice(t,1),this.session.selectionMarkerCount=this.session.$selectionMarkers.length},this.removeSelectionMarkers=function(e){var t=this.session.$selectionMarkers;for(var n=e.length;n--;){var r=e[n];if(!r.marker)continue;this.session.removeMarker(r.marker);var i=t.indexOf(r);i!=-1&&t.splice(i,1)}this.session.selectionMarkerCount=t.length},this.$onAddRange=function(e){this.addSelectionMarker(e.range),this.renderer.updateCursor(),this.renderer.updateBackMarkers()},this.$onRemoveRange=function(e){this.removeSelectionMarkers(e.ranges),this.renderer.updateCursor(),this.renderer.updateBackMarkers()},this.$onMultiSelect=function(e){if(this.inMultiSelectMode)return;this.inMultiSelectMode=!0,this.setStyle("ace_multiselect"),this.keyBinding.addKeyboardHandler(f.keyboardHandler),this.commands.setDefaultHandler("exec",this.$onMultiSelectExec),this.renderer.updateCursor(),this.renderer.updateBackMarkers()},this.$onSingleSelect=function(e){if(this.session.multiSelect.inVirtualMode)return;this.inMultiSelectMode=!1,this.unsetStyle("ace_multiselect"),this.keyBinding.removeKeyboardHandler(f.keyboardHandler),this.commands.removeDefaultHandler("exec",this.$onMultiSelectExec),this.renderer.updateCursor(),this.renderer.updateBackMarkers(),this._emit("changeSelection")},this.$onMultiSelectExec=function(e){var t=e.command,n=e.editor;if(!n.multiSelect)return;if(!t.multiSelectAction){var r=t.exec(n,e.args||{});n.multiSelect.addRange(n.multiSelect.toOrientedRange()),n.multiSelect.mergeOverlappingRanges()}else t.multiSelectAction=="forEach"?r=n.forEachSelection(t,e.args):t.multiSelectAction=="forEachLine"?r=n.forEachSelection(t,e.args,!0):t.multiSelectAction=="single"?(n.exitMultiSelectMode(),r=t.exec(n,e.args||{})):r=t.multiSelectAction(n,e.args||{});return r},this.forEachSelection=function(e,t,n){if(this.inVirtualSelectionMode)return;var r=this.session,i=this.selection,o=i.rangeList,u,a=i._eventRegistry;i._eventRegistry={};var f=new s(r);this.inVirtualSelectionMode=!0;for(var l=o.ranges.length;l--;){if(n)while(l>0&&o.ranges[l].start.row==o.ranges[l-1].end.row)l--;f.fromOrientedRange(o.ranges[l]),f.id=o.ranges[l].marker,this.selection=r.selection=f;var c=e.exec(this,t||{});u!==undefined&&(u=c),f.toOrientedRange(o.ranges[l])}f.detach(),this.selection=r.selection=i,this.inVirtualSelectionMode=!1,i._eventRegistry=a,i.mergeOverlappingRanges();var h=this.renderer.$scrollAnimation;return this.onCursorChange(),this.onSelectionChange(),h&&h.from==h.to&&this.renderer.animateScrolling(h.from),u},this.exitMultiSelectMode=function(){if(!this.inMultiSelectMode||this.inVirtualSelectionMode)return;this.multiSelect.toSingleRange()},this.getSelectedText=function(){var e="";if(this.inMultiSelectMode&&!this.inVirtualSelectionMode){var t=this.multiSelect.rangeList.ranges,n=[];for(var r=0;r<t.length;r++)n.push(this.session.getTextRange(t[r]));var i=this.session.getDocument().getNewLineCharacter();e=n.join(i),e.length==(n.length-1)*i.length&&(e="")}else this.selection.isEmpty()||(e=this.session.getTextRange(this.getSelectionRange()));return e},this.onPaste=function(e){if(this.$readOnly)return;var t={text:e};this._signal("paste",t),e=t.text;if(!this.inMultiSelectMode||this.inVirtualSelectionMode)return this.insert(e);var n=e.split(/\r\n|\r|\n/),r=this.selection.rangeList.ranges;if(n.length>r.length||n.length<2||!n[1])return this.commands.exec("insertstring",this,e);for(var i=r.length;i--;){var s=r[i];s.isEmpty()||this.session.remove(s),this.session.insert(s.start,n[i])}},this.findAll=function(e,t,n){t=t||{},t.needle=e||t.needle,this.$search.set(t);var r=this.$search.findAll(this.session);if(!r.length)return 0;this.$blockScrolling+=1;var i=this.multiSelect;n||i.toSingleRange(r[0]);for(var s=r.length;s--;)i.addRange(r[s],!0);return this.$blockScrolling-=1,r.length},this.selectMoreLines=function(e,t){var n=this.selection.toOrientedRange(),r=n.cursor==n.end,s=this.session.documentToScreenPosition(n.cursor);this.selection.$desiredColumn&&(s.column=this.selection.$desiredColumn);var o=this.session.screenToDocumentPosition(s.row+e,s.column);if(!n.isEmpty())var u=this.session.documentToScreenPosition(r?n.end:n.start),a=this.session.screenToDocumentPosition(u.row+e,u.column);else var a=o;if(r){var f=i.fromPoints(o,a);f.cursor=f.start}else{var f=i.fromPoints(a,o);f.cursor=f.end}f.desiredColumn=s.column;if(!this.selection.inMultiSelectMode)this.selection.addRange(n);else if(t)var l=n.cursor;this.selection.addRange(f),l&&this.selection.substractPoint(l)},this.transposeSelections=function(e){var t=this.session,n=t.multiSelect,r=n.ranges;for(var i=r.length;i--;){var s=r[i];if(s.isEmpty()){var o=t.getWordRange(s.start.row,s.start.column);s.start.row=o.start.row,s.start.column=o.start.column,s.end.row=o.end.row,s.end.column=o.end.column}}n.mergeOverlappingRanges();var u=[];for(var i=r.length;i--;){var s=r[i];u.unshift(t.getTextRange(s))}e<0?u.unshift(u.pop()):u.push(u.shift());for(var i=r.length;i--;){var s=r[i],o=s.clone();t.replace(s,u[i]),s.start.row=o.start.row,s.start.column=o.start.column}},this.selectMore=function(e,t){var n=this.session,r=n.multiSelect,i=r.toOrientedRange();i.isEmpty()&&(i=n.getWordRange(i.start.row,i.start.column),i.cursor=e==-1?i.start:i.end,this.multiSelect.addRange(i));var s=n.getTextRange(i),o=h(n,s,e);o&&(o.cursor=e==-1?o.start:o.end,this.$blockScrolling+=1,this.session.unfold(o),this.multiSelect.addRange(o),this.$blockScrolling-=1,this.renderer.scrollCursorIntoView(null,.5)),t&&this.multiSelect.substractPoint(i.cursor)},this.alignCursors=function(){var e=this.session,t=e.multiSelect,n=t.ranges;if(!n.length){var r=this.selection.getRange(),s=r.start.row,o=r.end.row,u=s==o;if(u){var f=this.session.getLength(),l;do l=this.session.getLine(o);while(/[=:]/.test(l)&&++o<f);do l=this.session.getLine(s);while(/[=:]/.test(l)&&--s>0);s<0&&(s=0),o>=f&&(o=f-1)}var c=this.session.doc.removeLines(s,o);c=this.$reAlignText(c,u),this.session.doc.insert({row:s,column:0},c.join("\n")+"\n"),u||(r.start.column=0,r.end.column=c[c.length-1].length),this.selection.setRange(r)}else{var h=-1,p=n.filter(function(e){if(e.cursor.row==h)return!0;h=e.cursor.row});t.$onRemoveRange(p);var d=0,v=Infinity,m=n.map(function(t){var n=t.cursor,r=e.getLine(n.row),i=r.substr(n.column).search(/\S/g);return i==-1&&(i=0),n.column>d&&(d=n.column),i<v&&(v=i),i});n.forEach(function(t,n){var r=t.cursor,s=d-r.column,o=m[n]-v;s>o?e.insert(r,a.stringRepeat(" ",s-o)):e.remove(new i(r.row,r.column,r.row,r.column-s+o)),t.start.column=t.end.column=d,t.start.row=t.end.row=r.row,t.cursor=t.end}),t.fromOrientedRange(n[0]),this.renderer.updateCursor(),this.renderer.updateBackMarkers()}},this.$reAlignText=function(e,t){function u(e){return a.stringRepeat(" ",e)}function f(e){return e[2]?u(i)+e[2]+u(s-e[2].length+o)+e[4].replace(/^([=:])\s+/,"$1 "):e[0]}function l(e){return e[2]?u(i+s-e[2].length)+e[2]+u(o," ")+e[4].replace(/^([=:])\s+/,"$1 "):e[0]}function c(e){return e[2]?u(i)+e[2]+u(o)+e[4].replace(/^([=:])\s+/,"$1 "):e[0]}var n=!0,r=!0,i,s,o;return e.map(function(e){var t=e.match(/(\s*)(.*?)(\s*)([=:].*)/);return t?i==null?(i=t[1].length,s=t[2].length,o=t[3].length,t):(i+s+o!=t[1].length+t[2].length+t[3].length&&(r=!1),i!=t[1].length&&(n=!1),i>t[1].length&&(i=t[1].length),s<t[2].length&&(s=t[2].length),o>t[3].length&&(o=t[3].length),t):[e]}).map(t?f:n?r?l:f:c)}}).call(d.prototype),t.onSessionChange=function(e){var t=e.session;t.multiSelect||(t.$selectionMarkers=[],t.selection.$initRangeList(),t.multiSelect=t.selection),this.multiSelect=t.multiSelect;var n=e.oldSession;n&&(n.multiSelect.removeEventListener("addRange",this.$onAddRange),n.multiSelect.removeEventListener("removeRange",this.$onRemoveRange),n.multiSelect.removeEventListener("multiSelect",this.$onMultiSelect),n.multiSelect.removeEventListener("singleSelect",this.$onSingleSelect)),t.multiSelect.on("addRange",this.$onAddRange),t.multiSelect.on("removeRange",this.$onRemoveRange),t.multiSelect.on("multiSelect",this.$onMultiSelect),t.multiSelect.on("singleSelect",this.$onSingleSelect),this.inMultiSelectMode!=t.selection.inMultiSelectMode&&(t.selection.inMultiSelectMode?this.$onMultiSelect():this.$onSingleSelect())},t.MultiSelect=m,e("./config").defineOptions(d.prototype,"editor",{enableMultiselect:{set:function(e){m(this),e?(this.on("changeSession",this.$multiselectOnSessionChange),this.on("mousedown",o)):(this.off("changeSession",this.$multiselectOnSessionChange),this.off("mousedown",o))},value:!0}})}),define("ace/editor",["require","exports","module","ace/lib/fixoldbrowsers","ace/lib/oop","ace/lib/dom","ace/lib/lang","ace/lib/useragent","ace/keyboard/textinput","ace/mouse/mouse_handler","ace/mouse/fold_handler","ace/keyboard/keybinding","ace/edit_session","ace/search","ace/range","ace/lib/event_emitter","ace/commands/command_manager","ace/commands/default_commands","ace/config"],function(e,t,n){e("./lib/fixoldbrowsers");var r=e("./lib/oop"),i=e("./lib/dom"),s=e("./lib/lang"),o=e("./lib/useragent"),u=e("./keyboard/textinput").TextInput,a=e("./mouse/mouse_handler").MouseHandler,f=e("./mouse/fold_handler").FoldHandler,l=e("./keyboard/keybinding").KeyBinding,c=e("./edit_session").EditSession,h=e("./search").Search,p=e("./range").Range,d=e("./lib/event_emitter").EventEmitter,v=e("./commands/command_manager").CommandManager,m=e("./commands/default_commands").commands,g=e("./config"),y=function(e,t){var n=e.getContainerElement();this.container=n,this.renderer=e,this.commands=new v(o.isMac?"mac":"win",m),this.textInput=new u(e.getTextAreaContainer(),this),this.renderer.textarea=this.textInput.getElement(),this.keyBinding=new l(this),this.$mouseHandler=new a(this),new f(this),this.$blockScrolling=0,this.$search=(new h).set({wrap:!0}),this.$historyTracker=this.$historyTracker.bind(this),this.commands.on("exec",this.$historyTracker),this.$initOperationListeners(),this._$emitInputEvent=s.delayedCall(function(){this._signal("input",{}),this.session.bgTokenizer&&this.session.bgTokenizer.scheduleStart()}.bind(this)),this.on("change",function(e,t){t._$emitInputEvent.schedule(31)}),this.setSession(t||new c("")),g.resetOptions(this),g._signal("editor",this)};(function(){r.implement(this,d),this.$initOperationListeners=function(){function e(e){return e[e.length-1]}this.selections=[],this.commands.on("exec",function(t){this.startOperation(t);var n=t.command;if(n.aceCommandGroup=="fileJump"){var r=this.prevOp;if(!r||r.command.aceCommandGroup!="fileJump")this.lastFileJumpPos=e(this.selections)}else this.lastFileJumpPos=null}.bind(this),!0),this.commands.on("afterExec",function(e){var t=e.command;t.aceCommandGroup=="fileJump"&&this.lastFileJumpPos&&!this.curOp.selectionChanged&&this.selection.fromJSON(this.lastFileJumpPos),this.endOperation(e)}.bind(this),!0),this.$opResetTimer=s.delayedCall(this.endOperation.bind(this)),this.on("change",function(){this.curOp||this.startOperation(),this.curOp.docChanged=!0}.bind(this),!0),this.on("changeSelection",function(){this.curOp||this.startOperation(),this.curOp.selectionChanged=!0}.bind(this),!0)},this.curOp=null,this.prevOp={},this.startOperation=function(e){if(this.curOp){if(!e||this.curOp.command)return;this.prevOp=this.curOp}e||(this.previousCommand=null,e={}),this.$opResetTimer.schedule(),this.curOp={command:e.command||{},args:e.args,scrollTop:this.renderer.scrollTop};var t=this.curOp.command;t&&t.scrollIntoView&&this.$blockScrolling++,this.selections.push(this.selection.toJSON())},this.endOperation=function(){if(this.curOp){var e=this.curOp.command;if(e&&e.scrollIntoView){this.$blockScrolling--;switch(e.scrollIntoView){case"center":this.renderer.scrollCursorIntoView(null,.5);break;case"animate":case"cursor":this.renderer.scrollCursorIntoView();break;case"selectionPart":var t=this.selection.getRange(),n=this.renderer.layerConfig;(t.start.row>=n.lastRow||t.end.row<=n.firstRow)&&this.renderer.scrollSelectionIntoView(this.selection.anchor,this.selection.lead);break;default:}e.scrollIntoView=="animate"&&this.renderer.animateScrolling(this.curOp.scrollTop)}this.prevOp=this.curOp,this.curOp=null}},this.$historyTracker=function(e){if(!this.$mergeUndoDeltas)return;var t=this.prevOp,n=["backspace","del","insertstring"],r=t.command&&e.command.name==t.command.name;if(e.command.name=="insertstring"){var i=e.args;this.mergeNextCommand===undefined&&(this.mergeNextCommand=!0),r=r&&this.mergeNextCommand&&(!/\s/.test(i)||/\s/.test(t.args)),this.mergeNextCommand=!0}else r=r&&n.indexOf(e.command.name)!==-1;this.$mergeUndoDeltas!="always"&&Date.now()-this.sequenceStartTime>2e3&&(r=!1),r?this.session.mergeUndoDeltas=!0:n.indexOf(e.command.name)!==-1&&(this.sequenceStartTime=Date.now())},this.setKeyboardHandler=function(e){if(!e)this.keyBinding.setKeyboardHandler(null);else if(typeof e=="string"){this.$keybindingId=e;var t=this;g.loadModule(["keybinding",e],function(n){t.$keybindingId==e&&t.keyBinding.setKeyboardHandler(n&&n.handler)})}else this.$keybindingId=null,this.keyBinding.setKeyboardHandler(e)},this.getKeyboardHandler=function(){return this.keyBinding.getKeyboardHandler()},this.setSession=function(e){if(this.session==e)return;var t=this.session;if(t){this.session.removeEventListener("change",this.$onDocumentChange),this.session.removeEventListener("changeMode",this.$onChangeMode),this.session.removeEventListener("tokenizerUpdate",this.$onTokenizerUpdate),this.session.removeEventListener("changeTabSize",this.$onChangeTabSize),this.session.removeEventListener("changeWrapLimit",this.$onChangeWrapLimit),this.session.removeEventListener("changeWrapMode",this.$onChangeWrapMode),this.session.removeEventListener("onChangeFold",this.$onChangeFold),this.session.removeEventListener("changeFrontMarker",this.$onChangeFrontMarker),this.session.removeEventListener("changeBackMarker",this.$onChangeBackMarker),this.session.removeEventListener("changeBreakpoint",this.$onChangeBreakpoint),this.session.removeEventListener("changeAnnotation",this.$onChangeAnnotation),this.session.removeEventListener("changeOverwrite",this.$onCursorChange),this.session.removeEventListener("changeScrollTop",this.$onScrollTopChange),this.session.removeEventListener("changeScrollLeft",this.$onScrollLeftChange);var n=this.session.getSelection();n.removeEventListener("changeCursor",this.$onCursorChange),n.removeEventListener("changeSelection",this.$onSelectionChange)}this.session=e,e&&(this.$onDocumentChange=this.onDocumentChange.bind(this),e.addEventListener("change",this.$onDocumentChange),this.renderer.setSession(e),this.$onChangeMode=this.onChangeMode.bind(this),e.addEventListener("changeMode",this.$onChangeMode),this.$onTokenizerUpdate=this.onTokenizerUpdate.bind(this),e.addEventListener("tokenizerUpdate",this.$onTokenizerUpdate),this.$onChangeTabSize=this.renderer.onChangeTabSize.bind(this.renderer),e.addEventListener("changeTabSize",this.$onChangeTabSize),this.$onChangeWrapLimit=this.onChangeWrapLimit.bind(this),e.addEventListener("changeWrapLimit",this.$onChangeWrapLimit),this.$onChangeWrapMode=this.onChangeWrapMode.bind(this),e.addEventListener("changeWrapMode",this.$onChangeWrapMode),this.$onChangeFold=this.onChangeFold.bind(this),e.addEventListener("changeFold",this.$onChangeFold),this.$onChangeFrontMarker=this.onChangeFrontMarker.bind(this),this.session.addEventListener("changeFrontMarker",this.$onChangeFrontMarker),this.$onChangeBackMarker=this.onChangeBackMarker.bind(this),this.session.addEventListener("changeBackMarker",this.$onChangeBackMarker),this.$onChangeBreakpoint=this.onChangeBreakpoint.bind(this),this.session.addEventListener("changeBreakpoint",this.$onChangeBreakpoint),this.$onChangeAnnotation=this.onChangeAnnotation.bind(this),this.session.addEventListener("changeAnnotation",this.$onChangeAnnotation),this.$onCursorChange=this.onCursorChange.bind(this),this.session.addEventListener("changeOverwrite",this.$onCursorChange),this.$onScrollTopChange=this.onScrollTopChange.bind(this),this.session.addEventListener("changeScrollTop",this.$onScrollTopChange),this.$onScrollLeftChange=this.onScrollLeftChange.bind(this),this.session.addEventListener("changeScrollLeft",this.$onScrollLeftChange),this.selection=e.getSelection(),this.selection.addEventListener("changeCursor",this.$onCursorChange),this.$onSelectionChange=this.onSelectionChange.bind(this),this.selection.addEventListener("changeSelection",this.$onSelectionChange),this.onChangeMode(),this.$blockScrolling+=1,this.onCursorChange(),this.$blockScrolling-=1,this.onScrollTopChange(),this.onScrollLeftChange(),this.onSelectionChange(),this.onChangeFrontMarker(),this.onChangeBackMarker(),this.onChangeBreakpoint(),this.onChangeAnnotation(),this.session.getUseWrapMode()&&this.renderer.adjustWrapLimit(),this.renderer.updateFull()),this._signal("changeSession",{session:e,oldSession:t}),t&&t._signal("changeEditor",{oldEditor:this}),e&&e._signal("changeEditor",{editor:this})},this.getSession=function(){return this.session},this.setValue=function(e,t){return this.session.doc.setValue(e),t?t==1?this.navigateFileEnd():t==-1&&this.navigateFileStart():this.selectAll(),e},this.getValue=function(){return this.session.getValue()},this.getSelection=function(){return this.selection},this.resize=function(e){this.renderer.onResize(e)},this.setTheme=function(e,t){this.renderer.setTheme(e,t)},this.getTheme=function(){return this.renderer.getTheme()},this.setStyle=function(e){this.renderer.setStyle(e)},this.unsetStyle=function(e){this.renderer.unsetStyle(e)},this.getFontSize=function(){return this.getOption("fontSize")||i.computedStyle(this.container,"fontSize")},this.setFontSize=function(e){this.setOption("fontSize",e)},this.$highlightBrackets=function(){this.session.$bracketHighlight&&(this.session.removeMarker(this.session.$bracketHighlight),this.session.$bracketHighlight=null);if(this.$highlightPending)return;var e=this;this.$highlightPending=!0,setTimeout(function(){e.$highlightPending=!1;var t=e.session.findMatchingBracket(e.getCursorPosition());if(t)var n=new p(t.row,t.column,t.row,t.column+1);else if(e.session.$mode.getMatching)var n=e.session.$mode.getMatching(e.session);n&&(e.session.$bracketHighlight=e.session.addMarker(n,"ace_bracket","text"))},50)},this.focus=function(){var e=this;setTimeout(function(){e.textInput.focus()}),this.textInput.focus()},this.isFocused=function(){return this.textInput.isFocused()},this.blur=function(){this.textInput.blur()},this.onFocus=function(){if(this.$isFocused)return;this.$isFocused=!0,this.renderer.showCursor(),this.renderer.visualizeFocus(),this._emit("focus")},this.onBlur=function(){if(!this.$isFocused)return;this.$isFocused=!1,this.renderer.hideCursor(),this.renderer.visualizeBlur(),this._emit("blur")},this.$cursorChange=function(){this.renderer.updateCursor()},this.onDocumentChange=function(e){var t=e.data,n=t.range,r;n.start.row==n.end.row&&t.action!="insertLines"&&t.action!="removeLines"?r=n.end.row:r=Infinity,this.renderer.updateLines(n.start.row,r),this._signal("change",e),this.$cursorChange()},this.onTokenizerUpdate=function(e){var t=e.data;this.renderer.updateLines(t.first,t.last)},this.onScrollTopChange=function(){this.renderer.scrollToY(this.session.getScrollTop())},this.onScrollLeftChange=function(){this.renderer.scrollToX(this.session.getScrollLeft())},this.onCursorChange=function(){this.$cursorChange(),this.$blockScrolling||this.renderer.scrollCursorIntoView(),this.$highlightBrackets(),this.$updateHighlightActiveLine(),this._signal("changeSelection")},this.$updateHighlightActiveLine=function(){var e=this.getSession(),t;if(this.$highlightActiveLine){if(this.$selectionStyle!="line"||!this.selection.isMultiLine())t=this.getCursorPosition();this.renderer.$maxLines&&this.session.getLength()===1&&!(this.renderer.$minLines>1)&&(t=!1)}if(e.$highlightLineMarker&&!t)e.removeMarker(e.$highlightLineMarker.id),e.$highlightLineMarker=null;else if(!e.$highlightLineMarker&&t){var n=new p(t.row,t.column,t.row,Infinity);n.id=e.addMarker(n,"ace_active-line","screenLine"),e.$highlightLineMarker=n}else t&&(e.$highlightLineMarker.start.row=t.row,e.$highlightLineMarker.end.row=t.row,e.$highlightLineMarker.start.column=t.column,e._signal("changeBackMarker"))},this.onSelectionChange=function(e){var t=this.session;t.$selectionMarker&&t.removeMarker(t.$selectionMarker),t.$selectionMarker=null;if(!this.selection.isEmpty()){var n=this.selection.getRange(),r=this.getSelectionStyle();t.$selectionMarker=t.addMarker(n,"ace_selection",r)}else this.$updateHighlightActiveLine();var i=this.$highlightSelectedWord&&this.$getSelectionHighLightRegexp();this.session.highlight(i),this._signal("changeSelection")},this.$getSelectionHighLightRegexp=function(){var e=this.session,t=this.getSelectionRange();if(t.isEmpty()||t.isMultiLine())return;var n=t.start.column-1,r=t.end.column+1,i=e.getLine(t.start.row),s=i.length,o=i.substring(Math.max(n,0),Math.min(r,s));if(n>=0&&/^[\w\d]/.test(o)||r<=s&&/[\w\d]$/.test(o))return;o=i.substring(t.start.column,t.end.column);if(!/^[\w\d]+$/.test(o))return;var u=this.$search.$assembleRegExp({wholeWord:!0,caseSensitive:!0,needle:o});return u},this.onChangeFrontMarker=function(){this.renderer.updateFrontMarkers()},this.onChangeBackMarker=function(){this.renderer.updateBackMarkers()},this.onChangeBreakpoint=function(){this.renderer.updateBreakpoints()},this.onChangeAnnotation=function(){this.renderer.setAnnotations(this.session.getAnnotations())},this.onChangeMode=function(e){this.renderer.updateText(),this._emit("changeMode",e)},this.onChangeWrapLimit=function(){this.renderer.updateFull()},this.onChangeWrapMode=function(){this.renderer.onResize(!0)},this.onChangeFold=function(){this.$updateHighlightActiveLine(),this.renderer.updateFull()},this.getSelectedText=function(){return this.session.getTextRange(this.getSelectionRange())},this.getCopyText=function(){var e=this.getSelectedText();return this._signal("copy",e),e},this.onCopy=function(){this.commands.exec("copy",this)},this.onCut=function(){this.commands.exec("cut",this)},this.onPaste=function(e){if(this.$readOnly)return;var t={text:e};this._signal("paste",t),this.insert(t.text,!0)},this.execCommand=function(e,t){this.commands.exec(e,this,t)},this.insert=function(e,t){var n=this.session,r=n.getMode(),i=this.getCursorPosition();if(this.getBehavioursEnabled()&&!t){var s=r.transformAction(n.getState(i.row),"insertion",this,n,e);s&&(e!==s.text&&(this.session.mergeUndoDeltas=!1,this.$mergeNextCommand=!1),e=s.text)}e==" "&&(e=this.session.getTabString());if(!this.selection.isEmpty()){var o=this.getSelectionRange();i=this.session.remove(o),this.clearSelection()}else if(this.session.getOverwrite()){var o=new p.fromPoints(i,i);o.end.column+=e.length,this.session.remove(o)}if(e=="\n"||e=="\r\n"){var u=n.getLine(i.row);if(i.column>u.search(/\S|$/)){var a=u.substr(i.column).search(/\S|$/);n.doc.removeInLine(i.row,i.column,i.column+a)}}this.clearSelection();var f=i.column,l=n.getState(i.row),u=n.getLine(i.row),c=r.checkOutdent(l,u,e),h=n.insert(i,e);s&&s.selection&&(s.selection.length==2?this.selection.setSelectionRange(new p(i.row,f+s.selection[0],i.row,f+s.selection[1])):this.selection.setSelectionRange(new p(i.row+s.selection[0],s.selection[1],i.row+s.selection[2],s.selection[3])));if(n.getDocument().isNewLine(e)){var d=r.getNextLineIndent(l,u.slice(0,i.column),n.getTabString());n.insert({row:i.row+1,column:0},d)}c&&r.autoOutdent(l,n,i.row)},this.onTextInput=function(e){this.keyBinding.onTextInput(e)},this.onCommandKey=function(e,t,n){this.keyBinding.onCommandKey(e,t,n)},this.setOverwrite=function(e){this.session.setOverwrite(e)},this.getOverwrite=function(){return this.session.getOverwrite()},this.toggleOverwrite=function(){this.session.toggleOverwrite()},this.setScrollSpeed=function(e){this.setOption("scrollSpeed",e)},this.getScrollSpeed=function(){return this.getOption("scrollSpeed")},this.setDragDelay=function(e){this.setOption("dragDelay",e)},this.getDragDelay=function(){return this.getOption("dragDelay")},this.setSelectionStyle=function(e){this.setOption("selectionStyle",e)},this.getSelectionStyle=function(){return this.getOption("selectionStyle")},this.setHighlightActiveLine=function(e){this.setOption("highlightActiveLine",e)},this.getHighlightActiveLine=function(){return this.getOption("highlightActiveLine")},this.setHighlightGutterLine=function(e){this.setOption("highlightGutterLine",e)},this.getHighlightGutterLine=function(){return this.getOption("highlightGutterLine")},this.setHighlightSelectedWord=function(e){this.setOption("highlightSelectedWord",e)},this.getHighlightSelectedWord=function(){return this.$highlightSelectedWord},this.setAnimatedScroll=function(e){this.renderer.setAnimatedScroll(e)},this.getAnimatedScroll=function(){return this.renderer.getAnimatedScroll()},this.setShowInvisibles=function(e){this.renderer.setShowInvisibles(e)},this.getShowInvisibles=function(){return this.renderer.getShowInvisibles()},this.setDisplayIndentGuides=function(e){this.renderer.setDisplayIndentGuides(e)},this.getDisplayIndentGuides=function(){return this.renderer.getDisplayIndentGuides()},this.setShowPrintMargin=function(e){this.renderer.setShowPrintMargin(e)},this.getShowPrintMargin=function(){return this.renderer.getShowPrintMargin()},this.setPrintMarginColumn=function(e){this.renderer.setPrintMarginColumn(e)},this.getPrintMarginColumn=function(){return this.renderer.getPrintMarginColumn()},this.setReadOnly=function(e){this.setOption("readOnly",e)},this.getReadOnly=function(){return this.getOption("readOnly")},this.setBehavioursEnabled=function(e){this.setOption("behavioursEnabled",e)},this.getBehavioursEnabled=function(){return this.getOption("behavioursEnabled")},this.setWrapBehavioursEnabled=function(e){this.setOption("wrapBehavioursEnabled",e)},this.getWrapBehavioursEnabled=function(){return this.getOption("wrapBehavioursEnabled")},this.setShowFoldWidgets=function(e){this.setOption("showFoldWidgets",e)},this.getShowFoldWidgets=function(){return this.getOption("showFoldWidgets")},this.setFadeFoldWidgets=function(e){this.setOption("fadeFoldWidgets",e)},this.getFadeFoldWidgets=function(){return this.getOption("fadeFoldWidgets")},this.remove=function(e){this.selection.isEmpty()&&(e=="left"?this.selection.selectLeft():this.selection.selectRight());var t=this.getSelectionRange();if(this.getBehavioursEnabled()){var n=this.session,r=n.getState(t.start.row),i=n.getMode().transformAction(r,"deletion",this,n,t);if(t.end.column===0){var s=n.getTextRange(t);if(s[s.length-1]=="\n"){var o=n.getLine(t.end.row);/^\s+$/.test(o)&&(t.end.column=o.length)}}i&&(t=i)}this.session.remove(t),this.clearSelection()},this.removeWordRight=function(){this.selection.isEmpty()&&this.selection.selectWordRight(),this.session.remove(this.getSelectionRange()),this.clearSelection()},this.removeWordLeft=function(){this.selection.isEmpty()&&this.selection.selectWordLeft(),this.session.remove(this.getSelectionRange()),this.clearSelection()},this.removeToLineStart=function(){this.selection.isEmpty()&&this.selection.selectLineStart(),this.session.remove(this.getSelectionRange()),this.clearSelection()},this.removeToLineEnd=function(){this.selection.isEmpty()&&this.selection.selectLineEnd();var e=this.getSelectionRange();e.start.column==e.end.column&&e.start.row==e.end.row&&(e.end.column=0,e.end.row++),this.session.remove(e),this.clearSelection()},this.splitLine=function(){this.selection.isEmpty()||(this.session.remove(this.getSelectionRange()),this.clearSelection());var e=this.getCursorPosition();this.insert("\n"),this.moveCursorToPosition(e)},this.transposeLetters=function(){if(!this.selection.isEmpty())return;var e=this.getCursorPosition(),t=e.column;if(t===0)return;var n=this.session.getLine(e.row),r,i;t<n.length?(r=n.charAt(t)+n.charAt(t-1),i=new p(e.row,t-1,e.row,t+1)):(r=n.charAt(t-1)+n.charAt(t-2),i=new p(e.row,t-2,e.row,t)),this.session.replace(i,r)},this.toLowerCase=function(){var e=this.getSelectionRange();this.selection.isEmpty()&&this.selection.selectWord();var t=this.getSelectionRange(),n=this.session.getTextRange(t);this.session.replace(t,n.toLowerCase()),this.selection.setSelectionRange(e)},this.toUpperCase=function(){var e=this.getSelectionRange();this.selection.isEmpty()&&this.selection.selectWord();var t=this.getSelectionRange(),n=this.session.getTextRange(t);this.session.replace(t,n.toUpperCase()),this.selection.setSelectionRange(e)},this.indent=function(){var e=this.session,t=this.getSelectionRange();if(t.start.row<t.end.row){var n=this.$getSelectedRows();e.indentRows(n.first,n.last," ");return}if(t.start.column<t.end.column){var r=e.getTextRange(t);if(!/^\s+$/.test(r)){var n=this.$getSelectedRows();e.indentRows(n.first,n.last," ");return}}var i=e.getLine(t.start.row),o=t.start,u=e.getTabSize(),a=e.documentToScreenColumn(o.row,o.column);if(this.session.getUseSoftTabs())var f=u-a%u,l=s.stringRepeat(" ",f);else{var f=a%u;while(i[t.start.column]==" "&&f)t.start.column--,f--;this.selection.setSelectionRange(t),l=" "}return this.insert(l)},this.blockIndent=function(){var e=this.$getSelectedRows();this.session.indentRows(e.first,e.last," ")},this.blockOutdent=function(){var e=this.session.getSelection();this.session.outdentRows(e.getRange())},this.sortLines=function(){var e=this.$getSelectedRows(),t=this.session,n=[];for(i=e.first;i<=e.last;i++)n.push(t.getLine(i));n.sort(function(e,t){return e.toLowerCase()<t.toLowerCase()?-1:e.toLowerCase()>t.toLowerCase()?1:0});var r=new p(0,0,0,0);for(var i=e.first;i<=e.last;i++){var s=t.getLine(i);r.start.row=i,r.end.row=i,r.end.column=s.length,t.replace(r,n[i-e.first])}},this.toggleCommentLines=function(){var e=this.session.getState(this.getCursorPosition().row),t=this.$getSelectedRows();this.session.getMode().toggleCommentLines(e,this.session,t.first,t.last)},this.toggleBlockComment=function(){var e=this.getCursorPosition(),t=this.session.getState(e.row),n=this.getSelectionRange();this.session.getMode().toggleBlockComment(t,this.session,n,e)},this.getNumberAt=function(e,t){var n=/[\-]?[0-9]+(?:\.[0-9]+)?/g;n.lastIndex=0;var r=this.session.getLine(e);while(n.lastIndex<t){var i=n.exec(r);if(i.index<=t&&i.index+i[0].length>=t){var s={value:i[0],start:i.index,end:i.index+i[0].length};return s}}return null},this.modifyNumber=function(e){var t=this.selection.getCursor().row,n=this.selection.getCursor().column,r=new p(t,n-1,t,n),i=this.session.getTextRange(r);if(!isNaN(parseFloat(i))&&isFinite(i)){var s=this.getNumberAt(t,n);if(s){var o=s.value.indexOf(".")>=0?s.start+s.value.indexOf(".")+1:s.end,u=s.start+s.value.length-o,a=parseFloat(s.value);a*=Math.pow(10,u),o!==s.end&&n<o?e*=Math.pow(10,s.end-n-1):e*=Math.pow(10,s.end-n),a+=e,a/=Math.pow(10,u);var f=a.toFixed(u),l=new p(t,s.start,t,s.end);this.session.replace(l,f),this.moveCursorTo(t,Math.max(s.start+1,n+f.length-s.value.length))}}},this.removeLines=function(){var e=this.$getSelectedRows(),t;e.first===0||e.last+1<this.session.getLength()?t=new p(e.first,0,e.last+1,0):t=new p(e.first-1,this.session.getLine(e.first-1).length,e.last,this.session.getLine(e.last).length),this.session.remove(t),this.clearSelection()},this.duplicateSelection=function(){var e=this.selection,t=this.session,n=e.getRange(),r=e.isBackwards();if(n.isEmpty()){var i=n.start.row;t.duplicateLines(i,i)}else{var s=r?n.start:n.end,o=t.insert(s,t.getTextRange(n),!1);n.start=s,n.end=o,e.setSelectionRange(n,r)}},this.moveLinesDown=function(){this.$moveLines(function(e,t){return this.session.moveLinesDown(e,t)})},this.moveLinesUp=function(){this.$moveLines(function(e,t){return this.session.moveLinesUp(e,t)})},this.moveText=function(e,t,n){return this.session.moveText(e,t,n)},this.copyLinesUp=function(){this.$moveLines(function(e,t){return this.session.duplicateLines(e,t),0})},this.copyLinesDown=function(){this.$moveLines(function(e,t){return this.session.duplicateLines(e,t)})},this.$moveLines=function(e){var t=this.selection;if(!t.inMultiSelectMode||this.inVirtualSelectionMode){var n=t.toOrientedRange(),r=this.$getSelectedRows(n),i=e.call(this,r.first,r.last);n.moveBy(i,0),t.fromOrientedRange(n)}else{var s=t.rangeList.ranges;t.rangeList.detach(this.session);for(var o=s.length;o--;){var u=o,r=s[o].collapseRows(),a=r.end.row,f=r.start.row;while(o--){r=s[o].collapseRows();if(!(f-r.end.row<=1))break;f=r.end.row}o++;var i=e.call(this,f,a);while(u>=o)s[u].moveBy(i,0),u--}t.fromOrientedRange(t.ranges[0]),t.rangeList.attach(this.session)}},this.$getSelectedRows=function(){var e=this.getSelectionRange().collapseRows();return{first:this.session.getRowFoldStart(e.start.row),last:this.session.getRowFoldEnd(e.end.row)}},this.onCompositionStart=function(e){this.renderer.showComposition(this.getCursorPosition())},this.onCompositionUpdate=function(e){this.renderer.setCompositionText(e)},this.onCompositionEnd=function(){this.renderer.hideComposition()},this.getFirstVisibleRow=function(){return this.renderer.getFirstVisibleRow()},this.getLastVisibleRow=function(){return this.renderer.getLastVisibleRow()},this.isRowVisible=function(e){return e>=this.getFirstVisibleRow()&&e<=this.getLastVisibleRow()},this.isRowFullyVisible=function(e){return e>=this.renderer.getFirstFullyVisibleRow()&&e<=this.renderer.getLastFullyVisibleRow()},this.$getVisibleRowCount=function(){return this.renderer.getScrollBottomRow()-this.renderer.getScrollTopRow()+1},this.$moveByPage=function(e,t){var n=this.renderer,r=this.renderer.layerConfig,i=e*Math.floor(r.height/r.lineHeight);this.$blockScrolling++,t===!0?this.selection.$moveSelection(function(){this.moveCursorBy(i,0)}):t===!1&&(this.selection.moveCursorBy(i,0),this.selection.clearSelection()),this.$blockScrolling--;var s=n.scrollTop;n.scrollBy(0,i*r.lineHeight),t!=null&&n.scrollCursorIntoView(null,.5),n.animateScrolling(s)},this.selectPageDown=function(){this.$moveByPage(1,!0)},this.selectPageUp=function(){this.$moveByPage(-1,!0)},this.gotoPageDown=function(){this.$moveByPage(1,!1)},this.gotoPageUp=function(){this.$moveByPage(-1,!1)},this.scrollPageDown=function(){this.$moveByPage(1)},this.scrollPageUp=function(){this.$moveByPage(-1)},this.scrollToRow=function(e){this.renderer.scrollToRow(e)},this.scrollToLine=function(e,t,n,r){this.renderer.scrollToLine(e,t,n,r)},this.centerSelection=function(){var e=this.getSelectionRange(),t={row:Math.floor(e.start.row+(e.end.row-e.start.row)/2),column:Math.floor(e.start.column+(e.end.column-e.start.column)/2)};this.renderer.alignCursor(t,.5)},this.getCursorPosition=function(){return this.selection.getCursor()},this.getCursorPositionScreen=function(){return this.session.documentToScreenPosition(this.getCursorPosition())},this.getSelectionRange=function(){return this.selection.getRange()},this.selectAll=function(){this.$blockScrolling+=1,this.selection.selectAll(),this.$blockScrolling-=1},this.clearSelection=function(){this.selection.clearSelection()},this.moveCursorTo=function(e,t){this.selection.moveCursorTo(e,t)},this.moveCursorToPosition=function(e){this.selection.moveCursorToPosition(e)},this.jumpToMatching=function(e){var t=this.getCursorPosition(),n=this.session.getBracketRange(t);if(!n){n=this.find({needle:/[{}()\[\]]/g,preventScroll:!0,start:{row:t.row,column:t.column-1}});if(!n)return;var r=n.start;r.row==t.row&&Math.abs(r.column-t.column)<2&&(n=this.session.getBracketRange(r))}r=n&&n.cursor||r,r&&(e?n&&n.isEqual(this.getSelectionRange())?this.clearSelection():this.selection.selectTo(r.row,r.column):this.selection.moveTo(r.row,r.column))},this.gotoLine=function(e,t,n){this.selection.clearSelection(),this.session.unfold({row:e-1,column:t||0}),this.$blockScrolling+=1,this.exitMultiSelectMode&&this.exitMultiSelectMode(),this.moveCursorTo(e-1,t||0),this.$blockScrolling-=1,this.isRowFullyVisible(e-1)||this.scrollToLine(e-1,!0,n)},this.navigateTo=function(e,t){this.selection.moveTo(e,t)},this.navigateUp=function(e){if(this.selection.isMultiLine()&&!this.selection.isBackwards()){var t=this.selection.anchor.getPosition();return this.moveCursorToPosition(t)}this.selection.clearSelection(),this.selection.moveCursorBy(-e||-1,0)},this.navigateDown=function(e){if(this.selection.isMultiLine()&&this.selection.isBackwards()){var t=this.selection.anchor.getPosition();return this.moveCursorToPosition(t)}this.selection.clearSelection(),this.selection.moveCursorBy(e||1,0)},this.navigateLeft=function(e){if(!this.selection.isEmpty()){var t=this.getSelectionRange().start;this.moveCursorToPosition(t)}else{e=e||1;while(e--)this.selection.moveCursorLeft()}this.clearSelection()},this.navigateRight=function(e){if(!this.selection.isEmpty()){var t=this.getSelectionRange().end;this.moveCursorToPosition(t)}else{e=e||1;while(e--)this.selection.moveCursorRight()}this.clearSelection()},this.navigateLineStart=function(){this.selection.moveCursorLineStart(),this.clearSelection()},this.navigateLineEnd=function(){this.selection.moveCursorLineEnd(),this.clearSelection()},this.navigateFileEnd=function(){this.selection.moveCursorFileEnd(),this.clearSelection()},this.navigateFileStart=function(){this.selection.moveCursorFileStart(),this.clearSelection()},this.navigateWordRight=function(){this.selection.moveCursorWordRight(),this.clearSelection()},this.navigateWordLeft=function(){this.selection.moveCursorWordLeft(),this.clearSelection()},this.replace=function(e,t){t&&this.$search.set(t);var n=this.$search.find(this.session),r=0;return n?(this.$tryReplace(n,e)&&(r=1),n!==null&&(this.selection.setSelectionRange(n),this.renderer.scrollSelectionIntoView(n.start,n.end)),r):r},this.replaceAll=function(e,t){t&&this.$search.set(t);var n=this.$search.findAll(this.session),r=0;if(!n.length)return r;this.$blockScrolling+=1;var i=this.getSelectionRange();this.selection.moveTo(0,0);for(var s=n.length-1;s>=0;--s)this.$tryReplace(n[s],e)&&r++;return this.selection.setSelectionRange(i),this.$blockScrolling-=1,r},this.$tryReplace=function(e,t){var n=this.session.getTextRange(e);return t=this.$search.replace(n,t),t!==null?(e.end=this.session.replace(e,t),e):null},this.getLastSearchOptions=function(){return this.$search.getOptions()},this.find=function(e,t,n){t||(t={}),typeof e=="string"||e instanceof RegExp?t.needle=e:typeof e=="object"&&r.mixin(t,e);var i=this.selection.getRange();t.needle==null&&(e=this.session.getTextRange(i)||this.$search.$options.needle,e||(i=this.session.getWordRange(i.start.row,i.start.column),e=this.session.getTextRange(i)),this.$search.set({needle:e})),this.$search.set(t),t.start||this.$search.set({start:i});var s=this.$search.find(this.session);if(t.preventScroll)return s;if(s)return this.revealRange(s,n),s;t.backwards?i.start=i.end:i.end=i.start,this.selection.setRange(i)},this.findNext=function(e,t){this.find({skipCurrent:!0,backwards:!1},e,t)},this.findPrevious=function(e,t){this.find(e,{skipCurrent:!0,backwards:!0},t)},this.revealRange=function(e,t){this.$blockScrolling+=1,this.session.unfold(e),this.selection.setSelectionRange(e),this.$blockScrolling-=1;var n=this.renderer.scrollTop;this.renderer.scrollSelectionIntoView(e.start,e.end,.5),t!==!1&&this.renderer.animateScrolling(n)},this.undo=function(){this.$blockScrolling++,this.session.getUndoManager().undo(),this.$blockScrolling--,this.renderer.scrollCursorIntoView(null,.5)},this.redo=function(){this.$blockScrolling++,this.session.getUndoManager().redo(),this.$blockScrolling--,this.renderer.scrollCursorIntoView(null,.5)},this.destroy=function(){this.renderer.destroy(),this._signal("destroy",this)},this.setAutoScrollEditorIntoView=function(e){if(!e)return;var t,n=this,r=!1;this.$scrollAnchor||(this.$scrollAnchor=document.createElement("div"));var i=this.$scrollAnchor;i.style.cssText="position:absolute",this.container.insertBefore(i,this.container.firstChild);var s=this.on("changeSelection",function(){r=!0}),o=this.renderer.on("beforeRender",function(){r&&(t=n.renderer.container.getBoundingClientRect())}),u=this.renderer.on("afterRender",function(){if(r&&t&&n.isFocused()){var e=n.renderer,s=e.$cursorLayer.$pixelPos,o=e.layerConfig,u=s.top-o.offset;s.top>=0&&u+t.top<0?r=!0:s.top<o.height&&s.top+t.top+o.lineHeight>window.innerHeight?r=!1:r=null,r!=null&&(i.style.top=u+"px",i.style.left=s.left+"px",i.style.height=o.lineHeight+"px",i.scrollIntoView(r)),r=t=null}});this.setAutoScrollEditorIntoView=function(e){if(e)return;delete this.setAutoScrollEditorIntoView,this.removeEventListener("changeSelection",s),this.renderer.removeEventListener("afterRender",u),this.renderer.removeEventListener("beforeRender",o)}},this.$resetCursorStyle=function(){var e=this.$cursorStyle||"ace",t=this.renderer.$cursorLayer;if(!t)return;t.setSmoothBlinking(e=="smooth"),t.isBlinking=!this.$readOnly&&e!="wide"}}).call(y.prototype),g.defineOptions(y.prototype,"editor",{selectionStyle:{set:function(e){this.onSelectionChange(),this._signal("changeSelectionStyle",{data:e})},initialValue:"line"},highlightActiveLine:{set:function(){this.$updateHighlightActiveLine()},initialValue:!0},highlightSelectedWord:{set:function(e){this.$onSelectionChange()},initialValue:!0},readOnly:{set:function(e){this.textInput.setReadOnly(e),this.$resetCursorStyle()},initialValue:!1},cursorStyle:{set:function(e){this.$resetCursorStyle()},values:["ace","slim","smooth","wide"],initialValue:"ace"},mergeUndoDeltas:{values:[!1,!0,"always"],initialValue:!0},behavioursEnabled:{initialValue:!0},wrapBehavioursEnabled:{initialValue:!0},autoScrollEditorIntoView:{set:function(e){this.setAutoScrollEditorIntoView(e)}},hScrollBarAlwaysVisible:"renderer",vScrollBarAlwaysVisible:"renderer",highlightGutterLine:"renderer",animatedScroll:"renderer",showInvisibles:"renderer",showPrintMargin:"renderer",printMarginColumn:"renderer",printMargin:"renderer",fadeFoldWidgets:"renderer",showFoldWidgets:"renderer",showLineNumbers:"renderer",showGutter:"renderer",displayIndentGuides:"renderer",fontSize:"renderer",fontFamily:"renderer",maxLines:"renderer",minLines:"renderer",scrollPastEnd:"renderer",fixedWidthGutter:"renderer",theme:"renderer",scrollSpeed:"$mouseHandler",dragDelay:"$mouseHandler",dragEnabled:"$mouseHandler",focusTimout:"$mouseHandler",tooltipFollowsMouse:"$mouseHandler",firstLineNumber:"session",overwrite:"session",newLineMode:"session",useWorker:"session",useSoftTabs:"session",tabSize:"session",wrap:"session",foldStyle:"session",mode:"session"}),t.Editor=y}),define("ace/mouse/multi_select_handler",["require","exports","module","ace/lib/event"],function(e,t,n){function i(e,t){return e.row==t.row&&e.column==t.column}function s(e){var t=e.domEvent,n=t.altKey,s=t.shiftKey,o=e.getAccelKey(),u=e.getButton();if(e.editor.inMultiSelectMode&&u==2){e.editor.textInput.onContextMenu(e.domEvent);return}if(!o&&!n){u===0&&e.editor.inMultiSelectMode&&e.editor.exitMultiSelectMode();return}var a=e.editor,f=a.selection,l=a.inMultiSelectMode,c=e.getDocumentPosition(),h=f.getCursor(),p=e.inSelection()||f.isEmpty()&&i(c,h),d=e.x,v=e.y,m=function(e){d=e.clientX,v=e.clientY},g=function(){var e=a.renderer.pixelToScreenCoordinates(d,v),t=y.screenToDocumentPosition(e.row,e.column);if(i(w,e)&&i(t,f.selectionLead))return;w=e,a.selection.moveToPosition(t),a.renderer.scrollCursorIntoView(),a.removeSelectionMarkers(x),x=f.rectangularRangeBlock(w,b),x.forEach(a.addSelectionMarker,a),a.updateSelectionMarkers()},y=a.session,b=a.renderer.pixelToScreenCoordinates(d,v),w=b;if(o&&!n&&!s&&u===0){if(!l&&p)return;if(!l){var E=f.toOrientedRange();a.addSelectionMarker(E)}var S=f.rangeList.rangeAtPoint(c);a.$blockScrolling++,a.once("mouseup",function(){var e=f.toOrientedRange();S&&e.isEmpty()&&i(S.cursor,e.cursor)?f.substractPoint(e.cursor):(E&&(a.removeSelectionMarker(E),f.addRange(E)),f.addRange(e)),a.$blockScrolling--})}else if(n&&u===0){e.stop(),l&&!o?f.toSingleRange():!l&&o&&f.addRange();var x=[];s?(b=y.documentToScreenPosition(f.lead),g()):f.moveToPosition(c);var T=function(e){clearInterval(C),a.removeSelectionMarkers(x);for(var t=0;t<x.length;t++)f.addRange(x[t])},N=g;r.capture(a.container,m,T);var C=setInterval(function(){N()},20);return e.preventDefault()}}var r=e("../lib/event");t.onMouseDown=s}),define("ace/lib/useragent",["require","exports","module"],function(e,t,n){t.OS={LINUX:"LINUX",MAC:"MAC",WINDOWS:"WINDOWS"},t.getOS=function(){return t.isMac?t.OS.MAC:t.isLinux?t.OS.LINUX:t.OS.WINDOWS};if(typeof navigator!="object")return;var r=(navigator.platform.match(/mac|win|linux/i)||["other"])[0].toLowerCase(),i=navigator.userAgent;t.isWin=r=="win",t.isMac=r=="mac",t.isLinux=r=="linux",t.isIE=(navigator.appName=="Microsoft Internet Explorer"||navigator.appName.indexOf("MSAppHost")>=0)&&parseFloat(navigator.userAgent.match(/(?:Trident\/[0-9]+[\.0-9]+;.*rv:|MSIE )([0-9]+[\.0-9]+)/)[1]),t.isOldIE=t.isIE&&t.isIE<9,t.isGecko=t.isMozilla=window.controllers&&window.navigator.product==="Gecko",t.isOldGecko=t.isGecko&&parseInt((navigator.userAgent.match(/rv\:(\d+)/)||[])[1],10)<4,t.isOpera=window.opera&&Object.prototype.toString.call(window.opera)=="[object Opera]",t.isWebKit=parseFloat(i.split("WebKit/")[1])||undefined,t.isChrome=parseFloat(i.split(" Chrome/")[1])||undefined,t.isAIR=i.indexOf("AdobeAIR")>=0,t.isIPad=i.indexOf("iPad")>=0,t.isTouchPad=i.indexOf("TouchPad")>=0}),define("ace/commands/multi_select_commands",["require","exports","module","ace/keyboard/hash_handler"],function(e,t,n){t.defaultCommands=[{name:"addCursorAbove",exec:function(e){e.selectMoreLines(-1)},bindKey:{win:"Ctrl-Alt-Up",mac:"Ctrl-Alt-Up"},readonly:!0},{name:"addCursorBelow",exec:function(e){e.selectMoreLines(1)},bindKey:{win:"Ctrl-Alt-Down",mac:"Ctrl-Alt-Down"},readonly:!0},{name:"addCursorAboveSkipCurrent",exec:function(e){e.selectMoreLines(-1,!0)},bindKey:{win:"Ctrl-Alt-Shift-Up",mac:"Ctrl-Alt-Shift-Up"},readonly:!0},{name:"addCursorBelowSkipCurrent",exec:function(e){e.selectMoreLines(1,!0)},bindKey:{win:"Ctrl-Alt-Shift-Down",mac:"Ctrl-Alt-Shift-Down"},readonly:!0},{name:"selectMoreBefore",exec:function(e){e.selectMore(-1)},bindKey:{win:"Ctrl-Alt-Left",mac:"Ctrl-Alt-Left"},readonly:!0},{name:"selectMoreAfter",exec:function(e){e.selectMore(1)},bindKey:{win:"Ctrl-Alt-Right",mac:"Ctrl-Alt-Right"},readonly:!0},{name:"selectNextBefore",exec:function(e){e.selectMore(-1,!0)},bindKey:{win:"Ctrl-Alt-Shift-Left",mac:"Ctrl-Alt-Shift-Left"},readonly:!0},{name:"selectNextAfter",exec:function(e){e.selectMore(1,!0)},bindKey:{win:"Ctrl-Alt-Shift-Right",mac:"Ctrl-Alt-Shift-Right"},readonly:!0},{name:"splitIntoLines",exec:function(e){e.multiSelect.splitIntoLines()},bindKey:{win:"Ctrl-Alt-L",mac:"Ctrl-Alt-L"},readonly:!0},{name:"alignCursors",exec:function(e){e.alignCursors()},bindKey:{win:"Ctrl-Alt-A",mac:"Ctrl-Alt-A"}}],t.multiSelectCommands=[{name:"singleSelection",bindKey:"esc",exec:function(e){e.exitMultiSelectMode()},readonly:!0,isAvailable:function(e){return e&&e.inMultiSelectMode}}];var r=e("../keyboard/hash_handler").HashHandler;t.keyboardHandler=new r(t.multiSelectCommands)}),define("ace/lib/oop",["require","exports","module"],function(e,t,n){t.inherits=function(e,t){e.super_=t,e.prototype=Object.create(t.prototype,{constructor:{value:e,enumerable:!1,writable:!0,configurable:!0}})},t.mixin=function(e,t){for(var n in t)e[n]=t[n];return e},t.implement=function(e,n){t.mixin(e,n)}}),define("ace/worker/worker_client",["require","exports","module","ace/lib/oop","ace/lib/event_emitter","ace/config"],function(e,t,n){var r=e("../lib/oop"),i=e("../lib/event_emitter").EventEmitter,s=e("../config"),o=function(t,n,r,i){this.$sendDeltaQueue=this.$sendDeltaQueue.bind(this),this.changeListener=this.changeListener.bind(this),this.onMessage=this.onMessage.bind(this),e.nameToUrl&&!e.toUrl&&(e.toUrl=e.nameToUrl);if(s.get("packaged")||!e.toUrl)i=i||s.moduleUrl(n,"worker");else{var o=this.$normalizePath;i=i||o(e.toUrl("ace/worker/worker.js",null,"_"));var u={};t.forEach(function(t){u[t]=o(e.toUrl(t,null,"_").replace(/(\.js)?(\?.*)?$/,""))})}try{this.$worker=new Worker(i)}catch(a){if(!(a instanceof window.DOMException))throw a;var f=this.$workerBlob(i),l=window.URL||window.webkitURL,c=l.createObjectURL(f);this.$worker=new Worker(c),l.revokeObjectURL(c)}this.$worker.postMessage({init:!0,tlns:u,module:n,classname:r}),this.callbackId=1,this.callbacks={},this.$worker.onmessage=this.onMessage};(function(){r.implement(this,i),this.onMessage=function(e){var t=e.data;switch(t.type){case"log":window.console&&console.log&&console.log.apply(console,t.data);break;case"event":this._signal(t.name,{data:t.data});break;case"call":var n=this.callbacks[t.id];n&&(n(t.data),delete this.callbacks[t.id])}},this.$normalizePath=function(e){return location.host?(e=e.replace(/^[a-z]+:\/\/[^\/]+/,""),e=location.protocol+"//"+location.host+(e.charAt(0)=="/"?"":location.pathname.replace(/\/[^\/]*$/,""))+"/"+e.replace(/^[\/]+/,""),e):e},this.terminate=function(){this._signal("terminate",{}),this.deltaQueue=null,this.$worker.terminate(),this.$worker=null,this.$doc.removeEventListener("change",this.changeListener),this.$doc=null},this.send=function(e,t){this.$worker.postMessage({command:e,args:t})},this.call=function(e,t,n){if(n){var r=this.callbackId++;this.callbacks[r]=n,t.push(r)}this.send(e,t)},this.emit=function(e,t){try{this.$worker.postMessage({event:e,data:{data:t.data}})}catch(n){}},this.attachToDocument=function(e){this.$doc&&this.terminate(),this.$doc=e,this.call("setValue",[e.getValue()]),e.on("change",this.changeListener)},this.changeListener=function(e){this.deltaQueue?this.deltaQueue.push(e.data):(this.deltaQueue=[e.data],setTimeout(this.$sendDeltaQueue,0))},this.$sendDeltaQueue=function(){var e=this.deltaQueue;if(!e)return;this.deltaQueue=null,e.length>20&&e.length>this.$doc.getLength()>>1?this.call("setValue",[this.$doc.getValue()]):this.emit("change",{data:e})},this.$workerBlob=function(e){var t="importScripts('"+e+"');";try{return new Blob([t],{type:"application/javascript"})}catch(n){var r=window.BlobBuilder||window.WebKitBlobBuilder||window.MozBlobBuilder,i=new r;return i.append(t),i.getBlob("application/javascript")}}}).call(o.prototype);var u=function(e,t,n){this.$sendDeltaQueue=this.$sendDeltaQueue.bind(this),this.changeListener=this.changeListener.bind(this),this.callbackId=1,this.callbacks={},this.messageBuffer=[];var r=null,o=!1,u=Object.create(i),a=this;this.$worker={},this.$worker.terminate=function(){},this.$worker.postMessage=function(e){a.messageBuffer.push(e),r&&(o?setTimeout(f):f())},this.setEmitSync=function(e){o=e};var f=function(){var e=a.messageBuffer.shift();e.command?r[e.command].apply(r,e.args):e.event&&u._signal(e.event,e.data)};u.postMessage=function(e){a.onMessage({data:e})},u.callback=function(e,t){this.postMessage({type:"call",id:t,data:e})},u.emit=function(e,t){this.postMessage({type:"event",name:e,data:t})},s.loadModule(["worker",t],function(e){r=new e[n](u);while(a.messageBuffer.length)f()})};u.prototype=o.prototype,t.UIWorkerClient=u,t.WorkerClient=o}),define("ace/lib/keys",["require","exports","module","ace/lib/oop"],function(e,t,n){var r=e("./oop"),i=function(){var e={MODIFIER_KEYS:{16:"Shift",17:"Ctrl",18:"Alt",224:"Meta"},KEY_MODS:{ctrl:1,alt:2,option:2,shift:4,"super":8,meta:8,command:8,cmd:8},FUNCTION_KEYS:{8:"Backspace",9:"Tab",13:"Return",19:"Pause",27:"Esc",32:"Space",33:"PageUp",34:"PageDown",35:"End",36:"Home",37:"Left",38:"Up",39:"Right",40:"Down",44:"Print",45:"Insert",46:"Delete",96:"Numpad0",97:"Numpad1",98:"Numpad2",99:"Numpad3",100:"Numpad4",101:"Numpad5",102:"Numpad6",103:"Numpad7",104:"Numpad8",105:"Numpad9","-13":"NumpadEnter",112:"F1",113:"F2",114:"F3",115:"F4",116:"F5",117:"F6",118:"F7",119:"F8",120:"F9",121:"F10",122:"F11",123:"F12",144:"Numlock",145:"Scrolllock"},PRINTABLE_KEYS:{32:" ",48:"0",49:"1",50:"2",51:"3",52:"4",53:"5",54:"6",55:"7",56:"8",57:"9",59:";",61:"=",65:"a",66:"b",67:"c",68:"d",69:"e",70:"f",71:"g",72:"h",73:"i",74:"j",75:"k",76:"l",77:"m",78:"n",79:"o",80:"p",81:"q",82:"r",83:"s",84:"t",85:"u",86:"v",87:"w",88:"x",89:"y",90:"z",107:"+",109:"-",110:".",188:",",190:".",191:"/",192:"`",219:"[",220:"\\",221:"]",222:"'"}},t,n;for(n in e.FUNCTION_KEYS)t=e.FUNCTION_KEYS[n].toLowerCase(),e[t]=parseInt(n,10);for(n in e.PRINTABLE_KEYS)t=e.PRINTABLE_KEYS[n].toLowerCase(),e[t]=parseInt(n,10);return r.mixin(e,e.MODIFIER_KEYS),r.mixin(e,e.PRINTABLE_KEYS),r.mixin(e,e.FUNCTION_KEYS),e.enter=e["return"],e.escape=e.esc,e.del=e["delete"],e[173]="-",function(){var t=["cmd","ctrl","alt","shift"];for(var n=Math.pow(2,t.length);n--;)e.KEY_MODS[n]=t.filter(function(t){return n&e.KEY_MODS[t]}).join("-")+"-"}(),e}();r.mixin(t,i),t.keyCodeToString=function(e){return(i[e]||String.fromCharCode(e)).toLowerCase()}}),define("ace/placeholder",["require","exports","module","ace/range","ace/lib/event_emitter","ace/lib/oop"],function(e,t,n){var r=e("./range").Range,i=e("./lib/event_emitter").EventEmitter,s=e("./lib/oop"),o=function(e,t,n,r,i,s){var o=this;this.length=t,this.session=e,this.doc=e.getDocument(),this.mainClass=i,this.othersClass=s,this.$onUpdate=this.onUpdate.bind(this),this.doc.on("change",this.$onUpdate),this.$others=r,this.$onCursorChange=function(){setTimeout(function(){o.onCursorChange()})},this.$pos=n;var u=e.getUndoManager().$undoStack||e.getUndoManager().$undostack||{length:-1};this.$undoStackDepth=u.length,this.setup(),e.selection.on("changeCursor",this.$onCursorChange)};(function(){s.implement(this,i),this.setup=function(){var e=this,t=this.doc,n=this.session,i=this.$pos;this.pos=t.createAnchor(i.row,i.column),this.markerId=n.addMarker(new r(i.row,i.column,i.row,i.column+this.length),this.mainClass,null,!1),this.pos.on("change",function(t){n.removeMarker(e.markerId),e.markerId=n.addMarker(new r(t.value.row,t.value.column,t.value.row,t.value.column+e.length),e.mainClass,null,!1)}),this.others=[],this.$others.forEach(function(n){var r=t.createAnchor(n.row,n.column);e.others.push(r)}),n.setUndoSelect(!1)},this.showOtherMarkers=function(){if(this.othersActive)return;var e=this.session,t=this;this.othersActive=!0,this.others.forEach(function(n){n.markerId=e.addMarker(new r(n.row,n.column,n.row,n.column+t.length),t.othersClass,null,!1),n.on("change",function(i){e.removeMarker(n.markerId),n.markerId=e.addMarker(new r(i.value.row,i.value.column,i.value.row,i.value.column+t.length),t.othersClass,null,!1)})})},this.hideOtherMarkers=function(){if(!this.othersActive)return;this.othersActive=!1;for(var e=0;e<this.others.length;e++)this.session.removeMarker(this.others[e].markerId)},this.onUpdate=function(e){var t=e.data,n=t.range;if(n.start.row!==n.end.row)return;if(n.start.row!==this.pos.row)return;if(this.$updating)return;this.$updating=!0;var i=t.action==="insertText"?n.end.column-n.start.column:n.start.column-n.end.column;if(n.start.column>=this.pos.column&&n.start.column<=this.pos.column+this.length+1){var s=n.start.column-this.pos.column;this.length+=i;if(!this.session.$fromUndo){if(t.action==="insertText")for(var o=this.others.length-1;o>=0;o--){var u=this.others[o],a={row:u.row,column:u.column+s};u.row===n.start.row&&n.start.column<u.column&&(a.column+=i),this.doc.insert(a,t.text)}else if(t.action==="removeText")for(var o=this.others.length-1;o>=0;o--){var u=this.others[o],a={row:u.row,column:u.column+s};u.row===n.start.row&&n.start.column<u.column&&(a.column+=i),this.doc.remove(new r(a.row,a.column,a.row,a.column-i))}n.start.column===this.pos.column&&t.action==="insertText"?setTimeout(function(){this.pos.setPosition(this.pos.row,this.pos.column-i);for(var e=0;e<this.others.length;e++){var t=this.others[e],r={row:t.row,column:t.column-i};t.row===n.start.row&&n.start.column<t.column&&(r.column+=i),t.setPosition(r.row,r.column)}}.bind(this),0):n.start.column===this.pos.column&&t.action==="removeText"&&setTimeout(function(){for(var e=0;e<this.others.length;e++){var t=this.others[e];t.row===n.start.row&&n.start.column<t.column&&t.setPosition(t.row,t.column-i)}}.bind(this),0)}this.pos._emit("change",{value:this.pos});for(var o=0;o<this.others.length;o++)this.others[o]._emit("change",{value:this.others[o]})}this.$updating=!1},this.onCursorChange=function(e){if(this.$updating)return;var t=this.session.selection.getCursor();t.row===this.pos.row&&t.column>=this.pos.column&&t.column<=this.pos.column+this.length?(this.showOtherMarkers(),this._emit("cursorEnter",e)):(this.hideOtherMarkers(),this._emit("cursorLeave",e))},this.detach=function(){this.session.removeMarker(this.markerId),this.hideOtherMarkers(),this.doc.removeEventListener("change",this.$onUpdate),this.session.selection.removeEventListener("changeCursor",this.$onCursorChange),this.pos.detach();for(var e=0;e<this.others.length;e++)this.others[e].detach();this.session.setUndoSelect(!0)},this.cancel=function(){if(this.$undoStackDepth===-1)throw Error("Canceling placeholders only supported with undo manager attached to session.");var e=this.session.getUndoManager(),t=(e.$undoStack||e.$undostack).length-this.$undoStackDepth;for(var n=0;n<t;n++)e.undo(!0)}}).call(o.prototype),t.PlaceHolder=o}),define("ace/lib/event",["require","exports","module","ace/lib/keys","ace/lib/useragent"],function(e,t,n){function o(e,t,n){var o=s(t);if(!i.isMac&&u){if(u[91]||u[92])o|=8;if(u.altGr){if((3&o)==3)return;u.altGr=0}if(n===18||n===17){var f=t.location||t.keyLocation;if(n===17&&f===1)a=t.timeStamp;else if(n===18&&o===3&&f===2){var l=-a;a=t.timeStamp,l+=a,l<3&&(u.altGr=!0)}}}if(n in r.MODIFIER_KEYS){switch(r.MODIFIER_KEYS[n]){case"Alt":o=2;break;case"Shift":o=4;break;case"Ctrl":o=1;break;default:o=8}n=-1}o&8&&(n===91||n===93)&&(n=-1);if(!o&&n===13)if(t.location||t.keyLocation===3){e(t,o,-n);if(t.defaultPrevented)return}return!!o||n in r.FUNCTION_KEYS||n in r.PRINTABLE_KEYS?e(t,o,n):!1}var r=e("./keys"),i=e("./useragent");t.addListener=function(e,t,n){if(e.addEventListener)return e.addEventListener(t,n,!1);if(e.attachEvent){var r=function(){n.call(e,window.event)};n._wrapper=r,e.attachEvent("on"+t,r)}},t.removeListener=function(e,t,n){if(e.removeEventListener)return e.removeEventListener(t,n,!1);e.detachEvent&&e.detachEvent("on"+t,n._wrapper||n)},t.stopEvent=function(e){return t.stopPropagation(e),t.preventDefault(e),!1},t.stopPropagation=function(e){e.stopPropagation?e.stopPropagation():e.cancelBubble=!0},t.preventDefault=function(e){e.preventDefault?e.preventDefault():e.returnValue=!1},t.getButton=function(e){return e.type=="dblclick"?0:e.type=="contextmenu"||e.ctrlKey&&i.isMac?2:e.preventDefault?e.button:{1:0,2:2,4:1}[e.button]},t.capture=function(e,n,r){function i(e){n&&n(e),r&&r(e),t.removeListener(document,"mousemove",n,!0),t.removeListener(document,"mouseup",i,!0),t.removeListener(document,"dragstart",i,!0)}return t.addListener(document,"mousemove",n,!0),t.addListener(document,"mouseup",i,!0),t.addListener(document,"dragstart",i,!0),i},t.addMouseWheelListener=function(e,n){"onmousewheel"in e?t.addListener(e,"mousewheel",function(e){var t=8;e.wheelDeltaX!==undefined?(e.wheelX=-e.wheelDeltaX/t,e.wheelY=-e.wheelDeltaY/t):(e.wheelX=0,e.wheelY=-e.wheelDelta/t),n(e)}):"onwheel"in e?t.addListener(e,"wheel",function(e){var t=.35;switch(e.deltaMode){case e.DOM_DELTA_PIXEL:e.wheelX=e.deltaX*t||0,e.wheelY=e.deltaY*t||0;break;case e.DOM_DELTA_LINE:case e.DOM_DELTA_PAGE:e.wheelX=(e.deltaX||0)*5,e.wheelY=(e.deltaY||0)*5}n(e)}):t.addListener(e,"DOMMouseScroll",function(e){e.axis&&e.axis==e.HORIZONTAL_AXIS?(e.wheelX=(e.detail||0)*5,e.wheelY=0):(e.wheelX=0,e.wheelY=(e.detail||0)*5),n(e)})},t.addMultiMouseDownListener=function(e,n,r,s){var o=0,u,a,f,l={2:"dblclick",3:"tripleclick",4:"quadclick"};t.addListener(e,"mousedown",function(e){t.getButton(e)!==0?o=0:e.detail>1?(o++,o>4&&(o=1)):o=1;if(i.isIE){var n=Math.abs(e.clientX-u)>5||Math.abs(e.clientY-a)>5;n&&(o=1),o==1&&(u=e.clientX,a=e.clientY)}r[s]("mousedown",e);if(o>4)o=0;else if(o>1)return r[s](l[o],e)}),i.isOldIE&&t.addListener(e,"dblclick",function(e){o=2,f&&clearTimeout(f),f=setTimeout(function(){f=null},n[o-1]||600),r[s]("mousedown",e),r[s](l[o],e)})};var s=!i.isMac||!i.isOpera||"KeyboardEvent"in window?function(e){return 0|(e.ctrlKey?1:0)|(e.altKey?2:0)|(e.shiftKey?4:0)|(e.metaKey?8:0)}:function(e){return 0|(e.metaKey?1:0)|(e.altKey?2:0)|(e.shiftKey?4:0)|(e.ctrlKey?8:0)};t.getModifierString=function(e){return r.KEY_MODS[s(e)]};var u=null,a=0;t.addCommandKeyListener=function(e,n){var r=t.addListener;if(i.isOldGecko||i.isOpera&&!("KeyboardEvent"in window)){var s=null;r(e,"keydown",function(e){s=e.keyCode}),r(e,"keypress",function(e){return o(n,e,s)})}else{var a=null;r(e,"keydown",function(e){u[e.keyCode]=!0;var t=o(n,e,e.keyCode);return a=e.defaultPrevented,t}),r(e,"keypress",function(e){a&&(e.ctrlKey||e.altKey||e.shiftKey||e.metaKey)&&(t.stopEvent(e),a=null)}),r(e,"keyup",function(e){u[e.keyCode]=null}),u||(u=Object.create(null),r(window,"focus",function(e){u=Object.create(null)}))}};if(window.postMessage&&!i.isOldIE){var f=1;t.nextTick=function(e,n){n=n||window;var r="zero-timeout-message-"+f;t.addListener(n,"message",function i(s){s.data==r&&(t.stopPropagation(s),t.removeListener(n,"message",i),e())}),n.postMessage(r,"*")}}t.nextFrame=window.requestAnimationFrame||window.mozRequestAnimationFrame||window.webkitRequestAnimationFrame||window.msRequestAnimationFrame||window.oRequestAnimationFrame,t.nextFrame?t.nextFrame=t.nextFrame.bind(window):t.nextFrame=function(e){setTimeout(e,17)}}),define("ace/mode/folding/fold_mode",["require","exports","module","ace/range"],function(e,t,n){var r=e("../../range").Range,i=t.FoldMode=function(){};(function(){this.foldingStartMarker=null,this.foldingStopMarker=null,this.getFoldWidget=function(e,t,n){var r=e.getLine(n);return this.foldingStartMarker.test(r)?"start":t=="markbeginend"&&this.foldingStopMarker&&this.foldingStopMarker.test(r)?"end":""},this.getFoldWidgetRange=function(e,t,n){return null},this.indentationBlock=function(e,t,n){var i=/\S/,s=e.getLine(t),o=s.search(i);if(o==-1)return;var u=n||s.length,a=e.getLength(),f=t,l=t;while(++t<a){var c=e.getLine(t).search(i);if(c==-1)continue;if(c<=o)break;l=t}if(l>f){var h=e.getLine(l).length;return new r(f,u,l,h)}},this.openingBracketBlock=function(e,t,n,i,s){var o={row:n,column:i+1},u=e.$findClosingBracket(t,o,s);if(!u)return;var a=e.foldWidgets[u.row];return a==null&&(a=e.getFoldWidget(u.row)),a=="start"&&u.row>o.row&&(u.row--,u.column=e.getLine(u.row).length),r.fromPoints(o,u)},this.closingBracketBlock=function(e,t,n,i,s){var o={row:n,column:i},u=e.$findOpeningBracket(t,o);if(!u)return;return u.column++,o.column--,r.fromPoints(u,o)}}).call(i.prototype)}),define("ace/lib/dom",["require","exports","module"],function(e,t,n){if(typeof document=="undefined")return;var r="http://www.w3.org/1999/xhtml";t.getDocumentHead=function(e){return e||(e=document),e.head||e.getElementsByTagName("head")[0]||e.documentElement},t.createElement=function(e,t){return document.createElementNS?document.createElementNS(t||r,e):document.createElement(e)},t.hasCssClass=function(e,t){var n=e.className.split(/\s+/g);return n.indexOf(t)!==-1},t.addCssClass=function(e,n){t.hasCssClass(e,n)||(e.className+=" "+n)},t.removeCssClass=function(e,t){var n=e.className.split(/\s+/g);for(;;){var r=n.indexOf(t);if(r==-1)break;n.splice(r,1)}e.className=n.join(" ")},t.toggleCssClass=function(e,t){var n=e.className.split(/\s+/g),r=!0;for(;;){var i=n.indexOf(t);if(i==-1)break;r=!1,n.splice(i,1)}return r&&n.push(t),e.className=n.join(" "),r},t.setCssClass=function(e,n,r){r?t.addCssClass(e,n):t.removeCssClass(e,n)},t.hasCssString=function(e,t){var n=0,r;t=t||document;if(t.createStyleSheet&&(r=t.styleSheets)){while(n<r.length)if(r[n++].owningElement.id===e)return!0}else if(r=t.getElementsByTagName("style"))while(n<r.length)if(r[n++].id===e)return!0;return!1},t.importCssString=function(n,i,s){s=s||document;if(i&&t.hasCssString(i,s))return null;var o;s.createStyleSheet?(o=s.createStyleSheet(),o.cssText=n,i&&(o.owningElement.id=i)):(o=s.createElementNS?s.createElementNS(r,"style"):s.createElement("style"),o.appendChild(s.createTextNode(n)),i&&(o.id=i),t.getDocumentHead(s).appendChild(o))},t.importCssStylsheet=function(e,n){if(n.createStyleSheet)n.createStyleSheet(e);else{var r=t.createElement("link");r.rel="stylesheet",r.href=e,t.getDocumentHead(n).appendChild(r)}},t.getInnerWidth=function(e){return parseInt(t.computedStyle(e,"paddingLeft"),10)+parseInt(t.computedStyle(e,"paddingRight"),10)+e.clientWidth},t.getInnerHeight=function(e){return parseInt(t.computedStyle(e,"paddingTop"),10)+parseInt(t.computedStyle(e,"paddingBottom"),10)+e.clientHeight},window.pageYOffset!==undefined?(t.getPageScrollTop=function(){return window.pageYOffset},t.getPageScrollLeft=function(){return window.pageXOffset}):(t.getPageScrollTop=function(){return document.body.scrollTop},t.getPageScrollLeft=function(){return document.body.scrollLeft}),window.getComputedStyle?t.computedStyle=function(e,t){return t?(window.getComputedStyle(e,"")||{})[t]||"":window.getComputedStyle(e,"")||{}}:t.computedStyle=function(e,t){return t?e.currentStyle[t]:e.currentStyle},t.scrollbarWidth=function(e){var n=t.createElement("ace_inner");n.style.width="100%",n.style.minWidth="0px",n.style.height="200px",n.style.display="block";var r=t.createElement("ace_outer"),i=r.style;i.position="absolute",i.left="-10000px",i.overflow="hidden",i.width="200px",i.minWidth="0px",i.height="150px",i.display="block",r.appendChild(n);var s=e.documentElement;s.appendChild(r);var o=n.offsetWidth;i.overflow="scroll";var u=n.offsetWidth;return o==u&&(u=r.clientWidth),s.removeChild(r),o-u},t.setInnerHtml=function(e,t){var n=e.cloneNode(!1);return n.innerHTML=t,e.parentNode.replaceChild(n,e),n},"textContent"in document.documentElement?(t.setInnerText=function(e,t){e.textContent=t},t.getInnerText=function(e){return e.textContent}):(t.setInnerText=function(e,t){e.innerText=t},t.getInnerText=function(e){return e.innerText}),t.getParentWindow=function(e){return e.defaultView||e.parentWindow}}),define("ace/theme/textmate",["require","exports","module","ace/lib/dom"],function(e,t,n){t.isDark=!1,t.cssClass="ace-tm",t.cssText='.ace-tm .ace_gutter {background: #f0f0f0;color: #333;}.ace-tm .ace_print-margin {width: 1px;background: #e8e8e8;}.ace-tm .ace_fold {background-color: #6B72E6;}.ace-tm {background-color: #FFFFFF;color: black;}.ace-tm .ace_cursor {color: black;}.ace-tm .ace_invisible {color: rgb(191, 191, 191);}.ace-tm .ace_storage,.ace-tm .ace_keyword {color: blue;}.ace-tm .ace_constant {color: rgb(197, 6, 11);}.ace-tm .ace_constant.ace_buildin {color: rgb(88, 72, 246);}.ace-tm .ace_constant.ace_language {color: rgb(88, 92, 246);}.ace-tm .ace_constant.ace_library {color: rgb(6, 150, 14);}.ace-tm .ace_invalid {background-color: rgba(255, 0, 0, 0.1);color: red;}.ace-tm .ace_support.ace_function {color: rgb(60, 76, 114);}.ace-tm .ace_support.ace_constant {color: rgb(6, 150, 14);}.ace-tm .ace_support.ace_type,.ace-tm .ace_support.ace_class {color: rgb(109, 121, 222);}.ace-tm .ace_keyword.ace_operator {color: rgb(104, 118, 135);}.ace-tm .ace_string {color: rgb(3, 106, 7);}.ace-tm .ace_comment {color: rgb(76, 136, 107);}.ace-tm .ace_comment.ace_doc {color: rgb(0, 102, 255);}.ace-tm .ace_comment.ace_doc.ace_tag {color: rgb(128, 159, 191);}.ace-tm .ace_constant.ace_numeric {color: rgb(0, 0, 205);}.ace-tm .ace_variable {color: rgb(49, 132, 149);}.ace-tm .ace_xml-pe {color: rgb(104, 104, 91);}.ace-tm .ace_entity.ace_name.ace_function {color: #0000A2;}.ace-tm .ace_heading {color: rgb(12, 7, 255);}.ace-tm .ace_list {color:rgb(185, 6, 144);}.ace-tm .ace_meta.ace_tag {color:rgb(0, 22, 142);}.ace-tm .ace_string.ace_regex {color: rgb(255, 0, 0)}.ace-tm .ace_marker-layer .ace_selection {background: rgb(181, 213, 255);}.ace-tm.ace_multiselect .ace_selection.ace_start {box-shadow: 0 0 3px 0px white;border-radius: 2px;}.ace-tm .ace_marker-layer .ace_step {background: rgb(252, 255, 0);}.ace-tm .ace_marker-layer .ace_stack {background: rgb(164, 229, 101);}.ace-tm .ace_marker-layer .ace_bracket {margin: -1px 0 0 -1px;border: 1px solid rgb(192, 192, 192);}.ace-tm .ace_marker-layer .ace_active-line {background: rgba(0, 0, 0, 0.07);}.ace-tm .ace_gutter-active-line {background-color : #dcdcdc;}.ace-tm .ace_marker-layer .ace_selected-word {background: rgb(250, 250, 255);border: 1px solid rgb(200, 200, 250);}.ace-tm .ace_indent-guide {background: url("data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAACCAYAAACZgbYnAAAAE0lEQVQImWP4////f4bLly//BwAmVgd1/w11/gAAAABJRU5ErkJggg==") right repeat-y;}';var r=e("../lib/dom");r.importCssString(t.cssText,t.cssClass)}),define("ace/lib/es5-shim",["require","exports","module"],function(e,t,n){function r(){}function w(e){try{return Object.defineProperty(e,"sentinel",{}),"sentinel"in e}catch(t){}}function H(e){return e=+e,e!==e?e=0:e!==0&&e!==1/0&&e!==-1/0&&(e=(e>0||-1)*Math.floor(Math.abs(e))),e}function B(e){var t=typeof e;return e===null||t==="undefined"||t==="boolean"||t==="number"||t==="string"}function j(e){var t,n,r;if(B(e))return e;n=e.valueOf;if(typeof n=="function"){t=n.call(e);if(B(t))return t}r=e.toString;if(typeof r=="function"){t=r.call(e);if(B(t))return t}throw new TypeError}Function.prototype.bind||(Function.prototype.bind=function(t){var n=this;if(typeof n!="function")throw new TypeError("Function.prototype.bind called on incompatible "+n);var i=u.call(arguments,1),s=function(){if(this instanceof s){var e=n.apply(this,i.concat(u.call(arguments)));return Object(e)===e?e:this}return n.apply(t,i.concat(u.call(arguments)))};return n.prototype&&(r.prototype=n.prototype,s.prototype=new r,r.prototype=null),s});var i=Function.prototype.call,s=Array.prototype,o=Object.prototype,u=s.slice,a=i.bind(o.toString),f=i.bind(o.hasOwnProperty),l,c,h,p,d;if(d=f(o,"__defineGetter__"))l=i.bind(o.__defineGetter__),c=i.bind(o.__defineSetter__),h=i.bind(o.__lookupGetter__),p=i.bind(o.__lookupSetter__);if([1,2].splice(0).length!=2)if(!function(){function e(e){var t=new Array(e+2);return t[0]=t[1]=0,t}var t=[],n;t.splice.apply(t,e(20)),t.splice.apply(t,e(26)),n=t.length,t.splice(5,0,"XXX"),n+1==t.length;if(n+1==t.length)return!0}())Array.prototype.splice=function(e,t){var n=this.length;e>0?e>n&&(e=n):e==void 0?e=0:e<0&&(e=Math.max(n+e,0)),e+t<n||(t=n-e);var r=this.slice(e,e+t),i=u.call(arguments,2),s=i.length;if(e===n)s&&this.push.apply(this,i);else{var o=Math.min(t,n-e),a=e+o,f=a+s-o,l=n-a,c=n-o;if(f<a)for(var h=0;h<l;++h)this[f+h]=this[a+h];else if(f>a)for(h=l;h--;)this[f+h]=this[a+h];if(s&&e===c)this.length=c,this.push.apply(this,i);else{this.length=c+s;for(h=0;h<s;++h)this[e+h]=i[h]}}return r};else{var v=Array.prototype.splice;Array.prototype.splice=function(e,t){return arguments.length?v.apply(this,[e===void 0?0:e,t===void 0?this.length-e:t].concat(u.call(arguments,2))):[]}}Array.isArray||(Array.isArray=function(t){return a(t)=="[object Array]"});var m=Object("a"),g=m[0]!="a"||!(0 in m);Array.prototype.forEach||(Array.prototype.forEach=function(t){var n=F(this),r=g&&a(this)=="[object String]"?this.split(""):n,i=arguments[1],s=-1,o=r.length>>>0;if(a(t)!="[object Function]")throw new TypeError;while(++s<o)s in r&&t.call(i,r[s],s,n)}),Array.prototype.map||(Array.prototype.map=function(t){var n=F(this),r=g&&a(this)=="[object String]"?this.split(""):n,i=r.length>>>0,s=Array(i),o=arguments[1];if(a(t)!="[object Function]")throw new TypeError(t+" is not a function");for(var u=0;u<i;u++)u in r&&(s[u]=t.call(o,r[u],u,n));return s}),Array.prototype.filter||(Array.prototype.filter=function(t){var n=F(this),r=g&&a(this)=="[object String]"?this.split(""):n,i=r.length>>>0,s=[],o,u=arguments[1];if(a(t)!="[object Function]")throw new TypeError(t+" is not a function");for(var f=0;f<i;f++)f in r&&(o=r[f],t.call(u,o,f,n)&&s.push(o));return s}),Array.prototype.every||(Array.prototype.every=function(t){var n=F(this),r=g&&a(this)=="[object String]"?this.split(""):n,i=r.length>>>0,s=arguments[1];if(a(t)!="[object Function]")throw new TypeError(t+" is not a function");for(var o=0;o<i;o++)if(o in r&&!t.call(s,r[o],o,n))return!1;return!0}),Array.prototype.some||(Array.prototype.some=function(t){var n=F(this),r=g&&a(this)=="[object String]"?this.split(""):n,i=r.length>>>0,s=arguments[1];if(a(t)!="[object Function]")throw new TypeError(t+" is not a function");for(var o=0;o<i;o++)if(o in r&&t.call(s,r[o],o,n))return!0;return!1}),Array.prototype.reduce||(Array.prototype.reduce=function(t){var n=F(this),r=g&&a(this)=="[object String]"?this.split(""):n,i=r.length>>>0;if(a(t)!="[object Function]")throw new TypeError(t+" is not a function");if(!i&&arguments.length==1)throw new TypeError("reduce of empty array with no initial value");var s=0,o;if(arguments.length>=2)o=arguments[1];else do{if(s in r){o=r[s++];break}if(++s>=i)throw new TypeError("reduce of empty array with no initial value")}while(!0);for(;s<i;s++)s in r&&(o=t.call(void 0,o,r[s],s,n));return o}),Array.prototype.reduceRight||(Array.prototype.reduceRight=function(t){var n=F(this),r=g&&a(this)=="[object String]"?this.split(""):n,i=r.length>>>0;if(a(t)!="[object Function]")throw new TypeError(t+" is not a function");if(!i&&arguments.length==1)throw new TypeError("reduceRight of empty array with no initial value");var s,o=i-1;if(arguments.length>=2)s=arguments[1];else do{if(o in r){s=r[o--];break}if(--o<0)throw new TypeError("reduceRight of empty array with no initial value")}while(!0);do o in this&&(s=t.call(void 0,s,r[o],o,n));while(o--);return s});if(!Array.prototype.indexOf||[0,1].indexOf(1,2)!=-1)Array.prototype.indexOf=function(t){var n=g&&a(this)=="[object String]"?this.split(""):F(this),r=n.length>>>0;if(!r)return-1;var i=0;arguments.length>1&&(i=H(arguments[1])),i=i>=0?i:Math.max(0,r+i);for(;i<r;i++)if(i in n&&n[i]===t)return i;return-1};if(!Array.prototype.lastIndexOf||[0,1].lastIndexOf(0,-3)!=-1)Array.prototype.lastIndexOf=function(t){var n=g&&a(this)=="[object String]"?this.split(""):F(this),r=n.length>>>0;if(!r)return-1;var i=r-1;arguments.length>1&&(i=Math.min(i,H(arguments[1]))),i=i>=0?i:r-Math.abs(i);for(;i>=0;i--)if(i in n&&t===n[i])return i;return-1};Object.getPrototypeOf||(Object.getPrototypeOf=function(t){return t.__proto__||(t.constructor?t.constructor.prototype:o)});if(!Object.getOwnPropertyDescriptor){var y="Object.getOwnPropertyDescriptor called on a non-object: ";Object.getOwnPropertyDescriptor=function(t,n){if(typeof t!="object"&&typeof t!="function"||t===null)throw new TypeError(y+t);if(!f(t,n))return;var r,i,s;r={enumerable:!0,configurable:!0};if(d){var u=t.__proto__;t.__proto__=o;var i=h(t,n),s=p(t,n);t.__proto__=u;if(i||s)return i&&(r.get=i),s&&(r.set=s),r}return r.value=t[n],r}}Object.getOwnPropertyNames||(Object.getOwnPropertyNames=function(t){return Object.keys(t)});if(!Object.create){var b;Object.prototype.__proto__===null?b=function(){return{__proto__:null}}:b=function(){var e={};for(var t in e)e[t]=null;return e.constructor=e.hasOwnProperty=e.propertyIsEnumerable=e.isPrototypeOf=e.toLocaleString=e.toString=e.valueOf=e.__proto__=null,e},Object.create=function(t,n){var r;if(t===null)r=b();else{if(typeof t!="object")throw new TypeError("typeof prototype["+typeof t+"] != 'object'");var i=function(){};i.prototype=t,r=new i,r.__proto__=t}return n!==void 0&&Object.defineProperties(r,n),r}}if(Object.defineProperty){var E=w({}),S=typeof document=="undefined"||w(document.createElement("div"));if(!E||!S)var x=Object.defineProperty}if(!Object.defineProperty||x){var T="Property description must be an object: ",N="Object.defineProperty called on non-object: ",C="getters & setters can not be defined on this javascript engine";Object.defineProperty=function(t,n,r){if(typeof t!="object"&&typeof t!="function"||t===null)throw new TypeError(N+t);if(typeof r!="object"&&typeof r!="function"||r===null)throw new TypeError(T+r);if(x)try{return x.call(Object,t,n,r)}catch(i){}if(f(r,"value"))if(d&&(h(t,n)||p(t,n))){var s=t.__proto__;t.__proto__=o,delete t[n],t[n]=r.value,t.__proto__=s}else t[n]=r.value;else{if(!d)throw new TypeError(C);f(r,"get")&&l(t,n,r.get),f(r,"set")&&c(t,n,r.set)}return t}}Object.defineProperties||(Object.defineProperties=function(t,n){for(var r in n)f(n,r)&&Object.defineProperty(t,r,n[r]);return t}),Object.seal||(Object.seal=function(t){return t}),Object.freeze||(Object.freeze=function(t){return t});try{Object.freeze(function(){})}catch(k){Object.freeze=function(t){return function(n){return typeof n=="function"?n:t(n)}}(Object.freeze)}Object.preventExtensions||(Object.preventExtensions=function(t){return t}),Object.isSealed||(Object.isSealed=function(t){return!1}),Object.isFrozen||(Object.isFrozen=function(t){return!1}),Object.isExtensible||(Object.isExtensible=function(t){if(Object(t)===t)throw new TypeError;var n="";while(f(t,n))n+="?";t[n]=!0;var r=f(t,n);return delete t[n],r});if(!Object.keys){var L=!0,A=["toString","toLocaleString","valueOf","hasOwnProperty","isPrototypeOf","propertyIsEnumerable","constructor"],O=A.length;for(var M in{toString:null})L=!1;Object.keys=function I(e){if(typeof e!="object"&&typeof e!="function"||e===null)throw new TypeError("Object.keys called on a non-object");var I=[];for(var t in e)f(e,t)&&I.push(t);if(L)for(var n=0,r=O;n<r;n++){var i=A[n];f(e,i)&&I.push(i)}return I}}Date.now||(Date.now=function(){return(new Date).getTime()});var _=" \n\x0b\f\r \xa0\u1680\u180e\u2000\u2001\u2002\u2003\u2004\u2005\u2006\u2007\u2008\u2009\u200a\u202f\u205f\u3000\u2028\u2029\ufeff";if(!String.prototype.trim||_.trim()){_="["+_+"]";var D=new RegExp("^"+_+_+"*"),P=new RegExp(_+_+"*$");String.prototype.trim=function(){return String(this).replace(D,"").replace(P,"")}}var F=function(e){if(e==null)throw new TypeError("can't convert "+e+" to object");return Object(e)}}),define("ace/lib/regexp",["require","exports","module"],function(e,t,n){function o(e){return(e.global?"g":"")+(e.ignoreCase?"i":"")+(e.multiline?"m":"")+(e.extended?"x":"")+(e.sticky?"y":"")}function u(e,t,n){if(Array.prototype.indexOf)return e.indexOf(t,n);for(var r=n||0;r<e.length;r++)if(e[r]===t)return r;return-1}var r={exec:RegExp.prototype.exec,test:RegExp.prototype.test,match:String.prototype.match,replace:String.prototype.replace,split:String.prototype.split},i=r.exec.call(/()??/,"")[1]===undefined,s=function(){var e=/^/g;return r.test.call(e,""),!e.lastIndex}();if(s&&i)return;RegExp.prototype.exec=function(e){var t=r.exec.apply(this,arguments),n,a;if(typeof e=="string"&&t){!i&&t.length>1&&u(t,"")>-1&&(a=RegExp(this.source,r.replace.call(o(this),"g","")),r.replace.call(e.slice(t.index),a,function(){for(var e=1;e<arguments.length-2;e++)arguments[e]===undefined&&(t[e]=undefined)}));if(this._xregexp&&this._xregexp.captureNames)for(var f=1;f<t.length;f++)n=this._xregexp.captureNames[f-1],n&&(t[n]=t[f]);!s&&this.global&&!t[0].length&&this.lastIndex>t.index&&this.lastIndex--}return t},s||(RegExp.prototype.test=function(e){var t=r.exec.call(this,e);return t&&this.global&&!t[0].length&&this.lastIndex>t.index&&this.lastIndex--,!!t})}),define("ace/ext/error_marker",["require","exports","module","ace/line_widgets","ace/lib/dom","ace/range"],function(e,t,n){function o(e,t,n){var r=0,i=e.length-1;while(r<=i){var s=r+i>>1,o=n(t,e[s]);if(o>0)r=s+1;else{if(!(o<0))return s;i=s-1}}return-(r+1)}function u(e,t,n){var r=e.getAnnotations().sort(s.comparePoints);if(!r.length)return;var i=o(r,{row:t,column:-1},s.comparePoints);i<0&&(i=-i-1),i>=r.length-1?i=n>0?0:r.length-1:i===0&&n<0&&(i=r.length-1);var u=r[i];if(!u||!n)return;if(u.row===t){do u=r[i+=n];while(u&&u.row===t);if(!u)return r.slice()}var a=[];t=u.row;do a[n<0?"unshift":"push"](u),u=r[i+=n];while(u&&u.row==t);return a.length&&a}var r=e("ace/line_widgets").LineWidgets,i=e("ace/lib/dom"),s=e("ace/range").Range;t.showErrorMarker=function(e,t){var n=e.session;n.widgetManager||(n.widgetManager=new r(n),n.widgetManager.attach(e));var s=e.getCursorPosition(),o=s.row,a=n.lineWidgets&&n.lineWidgets[o];a?a.destroy():o-=t;var f=u(n,o,t),l;if(f){var c=f[0];s.column=(c.pos&&typeof c.column!="number"?c.pos.sc:c.column)||0,s.row=c.row,l=e.renderer.$gutterLayer.$annotations[s.row]}else{if(a)return;l={text:["Looks good!"],className:"ace_ok"}}e.session.unfold(s.row),e.selection.moveToPosition(s);var h={row:s.row,fixedWidth:!0,coverGutter:!0,el:i.createElement("div")},p=h.el.appendChild(i.createElement("div")),d=h.el.appendChild(i.createElement("div"));d.className="error_widget_arrow "+l.className;var v=e.renderer.$cursorLayer.getPixelPosition(s).left;d.style.left=v+e.renderer.gutterWidth-5+"px",h.el.className="error_widget_wrapper",p.className="error_widget "+l.className,p.innerHTML=l.text.join("<br>"),p.appendChild(i.createElement("div"));var m=function(e,t,n){if(t===0&&(n==="esc"||n==="return"))return h.destroy(),{command:"null"}};h.destroy=function(){if(e.$mouseHandler.isMousePressed)return;e.keyBinding.removeKeyboardHandler(m),n.widgetManager.removeLineWidget(h),e.off("changeSelection",h.destroy),e.off("changeSession",h.destroy),e.off("mouseup",h.destroy),e.off("change",h.destroy)},e.keyBinding.addKeyboardHandler(m),e.on("changeSelection",h.destroy),e.on("changeSession",h.destroy),e.on("mouseup",h.destroy),e.on("change",h.destroy),e.session.widgetManager.addLineWidget(h),h.el.onmousedown=e.focus.bind(e),e.renderer.scrollCursorIntoView(null,.5,{bottom:h.el.offsetHeight})},i.importCssString(" .error_widget_wrapper { background: inherit; color: inherit; border:none } .error_widget { border-top: solid 2px; border-bottom: solid 2px; margin: 5px 0; padding: 10px 40px; white-space: pre-wrap; } .error_widget.ace_error, .error_widget_arrow.ace_error{ border-color: #ff5a5a } .error_widget.ace_warning, .error_widget_arrow.ace_warning{ border-color: #F1D817 } .error_widget.ace_info, .error_widget_arrow.ace_info{ border-color: #5a5a5a } .error_widget.ace_ok, .error_widget_arrow.ace_ok{ border-color: #5aaa5a } .error_widget_arrow { position: absolute; border: solid 5px; border-top-color: transparent!important; border-right-color: transparent!important; border-left-color: transparent!important; top: -5px; }","")}),define("ace/lib/fixoldbrowsers",["require","exports","module","ace/lib/regexp","ace/lib/es5-shim"],function(e,t,n){e("./regexp"),e("./es5-shim")}),define("ace/line_widgets",["require","exports","module","ace/lib/oop","ace/lib/dom","ace/range"],function(e,t,n){function o(e){this.session=e,this.session.widgetManager=this,this.session.getRowLength=this.getRowLength,this.session.$getWidgetScreenLength=this.$getWidgetScreenLength,this.updateOnChange=this.updateOnChange.bind(this),this.renderWidgets=this.renderWidgets.bind(this),this.measureWidgets=this.measureWidgets.bind(this),this.session._changedWidgets=[],this.detach=this.detach.bind(this),this.session.on("change",this.updateOnChange)}var r=e("./lib/oop"),i=e("./lib/dom"),s=e("./range").Range;(function(){this.getRowLength=function(e){var t;return this.lineWidgets?t=this.lineWidgets[e]&&this.lineWidgets[e].rowCount||0:t=0,!this.$useWrapMode||!this.$wrapData[e]?1+t:this.$wrapData[e].length+1+t},this.$getWidgetScreenLength=function(){var e=0;return this.lineWidgets.forEach(function(t){t&&t.rowCount&&(e+=t.rowCount)}),e},this.attach=function(e){e.widgetManager&&e.widgetManager!=this&&e.widgetManager.detach();if(this.editor==e)return;this.detach(),this.editor=e,this.editor.on("changeSession",this.detach),e.widgetManager=this,e.setOption("enableLineWidgets",!0),e.renderer.on("beforeRender",this.measureWidgets),e.renderer.on("afterRender",this.renderWidgets)},this.detach=function(e){if(e&&e.session==this.session)return;var t=this.editor;if(!t)return;t.off("changeSession",this.detach),this.editor=null,t.widgetManager=null,t.renderer.off("beforeRender",this.measureWidgets),t.renderer.off("afterRender",this.renderWidgets);var n=this.session.lineWidgets;n&&n.forEach(function(e){e&&e.el&&e.el.parentNode&&(e._inDocument=!1,e.el.parentNode.removeChild(e.el))})},this.updateOnChange=function(e){var t=this.session.lineWidgets;if(!t)return;var n=e.data,r=n.range,i=r.start.row,s=r.end.row-i;if(s!==0)if(n.action=="removeText"||n.action=="removeLines"){var o=t.splice(i+1,s);o.forEach(function(e){e&&this.removeLineWidget(e)},this),this.$updateRows()}else{var u=new Array(s);u.unshift(i,0),t.splice.apply(t,u),this.$updateRows()}},this.$updateRows=function(){var e=this.session.lineWidgets;if(!e)return;var t=!0;e.forEach(function(e,n){e&&(t=!1,e.row=n)}),t&&(this.session.lineWidgets=null)},this.addLineWidget=function(e){this.session.lineWidgets||(this.session.lineWidgets=new Array(this.session.getLength())),this.session.lineWidgets[e.row]=e;var t=this.editor.renderer;return e.html&&!e.el&&(e.el=i.createElement("div"),e.el.innerHTML=e.html),e.el&&(i.addCssClass(e.el,"ace_lineWidgetContainer"),e.el.style.position="absolute",e.el.style.zIndex=5,t.container.appendChild(e.el),e._inDocument=!0),e.coverGutter||(e.el.style.zIndex=3),e.pixelHeight||(e.pixelHeight=e.el.offsetHeight),e.rowCount==null&&(e.rowCount=e.pixelHeight/t.layerConfig.lineHeight),this.session._emit("changeFold",{data:{start:{row:e.row}}}),this.$updateRows(),this.renderWidgets(null,t),e},this.removeLineWidget=function(e){e._inDocument=!1,e.el&&e.el.parentNode&&e.el.parentNode.removeChild(e.el);if(e.editor&&e.editor.destroy)try{e.editor.destroy()}catch(t){}this.session.lineWidgets&&(this.session.lineWidgets[e.row]=undefined),this.session._emit("changeFold",{data:{start:{row:e.row}}}),this.$updateRows()},this.onWidgetChanged=function(e){this.session._changedWidgets.push(e),this.editor&&this.editor.renderer.updateFull()},this.measureWidgets=function(e,t){var n=this.session._changedWidgets,r=t.layerConfig;if(!n||!n.length)return;var i=Infinity;for(var s=0;s<n.length;s++){var o=n[s];o._inDocument||(o._inDocument=!0,t.container.appendChild(o.el)),o.h=o.el.offsetHeight,o.fixedWidth||(o.w=o.el.offsetWidth,o.screenWidth=Math.ceil(o.w/r.characterWidth));var u=o.h/r.lineHeight;o.coverLine&&(u-=this.session.getRowLineCount(o.row),u<0&&(u=0)),o.rowCount!=u&&(o.rowCount=u,o.row<i&&(i=o.row))}i!=Infinity&&(this.session._emit("changeFold",{data:{start:{row:i}}}),this.session.lineWidgetWidth=null),this.session._changedWidgets=[]},this.renderWidgets=function(e,t){var n=t.layerConfig,r=this.session.lineWidgets;if(!r)return;var i=Math.min(this.firstRow,n.firstRow),s=Math.max(this.lastRow,n.lastRow,r.length);while(i>0&&!r[i])i--;this.firstRow=n.firstRow,this.lastRow=n.lastRow,t.$cursorLayer.config=n;for(var o=i;o<=s;o++){var u=r[o];if(!u||!u.el)continue;u._inDocument||(u._inDocument=!0,t.container.appendChild(u.el));var a=t.$cursorLayer.getPixelPosition({row:o,column:0},!0).top;u.coverLine||(a+=n.lineHeight*this.session.getRowLineCount(u.row)),u.el.style.top=a-n.offset+"px";var f=u.coverGutter?0:t.gutterWidth;u.fixedWidth||(f-=t.scrollLeft),u.el.style.left=f+"px",u.fixedWidth?u.el.style.right=t.scrollBar.getWidth()+"px":u.el.style.right=""}}}).call(o.prototype),t.LineWidgets=o}),define("ace/document",["require","exports","module","ace/lib/oop","ace/lib/event_emitter","ace/range","ace/anchor"],function(e,t,n){var r=e("./lib/oop"),i=e("./lib/event_emitter").EventEmitter,s=e("./range").Range,o=e("./anchor").Anchor,u=function(e){this.$lines=[],e.length===0?this.$lines=[""]:Array.isArray(e)?this._insertLines(0,e):this.insert({row:0,column:0},e)};(function(){r.implement(this,i),this.setValue=function(e){var t=this.getLength();this.remove(new s(0,0,t,this.getLine(t-1).length)),this.insert({row:0,column:0},e)},this.getValue=function(){return this.getAllLines().join(this.getNewLineCharacter())},this.createAnchor=function(e,t){return new o(this,e,t)},"aaa".split(/a/).length===0?this.$split=function(e){return e.replace(/\r\n|\r/g,"\n").split("\n")}:this.$split=function(e){return e.split(/\r\n|\r|\n/)},this.$detectNewLine=function(e){var t=e.match(/^.*?(\r\n|\r|\n)/m);this.$autoNewLine=t?t[1]:"\n",this._signal("changeNewLineMode")},this.getNewLineCharacter=function(){switch(this.$newLineMode){case"windows":return"\r\n";case"unix":return"\n";default:return this.$autoNewLine||"\n"}},this.$autoNewLine="",this.$newLineMode="auto",this.setNewLineMode=function(e){if(this.$newLineMode===e)return;this.$newLineMode=e,this._signal("changeNewLineMode")},this.getNewLineMode=function(){return this.$newLineMode},this.isNewLine=function(e){return e=="\r\n"||e=="\r"||e=="\n"},this.getLine=function(e){return this.$lines[e]||""},this.getLines=function(e,t){return this.$lines.slice(e,t+1)},this.getAllLines=function(){return this.getLines(0,this.getLength())},this.getLength=function(){return this.$lines.length},this.getTextRange=function(e){if(e.start.row==e.end.row)return this.getLine(e.start.row).substring(e.start.column,e.end.column);var t=this.getLines(e.start.row,e.end.row);t[0]=(t[0]||"").substring(e.start.column);var n=t.length-1;return e.end.row-e.start.row==n&&(t[n]=t[n].substring(0,e.end.column)),t.join(this.getNewLineCharacter())},this.$clipPosition=function(e){var t=this.getLength();return e.row>=t?(e.row=Math.max(0,t-1),e.column=this.getLine(t-1).length):e.row<0&&(e.row=0),e},this.insert=function(e,t){if(!t||t.length===0)return e;e=this.$clipPosition(e),this.getLength()<=1&&this.$detectNewLine(t);var n=this.$split(t),r=n.splice(0,1)[0],i=n.length==0?null:n.splice(n.length-1,1)[0];return e=this.insertInLine(e,r),i!==null&&(e=this.insertNewLine(e),e=this._insertLines(e.row,n),e=this.insertInLine(e,i||"")),e},this.insertLines=function(e,t){return e>=this.getLength()?this.insert({row:e,column:0},"\n"+t.join("\n")):this._insertLines(Math.max(e,0),t)},this._insertLines=function(e,t){if(t.length==0)return{row:e,column:0};while(t.length>61440){var n=this._insertLines(e,t.slice(0,61440));t=t.slice(61440),e=n.row}var r=[e,0];r.push.apply(r,t),this.$lines.splice.apply(this.$lines,r);var i=new s(e,0,e+t.length,0),o={action:"insertLines",range:i,lines:t};return this._signal("change",{data:o}),i.end},this.insertNewLine=function(e){e=this.$clipPosition(e);var t=this.$lines[e.row]||"";this.$lines[e.row]=t.substring(0,e.column),this.$lines.splice(e.row+1,0,t.substring(e.column,t.length));var n={row:e.row+1,column:0},r={action:"insertText",range:s.fromPoints(e,n),text:this.getNewLineCharacter()};return this._signal("change",{data:r}),n},this.insertInLine=function(e,t){if(t.length==0)return e;var n=this.$lines[e.row]||"";this.$lines[e.row]=n.substring(0,e.column)+t+n.substring(e.column);var r={row:e.row,column:e.column+t.length},i={action:"insertText",range:s.fromPoints(e,r),text:t};return this._signal("change",{data:i}),r},this.remove=function(e){e instanceof s||(e=s.fromPoints(e.start,e.end)),e.start=this.$clipPosition(e.start),e.end=this.$clipPosition(e.end);if(e.isEmpty())return e.start;var t=e.start.row,n=e.end.row;if(e.isMultiLine()){var r=e.start.column==0?t:t+1,i=n-1;e.end.column>0&&this.removeInLine(n,0,e.end.column),i>=r&&this._removeLines(r,i),r!=t&&(this.removeInLine(t,e.start.column,this.getLine(t).length),this.removeNewLine(e.start.row))}else this.removeInLine(t,e.start.column,e.end.column);return e.start},this.removeInLine=function(e,t,n){if(t==n)return;var r=new s(e,t,e,n),i=this.getLine(e),o=i.substring(t,n),u=i.substring(0,t)+i.substring(n,i.length);this.$lines.splice(e,1,u);var a={action:"removeText",range:r,text:o};return this._signal("change",{data:a}),r.start},this.removeLines=function(e,t){return e<0||t>=this.getLength()?this.remove(new s(e,0,t+1,0)):this._removeLines(e,t)},this._removeLines=function(e,t){var n=new s(e,0,t+1,0),r=this.$lines.splice(e,t-e+1),i={action:"removeLines",range:n,nl:this.getNewLineCharacter(),lines:r};return this._signal("change",{data:i}),r},this.removeNewLine=function(e){var t=this.getLine(e),n=this.getLine(e+1),r=new s(e,t.length,e+1,0),i=t+n;this.$lines.splice(e,2,i);var o={action:"removeText",range:r,text:this.getNewLineCharacter()};this._signal("change",{data:o})},this.replace=function(e,t){e instanceof s||(e=s.fromPoints(e.start,e.end));if(t.length==0&&e.isEmpty())return e.start;if(t==this.getTextRange(e))return e.end;this.remove(e);if(t)var n=this.insert(e.start,t);else n=e.start;return n},this.applyDeltas=function(e){for(var t=0;t<e.length;t++){var n=e[t],r=s.fromPoints(n.range.start,n.range.end);n.action=="insertLines"?this.insertLines(r.start.row,n.lines):n.action=="insertText"?this.insert(r.start,n.text):n.action=="removeLines"?this._removeLines(r.start.row,r.end.row-1):n.action=="removeText"&&this.remove(r)}},this.revertDeltas=function(e){for(var t=e.length-1;t>=0;t--){var n=e[t],r=s.fromPoints(n.range.start,n.range.end);n.action=="insertLines"?this._removeLines(r.start.row,r.end.row-1):n.action=="insertText"?this.remove(r):n.action=="removeLines"?this._insertLines(r.start.row,n.lines):n.action=="removeText"&&this.insert(r.start,n.text)}},this.indexToPosition=function(e,t){var n=this.$lines||this.getAllLines(),r=this.getNewLineCharacter().length;for(var i=t||0,s=n.length;i<s;i++){e-=n[i].length+r;if(e<0)return{row:i,column:e+n[i].length+r}}return{row:s-1,column:n[s-1].length}},this.positionToIndex=function(e,t){var n=this.$lines||this.getAllLines(),r=this.getNewLineCharacter().length,i=0,s=Math.min(e.row,n.length);for(var o=t||0;o<s;++o)i+=n[o].length+r;return i+e.column}}).call(u.prototype),t.Document=u}),function(){window.require(["ace/ace"],function(e){e&&e.config.init(!0),window.ace||(window.ace=e);for(var t in e)e.hasOwnProperty(t)&&(ace[t]=e[t])})}()
\ No newline at end of file
--- /dev/null
+/* ***** BEGIN LICENSE BLOCK *****
+ * Distributed under the BSD license:
+ *
+ * Copyright (c) 2010, Ajax.org B.V.
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are met:
+ * * Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * * Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ * * Neither the name of Ajax.org B.V. nor the
+ * names of its contributors may be used to endorse or promote products
+ * derived from this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
+ * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
+ * DISCLAIMED. IN NO EVENT SHALL AJAX.ORG B.V. BE LIABLE FOR ANY
+ * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
+ * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
+ * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
+ * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
+ * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ *
+ * ***** END LICENSE BLOCK ***** */
+
+define('ace/mode/css', ['require', 'exports', 'module' , 'ace/lib/oop', 'ace/mode/text', 'ace/tokenizer', 'ace/mode/css_highlight_rules', 'ace/mode/matching_brace_outdent', 'ace/worker/worker_client', 'ace/mode/behaviour/css', 'ace/mode/folding/cstyle'], function(require, exports, module) {
+
+
+var oop = require("../lib/oop");
+var TextMode = require("./text").Mode;
+var Tokenizer = require("../tokenizer").Tokenizer;
+var CssHighlightRules = require("./css_highlight_rules").CssHighlightRules;
+var MatchingBraceOutdent = require("./matching_brace_outdent").MatchingBraceOutdent;
+var WorkerClient = require("../worker/worker_client").WorkerClient;
+var CssBehaviour = require("./behaviour/css").CssBehaviour;
+var CStyleFoldMode = require("./folding/cstyle").FoldMode;
+
+var Mode = function() {
+ this.HighlightRules = CssHighlightRules;
+ this.$outdent = new MatchingBraceOutdent();
+ this.$behaviour = new CssBehaviour();
+ this.foldingRules = new CStyleFoldMode();
+};
+oop.inherits(Mode, TextMode);
+
+(function() {
+
+ this.foldingRules = "cStyle";
+ this.blockComment = {start: "/*", end: "*/"};
+
+ this.getNextLineIndent = function(state, line, tab) {
+ var indent = this.$getIndent(line);
+ var tokens = this.getTokenizer().getLineTokens(line, state).tokens;
+ if (tokens.length && tokens[tokens.length-1].type == "comment") {
+ return indent;
+ }
+
+ var match = line.match(/^.*\{\s*$/);
+ if (match) {
+ indent += tab;
+ }
+
+ return indent;
+ };
+
+ this.checkOutdent = function(state, line, input) {
+ return this.$outdent.checkOutdent(line, input);
+ };
+
+ this.autoOutdent = function(state, doc, row) {
+ this.$outdent.autoOutdent(doc, row);
+ };
+
+ this.createWorker = function(session) {
+ var worker = new WorkerClient(["ace"], "ace/mode/css_worker", "Worker");
+ worker.attachToDocument(session.getDocument());
+
+ worker.on("csslint", function(e) {
+ session.setAnnotations(e.data);
+ });
+
+ worker.on("terminate", function() {
+ session.clearAnnotations();
+ });
+
+ return worker;
+ };
+
+ this.$id = "ace/mode/css";
+}).call(Mode.prototype);
+
+exports.Mode = Mode;
+
+});
+
+define('ace/mode/css_highlight_rules', ['require', 'exports', 'module' , 'ace/lib/oop', 'ace/lib/lang', 'ace/mode/text_highlight_rules'], function(require, exports, module) {
+
+
+var oop = require("../lib/oop");
+var lang = require("../lib/lang");
+var TextHighlightRules = require("./text_highlight_rules").TextHighlightRules;
+var supportType = exports.supportType = "animation-fill-mode|alignment-adjust|alignment-baseline|animation-delay|animation-direction|animation-duration|animation-iteration-count|animation-name|animation-play-state|animation-timing-function|animation|appearance|azimuth|backface-visibility|background-attachment|background-break|background-clip|background-color|background-image|background-origin|background-position|background-repeat|background-size|background|baseline-shift|binding|bleed|bookmark-label|bookmark-level|bookmark-state|bookmark-target|border-bottom|border-bottom-color|border-bottom-left-radius|border-bottom-right-radius|border-bottom-style|border-bottom-width|border-collapse|border-color|border-image|border-image-outset|border-image-repeat|border-image-slice|border-image-source|border-image-width|border-left|border-left-color|border-left-style|border-left-width|border-radius|border-right|border-right-color|border-right-style|border-right-width|border-spacing|border-style|border-top|border-top-color|border-top-left-radius|border-top-right-radius|border-top-style|border-top-width|border-width|border|bottom|box-align|box-decoration-break|box-direction|box-flex-group|box-flex|box-lines|box-ordinal-group|box-orient|box-pack|box-shadow|box-sizing|break-after|break-before|break-inside|caption-side|clear|clip|color-profile|color|column-count|column-fill|column-gap|column-rule|column-rule-color|column-rule-style|column-rule-width|column-span|column-width|columns|content|counter-increment|counter-reset|crop|cue-after|cue-before|cue|cursor|direction|display|dominant-baseline|drop-initial-after-adjust|drop-initial-after-align|drop-initial-before-adjust|drop-initial-before-align|drop-initial-size|drop-initial-value|elevation|empty-cells|fit|fit-position|float-offset|float|font-family|font-size|font-size-adjust|font-stretch|font-style|font-variant|font-weight|font|grid-columns|grid-rows|hanging-punctuation|height|hyphenate-after|hyphenate-before|hyphenate-character|hyphenate-lines|hyphenate-resource|hyphens|icon|image-orientation|image-rendering|image-resolution|inline-box-align|left|letter-spacing|line-height|line-stacking-ruby|line-stacking-shift|line-stacking-strategy|line-stacking|list-style-image|list-style-position|list-style-type|list-style|margin-bottom|margin-left|margin-right|margin-top|margin|mark-after|mark-before|mark|marks|marquee-direction|marquee-play-count|marquee-speed|marquee-style|max-height|max-width|min-height|min-width|move-to|nav-down|nav-index|nav-left|nav-right|nav-up|opacity|orphans|outline-color|outline-offset|outline-style|outline-width|outline|overflow-style|overflow-x|overflow-y|overflow|padding-bottom|padding-left|padding-right|padding-top|padding|page-break-after|page-break-before|page-break-inside|page-policy|page|pause-after|pause-before|pause|perspective-origin|perspective|phonemes|pitch-range|pitch|play-during|pointer-events|position|presentation-level|punctuation-trim|quotes|rendering-intent|resize|rest-after|rest-before|rest|richness|right|rotation-point|rotation|ruby-align|ruby-overhang|ruby-position|ruby-span|size|speak-header|speak-numeral|speak-punctuation|speak|speech-rate|stress|string-set|table-layout|target-name|target-new|target-position|target|text-align-last|text-align|text-decoration|text-emphasis|text-height|text-indent|text-justify|text-outline|text-shadow|text-transform|text-wrap|top|transform-origin|transform-style|transform|transition-delay|transition-duration|transition-property|transition-timing-function|transition|unicode-bidi|vertical-align|visibility|voice-balance|voice-duration|voice-family|voice-pitch-range|voice-pitch|voice-rate|voice-stress|voice-volume|volume|white-space-collapse|white-space|widows|width|word-break|word-spacing|word-wrap|z-index";
+var supportFunction = exports.supportFunction = "rgb|rgba|url|attr|counter|counters";
+var supportConstant = exports.supportConstant = "absolute|after-edge|after|all-scroll|all|alphabetic|always|antialiased|armenian|auto|avoid-column|avoid-page|avoid|balance|baseline|before-edge|before|below|bidi-override|block-line-height|block|bold|bolder|border-box|both|bottom|box|break-all|break-word|capitalize|caps-height|caption|center|central|char|circle|cjk-ideographic|clone|close-quote|col-resize|collapse|column|consider-shifts|contain|content-box|cover|crosshair|cubic-bezier|dashed|decimal-leading-zero|decimal|default|disabled|disc|disregard-shifts|distribute-all-lines|distribute-letter|distribute-space|distribute|dotted|double|e-resize|ease-in|ease-in-out|ease-out|ease|ellipsis|end|exclude-ruby|fill|fixed|georgian|glyphs|grid-height|groove|hand|hanging|hebrew|help|hidden|hiragana-iroha|hiragana|horizontal|icon|ideograph-alpha|ideograph-numeric|ideograph-parenthesis|ideograph-space|ideographic|inactive|include-ruby|inherit|initial|inline-block|inline-box|inline-line-height|inline-table|inline|inset|inside|inter-ideograph|inter-word|invert|italic|justify|katakana-iroha|katakana|keep-all|last|left|lighter|line-edge|line-through|line|linear|list-item|local|loose|lower-alpha|lower-greek|lower-latin|lower-roman|lowercase|lr-tb|ltr|mathematical|max-height|max-size|medium|menu|message-box|middle|move|n-resize|ne-resize|newspaper|no-change|no-close-quote|no-drop|no-open-quote|no-repeat|none|normal|not-allowed|nowrap|nw-resize|oblique|open-quote|outset|outside|overline|padding-box|page|pointer|pre-line|pre-wrap|pre|preserve-3d|progress|relative|repeat-x|repeat-y|repeat|replaced|reset-size|ridge|right|round|row-resize|rtl|s-resize|scroll|se-resize|separate|slice|small-caps|small-caption|solid|space|square|start|static|status-bar|step-end|step-start|steps|stretch|strict|sub|super|sw-resize|table-caption|table-cell|table-column-group|table-column|table-footer-group|table-header-group|table-row-group|table-row|table|tb-rl|text-after-edge|text-before-edge|text-bottom|text-size|text-top|text|thick|thin|transparent|underline|upper-alpha|upper-latin|upper-roman|uppercase|use-script|vertical-ideographic|vertical-text|visible|w-resize|wait|whitespace|z-index|zero";
+var supportConstantColor = exports.supportConstantColor = "aqua|black|blue|fuchsia|gray|green|lime|maroon|navy|olive|orange|purple|red|silver|teal|white|yellow";
+var supportConstantFonts = exports.supportConstantFonts = "arial|century|comic|courier|garamond|georgia|helvetica|impact|lucida|symbol|system|tahoma|times|trebuchet|utopia|verdana|webdings|sans-serif|serif|monospace";
+
+var numRe = exports.numRe = "\\-?(?:(?:[0-9]+)|(?:[0-9]*\\.[0-9]+))";
+var pseudoElements = exports.pseudoElements = "(\\:+)\\b(after|before|first-letter|first-line|moz-selection|selection)\\b";
+var pseudoClasses = exports.pseudoClasses = "(:)\\b(active|checked|disabled|empty|enabled|first-child|first-of-type|focus|hover|indeterminate|invalid|last-child|last-of-type|link|not|nth-child|nth-last-child|nth-last-of-type|nth-of-type|only-child|only-of-type|required|root|target|valid|visited)\\b";
+
+var CssHighlightRules = function() {
+
+ var keywordMapper = this.createKeywordMapper({
+ "support.function": supportFunction,
+ "support.constant": supportConstant,
+ "support.type": supportType,
+ "support.constant.color": supportConstantColor,
+ "support.constant.fonts": supportConstantFonts
+ }, "text", true);
+
+ this.$rules = {
+ "start" : [{
+ token : "comment", // multi line comment
+ regex : "\\/\\*",
+ push : "comment"
+ }, {
+ token: "paren.lparen",
+ regex: "\\{",
+ push: "ruleset"
+ }, {
+ token: "string",
+ regex: "@.*?{",
+ push: "media"
+ }, {
+ token: "keyword",
+ regex: "#[a-z0-9-_]+"
+ }, {
+ token: "variable",
+ regex: "\\.[a-z0-9-_]+"
+ }, {
+ token: "string",
+ regex: ":[a-z0-9-_]+"
+ }, {
+ token: "constant",
+ regex: "[a-z0-9-_]+"
+ }, {
+ caseInsensitive: true
+ }],
+
+ "media" : [{
+ token : "comment", // multi line comment
+ regex : "\\/\\*",
+ push : "comment"
+ }, {
+ token: "paren.lparen",
+ regex: "\\{",
+ push: "ruleset"
+ }, {
+ token: "string",
+ regex: "\\}",
+ next: "pop"
+ }, {
+ token: "keyword",
+ regex: "#[a-z0-9-_]+"
+ }, {
+ token: "variable",
+ regex: "\\.[a-z0-9-_]+"
+ }, {
+ token: "string",
+ regex: ":[a-z0-9-_]+"
+ }, {
+ token: "constant",
+ regex: "[a-z0-9-_]+"
+ }, {
+ caseInsensitive: true
+ }],
+
+ "comment" : [{
+ token : "comment",
+ regex : "\\*\\/",
+ next : "pop"
+ }, {
+ defaultToken : "comment"
+ }],
+
+ "ruleset" : [
+ {
+ token : "paren.rparen",
+ regex : "\\}",
+ next: "pop"
+ }, {
+ token : "comment", // multi line comment
+ regex : "\\/\\*",
+ push : "comment"
+ }, {
+ token : "string", // single line
+ regex : '["](?:(?:\\\\.)|(?:[^"\\\\]))*?["]'
+ }, {
+ token : "string", // single line
+ regex : "['](?:(?:\\\\.)|(?:[^'\\\\]))*?[']"
+ }, {
+ token : ["constant.numeric", "keyword"],
+ regex : "(" + numRe + ")(ch|cm|deg|em|ex|fr|gd|grad|Hz|in|kHz|mm|ms|pc|pt|px|rad|rem|s|turn|vh|vm|vw|%)"
+ }, {
+ token : "constant.numeric",
+ regex : numRe
+ }, {
+ token : "constant.numeric", // hex6 color
+ regex : "#[a-f0-9]{6}"
+ }, {
+ token : "constant.numeric", // hex3 color
+ regex : "#[a-f0-9]{3}"
+ }, {
+ token : ["punctuation", "entity.other.attribute-name.pseudo-element.css"],
+ regex : pseudoElements
+ }, {
+ token : ["punctuation", "entity.other.attribute-name.pseudo-class.css"],
+ regex : pseudoClasses
+ }, {
+ token : ["support.function", "string", "support.function"],
+ regex : "(url\\()(.*)(\\))"
+ }, {
+ token : keywordMapper,
+ regex : "\\-?[a-zA-Z_][a-zA-Z0-9_\\-]*"
+ }, {
+ caseInsensitive: true
+ }]
+ };
+
+ this.normalizeRules();
+};
+
+oop.inherits(CssHighlightRules, TextHighlightRules);
+
+exports.CssHighlightRules = CssHighlightRules;
+
+});
+
+define('ace/mode/matching_brace_outdent', ['require', 'exports', 'module' , 'ace/range'], function(require, exports, module) {
+
+
+var Range = require("../range").Range;
+
+var MatchingBraceOutdent = function() {};
+
+(function() {
+
+ this.checkOutdent = function(line, input) {
+ if (! /^\s+$/.test(line))
+ return false;
+
+ return /^\s*\}/.test(input);
+ };
+
+ this.autoOutdent = function(doc, row) {
+ var line = doc.getLine(row);
+ var match = line.match(/^(\s*\})/);
+
+ if (!match) return 0;
+
+ var column = match[1].length;
+ var openBracePos = doc.findMatchingBracket({row: row, column: column});
+
+ if (!openBracePos || openBracePos.row == row) return 0;
+
+ var indent = this.$getIndent(doc.getLine(openBracePos.row));
+ doc.replace(new Range(row, 0, row, column-1), indent);
+ };
+
+ this.$getIndent = function(line) {
+ return line.match(/^\s*/)[0];
+ };
+
+}).call(MatchingBraceOutdent.prototype);
+
+exports.MatchingBraceOutdent = MatchingBraceOutdent;
+});
+
+define('ace/mode/behaviour/css', ['require', 'exports', 'module' , 'ace/lib/oop', 'ace/mode/behaviour', 'ace/mode/behaviour/cstyle', 'ace/token_iterator'], function(require, exports, module) {
+
+
+var oop = require("../../lib/oop");
+var Behaviour = require("../behaviour").Behaviour;
+var CstyleBehaviour = require("./cstyle").CstyleBehaviour;
+var TokenIterator = require("../../token_iterator").TokenIterator;
+
+var CssBehaviour = function () {
+
+ this.inherit(CstyleBehaviour);
+
+ this.add("colon", "insertion", function (state, action, editor, session, text) {
+ if (text === ':') {
+ var cursor = editor.getCursorPosition();
+ var iterator = new TokenIterator(session, cursor.row, cursor.column);
+ var token = iterator.getCurrentToken();
+ if (token && token.value.match(/\s+/)) {
+ token = iterator.stepBackward();
+ }
+ if (token && token.type === 'support.type') {
+ var line = session.doc.getLine(cursor.row);
+ var rightChar = line.substring(cursor.column, cursor.column + 1);
+ if (rightChar === ':') {
+ return {
+ text: '',
+ selection: [1, 1]
+ }
+ }
+ if (!line.substring(cursor.column).match(/^\s*;/)) {
+ return {
+ text: ':;',
+ selection: [1, 1]
+ }
+ }
+ }
+ }
+ });
+
+ this.add("colon", "deletion", function (state, action, editor, session, range) {
+ var selected = session.doc.getTextRange(range);
+ if (!range.isMultiLine() && selected === ':') {
+ var cursor = editor.getCursorPosition();
+ var iterator = new TokenIterator(session, cursor.row, cursor.column);
+ var token = iterator.getCurrentToken();
+ if (token && token.value.match(/\s+/)) {
+ token = iterator.stepBackward();
+ }
+ if (token && token.type === 'support.type') {
+ var line = session.doc.getLine(range.start.row);
+ var rightChar = line.substring(range.end.column, range.end.column + 1);
+ if (rightChar === ';') {
+ range.end.column ++;
+ return range;
+ }
+ }
+ }
+ });
+
+ this.add("semicolon", "insertion", function (state, action, editor, session, text) {
+ if (text === ';') {
+ var cursor = editor.getCursorPosition();
+ var line = session.doc.getLine(cursor.row);
+ var rightChar = line.substring(cursor.column, cursor.column + 1);
+ if (rightChar === ';') {
+ return {
+ text: '',
+ selection: [1, 1]
+ }
+ }
+ }
+ });
+
+}
+oop.inherits(CssBehaviour, CstyleBehaviour);
+
+exports.CssBehaviour = CssBehaviour;
+});
+
+define('ace/mode/behaviour/cstyle', ['require', 'exports', 'module' , 'ace/lib/oop', 'ace/mode/behaviour', 'ace/token_iterator', 'ace/lib/lang'], function(require, exports, module) {
+
+
+var oop = require("../../lib/oop");
+var Behaviour = require("../behaviour").Behaviour;
+var TokenIterator = require("../../token_iterator").TokenIterator;
+var lang = require("../../lib/lang");
+
+var SAFE_INSERT_IN_TOKENS =
+ ["text", "paren.rparen", "punctuation.operator"];
+var SAFE_INSERT_BEFORE_TOKENS =
+ ["text", "paren.rparen", "punctuation.operator", "comment"];
+
+var context;
+var contextCache = {}
+var initContext = function(editor) {
+ var id = -1;
+ if (editor.multiSelect) {
+ id = editor.selection.id;
+ if (contextCache.rangeCount != editor.multiSelect.rangeCount)
+ contextCache = {rangeCount: editor.multiSelect.rangeCount};
+ }
+ if (contextCache[id])
+ return context = contextCache[id];
+ context = contextCache[id] = {
+ autoInsertedBrackets: 0,
+ autoInsertedRow: -1,
+ autoInsertedLineEnd: "",
+ maybeInsertedBrackets: 0,
+ maybeInsertedRow: -1,
+ maybeInsertedLineStart: "",
+ maybeInsertedLineEnd: ""
+ };
+};
+
+var CstyleBehaviour = function() {
+ this.add("braces", "insertion", function(state, action, editor, session, text) {
+ var cursor = editor.getCursorPosition();
+ var line = session.doc.getLine(cursor.row);
+ if (text == '{') {
+ initContext(editor);
+ var selection = editor.getSelectionRange();
+ var selected = session.doc.getTextRange(selection);
+ if (selected !== "" && selected !== "{" && editor.getWrapBehavioursEnabled()) {
+ return {
+ text: '{' + selected + '}',
+ selection: false
+ };
+ } else if (CstyleBehaviour.isSaneInsertion(editor, session)) {
+ if (/[\]\}\)]/.test(line[cursor.column]) || editor.inMultiSelectMode) {
+ CstyleBehaviour.recordAutoInsert(editor, session, "}");
+ return {
+ text: '{}',
+ selection: [1, 1]
+ };
+ } else {
+ CstyleBehaviour.recordMaybeInsert(editor, session, "{");
+ return {
+ text: '{',
+ selection: [1, 1]
+ };
+ }
+ }
+ } else if (text == '}') {
+ initContext(editor);
+ var rightChar = line.substring(cursor.column, cursor.column + 1);
+ if (rightChar == '}') {
+ var matching = session.$findOpeningBracket('}', {column: cursor.column + 1, row: cursor.row});
+ if (matching !== null && CstyleBehaviour.isAutoInsertedClosing(cursor, line, text)) {
+ CstyleBehaviour.popAutoInsertedClosing();
+ return {
+ text: '',
+ selection: [1, 1]
+ };
+ }
+ }
+ } else if (text == "\n" || text == "\r\n") {
+ initContext(editor);
+ var closing = "";
+ if (CstyleBehaviour.isMaybeInsertedClosing(cursor, line)) {
+ closing = lang.stringRepeat("}", context.maybeInsertedBrackets);
+ CstyleBehaviour.clearMaybeInsertedClosing();
+ }
+ var rightChar = line.substring(cursor.column, cursor.column + 1);
+ if (rightChar === '}') {
+ var openBracePos = session.findMatchingBracket({row: cursor.row, column: cursor.column+1}, '}');
+ if (!openBracePos)
+ return null;
+ var next_indent = this.$getIndent(session.getLine(openBracePos.row));
+ } else if (closing) {
+ var next_indent = this.$getIndent(line);
+ } else {
+ CstyleBehaviour.clearMaybeInsertedClosing();
+ return;
+ }
+ var indent = next_indent + session.getTabString();
+
+ return {
+ text: '\n' + indent + '\n' + next_indent + closing,
+ selection: [1, indent.length, 1, indent.length]
+ };
+ } else {
+ CstyleBehaviour.clearMaybeInsertedClosing();
+ }
+ });
+
+ this.add("braces", "deletion", function(state, action, editor, session, range) {
+ var selected = session.doc.getTextRange(range);
+ if (!range.isMultiLine() && selected == '{') {
+ initContext(editor);
+ var line = session.doc.getLine(range.start.row);
+ var rightChar = line.substring(range.end.column, range.end.column + 1);
+ if (rightChar == '}') {
+ range.end.column++;
+ return range;
+ } else {
+ context.maybeInsertedBrackets--;
+ }
+ }
+ });
+
+ this.add("parens", "insertion", function(state, action, editor, session, text) {
+ if (text == '(') {
+ initContext(editor);
+ var selection = editor.getSelectionRange();
+ var selected = session.doc.getTextRange(selection);
+ if (selected !== "" && editor.getWrapBehavioursEnabled()) {
+ return {
+ text: '(' + selected + ')',
+ selection: false
+ };
+ } else if (CstyleBehaviour.isSaneInsertion(editor, session)) {
+ CstyleBehaviour.recordAutoInsert(editor, session, ")");
+ return {
+ text: '()',
+ selection: [1, 1]
+ };
+ }
+ } else if (text == ')') {
+ initContext(editor);
+ var cursor = editor.getCursorPosition();
+ var line = session.doc.getLine(cursor.row);
+ var rightChar = line.substring(cursor.column, cursor.column + 1);
+ if (rightChar == ')') {
+ var matching = session.$findOpeningBracket(')', {column: cursor.column + 1, row: cursor.row});
+ if (matching !== null && CstyleBehaviour.isAutoInsertedClosing(cursor, line, text)) {
+ CstyleBehaviour.popAutoInsertedClosing();
+ return {
+ text: '',
+ selection: [1, 1]
+ };
+ }
+ }
+ }
+ });
+
+ this.add("parens", "deletion", function(state, action, editor, session, range) {
+ var selected = session.doc.getTextRange(range);
+ if (!range.isMultiLine() && selected == '(') {
+ initContext(editor);
+ var line = session.doc.getLine(range.start.row);
+ var rightChar = line.substring(range.start.column + 1, range.start.column + 2);
+ if (rightChar == ')') {
+ range.end.column++;
+ return range;
+ }
+ }
+ });
+
+ this.add("brackets", "insertion", function(state, action, editor, session, text) {
+ if (text == '[') {
+ initContext(editor);
+ var selection = editor.getSelectionRange();
+ var selected = session.doc.getTextRange(selection);
+ if (selected !== "" && editor.getWrapBehavioursEnabled()) {
+ return {
+ text: '[' + selected + ']',
+ selection: false
+ };
+ } else if (CstyleBehaviour.isSaneInsertion(editor, session)) {
+ CstyleBehaviour.recordAutoInsert(editor, session, "]");
+ return {
+ text: '[]',
+ selection: [1, 1]
+ };
+ }
+ } else if (text == ']') {
+ initContext(editor);
+ var cursor = editor.getCursorPosition();
+ var line = session.doc.getLine(cursor.row);
+ var rightChar = line.substring(cursor.column, cursor.column + 1);
+ if (rightChar == ']') {
+ var matching = session.$findOpeningBracket(']', {column: cursor.column + 1, row: cursor.row});
+ if (matching !== null && CstyleBehaviour.isAutoInsertedClosing(cursor, line, text)) {
+ CstyleBehaviour.popAutoInsertedClosing();
+ return {
+ text: '',
+ selection: [1, 1]
+ };
+ }
+ }
+ }
+ });
+
+ this.add("brackets", "deletion", function(state, action, editor, session, range) {
+ var selected = session.doc.getTextRange(range);
+ if (!range.isMultiLine() && selected == '[') {
+ initContext(editor);
+ var line = session.doc.getLine(range.start.row);
+ var rightChar = line.substring(range.start.column + 1, range.start.column + 2);
+ if (rightChar == ']') {
+ range.end.column++;
+ return range;
+ }
+ }
+ });
+
+ this.add("string_dquotes", "insertion", function(state, action, editor, session, text) {
+ if (text == '"' || text == "'") {
+ initContext(editor);
+ var quote = text;
+ var selection = editor.getSelectionRange();
+ var selected = session.doc.getTextRange(selection);
+ if (selected !== "" && selected !== "'" && selected != '"' && editor.getWrapBehavioursEnabled()) {
+ return {
+ text: quote + selected + quote,
+ selection: false
+ };
+ } else {
+ var cursor = editor.getCursorPosition();
+ var line = session.doc.getLine(cursor.row);
+ var leftChar = line.substring(cursor.column-1, cursor.column);
+ if (leftChar == '\\') {
+ return null;
+ }
+ var tokens = session.getTokens(selection.start.row);
+ var col = 0, token;
+ var quotepos = -1; // Track whether we're inside an open quote.
+
+ for (var x = 0; x < tokens.length; x++) {
+ token = tokens[x];
+ if (token.type == "string") {
+ quotepos = -1;
+ } else if (quotepos < 0) {
+ quotepos = token.value.indexOf(quote);
+ }
+ if ((token.value.length + col) > selection.start.column) {
+ break;
+ }
+ col += tokens[x].value.length;
+ }
+ if (!token || (quotepos < 0 && token.type !== "comment" && (token.type !== "string" || ((selection.start.column !== token.value.length+col-1) && token.value.lastIndexOf(quote) === token.value.length-1)))) {
+ if (!CstyleBehaviour.isSaneInsertion(editor, session))
+ return;
+ return {
+ text: quote + quote,
+ selection: [1,1]
+ };
+ } else if (token && token.type === "string") {
+ var rightChar = line.substring(cursor.column, cursor.column + 1);
+ if (rightChar == quote) {
+ return {
+ text: '',
+ selection: [1, 1]
+ };
+ }
+ }
+ }
+ }
+ });
+
+ this.add("string_dquotes", "deletion", function(state, action, editor, session, range) {
+ var selected = session.doc.getTextRange(range);
+ if (!range.isMultiLine() && (selected == '"' || selected == "'")) {
+ initContext(editor);
+ var line = session.doc.getLine(range.start.row);
+ var rightChar = line.substring(range.start.column + 1, range.start.column + 2);
+ if (rightChar == selected) {
+ range.end.column++;
+ return range;
+ }
+ }
+ });
+
+};
+
+
+CstyleBehaviour.isSaneInsertion = function(editor, session) {
+ var cursor = editor.getCursorPosition();
+ var iterator = new TokenIterator(session, cursor.row, cursor.column);
+ if (!this.$matchTokenType(iterator.getCurrentToken() || "text", SAFE_INSERT_IN_TOKENS)) {
+ var iterator2 = new TokenIterator(session, cursor.row, cursor.column + 1);
+ if (!this.$matchTokenType(iterator2.getCurrentToken() || "text", SAFE_INSERT_IN_TOKENS))
+ return false;
+ }
+ iterator.stepForward();
+ return iterator.getCurrentTokenRow() !== cursor.row ||
+ this.$matchTokenType(iterator.getCurrentToken() || "text", SAFE_INSERT_BEFORE_TOKENS);
+};
+
+CstyleBehaviour.$matchTokenType = function(token, types) {
+ return types.indexOf(token.type || token) > -1;
+};
+
+CstyleBehaviour.recordAutoInsert = function(editor, session, bracket) {
+ var cursor = editor.getCursorPosition();
+ var line = session.doc.getLine(cursor.row);
+ if (!this.isAutoInsertedClosing(cursor, line, context.autoInsertedLineEnd[0]))
+ context.autoInsertedBrackets = 0;
+ context.autoInsertedRow = cursor.row;
+ context.autoInsertedLineEnd = bracket + line.substr(cursor.column);
+ context.autoInsertedBrackets++;
+};
+
+CstyleBehaviour.recordMaybeInsert = function(editor, session, bracket) {
+ var cursor = editor.getCursorPosition();
+ var line = session.doc.getLine(cursor.row);
+ if (!this.isMaybeInsertedClosing(cursor, line))
+ context.maybeInsertedBrackets = 0;
+ context.maybeInsertedRow = cursor.row;
+ context.maybeInsertedLineStart = line.substr(0, cursor.column) + bracket;
+ context.maybeInsertedLineEnd = line.substr(cursor.column);
+ context.maybeInsertedBrackets++;
+};
+
+CstyleBehaviour.isAutoInsertedClosing = function(cursor, line, bracket) {
+ return context.autoInsertedBrackets > 0 &&
+ cursor.row === context.autoInsertedRow &&
+ bracket === context.autoInsertedLineEnd[0] &&
+ line.substr(cursor.column) === context.autoInsertedLineEnd;
+};
+
+CstyleBehaviour.isMaybeInsertedClosing = function(cursor, line) {
+ return context.maybeInsertedBrackets > 0 &&
+ cursor.row === context.maybeInsertedRow &&
+ line.substr(cursor.column) === context.maybeInsertedLineEnd &&
+ line.substr(0, cursor.column) == context.maybeInsertedLineStart;
+};
+
+CstyleBehaviour.popAutoInsertedClosing = function() {
+ context.autoInsertedLineEnd = context.autoInsertedLineEnd.substr(1);
+ context.autoInsertedBrackets--;
+};
+
+CstyleBehaviour.clearMaybeInsertedClosing = function() {
+ if (context) {
+ context.maybeInsertedBrackets = 0;
+ context.maybeInsertedRow = -1;
+ }
+};
+
+
+
+oop.inherits(CstyleBehaviour, Behaviour);
+
+exports.CstyleBehaviour = CstyleBehaviour;
+});
+
+define('ace/mode/folding/cstyle', ['require', 'exports', 'module' , 'ace/lib/oop', 'ace/range', 'ace/mode/folding/fold_mode'], function(require, exports, module) {
+
+
+var oop = require("../../lib/oop");
+var Range = require("../../range").Range;
+var BaseFoldMode = require("./fold_mode").FoldMode;
+
+var FoldMode = exports.FoldMode = function(commentRegex) {
+ if (commentRegex) {
+ this.foldingStartMarker = new RegExp(
+ this.foldingStartMarker.source.replace(/\|[^|]*?$/, "|" + commentRegex.start)
+ );
+ this.foldingStopMarker = new RegExp(
+ this.foldingStopMarker.source.replace(/\|[^|]*?$/, "|" + commentRegex.end)
+ );
+ }
+};
+oop.inherits(FoldMode, BaseFoldMode);
+
+(function() {
+
+ this.foldingStartMarker = /(\{|\[)[^\}\]]*$|^\s*(\/\*)/;
+ this.foldingStopMarker = /^[^\[\{]*(\}|\])|^[\s\*]*(\*\/)/;
+
+ this.getFoldWidgetRange = function(session, foldStyle, row, forceMultiline) {
+ var line = session.getLine(row);
+ var match = line.match(this.foldingStartMarker);
+ if (match) {
+ var i = match.index;
+
+ if (match[1])
+ return this.openingBracketBlock(session, match[1], row, i);
+
+ var range = session.getCommentFoldRange(row, i + match[0].length, 1);
+
+ if (range && !range.isMultiLine()) {
+ if (forceMultiline) {
+ range = this.getSectionRange(session, row);
+ } else if (foldStyle != "all")
+ range = null;
+ }
+
+ return range;
+ }
+
+ if (foldStyle === "markbegin")
+ return;
+
+ var match = line.match(this.foldingStopMarker);
+ if (match) {
+ var i = match.index + match[0].length;
+
+ if (match[1])
+ return this.closingBracketBlock(session, match[1], row, i);
+
+ return session.getCommentFoldRange(row, i, -1);
+ }
+ };
+
+ this.getSectionRange = function(session, row) {
+ var line = session.getLine(row);
+ var startIndent = line.search(/\S/);
+ var startRow = row;
+ var startColumn = line.length;
+ row = row + 1;
+ var endRow = row;
+ var maxRow = session.getLength();
+ while (++row < maxRow) {
+ line = session.getLine(row);
+ var indent = line.search(/\S/);
+ if (indent === -1)
+ continue;
+ if (startIndent > indent)
+ break;
+ var subRange = this.getFoldWidgetRange(session, "all", row);
+
+ if (subRange) {
+ if (subRange.start.row <= startRow) {
+ break;
+ } else if (subRange.isMultiLine()) {
+ row = subRange.end.row;
+ } else if (startIndent == indent) {
+ break;
+ }
+ }
+ endRow = row;
+ }
+
+ return new Range(startRow, startColumn, endRow, session.getLine(endRow).length);
+ };
+
+}).call(FoldMode.prototype);
+
+});
\ No newline at end of file
--- /dev/null
+/* ***** BEGIN LICENSE BLOCK *****
+ * Distributed under the BSD license:
+ *
+ * Copyright (c) 2010, Ajax.org B.V.
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are met:
+ * * Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * * Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ * * Neither the name of Ajax.org B.V. nor the
+ * names of its contributors may be used to endorse or promote products
+ * derived from this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
+ * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
+ * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
+ * DISCLAIMED. IN NO EVENT SHALL AJAX.ORG B.V. BE LIABLE FOR ANY
+ * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
+ * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
+ * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
+ * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
+ * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ *
+ * ***** END LICENSE BLOCK ***** */
+
+define('ace/theme/textmate', ['require', 'exports', 'module' , 'ace/lib/dom'], function(require, exports, module) {
+
+
+exports.isDark = false;
+exports.cssClass = "ace-tm";
+exports.cssText = ".ace-tm .ace_gutter {\
+background: #f0f0f0;\
+color: #333;\
+}\
+.ace-tm .ace_print-margin {\
+width: 1px;\
+background: #e8e8e8;\
+}\
+.ace-tm .ace_fold {\
+background-color: #6B72E6;\
+}\
+.ace-tm {\
+background-color: #FFFFFF;\
+color: black;\
+}\
+.ace-tm .ace_cursor {\
+color: black;\
+}\
+.ace-tm .ace_invisible {\
+color: rgb(191, 191, 191);\
+}\
+.ace-tm .ace_storage,\
+.ace-tm .ace_keyword {\
+color: blue;\
+}\
+.ace-tm .ace_constant {\
+color: rgb(197, 6, 11);\
+}\
+.ace-tm .ace_constant.ace_buildin {\
+color: rgb(88, 72, 246);\
+}\
+.ace-tm .ace_constant.ace_language {\
+color: rgb(88, 92, 246);\
+}\
+.ace-tm .ace_constant.ace_library {\
+color: rgb(6, 150, 14);\
+}\
+.ace-tm .ace_invalid {\
+background-color: rgba(255, 0, 0, 0.1);\
+color: red;\
+}\
+.ace-tm .ace_support.ace_function {\
+color: rgb(60, 76, 114);\
+}\
+.ace-tm .ace_support.ace_constant {\
+color: rgb(6, 150, 14);\
+}\
+.ace-tm .ace_support.ace_type,\
+.ace-tm .ace_support.ace_class {\
+color: rgb(109, 121, 222);\
+}\
+.ace-tm .ace_keyword.ace_operator {\
+color: rgb(104, 118, 135);\
+}\
+.ace-tm .ace_string {\
+color: rgb(3, 106, 7);\
+}\
+.ace-tm .ace_comment {\
+color: rgb(76, 136, 107);\
+}\
+.ace-tm .ace_comment.ace_doc {\
+color: rgb(0, 102, 255);\
+}\
+.ace-tm .ace_comment.ace_doc.ace_tag {\
+color: rgb(128, 159, 191);\
+}\
+.ace-tm .ace_constant.ace_numeric {\
+color: rgb(0, 0, 205);\
+}\
+.ace-tm .ace_variable {\
+color: rgb(49, 132, 149);\
+}\
+.ace-tm .ace_xml-pe {\
+color: rgb(104, 104, 91);\
+}\
+.ace-tm .ace_entity.ace_name.ace_function {\
+color: #0000A2;\
+}\
+.ace-tm .ace_heading {\
+color: rgb(12, 7, 255);\
+}\
+.ace-tm .ace_list {\
+color:rgb(185, 6, 144);\
+}\
+.ace-tm .ace_meta.ace_tag {\
+color:rgb(0, 22, 142);\
+}\
+.ace-tm .ace_string.ace_regex {\
+color: rgb(255, 0, 0)\
+}\
+.ace-tm .ace_marker-layer .ace_selection {\
+background: rgb(181, 213, 255);\
+}\
+.ace-tm.ace_multiselect .ace_selection.ace_start {\
+box-shadow: 0 0 3px 0px white;\
+border-radius: 2px;\
+}\
+.ace-tm .ace_marker-layer .ace_step {\
+background: rgb(252, 255, 0);\
+}\
+.ace-tm .ace_marker-layer .ace_stack {\
+background: rgb(164, 229, 101);\
+}\
+.ace-tm .ace_marker-layer .ace_bracket {\
+margin: -1px 0 0 -1px;\
+border: 1px solid rgb(192, 192, 192);\
+}\
+.ace-tm .ace_marker-layer .ace_active-line {\
+background: rgba(0, 0, 0, 0.07);\
+}\
+.ace-tm .ace_gutter-active-line {\
+background-color : #dcdcdc;\
+}\
+.ace-tm .ace_marker-layer .ace_selected-word {\
+background: rgb(250, 250, 255);\
+border: 1px solid rgb(200, 200, 250);\
+}\
+.ace-tm .ace_indent-guide {\
+background: url(\"data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAACCAYAAACZgbYnAAAAE0lEQVQImWP4////f4bLly//BwAmVgd1/w11/gAAAABJRU5ErkJggg==\") right repeat-y;\
+}\
+";
+
+var dom = require("../lib/dom");
+ console.log(exports);
+dom.importCssString(exports.cssText, exports.cssClass);
+});
\ No newline at end of file
--- /dev/null
+"no use strict";
+;(function(window) {
+if (typeof window.window != "undefined" && window.document) {
+ return;
+}
+
+window.console = function() {
+ var msgs = Array.prototype.slice.call(arguments, 0);
+ postMessage({type: "log", data: msgs});
+};
+window.console.error =
+window.console.warn =
+window.console.log =
+window.console.trace = window.console;
+
+window.window = window;
+window.ace = window;
+
+window.onerror = function(message, file, line, col, err) {
+ console.error("Worker " + (err ? err.stack : message));
+};
+
+window.normalizeModule = function(parentId, moduleName) {
+ if (moduleName.indexOf("!") !== -1) {
+ var chunks = moduleName.split("!");
+ return window.normalizeModule(parentId, chunks[0]) + "!" + window.normalizeModule(parentId, chunks[1]);
+ }
+ if (moduleName.charAt(0) == ".") {
+ var base = parentId.split("/").slice(0, -1).join("/");
+ moduleName = (base ? base + "/" : "") + moduleName;
+
+ while(moduleName.indexOf(".") !== -1 && previous != moduleName) {
+ var previous = moduleName;
+ moduleName = moduleName.replace(/^\.\//, "").replace(/\/\.\//, "/").replace(/[^\/]+\/\.\.\//, "");
+ }
+ }
+
+ return moduleName;
+};
+
+window.require = function(parentId, id) {
+ if (!id) {
+ id = parentId;
+ parentId = null;
+ }
+ if (!id.charAt)
+ throw new Error("worker.js require() accepts only (parentId, id) as arguments");
+
+ id = window.normalizeModule(parentId, id);
+
+ var module = window.require.modules[id];
+ if (module) {
+ if (!module.initialized) {
+ module.initialized = true;
+ module.exports = module.factory().exports;
+ }
+ return module.exports;
+ }
+
+ var chunks = id.split("/");
+ if (!window.require.tlns)
+ return console.log("unable to load " + id);
+ chunks[0] = window.require.tlns[chunks[0]] || chunks[0];
+ var path = chunks.join("/") + ".js";
+
+ window.require.id = id;
+ importScripts(path);
+ return window.require(parentId, id);
+};
+window.require.modules = {};
+window.require.tlns = {};
+
+window.define = function(id, deps, factory) {
+ if (arguments.length == 2) {
+ factory = deps;
+ if (typeof id != "string") {
+ deps = id;
+ id = window.require.id;
+ }
+ } else if (arguments.length == 1) {
+ factory = id;
+ deps = [];
+ id = window.require.id;
+ }
+
+ if (!deps.length)
+ deps = ['require', 'exports', 'module'];
+
+ if (id.indexOf("text!") === 0)
+ return;
+
+ var req = function(childId) {
+ return window.require(id, childId);
+ };
+
+ window.require.modules[id] = {
+ exports: {},
+ factory: function() {
+ var module = this;
+ var returnExports = factory.apply(this, deps.map(function(dep) {
+ switch(dep) {
+ case 'require': return req;
+ case 'exports': return module.exports;
+ case 'module': return module;
+ default: return req(dep);
+ }
+ }));
+ if (returnExports)
+ module.exports = returnExports;
+ return module;
+ }
+ };
+};
+window.define.amd = {};
+
+window.initBaseUrls = function initBaseUrls(topLevelNamespaces) {
+ require.tlns = topLevelNamespaces;
+};
+
+window.initSender = function initSender() {
+
+ var EventEmitter = window.require("ace/lib/event_emitter").EventEmitter;
+ var oop = window.require("ace/lib/oop");
+
+ var Sender = function() {};
+
+ (function() {
+
+ oop.implement(this, EventEmitter);
+
+ this.callback = function(data, callbackId) {
+ postMessage({
+ type: "call",
+ id: callbackId,
+ data: data
+ });
+ };
+
+ this.emit = function(name, data) {
+ postMessage({
+ type: "event",
+ name: name,
+ data: data
+ });
+ };
+
+ }).call(Sender.prototype);
+
+ return new Sender();
+};
+
+var main = window.main = null;
+var sender = window.sender = null;
+
+window.onmessage = function(e) {
+ var msg = e.data;
+ if (msg.command) {
+ if (main[msg.command])
+ main[msg.command].apply(main, msg.args);
+ else
+ throw new Error("Unknown command:" + msg.command);
+ }
+ else if (msg.init) {
+ initBaseUrls(msg.tlns);
+ require("ace/lib/es5-shim");
+ sender = window.sender = initSender();
+ var clazz = require(msg.module)[msg.classname];
+ main = window.main = new clazz(sender);
+ }
+ else if (msg.event && sender) {
+ sender._signal(msg.event, msg.data);
+ }
+};
+})(this);
+
+define('ace/mode/css_worker', ['require', 'exports', 'module' , 'ace/lib/oop', 'ace/lib/lang', 'ace/worker/mirror', 'ace/mode/css/csslint'], function(require, exports, module) {
+
+
+var oop = require("../lib/oop");
+var lang = require("../lib/lang");
+var Mirror = require("../worker/mirror").Mirror;
+var CSSLint = require("./css/csslint").CSSLint;
+
+var Worker = exports.Worker = function(sender) {
+ Mirror.call(this, sender);
+ this.setTimeout(400);
+ this.ruleset = null;
+ this.setDisabledRules("ids");
+ this.setInfoRules("adjoining-classes|qualified-headings|zero-units|gradients|import|outline-none");
+};
+
+oop.inherits(Worker, Mirror);
+
+(function() {
+ this.setInfoRules = function(ruleNames) {
+ if (typeof ruleNames == "string")
+ ruleNames = ruleNames.split("|");
+ this.infoRules = lang.arrayToMap(ruleNames);
+ this.doc.getValue() && this.deferredUpdate.schedule(100);
+ };
+
+ this.setDisabledRules = function(ruleNames) {
+ if (!ruleNames) {
+ this.ruleset = null;
+ } else {
+ if (typeof ruleNames == "string")
+ ruleNames = ruleNames.split("|");
+ var all = {};
+
+ CSSLint.getRules().forEach(function(x){
+ all[x.id] = true;
+ });
+ ruleNames.forEach(function(x) {
+ delete all[x];
+ });
+
+ this.ruleset = all;
+ }
+ this.doc.getValue() && this.deferredUpdate.schedule(100);
+ };
+
+ this.onUpdate = function() {
+ var value = this.doc.getValue();
+ var infoRules = this.infoRules;
+
+ var result = CSSLint.verify(value, this.ruleset);
+ this.sender.emit("csslint", result.messages.map(function(msg) {
+ return {
+ row: msg.line - 1,
+ column: msg.col - 1,
+ text: msg.message,
+ type: infoRules[msg.rule.id] ? "info" : msg.type,
+ rule: msg.rule.name
+ }
+ }));
+ };
+
+}).call(Worker.prototype);
+
+});
+
+define('ace/lib/oop', ['require', 'exports', 'module' ], function(require, exports, module) {
+
+
+exports.inherits = function(ctor, superCtor) {
+ ctor.super_ = superCtor;
+ ctor.prototype = Object.create(superCtor.prototype, {
+ constructor: {
+ value: ctor,
+ enumerable: false,
+ writable: true,
+ configurable: true
+ }
+ });
+};
+
+exports.mixin = function(obj, mixin) {
+ for (var key in mixin) {
+ obj[key] = mixin[key];
+ }
+ return obj;
+};
+
+exports.implement = function(proto, mixin) {
+ exports.mixin(proto, mixin);
+};
+
+});
+
+define('ace/lib/lang', ['require', 'exports', 'module' ], function(require, exports, module) {
+
+
+exports.last = function(a) {
+ return a[a.length - 1];
+};
+
+exports.stringReverse = function(string) {
+ return string.split("").reverse().join("");
+};
+
+exports.stringRepeat = function (string, count) {
+ var result = '';
+ while (count > 0) {
+ if (count & 1)
+ result += string;
+
+ if (count >>= 1)
+ string += string;
+ }
+ return result;
+};
+
+var trimBeginRegexp = /^\s\s*/;
+var trimEndRegexp = /\s\s*$/;
+
+exports.stringTrimLeft = function (string) {
+ return string.replace(trimBeginRegexp, '');
+};
+
+exports.stringTrimRight = function (string) {
+ return string.replace(trimEndRegexp, '');
+};
+
+exports.copyObject = function(obj) {
+ var copy = {};
+ for (var key in obj) {
+ copy[key] = obj[key];
+ }
+ return copy;
+};
+
+exports.copyArray = function(array){
+ var copy = [];
+ for (var i=0, l=array.length; i<l; i++) {
+ if (array[i] && typeof array[i] == "object")
+ copy[i] = this.copyObject( array[i] );
+ else
+ copy[i] = array[i];
+ }
+ return copy;
+};
+
+exports.deepCopy = function (obj) {
+ if (typeof obj !== "object" || !obj)
+ return obj;
+ var cons = obj.constructor;
+ if (cons === RegExp)
+ return obj;
+
+ var copy = cons();
+ for (var key in obj) {
+ if (typeof obj[key] === "object") {
+ copy[key] = exports.deepCopy(obj[key]);
+ } else {
+ copy[key] = obj[key];
+ }
+ }
+ return copy;
+};
+
+exports.arrayToMap = function(arr) {
+ var map = {};
+ for (var i=0; i<arr.length; i++) {
+ map[arr[i]] = 1;
+ }
+ return map;
+
+};
+
+exports.createMap = function(props) {
+ var map = Object.create(null);
+ for (var i in props) {
+ map[i] = props[i];
+ }
+ return map;
+};
+exports.arrayRemove = function(array, value) {
+ for (var i = 0; i <= array.length; i++) {
+ if (value === array[i]) {
+ array.splice(i, 1);
+ }
+ }
+};
+
+exports.escapeRegExp = function(str) {
+ return str.replace(/([.*+?^${}()|[\]\/\\])/g, '\\$1');
+};
+
+exports.escapeHTML = function(str) {
+ return str.replace(/&/g, "&").replace(/"/g, """).replace(/'/g, "'").replace(/</g, "<");
+};
+
+exports.getMatchOffsets = function(string, regExp) {
+ var matches = [];
+
+ string.replace(regExp, function(str) {
+ matches.push({
+ offset: arguments[arguments.length-2],
+ length: str.length
+ });
+ });
+
+ return matches;
+};
+exports.deferredCall = function(fcn) {
+
+ var timer = null;
+ var callback = function() {
+ timer = null;
+ fcn();
+ };
+
+ var deferred = function(timeout) {
+ deferred.cancel();
+ timer = setTimeout(callback, timeout || 0);
+ return deferred;
+ };
+
+ deferred.schedule = deferred;
+
+ deferred.call = function() {
+ this.cancel();
+ fcn();
+ return deferred;
+ };
+
+ deferred.cancel = function() {
+ clearTimeout(timer);
+ timer = null;
+ return deferred;
+ };
+
+ deferred.isPending = function() {
+ return timer;
+ };
+
+ return deferred;
+};
+
+
+exports.delayedCall = function(fcn, defaultTimeout) {
+ var timer = null;
+ var callback = function() {
+ timer = null;
+ fcn();
+ };
+
+ var _self = function(timeout) {
+ if (timer == null)
+ timer = setTimeout(callback, timeout || defaultTimeout);
+ };
+
+ _self.delay = function(timeout) {
+ timer && clearTimeout(timer);
+ timer = setTimeout(callback, timeout || defaultTimeout);
+ };
+ _self.schedule = _self;
+
+ _self.call = function() {
+ this.cancel();
+ fcn();
+ };
+
+ _self.cancel = function() {
+ timer && clearTimeout(timer);
+ timer = null;
+ };
+
+ _self.isPending = function() {
+ return timer;
+ };
+
+ return _self;
+};
+});
+
+define('ace/lib/es5-shim', ['require', 'exports', 'module' ], function(require, exports, module) {
+
+function Empty() {}
+
+if (!Function.prototype.bind) {
+ Function.prototype.bind = function bind(that) { // .length is 1
+ var target = this;
+ if (typeof target != "function") {
+ throw new TypeError("Function.prototype.bind called on incompatible " + target);
+ }
+ var args = slice.call(arguments, 1); // for normal call
+ var bound = function () {
+
+ if (this instanceof bound) {
+
+ var result = target.apply(
+ this,
+ args.concat(slice.call(arguments))
+ );
+ if (Object(result) === result) {
+ return result;
+ }
+ return this;
+
+ } else {
+ return target.apply(
+ that,
+ args.concat(slice.call(arguments))
+ );
+
+ }
+
+ };
+ if(target.prototype) {
+ Empty.prototype = target.prototype;
+ bound.prototype = new Empty();
+ Empty.prototype = null;
+ }
+ return bound;
+ };
+}
+var call = Function.prototype.call;
+var prototypeOfArray = Array.prototype;
+var prototypeOfObject = Object.prototype;
+var slice = prototypeOfArray.slice;
+var _toString = call.bind(prototypeOfObject.toString);
+var owns = call.bind(prototypeOfObject.hasOwnProperty);
+var defineGetter;
+var defineSetter;
+var lookupGetter;
+var lookupSetter;
+var supportsAccessors;
+if ((supportsAccessors = owns(prototypeOfObject, "__defineGetter__"))) {
+ defineGetter = call.bind(prototypeOfObject.__defineGetter__);
+ defineSetter = call.bind(prototypeOfObject.__defineSetter__);
+ lookupGetter = call.bind(prototypeOfObject.__lookupGetter__);
+ lookupSetter = call.bind(prototypeOfObject.__lookupSetter__);
+}
+if ([1,2].splice(0).length != 2) {
+ if(function() { // test IE < 9 to splice bug - see issue #138
+ function makeArray(l) {
+ var a = new Array(l+2);
+ a[0] = a[1] = 0;
+ return a;
+ }
+ var array = [], lengthBefore;
+
+ array.splice.apply(array, makeArray(20));
+ array.splice.apply(array, makeArray(26));
+
+ lengthBefore = array.length; //46
+ array.splice(5, 0, "XXX"); // add one element
+
+ lengthBefore + 1 == array.length
+
+ if (lengthBefore + 1 == array.length) {
+ return true;// has right splice implementation without bugs
+ }
+ }()) {//IE 6/7
+ var array_splice = Array.prototype.splice;
+ Array.prototype.splice = function(start, deleteCount) {
+ if (!arguments.length) {
+ return [];
+ } else {
+ return array_splice.apply(this, [
+ start === void 0 ? 0 : start,
+ deleteCount === void 0 ? (this.length - start) : deleteCount
+ ].concat(slice.call(arguments, 2)))
+ }
+ };
+ } else {//IE8
+ Array.prototype.splice = function(pos, removeCount){
+ var length = this.length;
+ if (pos > 0) {
+ if (pos > length)
+ pos = length;
+ } else if (pos == void 0) {
+ pos = 0;
+ } else if (pos < 0) {
+ pos = Math.max(length + pos, 0);
+ }
+
+ if (!(pos+removeCount < length))
+ removeCount = length - pos;
+
+ var removed = this.slice(pos, pos+removeCount);
+ var insert = slice.call(arguments, 2);
+ var add = insert.length;
+ if (pos === length) {
+ if (add) {
+ this.push.apply(this, insert);
+ }
+ } else {
+ var remove = Math.min(removeCount, length - pos);
+ var tailOldPos = pos + remove;
+ var tailNewPos = tailOldPos + add - remove;
+ var tailCount = length - tailOldPos;
+ var lengthAfterRemove = length - remove;
+
+ if (tailNewPos < tailOldPos) { // case A
+ for (var i = 0; i < tailCount; ++i) {
+ this[tailNewPos+i] = this[tailOldPos+i];
+ }
+ } else if (tailNewPos > tailOldPos) { // case B
+ for (i = tailCount; i--; ) {
+ this[tailNewPos+i] = this[tailOldPos+i];
+ }
+ } // else, add == remove (nothing to do)
+
+ if (add && pos === lengthAfterRemove) {
+ this.length = lengthAfterRemove; // truncate array
+ this.push.apply(this, insert);
+ } else {
+ this.length = lengthAfterRemove + add; // reserves space
+ for (i = 0; i < add; ++i) {
+ this[pos+i] = insert[i];
+ }
+ }
+ }
+ return removed;
+ };
+ }
+}
+if (!Array.isArray) {
+ Array.isArray = function isArray(obj) {
+ return _toString(obj) == "[object Array]";
+ };
+}
+var boxedString = Object("a"),
+ splitString = boxedString[0] != "a" || !(0 in boxedString);
+
+if (!Array.prototype.forEach) {
+ Array.prototype.forEach = function forEach(fun /*, thisp*/) {
+ var object = toObject(this),
+ self = splitString && _toString(this) == "[object String]" ?
+ this.split("") :
+ object,
+ thisp = arguments[1],
+ i = -1,
+ length = self.length >>> 0;
+ if (_toString(fun) != "[object Function]") {
+ throw new TypeError(); // TODO message
+ }
+
+ while (++i < length) {
+ if (i in self) {
+ fun.call(thisp, self[i], i, object);
+ }
+ }
+ };
+}
+if (!Array.prototype.map) {
+ Array.prototype.map = function map(fun /*, thisp*/) {
+ var object = toObject(this),
+ self = splitString && _toString(this) == "[object String]" ?
+ this.split("") :
+ object,
+ length = self.length >>> 0,
+ result = Array(length),
+ thisp = arguments[1];
+ if (_toString(fun) != "[object Function]") {
+ throw new TypeError(fun + " is not a function");
+ }
+
+ for (var i = 0; i < length; i++) {
+ if (i in self)
+ result[i] = fun.call(thisp, self[i], i, object);
+ }
+ return result;
+ };
+}
+if (!Array.prototype.filter) {
+ Array.prototype.filter = function filter(fun /*, thisp */) {
+ var object = toObject(this),
+ self = splitString && _toString(this) == "[object String]" ?
+ this.split("") :
+ object,
+ length = self.length >>> 0,
+ result = [],
+ value,
+ thisp = arguments[1];
+ if (_toString(fun) != "[object Function]") {
+ throw new TypeError(fun + " is not a function");
+ }
+
+ for (var i = 0; i < length; i++) {
+ if (i in self) {
+ value = self[i];
+ if (fun.call(thisp, value, i, object)) {
+ result.push(value);
+ }
+ }
+ }
+ return result;
+ };
+}
+if (!Array.prototype.every) {
+ Array.prototype.every = function every(fun /*, thisp */) {
+ var object = toObject(this),
+ self = splitString && _toString(this) == "[object String]" ?
+ this.split("") :
+ object,
+ length = self.length >>> 0,
+ thisp = arguments[1];
+ if (_toString(fun) != "[object Function]") {
+ throw new TypeError(fun + " is not a function");
+ }
+
+ for (var i = 0; i < length; i++) {
+ if (i in self && !fun.call(thisp, self[i], i, object)) {
+ return false;
+ }
+ }
+ return true;
+ };
+}
+if (!Array.prototype.some) {
+ Array.prototype.some = function some(fun /*, thisp */) {
+ var object = toObject(this),
+ self = splitString && _toString(this) == "[object String]" ?
+ this.split("") :
+ object,
+ length = self.length >>> 0,
+ thisp = arguments[1];
+ if (_toString(fun) != "[object Function]") {
+ throw new TypeError(fun + " is not a function");
+ }
+
+ for (var i = 0; i < length; i++) {
+ if (i in self && fun.call(thisp, self[i], i, object)) {
+ return true;
+ }
+ }
+ return false;
+ };
+}
+if (!Array.prototype.reduce) {
+ Array.prototype.reduce = function reduce(fun /*, initial*/) {
+ var object = toObject(this),
+ self = splitString && _toString(this) == "[object String]" ?
+ this.split("") :
+ object,
+ length = self.length >>> 0;
+ if (_toString(fun) != "[object Function]") {
+ throw new TypeError(fun + " is not a function");
+ }
+ if (!length && arguments.length == 1) {
+ throw new TypeError("reduce of empty array with no initial value");
+ }
+
+ var i = 0;
+ var result;
+ if (arguments.length >= 2) {
+ result = arguments[1];
+ } else {
+ do {
+ if (i in self) {
+ result = self[i++];
+ break;
+ }
+ if (++i >= length) {
+ throw new TypeError("reduce of empty array with no initial value");
+ }
+ } while (true);
+ }
+
+ for (; i < length; i++) {
+ if (i in self) {
+ result = fun.call(void 0, result, self[i], i, object);
+ }
+ }
+
+ return result;
+ };
+}
+if (!Array.prototype.reduceRight) {
+ Array.prototype.reduceRight = function reduceRight(fun /*, initial*/) {
+ var object = toObject(this),
+ self = splitString && _toString(this) == "[object String]" ?
+ this.split("") :
+ object,
+ length = self.length >>> 0;
+ if (_toString(fun) != "[object Function]") {
+ throw new TypeError(fun + " is not a function");
+ }
+ if (!length && arguments.length == 1) {
+ throw new TypeError("reduceRight of empty array with no initial value");
+ }
+
+ var result, i = length - 1;
+ if (arguments.length >= 2) {
+ result = arguments[1];
+ } else {
+ do {
+ if (i in self) {
+ result = self[i--];
+ break;
+ }
+ if (--i < 0) {
+ throw new TypeError("reduceRight of empty array with no initial value");
+ }
+ } while (true);
+ }
+
+ do {
+ if (i in this) {
+ result = fun.call(void 0, result, self[i], i, object);
+ }
+ } while (i--);
+
+ return result;
+ };
+}
+if (!Array.prototype.indexOf || ([0, 1].indexOf(1, 2) != -1)) {
+ Array.prototype.indexOf = function indexOf(sought /*, fromIndex */ ) {
+ var self = splitString && _toString(this) == "[object String]" ?
+ this.split("") :
+ toObject(this),
+ length = self.length >>> 0;
+
+ if (!length) {
+ return -1;
+ }
+
+ var i = 0;
+ if (arguments.length > 1) {
+ i = toInteger(arguments[1]);
+ }
+ i = i >= 0 ? i : Math.max(0, length + i);
+ for (; i < length; i++) {
+ if (i in self && self[i] === sought) {
+ return i;
+ }
+ }
+ return -1;
+ };
+}
+if (!Array.prototype.lastIndexOf || ([0, 1].lastIndexOf(0, -3) != -1)) {
+ Array.prototype.lastIndexOf = function lastIndexOf(sought /*, fromIndex */) {
+ var self = splitString && _toString(this) == "[object String]" ?
+ this.split("") :
+ toObject(this),
+ length = self.length >>> 0;
+
+ if (!length) {
+ return -1;
+ }
+ var i = length - 1;
+ if (arguments.length > 1) {
+ i = Math.min(i, toInteger(arguments[1]));
+ }
+ i = i >= 0 ? i : length - Math.abs(i);
+ for (; i >= 0; i--) {
+ if (i in self && sought === self[i]) {
+ return i;
+ }
+ }
+ return -1;
+ };
+}
+if (!Object.getPrototypeOf) {
+ Object.getPrototypeOf = function getPrototypeOf(object) {
+ return object.__proto__ || (
+ object.constructor ?
+ object.constructor.prototype :
+ prototypeOfObject
+ );
+ };
+}
+if (!Object.getOwnPropertyDescriptor) {
+ var ERR_NON_OBJECT = "Object.getOwnPropertyDescriptor called on a " +
+ "non-object: ";
+ Object.getOwnPropertyDescriptor = function getOwnPropertyDescriptor(object, property) {
+ if ((typeof object != "object" && typeof object != "function") || object === null)
+ throw new TypeError(ERR_NON_OBJECT + object);
+ if (!owns(object, property))
+ return;
+
+ var descriptor, getter, setter;
+ descriptor = { enumerable: true, configurable: true };
+ if (supportsAccessors) {
+ var prototype = object.__proto__;
+ object.__proto__ = prototypeOfObject;
+
+ var getter = lookupGetter(object, property);
+ var setter = lookupSetter(object, property);
+ object.__proto__ = prototype;
+
+ if (getter || setter) {
+ if (getter) descriptor.get = getter;
+ if (setter) descriptor.set = setter;
+ return descriptor;
+ }
+ }
+ descriptor.value = object[property];
+ return descriptor;
+ };
+}
+if (!Object.getOwnPropertyNames) {
+ Object.getOwnPropertyNames = function getOwnPropertyNames(object) {
+ return Object.keys(object);
+ };
+}
+if (!Object.create) {
+ var createEmpty;
+ if (Object.prototype.__proto__ === null) {
+ createEmpty = function () {
+ return { "__proto__": null };
+ };
+ } else {
+ createEmpty = function () {
+ var empty = {};
+ for (var i in empty)
+ empty[i] = null;
+ empty.constructor =
+ empty.hasOwnProperty =
+ empty.propertyIsEnumerable =
+ empty.isPrototypeOf =
+ empty.toLocaleString =
+ empty.toString =
+ empty.valueOf =
+ empty.__proto__ = null;
+ return empty;
+ }
+ }
+
+ Object.create = function create(prototype, properties) {
+ var object;
+ if (prototype === null) {
+ object = createEmpty();
+ } else {
+ if (typeof prototype != "object")
+ throw new TypeError("typeof prototype["+(typeof prototype)+"] != 'object'");
+ var Type = function () {};
+ Type.prototype = prototype;
+ object = new Type();
+ object.__proto__ = prototype;
+ }
+ if (properties !== void 0)
+ Object.defineProperties(object, properties);
+ return object;
+ };
+}
+
+function doesDefinePropertyWork(object) {
+ try {
+ Object.defineProperty(object, "sentinel", {});
+ return "sentinel" in object;
+ } catch (exception) {
+ }
+}
+if (Object.defineProperty) {
+ var definePropertyWorksOnObject = doesDefinePropertyWork({});
+ var definePropertyWorksOnDom = typeof document == "undefined" ||
+ doesDefinePropertyWork(document.createElement("div"));
+ if (!definePropertyWorksOnObject || !definePropertyWorksOnDom) {
+ var definePropertyFallback = Object.defineProperty;
+ }
+}
+
+if (!Object.defineProperty || definePropertyFallback) {
+ var ERR_NON_OBJECT_DESCRIPTOR = "Property description must be an object: ";
+ var ERR_NON_OBJECT_TARGET = "Object.defineProperty called on non-object: "
+ var ERR_ACCESSORS_NOT_SUPPORTED = "getters & setters can not be defined " +
+ "on this javascript engine";
+
+ Object.defineProperty = function defineProperty(object, property, descriptor) {
+ if ((typeof object != "object" && typeof object != "function") || object === null)
+ throw new TypeError(ERR_NON_OBJECT_TARGET + object);
+ if ((typeof descriptor != "object" && typeof descriptor != "function") || descriptor === null)
+ throw new TypeError(ERR_NON_OBJECT_DESCRIPTOR + descriptor);
+ if (definePropertyFallback) {
+ try {
+ return definePropertyFallback.call(Object, object, property, descriptor);
+ } catch (exception) {
+ }
+ }
+ if (owns(descriptor, "value")) {
+
+ if (supportsAccessors && (lookupGetter(object, property) ||
+ lookupSetter(object, property)))
+ {
+ var prototype = object.__proto__;
+ object.__proto__ = prototypeOfObject;
+ delete object[property];
+ object[property] = descriptor.value;
+ object.__proto__ = prototype;
+ } else {
+ object[property] = descriptor.value;
+ }
+ } else {
+ if (!supportsAccessors)
+ throw new TypeError(ERR_ACCESSORS_NOT_SUPPORTED);
+ if (owns(descriptor, "get"))
+ defineGetter(object, property, descriptor.get);
+ if (owns(descriptor, "set"))
+ defineSetter(object, property, descriptor.set);
+ }
+
+ return object;
+ };
+}
+if (!Object.defineProperties) {
+ Object.defineProperties = function defineProperties(object, properties) {
+ for (var property in properties) {
+ if (owns(properties, property))
+ Object.defineProperty(object, property, properties[property]);
+ }
+ return object;
+ };
+}
+if (!Object.seal) {
+ Object.seal = function seal(object) {
+ return object;
+ };
+}
+if (!Object.freeze) {
+ Object.freeze = function freeze(object) {
+ return object;
+ };
+}
+try {
+ Object.freeze(function () {});
+} catch (exception) {
+ Object.freeze = (function freeze(freezeObject) {
+ return function freeze(object) {
+ if (typeof object == "function") {
+ return object;
+ } else {
+ return freezeObject(object);
+ }
+ };
+ })(Object.freeze);
+}
+if (!Object.preventExtensions) {
+ Object.preventExtensions = function preventExtensions(object) {
+ return object;
+ };
+}
+if (!Object.isSealed) {
+ Object.isSealed = function isSealed(object) {
+ return false;
+ };
+}
+if (!Object.isFrozen) {
+ Object.isFrozen = function isFrozen(object) {
+ return false;
+ };
+}
+if (!Object.isExtensible) {
+ Object.isExtensible = function isExtensible(object) {
+ if (Object(object) === object) {
+ throw new TypeError(); // TODO message
+ }
+ var name = '';
+ while (owns(object, name)) {
+ name += '?';
+ }
+ object[name] = true;
+ var returnValue = owns(object, name);
+ delete object[name];
+ return returnValue;
+ };
+}
+if (!Object.keys) {
+ var hasDontEnumBug = true,
+ dontEnums = [
+ "toString",
+ "toLocaleString",
+ "valueOf",
+ "hasOwnProperty",
+ "isPrototypeOf",
+ "propertyIsEnumerable",
+ "constructor"
+ ],
+ dontEnumsLength = dontEnums.length;
+
+ for (var key in {"toString": null}) {
+ hasDontEnumBug = false;
+ }
+
+ Object.keys = function keys(object) {
+
+ if (
+ (typeof object != "object" && typeof object != "function") ||
+ object === null
+ ) {
+ throw new TypeError("Object.keys called on a non-object");
+ }
+
+ var keys = [];
+ for (var name in object) {
+ if (owns(object, name)) {
+ keys.push(name);
+ }
+ }
+
+ if (hasDontEnumBug) {
+ for (var i = 0, ii = dontEnumsLength; i < ii; i++) {
+ var dontEnum = dontEnums[i];
+ if (owns(object, dontEnum)) {
+ keys.push(dontEnum);
+ }
+ }
+ }
+ return keys;
+ };
+
+}
+if (!Date.now) {
+ Date.now = function now() {
+ return new Date().getTime();
+ };
+}
+var ws = "\x09\x0A\x0B\x0C\x0D\x20\xA0\u1680\u180E\u2000\u2001\u2002\u2003" +
+ "\u2004\u2005\u2006\u2007\u2008\u2009\u200A\u202F\u205F\u3000\u2028" +
+ "\u2029\uFEFF";
+if (!String.prototype.trim || ws.trim()) {
+ ws = "[" + ws + "]";
+ var trimBeginRegexp = new RegExp("^" + ws + ws + "*"),
+ trimEndRegexp = new RegExp(ws + ws + "*$");
+ String.prototype.trim = function trim() {
+ return String(this).replace(trimBeginRegexp, "").replace(trimEndRegexp, "");
+ };
+}
+
+function toInteger(n) {
+ n = +n;
+ if (n !== n) { // isNaN
+ n = 0;
+ } else if (n !== 0 && n !== (1/0) && n !== -(1/0)) {
+ n = (n > 0 || -1) * Math.floor(Math.abs(n));
+ }
+ return n;
+}
+
+function isPrimitive(input) {
+ var type = typeof input;
+ return (
+ input === null ||
+ type === "undefined" ||
+ type === "boolean" ||
+ type === "number" ||
+ type === "string"
+ );
+}
+
+function toPrimitive(input) {
+ var val, valueOf, toString;
+ if (isPrimitive(input)) {
+ return input;
+ }
+ valueOf = input.valueOf;
+ if (typeof valueOf === "function") {
+ val = valueOf.call(input);
+ if (isPrimitive(val)) {
+ return val;
+ }
+ }
+ toString = input.toString;
+ if (typeof toString === "function") {
+ val = toString.call(input);
+ if (isPrimitive(val)) {
+ return val;
+ }
+ }
+ throw new TypeError();
+}
+var toObject = function (o) {
+ if (o == null) { // this matches both null and undefined
+ throw new TypeError("can't convert "+o+" to object");
+ }
+ return Object(o);
+};
+
+});
+
+define('ace/document', ['require', 'exports', 'module' , 'ace/lib/oop', 'ace/lib/event_emitter', 'ace/range', 'ace/anchor'], function(require, exports, module) {
+
+
+var oop = require("./lib/oop");
+var EventEmitter = require("./lib/event_emitter").EventEmitter;
+var Range = require("./range").Range;
+var Anchor = require("./anchor").Anchor;
+
+var Document = function(text) {
+ this.$lines = [];
+ if (text.length === 0) {
+ this.$lines = [""];
+ } else if (Array.isArray(text)) {
+ this._insertLines(0, text);
+ } else {
+ this.insert({row: 0, column:0}, text);
+ }
+};
+
+(function() {
+
+ oop.implement(this, EventEmitter);
+ this.setValue = function(text) {
+ var len = this.getLength();
+ this.remove(new Range(0, 0, len, this.getLine(len-1).length));
+ this.insert({row: 0, column:0}, text);
+ };
+ this.getValue = function() {
+ return this.getAllLines().join(this.getNewLineCharacter());
+ };
+ this.createAnchor = function(row, column) {
+ return new Anchor(this, row, column);
+ };
+ if ("aaa".split(/a/).length === 0)
+ this.$split = function(text) {
+ return text.replace(/\r\n|\r/g, "\n").split("\n");
+ };
+ else
+ this.$split = function(text) {
+ return text.split(/\r\n|\r|\n/);
+ };
+
+
+ this.$detectNewLine = function(text) {
+ var match = text.match(/^.*?(\r\n|\r|\n)/m);
+ this.$autoNewLine = match ? match[1] : "\n";
+ this._signal("changeNewLineMode");
+ };
+ this.getNewLineCharacter = function() {
+ switch (this.$newLineMode) {
+ case "windows":
+ return "\r\n";
+ case "unix":
+ return "\n";
+ default:
+ return this.$autoNewLine || "\n";
+ }
+ };
+
+ this.$autoNewLine = "";
+ this.$newLineMode = "auto";
+ this.setNewLineMode = function(newLineMode) {
+ if (this.$newLineMode === newLineMode)
+ return;
+
+ this.$newLineMode = newLineMode;
+ this._signal("changeNewLineMode");
+ };
+ this.getNewLineMode = function() {
+ return this.$newLineMode;
+ };
+ this.isNewLine = function(text) {
+ return (text == "\r\n" || text == "\r" || text == "\n");
+ };
+ this.getLine = function(row) {
+ return this.$lines[row] || "";
+ };
+ this.getLines = function(firstRow, lastRow) {
+ return this.$lines.slice(firstRow, lastRow + 1);
+ };
+ this.getAllLines = function() {
+ return this.getLines(0, this.getLength());
+ };
+ this.getLength = function() {
+ return this.$lines.length;
+ };
+ this.getTextRange = function(range) {
+ if (range.start.row == range.end.row) {
+ return this.getLine(range.start.row)
+ .substring(range.start.column, range.end.column);
+ }
+ var lines = this.getLines(range.start.row, range.end.row);
+ lines[0] = (lines[0] || "").substring(range.start.column);
+ var l = lines.length - 1;
+ if (range.end.row - range.start.row == l)
+ lines[l] = lines[l].substring(0, range.end.column);
+ return lines.join(this.getNewLineCharacter());
+ };
+
+ this.$clipPosition = function(position) {
+ var length = this.getLength();
+ if (position.row >= length) {
+ position.row = Math.max(0, length - 1);
+ position.column = this.getLine(length-1).length;
+ } else if (position.row < 0)
+ position.row = 0;
+ return position;
+ };
+ this.insert = function(position, text) {
+ if (!text || text.length === 0)
+ return position;
+
+ position = this.$clipPosition(position);
+ if (this.getLength() <= 1)
+ this.$detectNewLine(text);
+
+ var lines = this.$split(text);
+ var firstLine = lines.splice(0, 1)[0];
+ var lastLine = lines.length == 0 ? null : lines.splice(lines.length - 1, 1)[0];
+
+ position = this.insertInLine(position, firstLine);
+ if (lastLine !== null) {
+ position = this.insertNewLine(position); // terminate first line
+ position = this._insertLines(position.row, lines);
+ position = this.insertInLine(position, lastLine || "");
+ }
+ return position;
+ };
+ this.insertLines = function(row, lines) {
+ if (row >= this.getLength())
+ return this.insert({row: row, column: 0}, "\n" + lines.join("\n"));
+ return this._insertLines(Math.max(row, 0), lines);
+ };
+ this._insertLines = function(row, lines) {
+ if (lines.length == 0)
+ return {row: row, column: 0};
+ while (lines.length > 0xF000) {
+ var end = this._insertLines(row, lines.slice(0, 0xF000));
+ lines = lines.slice(0xF000);
+ row = end.row;
+ }
+
+ var args = [row, 0];
+ args.push.apply(args, lines);
+ this.$lines.splice.apply(this.$lines, args);
+
+ var range = new Range(row, 0, row + lines.length, 0);
+ var delta = {
+ action: "insertLines",
+ range: range,
+ lines: lines
+ };
+ this._signal("change", { data: delta });
+ return range.end;
+ };
+ this.insertNewLine = function(position) {
+ position = this.$clipPosition(position);
+ var line = this.$lines[position.row] || "";
+
+ this.$lines[position.row] = line.substring(0, position.column);
+ this.$lines.splice(position.row + 1, 0, line.substring(position.column, line.length));
+
+ var end = {
+ row : position.row + 1,
+ column : 0
+ };
+
+ var delta = {
+ action: "insertText",
+ range: Range.fromPoints(position, end),
+ text: this.getNewLineCharacter()
+ };
+ this._signal("change", { data: delta });
+
+ return end;
+ };
+ this.insertInLine = function(position, text) {
+ if (text.length == 0)
+ return position;
+
+ var line = this.$lines[position.row] || "";
+
+ this.$lines[position.row] = line.substring(0, position.column) + text
+ + line.substring(position.column);
+
+ var end = {
+ row : position.row,
+ column : position.column + text.length
+ };
+
+ var delta = {
+ action: "insertText",
+ range: Range.fromPoints(position, end),
+ text: text
+ };
+ this._signal("change", { data: delta });
+
+ return end;
+ };
+ this.remove = function(range) {
+ if (!(range instanceof Range))
+ range = Range.fromPoints(range.start, range.end);
+ range.start = this.$clipPosition(range.start);
+ range.end = this.$clipPosition(range.end);
+
+ if (range.isEmpty())
+ return range.start;
+
+ var firstRow = range.start.row;
+ var lastRow = range.end.row;
+
+ if (range.isMultiLine()) {
+ var firstFullRow = range.start.column == 0 ? firstRow : firstRow + 1;
+ var lastFullRow = lastRow - 1;
+
+ if (range.end.column > 0)
+ this.removeInLine(lastRow, 0, range.end.column);
+
+ if (lastFullRow >= firstFullRow)
+ this._removeLines(firstFullRow, lastFullRow);
+
+ if (firstFullRow != firstRow) {
+ this.removeInLine(firstRow, range.start.column, this.getLine(firstRow).length);
+ this.removeNewLine(range.start.row);
+ }
+ }
+ else {
+ this.removeInLine(firstRow, range.start.column, range.end.column);
+ }
+ return range.start;
+ };
+ this.removeInLine = function(row, startColumn, endColumn) {
+ if (startColumn == endColumn)
+ return;
+
+ var range = new Range(row, startColumn, row, endColumn);
+ var line = this.getLine(row);
+ var removed = line.substring(startColumn, endColumn);
+ var newLine = line.substring(0, startColumn) + line.substring(endColumn, line.length);
+ this.$lines.splice(row, 1, newLine);
+
+ var delta = {
+ action: "removeText",
+ range: range,
+ text: removed
+ };
+ this._signal("change", { data: delta });
+ return range.start;
+ };
+ this.removeLines = function(firstRow, lastRow) {
+ if (firstRow < 0 || lastRow >= this.getLength())
+ return this.remove(new Range(firstRow, 0, lastRow + 1, 0));
+ return this._removeLines(firstRow, lastRow);
+ };
+
+ this._removeLines = function(firstRow, lastRow) {
+ var range = new Range(firstRow, 0, lastRow + 1, 0);
+ var removed = this.$lines.splice(firstRow, lastRow - firstRow + 1);
+
+ var delta = {
+ action: "removeLines",
+ range: range,
+ nl: this.getNewLineCharacter(),
+ lines: removed
+ };
+ this._signal("change", { data: delta });
+ return removed;
+ };
+ this.removeNewLine = function(row) {
+ var firstLine = this.getLine(row);
+ var secondLine = this.getLine(row+1);
+
+ var range = new Range(row, firstLine.length, row+1, 0);
+ var line = firstLine + secondLine;
+
+ this.$lines.splice(row, 2, line);
+
+ var delta = {
+ action: "removeText",
+ range: range,
+ text: this.getNewLineCharacter()
+ };
+ this._signal("change", { data: delta });
+ };
+ this.replace = function(range, text) {
+ if (!(range instanceof Range))
+ range = Range.fromPoints(range.start, range.end);
+ if (text.length == 0 && range.isEmpty())
+ return range.start;
+ if (text == this.getTextRange(range))
+ return range.end;
+
+ this.remove(range);
+ if (text) {
+ var end = this.insert(range.start, text);
+ }
+ else {
+ end = range.start;
+ }
+
+ return end;
+ };
+ this.applyDeltas = function(deltas) {
+ for (var i=0; i<deltas.length; i++) {
+ var delta = deltas[i];
+ var range = Range.fromPoints(delta.range.start, delta.range.end);
+
+ if (delta.action == "insertLines")
+ this.insertLines(range.start.row, delta.lines);
+ else if (delta.action == "insertText")
+ this.insert(range.start, delta.text);
+ else if (delta.action == "removeLines")
+ this._removeLines(range.start.row, range.end.row - 1);
+ else if (delta.action == "removeText")
+ this.remove(range);
+ }
+ };
+ this.revertDeltas = function(deltas) {
+ for (var i=deltas.length-1; i>=0; i--) {
+ var delta = deltas[i];
+
+ var range = Range.fromPoints(delta.range.start, delta.range.end);
+
+ if (delta.action == "insertLines")
+ this._removeLines(range.start.row, range.end.row - 1);
+ else if (delta.action == "insertText")
+ this.remove(range);
+ else if (delta.action == "removeLines")
+ this._insertLines(range.start.row, delta.lines);
+ else if (delta.action == "removeText")
+ this.insert(range.start, delta.text);
+ }
+ };
+ this.indexToPosition = function(index, startRow) {
+ var lines = this.$lines || this.getAllLines();
+ var newlineLength = this.getNewLineCharacter().length;
+ for (var i = startRow || 0, l = lines.length; i < l; i++) {
+ index -= lines[i].length + newlineLength;
+ if (index < 0)
+ return {row: i, column: index + lines[i].length + newlineLength};
+ }
+ return {row: l-1, column: lines[l-1].length};
+ };
+ this.positionToIndex = function(pos, startRow) {
+ var lines = this.$lines || this.getAllLines();
+ var newlineLength = this.getNewLineCharacter().length;
+ var index = 0;
+ var row = Math.min(pos.row, lines.length);
+ for (var i = startRow || 0; i < row; ++i)
+ index += lines[i].length + newlineLength;
+
+ return index + pos.column;
+ };
+
+}).call(Document.prototype);
+
+exports.Document = Document;
+});
+
+define('ace/lib/event_emitter', ['require', 'exports', 'module' ], function(require, exports, module) {
+
+
+var EventEmitter = {};
+var stopPropagation = function() { this.propagationStopped = true; };
+var preventDefault = function() { this.defaultPrevented = true; };
+
+EventEmitter._emit =
+EventEmitter._dispatchEvent = function(eventName, e) {
+ this._eventRegistry || (this._eventRegistry = {});
+ this._defaultHandlers || (this._defaultHandlers = {});
+
+ var listeners = this._eventRegistry[eventName] || [];
+ var defaultHandler = this._defaultHandlers[eventName];
+ if (!listeners.length && !defaultHandler)
+ return;
+
+ if (typeof e != "object" || !e)
+ e = {};
+
+ if (!e.type)
+ e.type = eventName;
+ if (!e.stopPropagation)
+ e.stopPropagation = stopPropagation;
+ if (!e.preventDefault)
+ e.preventDefault = preventDefault;
+
+ listeners = listeners.slice();
+ for (var i=0; i<listeners.length; i++) {
+ listeners[i](e, this);
+ if (e.propagationStopped)
+ break;
+ }
+
+ if (defaultHandler && !e.defaultPrevented)
+ return defaultHandler(e, this);
+};
+
+
+EventEmitter._signal = function(eventName, e) {
+ var listeners = (this._eventRegistry || {})[eventName];
+ if (!listeners)
+ return;
+ listeners = listeners.slice();
+ for (var i=0; i<listeners.length; i++)
+ listeners[i](e, this);
+};
+
+EventEmitter.once = function(eventName, callback) {
+ var _self = this;
+ callback && this.addEventListener(eventName, function newCallback() {
+ _self.removeEventListener(eventName, newCallback);
+ callback.apply(null, arguments);
+ });
+};
+
+
+EventEmitter.setDefaultHandler = function(eventName, callback) {
+ var handlers = this._defaultHandlers
+ if (!handlers)
+ handlers = this._defaultHandlers = {_disabled_: {}};
+
+ if (handlers[eventName]) {
+ var old = handlers[eventName];
+ var disabled = handlers._disabled_[eventName];
+ if (!disabled)
+ handlers._disabled_[eventName] = disabled = [];
+ disabled.push(old);
+ var i = disabled.indexOf(callback);
+ if (i != -1)
+ disabled.splice(i, 1);
+ }
+ handlers[eventName] = callback;
+};
+EventEmitter.removeDefaultHandler = function(eventName, callback) {
+ var handlers = this._defaultHandlers
+ if (!handlers)
+ return;
+ var disabled = handlers._disabled_[eventName];
+
+ if (handlers[eventName] == callback) {
+ var old = handlers[eventName];
+ if (disabled)
+ this.setDefaultHandler(eventName, disabled.pop());
+ } else if (disabled) {
+ var i = disabled.indexOf(callback);
+ if (i != -1)
+ disabled.splice(i, 1);
+ }
+};
+
+EventEmitter.on =
+EventEmitter.addEventListener = function(eventName, callback, capturing) {
+ this._eventRegistry = this._eventRegistry || {};
+
+ var listeners = this._eventRegistry[eventName];
+ if (!listeners)
+ listeners = this._eventRegistry[eventName] = [];
+
+ if (listeners.indexOf(callback) == -1)
+ listeners[capturing ? "unshift" : "push"](callback);
+ return callback;
+};
+
+EventEmitter.off =
+EventEmitter.removeListener =
+EventEmitter.removeEventListener = function(eventName, callback) {
+ this._eventRegistry = this._eventRegistry || {};
+
+ var listeners = this._eventRegistry[eventName];
+ if (!listeners)
+ return;
+
+ var index = listeners.indexOf(callback);
+ if (index !== -1)
+ listeners.splice(index, 1);
+};
+
+EventEmitter.removeAllListeners = function(eventName) {
+ if (this._eventRegistry) this._eventRegistry[eventName] = [];
+};
+
+exports.EventEmitter = EventEmitter;
+
+});
+
+define('ace/range', ['require', 'exports', 'module' ], function(require, exports, module) {
+
+var comparePoints = function(p1, p2) {
+ return p1.row - p2.row || p1.column - p2.column;
+};
+var Range = function(startRow, startColumn, endRow, endColumn) {
+ this.start = {
+ row: startRow,
+ column: startColumn
+ };
+
+ this.end = {
+ row: endRow,
+ column: endColumn
+ };
+};
+
+(function() {
+ this.isEqual = function(range) {
+ return this.start.row === range.start.row &&
+ this.end.row === range.end.row &&
+ this.start.column === range.start.column &&
+ this.end.column === range.end.column;
+ };
+ this.toString = function() {
+ return ("Range: [" + this.start.row + "/" + this.start.column +
+ "] -> [" + this.end.row + "/" + this.end.column + "]");
+ };
+
+ this.contains = function(row, column) {
+ return this.compare(row, column) == 0;
+ };
+ this.compareRange = function(range) {
+ var cmp,
+ end = range.end,
+ start = range.start;
+
+ cmp = this.compare(end.row, end.column);
+ if (cmp == 1) {
+ cmp = this.compare(start.row, start.column);
+ if (cmp == 1) {
+ return 2;
+ } else if (cmp == 0) {
+ return 1;
+ } else {
+ return 0;
+ }
+ } else if (cmp == -1) {
+ return -2;
+ } else {
+ cmp = this.compare(start.row, start.column);
+ if (cmp == -1) {
+ return -1;
+ } else if (cmp == 1) {
+ return 42;
+ } else {
+ return 0;
+ }
+ }
+ };
+ this.comparePoint = function(p) {
+ return this.compare(p.row, p.column);
+ };
+ this.containsRange = function(range) {
+ return this.comparePoint(range.start) == 0 && this.comparePoint(range.end) == 0;
+ };
+ this.intersects = function(range) {
+ var cmp = this.compareRange(range);
+ return (cmp == -1 || cmp == 0 || cmp == 1);
+ };
+ this.isEnd = function(row, column) {
+ return this.end.row == row && this.end.column == column;
+ };
+ this.isStart = function(row, column) {
+ return this.start.row == row && this.start.column == column;
+ };
+ this.setStart = function(row, column) {
+ if (typeof row == "object") {
+ this.start.column = row.column;
+ this.start.row = row.row;
+ } else {
+ this.start.row = row;
+ this.start.column = column;
+ }
+ };
+ this.setEnd = function(row, column) {
+ if (typeof row == "object") {
+ this.end.column = row.column;
+ this.end.row = row.row;
+ } else {
+ this.end.row = row;
+ this.end.column = column;
+ }
+ };
+ this.inside = function(row, column) {
+ if (this.compare(row, column) == 0) {
+ if (this.isEnd(row, column) || this.isStart(row, column)) {
+ return false;
+ } else {
+ return true;
+ }
+ }
+ return false;
+ };
+ this.insideStart = function(row, column) {
+ if (this.compare(row, column) == 0) {
+ if (this.isEnd(row, column)) {
+ return false;
+ } else {
+ return true;
+ }
+ }
+ return false;
+ };
+ this.insideEnd = function(row, column) {
+ if (this.compare(row, column) == 0) {
+ if (this.isStart(row, column)) {
+ return false;
+ } else {
+ return true;
+ }
+ }
+ return false;
+ };
+ this.compare = function(row, column) {
+ if (!this.isMultiLine()) {
+ if (row === this.start.row) {
+ return column < this.start.column ? -1 : (column > this.end.column ? 1 : 0);
+ };
+ }
+
+ if (row < this.start.row)
+ return -1;
+
+ if (row > this.end.row)
+ return 1;
+
+ if (this.start.row === row)
+ return column >= this.start.column ? 0 : -1;
+
+ if (this.end.row === row)
+ return column <= this.end.column ? 0 : 1;
+
+ return 0;
+ };
+ this.compareStart = function(row, column) {
+ if (this.start.row == row && this.start.column == column) {
+ return -1;
+ } else {
+ return this.compare(row, column);
+ }
+ };
+ this.compareEnd = function(row, column) {
+ if (this.end.row == row && this.end.column == column) {
+ return 1;
+ } else {
+ return this.compare(row, column);
+ }
+ };
+ this.compareInside = function(row, column) {
+ if (this.end.row == row && this.end.column == column) {
+ return 1;
+ } else if (this.start.row == row && this.start.column == column) {
+ return -1;
+ } else {
+ return this.compare(row, column);
+ }
+ };
+ this.clipRows = function(firstRow, lastRow) {
+ if (this.end.row > lastRow)
+ var end = {row: lastRow + 1, column: 0};
+ else if (this.end.row < firstRow)
+ var end = {row: firstRow, column: 0};
+
+ if (this.start.row > lastRow)
+ var start = {row: lastRow + 1, column: 0};
+ else if (this.start.row < firstRow)
+ var start = {row: firstRow, column: 0};
+
+ return Range.fromPoints(start || this.start, end || this.end);
+ };
+ this.extend = function(row, column) {
+ var cmp = this.compare(row, column);
+
+ if (cmp == 0)
+ return this;
+ else if (cmp == -1)
+ var start = {row: row, column: column};
+ else
+ var end = {row: row, column: column};
+
+ return Range.fromPoints(start || this.start, end || this.end);
+ };
+
+ this.isEmpty = function() {
+ return (this.start.row === this.end.row && this.start.column === this.end.column);
+ };
+ this.isMultiLine = function() {
+ return (this.start.row !== this.end.row);
+ };
+ this.clone = function() {
+ return Range.fromPoints(this.start, this.end);
+ };
+ this.collapseRows = function() {
+ if (this.end.column == 0)
+ return new Range(this.start.row, 0, Math.max(this.start.row, this.end.row-1), 0)
+ else
+ return new Range(this.start.row, 0, this.end.row, 0)
+ };
+ this.toScreenRange = function(session) {
+ var screenPosStart = session.documentToScreenPosition(this.start);
+ var screenPosEnd = session.documentToScreenPosition(this.end);
+
+ return new Range(
+ screenPosStart.row, screenPosStart.column,
+ screenPosEnd.row, screenPosEnd.column
+ );
+ };
+ this.moveBy = function(row, column) {
+ this.start.row += row;
+ this.start.column += column;
+ this.end.row += row;
+ this.end.column += column;
+ };
+
+}).call(Range.prototype);
+Range.fromPoints = function(start, end) {
+ return new Range(start.row, start.column, end.row, end.column);
+};
+Range.comparePoints = comparePoints;
+
+Range.comparePoints = function(p1, p2) {
+ return p1.row - p2.row || p1.column - p2.column;
+};
+
+
+exports.Range = Range;
+});
+
+define('ace/anchor', ['require', 'exports', 'module' , 'ace/lib/oop', 'ace/lib/event_emitter'], function(require, exports, module) {
+
+
+var oop = require("./lib/oop");
+var EventEmitter = require("./lib/event_emitter").EventEmitter;
+
+var Anchor = exports.Anchor = function(doc, row, column) {
+ this.$onChange = this.onChange.bind(this);
+ this.attach(doc);
+
+ if (typeof column == "undefined")
+ this.setPosition(row.row, row.column);
+ else
+ this.setPosition(row, column);
+};
+
+(function() {
+
+ oop.implement(this, EventEmitter);
+ this.getPosition = function() {
+ return this.$clipPositionToDocument(this.row, this.column);
+ };
+ this.getDocument = function() {
+ return this.document;
+ };
+ this.$insertRight = false;
+ this.onChange = function(e) {
+ var delta = e.data;
+ var range = delta.range;
+
+ if (range.start.row == range.end.row && range.start.row != this.row)
+ return;
+
+ if (range.start.row > this.row)
+ return;
+
+ if (range.start.row == this.row && range.start.column > this.column)
+ return;
+
+ var row = this.row;
+ var column = this.column;
+ var start = range.start;
+ var end = range.end;
+
+ if (delta.action === "insertText") {
+ if (start.row === row && start.column <= column) {
+ if (start.column === column && this.$insertRight) {
+ } else if (start.row === end.row) {
+ column += end.column - start.column;
+ } else {
+ column -= start.column;
+ row += end.row - start.row;
+ }
+ } else if (start.row !== end.row && start.row < row) {
+ row += end.row - start.row;
+ }
+ } else if (delta.action === "insertLines") {
+ if (start.row <= row) {
+ row += end.row - start.row;
+ }
+ } else if (delta.action === "removeText") {
+ if (start.row === row && start.column < column) {
+ if (end.column >= column)
+ column = start.column;
+ else
+ column = Math.max(0, column - (end.column - start.column));
+
+ } else if (start.row !== end.row && start.row < row) {
+ if (end.row === row)
+ column = Math.max(0, column - end.column) + start.column;
+ row -= (end.row - start.row);
+ } else if (end.row === row) {
+ row -= end.row - start.row;
+ column = Math.max(0, column - end.column) + start.column;
+ }
+ } else if (delta.action == "removeLines") {
+ if (start.row <= row) {
+ if (end.row <= row)
+ row -= end.row - start.row;
+ else {
+ row = start.row;
+ column = 0;
+ }
+ }
+ }
+
+ this.setPosition(row, column, true);
+ };
+ this.setPosition = function(row, column, noClip) {
+ var pos;
+ if (noClip) {
+ pos = {
+ row: row,
+ column: column
+ };
+ } else {
+ pos = this.$clipPositionToDocument(row, column);
+ }
+
+ if (this.row == pos.row && this.column == pos.column)
+ return;
+
+ var old = {
+ row: this.row,
+ column: this.column
+ };
+
+ this.row = pos.row;
+ this.column = pos.column;
+ this._signal("change", {
+ old: old,
+ value: pos
+ });
+ };
+ this.detach = function() {
+ this.document.removeEventListener("change", this.$onChange);
+ };
+ this.attach = function(doc) {
+ this.document = doc || this.document;
+ this.document.on("change", this.$onChange);
+ };
+ this.$clipPositionToDocument = function(row, column) {
+ var pos = {};
+
+ if (row >= this.document.getLength()) {
+ pos.row = Math.max(0, this.document.getLength() - 1);
+ pos.column = this.document.getLine(pos.row).length;
+ }
+ else if (row < 0) {
+ pos.row = 0;
+ pos.column = 0;
+ }
+ else {
+ pos.row = row;
+ pos.column = Math.min(this.document.getLine(pos.row).length, Math.max(0, column));
+ }
+
+ if (column < 0)
+ pos.column = 0;
+
+ return pos;
+ };
+
+}).call(Anchor.prototype);
+
+});
+define('ace/mode/css/csslint', ['require', 'exports', 'module' ], function(require, exports, module) {
+var parserlib = {};
+(function(){
+function EventTarget(){
+ this._listeners = {};
+}
+
+EventTarget.prototype = {
+ constructor: EventTarget,
+ addListener: function(type, listener){
+ if (!this._listeners[type]){
+ this._listeners[type] = [];
+ }
+
+ this._listeners[type].push(listener);
+ },
+ fire: function(event){
+ if (typeof event == "string"){
+ event = { type: event };
+ }
+ if (typeof event.target != "undefined"){
+ event.target = this;
+ }
+
+ if (typeof event.type == "undefined"){
+ throw new Error("Event object missing 'type' property.");
+ }
+
+ if (this._listeners[event.type]){
+ var listeners = this._listeners[event.type].concat();
+ for (var i=0, len=listeners.length; i < len; i++){
+ listeners[i].call(this, event);
+ }
+ }
+ },
+ removeListener: function(type, listener){
+ if (this._listeners[type]){
+ var listeners = this._listeners[type];
+ for (var i=0, len=listeners.length; i < len; i++){
+ if (listeners[i] === listener){
+ listeners.splice(i, 1);
+ break;
+ }
+ }
+
+
+ }
+ }
+};
+function StringReader(text){
+ this._input = text.replace(/\n\r?/g, "\n");
+ this._line = 1;
+ this._col = 1;
+ this._cursor = 0;
+}
+
+StringReader.prototype = {
+ constructor: StringReader,
+ getCol: function(){
+ return this._col;
+ },
+ getLine: function(){
+ return this._line ;
+ },
+ eof: function(){
+ return (this._cursor == this._input.length);
+ },
+ peek: function(count){
+ var c = null;
+ count = (typeof count == "undefined" ? 1 : count);
+ if (this._cursor < this._input.length){
+ c = this._input.charAt(this._cursor + count - 1);
+ }
+
+ return c;
+ },
+ read: function(){
+ var c = null;
+ if (this._cursor < this._input.length){
+ if (this._input.charAt(this._cursor) == "\n"){
+ this._line++;
+ this._col=1;
+ } else {
+ this._col++;
+ }
+ c = this._input.charAt(this._cursor++);
+ }
+
+ return c;
+ },
+ mark: function(){
+ this._bookmark = {
+ cursor: this._cursor,
+ line: this._line,
+ col: this._col
+ };
+ },
+
+ reset: function(){
+ if (this._bookmark){
+ this._cursor = this._bookmark.cursor;
+ this._line = this._bookmark.line;
+ this._col = this._bookmark.col;
+ delete this._bookmark;
+ }
+ },
+ readTo: function(pattern){
+
+ var buffer = "",
+ c;
+ while (buffer.length < pattern.length || buffer.lastIndexOf(pattern) != buffer.length - pattern.length){
+ c = this.read();
+ if (c){
+ buffer += c;
+ } else {
+ throw new Error("Expected \"" + pattern + "\" at line " + this._line + ", col " + this._col + ".");
+ }
+ }
+
+ return buffer;
+
+ },
+ readWhile: function(filter){
+
+ var buffer = "",
+ c = this.read();
+
+ while(c !== null && filter(c)){
+ buffer += c;
+ c = this.read();
+ }
+
+ return buffer;
+
+ },
+ readMatch: function(matcher){
+
+ var source = this._input.substring(this._cursor),
+ value = null;
+ if (typeof matcher == "string"){
+ if (source.indexOf(matcher) === 0){
+ value = this.readCount(matcher.length);
+ }
+ } else if (matcher instanceof RegExp){
+ if (matcher.test(source)){
+ value = this.readCount(RegExp.lastMatch.length);
+ }
+ }
+
+ return value;
+ },
+ readCount: function(count){
+ var buffer = "";
+
+ while(count--){
+ buffer += this.read();
+ }
+
+ return buffer;
+ }
+
+};
+function SyntaxError(message, line, col){
+ this.col = col;
+ this.line = line;
+ this.message = message;
+
+}
+SyntaxError.prototype = new Error();
+function SyntaxUnit(text, line, col, type){
+ this.col = col;
+ this.line = line;
+ this.text = text;
+ this.type = type;
+}
+SyntaxUnit.fromToken = function(token){
+ return new SyntaxUnit(token.value, token.startLine, token.startCol);
+};
+
+SyntaxUnit.prototype = {
+ constructor: SyntaxUnit,
+ valueOf: function(){
+ return this.toString();
+ },
+ toString: function(){
+ return this.text;
+ }
+
+};
+function TokenStreamBase(input, tokenData){
+ this._reader = input ? new StringReader(input.toString()) : null;
+ this._token = null;
+ this._tokenData = tokenData;
+ this._lt = [];
+ this._ltIndex = 0;
+
+ this._ltIndexCache = [];
+}
+TokenStreamBase.createTokenData = function(tokens){
+
+ var nameMap = [],
+ typeMap = {},
+ tokenData = tokens.concat([]),
+ i = 0,
+ len = tokenData.length+1;
+
+ tokenData.UNKNOWN = -1;
+ tokenData.unshift({name:"EOF"});
+
+ for (; i < len; i++){
+ nameMap.push(tokenData[i].name);
+ tokenData[tokenData[i].name] = i;
+ if (tokenData[i].text){
+ typeMap[tokenData[i].text] = i;
+ }
+ }
+
+ tokenData.name = function(tt){
+ return nameMap[tt];
+ };
+
+ tokenData.type = function(c){
+ return typeMap[c];
+ };
+
+ return tokenData;
+};
+
+TokenStreamBase.prototype = {
+ constructor: TokenStreamBase,
+ match: function(tokenTypes, channel){
+ if (!(tokenTypes instanceof Array)){
+ tokenTypes = [tokenTypes];
+ }
+
+ var tt = this.get(channel),
+ i = 0,
+ len = tokenTypes.length;
+
+ while(i < len){
+ if (tt == tokenTypes[i++]){
+ return true;
+ }
+ }
+ this.unget();
+ return false;
+ },
+ mustMatch: function(tokenTypes, channel){
+
+ var token;
+ if (!(tokenTypes instanceof Array)){
+ tokenTypes = [tokenTypes];
+ }
+
+ if (!this.match.apply(this, arguments)){
+ token = this.LT(1);
+ throw new SyntaxError("Expected " + this._tokenData[tokenTypes[0]].name +
+ " at line " + token.startLine + ", col " + token.startCol + ".", token.startLine, token.startCol);
+ }
+ },
+ advance: function(tokenTypes, channel){
+
+ while(this.LA(0) !== 0 && !this.match(tokenTypes, channel)){
+ this.get();
+ }
+
+ return this.LA(0);
+ },
+ get: function(channel){
+
+ var tokenInfo = this._tokenData,
+ reader = this._reader,
+ value,
+ i =0,
+ len = tokenInfo.length,
+ found = false,
+ token,
+ info;
+ if (this._lt.length && this._ltIndex >= 0 && this._ltIndex < this._lt.length){
+
+ i++;
+ this._token = this._lt[this._ltIndex++];
+ info = tokenInfo[this._token.type];
+ while((info.channel !== undefined && channel !== info.channel) &&
+ this._ltIndex < this._lt.length){
+ this._token = this._lt[this._ltIndex++];
+ info = tokenInfo[this._token.type];
+ i++;
+ }
+ if ((info.channel === undefined || channel === info.channel) &&
+ this._ltIndex <= this._lt.length){
+ this._ltIndexCache.push(i);
+ return this._token.type;
+ }
+ }
+ token = this._getToken();
+ if (token.type > -1 && !tokenInfo[token.type].hide){
+ token.channel = tokenInfo[token.type].channel;
+ this._token = token;
+ this._lt.push(token);
+ this._ltIndexCache.push(this._lt.length - this._ltIndex + i);
+ if (this._lt.length > 5){
+ this._lt.shift();
+ }
+ if (this._ltIndexCache.length > 5){
+ this._ltIndexCache.shift();
+ }
+ this._ltIndex = this._lt.length;
+ }
+ info = tokenInfo[token.type];
+ if (info &&
+ (info.hide ||
+ (info.channel !== undefined && channel !== info.channel))){
+ return this.get(channel);
+ } else {
+ return token.type;
+ }
+ },
+ LA: function(index){
+ var total = index,
+ tt;
+ if (index > 0){
+ if (index > 5){
+ throw new Error("Too much lookahead.");
+ }
+ while(total){
+ tt = this.get();
+ total--;
+ }
+ while(total < index){
+ this.unget();
+ total++;
+ }
+ } else if (index < 0){
+
+ if(this._lt[this._ltIndex+index]){
+ tt = this._lt[this._ltIndex+index].type;
+ } else {
+ throw new Error("Too much lookbehind.");
+ }
+
+ } else {
+ tt = this._token.type;
+ }
+
+ return tt;
+
+ },
+ LT: function(index){
+ this.LA(index);
+ return this._lt[this._ltIndex+index-1];
+ },
+ peek: function(){
+ return this.LA(1);
+ },
+ token: function(){
+ return this._token;
+ },
+ tokenName: function(tokenType){
+ if (tokenType < 0 || tokenType > this._tokenData.length){
+ return "UNKNOWN_TOKEN";
+ } else {
+ return this._tokenData[tokenType].name;
+ }
+ },
+ tokenType: function(tokenName){
+ return this._tokenData[tokenName] || -1;
+ },
+ unget: function(){
+ if (this._ltIndexCache.length){
+ this._ltIndex -= this._ltIndexCache.pop();//--;
+ this._token = this._lt[this._ltIndex - 1];
+ } else {
+ throw new Error("Too much lookahead.");
+ }
+ }
+
+};
+
+
+
+
+parserlib.util = {
+StringReader: StringReader,
+SyntaxError : SyntaxError,
+SyntaxUnit : SyntaxUnit,
+EventTarget : EventTarget,
+TokenStreamBase : TokenStreamBase
+};
+})();
+(function(){
+var EventTarget = parserlib.util.EventTarget,
+TokenStreamBase = parserlib.util.TokenStreamBase,
+StringReader = parserlib.util.StringReader,
+SyntaxError = parserlib.util.SyntaxError,
+SyntaxUnit = parserlib.util.SyntaxUnit;
+
+
+var Colors = {
+ aliceblue :"#f0f8ff",
+ antiquewhite :"#faebd7",
+ aqua :"#00ffff",
+ aquamarine :"#7fffd4",
+ azure :"#f0ffff",
+ beige :"#f5f5dc",
+ bisque :"#ffe4c4",
+ black :"#000000",
+ blanchedalmond :"#ffebcd",
+ blue :"#0000ff",
+ blueviolet :"#8a2be2",
+ brown :"#a52a2a",
+ burlywood :"#deb887",
+ cadetblue :"#5f9ea0",
+ chartreuse :"#7fff00",
+ chocolate :"#d2691e",
+ coral :"#ff7f50",
+ cornflowerblue :"#6495ed",
+ cornsilk :"#fff8dc",
+ crimson :"#dc143c",
+ cyan :"#00ffff",
+ darkblue :"#00008b",
+ darkcyan :"#008b8b",
+ darkgoldenrod :"#b8860b",
+ darkgray :"#a9a9a9",
+ darkgreen :"#006400",
+ darkkhaki :"#bdb76b",
+ darkmagenta :"#8b008b",
+ darkolivegreen :"#556b2f",
+ darkorange :"#ff8c00",
+ darkorchid :"#9932cc",
+ darkred :"#8b0000",
+ darksalmon :"#e9967a",
+ darkseagreen :"#8fbc8f",
+ darkslateblue :"#483d8b",
+ darkslategray :"#2f4f4f",
+ darkturquoise :"#00ced1",
+ darkviolet :"#9400d3",
+ deeppink :"#ff1493",
+ deepskyblue :"#00bfff",
+ dimgray :"#696969",
+ dodgerblue :"#1e90ff",
+ firebrick :"#b22222",
+ floralwhite :"#fffaf0",
+ forestgreen :"#228b22",
+ fuchsia :"#ff00ff",
+ gainsboro :"#dcdcdc",
+ ghostwhite :"#f8f8ff",
+ gold :"#ffd700",
+ goldenrod :"#daa520",
+ gray :"#808080",
+ green :"#008000",
+ greenyellow :"#adff2f",
+ honeydew :"#f0fff0",
+ hotpink :"#ff69b4",
+ indianred :"#cd5c5c",
+ indigo :"#4b0082",
+ ivory :"#fffff0",
+ khaki :"#f0e68c",
+ lavender :"#e6e6fa",
+ lavenderblush :"#fff0f5",
+ lawngreen :"#7cfc00",
+ lemonchiffon :"#fffacd",
+ lightblue :"#add8e6",
+ lightcoral :"#f08080",
+ lightcyan :"#e0ffff",
+ lightgoldenrodyellow :"#fafad2",
+ lightgray :"#d3d3d3",
+ lightgreen :"#90ee90",
+ lightpink :"#ffb6c1",
+ lightsalmon :"#ffa07a",
+ lightseagreen :"#20b2aa",
+ lightskyblue :"#87cefa",
+ lightslategray :"#778899",
+ lightsteelblue :"#b0c4de",
+ lightyellow :"#ffffe0",
+ lime :"#00ff00",
+ limegreen :"#32cd32",
+ linen :"#faf0e6",
+ magenta :"#ff00ff",
+ maroon :"#800000",
+ mediumaquamarine:"#66cdaa",
+ mediumblue :"#0000cd",
+ mediumorchid :"#ba55d3",
+ mediumpurple :"#9370d8",
+ mediumseagreen :"#3cb371",
+ mediumslateblue :"#7b68ee",
+ mediumspringgreen :"#00fa9a",
+ mediumturquoise :"#48d1cc",
+ mediumvioletred :"#c71585",
+ midnightblue :"#191970",
+ mintcream :"#f5fffa",
+ mistyrose :"#ffe4e1",
+ moccasin :"#ffe4b5",
+ navajowhite :"#ffdead",
+ navy :"#000080",
+ oldlace :"#fdf5e6",
+ olive :"#808000",
+ olivedrab :"#6b8e23",
+ orange :"#ffa500",
+ orangered :"#ff4500",
+ orchid :"#da70d6",
+ palegoldenrod :"#eee8aa",
+ palegreen :"#98fb98",
+ paleturquoise :"#afeeee",
+ palevioletred :"#d87093",
+ papayawhip :"#ffefd5",
+ peachpuff :"#ffdab9",
+ peru :"#cd853f",
+ pink :"#ffc0cb",
+ plum :"#dda0dd",
+ powderblue :"#b0e0e6",
+ purple :"#800080",
+ red :"#ff0000",
+ rosybrown :"#bc8f8f",
+ royalblue :"#4169e1",
+ saddlebrown :"#8b4513",
+ salmon :"#fa8072",
+ sandybrown :"#f4a460",
+ seagreen :"#2e8b57",
+ seashell :"#fff5ee",
+ sienna :"#a0522d",
+ silver :"#c0c0c0",
+ skyblue :"#87ceeb",
+ slateblue :"#6a5acd",
+ slategray :"#708090",
+ snow :"#fffafa",
+ springgreen :"#00ff7f",
+ steelblue :"#4682b4",
+ tan :"#d2b48c",
+ teal :"#008080",
+ thistle :"#d8bfd8",
+ tomato :"#ff6347",
+ turquoise :"#40e0d0",
+ violet :"#ee82ee",
+ wheat :"#f5deb3",
+ white :"#ffffff",
+ whitesmoke :"#f5f5f5",
+ yellow :"#ffff00",
+ yellowgreen :"#9acd32",
+ activeBorder :"Active window border.",
+ activecaption :"Active window caption.",
+ appworkspace :"Background color of multiple document interface.",
+ background :"Desktop background.",
+ buttonface :"The face background color for 3-D elements that appear 3-D due to one layer of surrounding border.",
+ buttonhighlight :"The color of the border facing the light source for 3-D elements that appear 3-D due to one layer of surrounding border.",
+ buttonshadow :"The color of the border away from the light source for 3-D elements that appear 3-D due to one layer of surrounding border.",
+ buttontext :"Text on push buttons.",
+ captiontext :"Text in caption, size box, and scrollbar arrow box.",
+ graytext :"Grayed (disabled) text. This color is set to #000 if the current display driver does not support a solid gray color.",
+ highlight :"Item(s) selected in a control.",
+ highlighttext :"Text of item(s) selected in a control.",
+ inactiveborder :"Inactive window border.",
+ inactivecaption :"Inactive window caption.",
+ inactivecaptiontext :"Color of text in an inactive caption.",
+ infobackground :"Background color for tooltip controls.",
+ infotext :"Text color for tooltip controls.",
+ menu :"Menu background.",
+ menutext :"Text in menus.",
+ scrollbar :"Scroll bar gray area.",
+ threeddarkshadow :"The color of the darker (generally outer) of the two borders away from the light source for 3-D elements that appear 3-D due to two concentric layers of surrounding border.",
+ threedface :"The face background color for 3-D elements that appear 3-D due to two concentric layers of surrounding border.",
+ threedhighlight :"The color of the lighter (generally outer) of the two borders facing the light source for 3-D elements that appear 3-D due to two concentric layers of surrounding border.",
+ threedlightshadow :"The color of the darker (generally inner) of the two borders facing the light source for 3-D elements that appear 3-D due to two concentric layers of surrounding border.",
+ threedshadow :"The color of the lighter (generally inner) of the two borders away from the light source for 3-D elements that appear 3-D due to two concentric layers of surrounding border.",
+ window :"Window background.",
+ windowframe :"Window frame.",
+ windowtext :"Text in windows."
+};
+function Combinator(text, line, col){
+
+ SyntaxUnit.call(this, text, line, col, Parser.COMBINATOR_TYPE);
+ this.type = "unknown";
+ if (/^\s+$/.test(text)){
+ this.type = "descendant";
+ } else if (text == ">"){
+ this.type = "child";
+ } else if (text == "+"){
+ this.type = "adjacent-sibling";
+ } else if (text == "~"){
+ this.type = "sibling";
+ }
+
+}
+
+Combinator.prototype = new SyntaxUnit();
+Combinator.prototype.constructor = Combinator;
+function MediaFeature(name, value){
+
+ SyntaxUnit.call(this, "(" + name + (value !== null ? ":" + value : "") + ")", name.startLine, name.startCol, Parser.MEDIA_FEATURE_TYPE);
+ this.name = name;
+ this.value = value;
+}
+
+MediaFeature.prototype = new SyntaxUnit();
+MediaFeature.prototype.constructor = MediaFeature;
+function MediaQuery(modifier, mediaType, features, line, col){
+
+ SyntaxUnit.call(this, (modifier ? modifier + " ": "") + (mediaType ? mediaType : "") + (mediaType && features.length > 0 ? " and " : "") + features.join(" and "), line, col, Parser.MEDIA_QUERY_TYPE);
+ this.modifier = modifier;
+ this.mediaType = mediaType;
+ this.features = features;
+
+}
+
+MediaQuery.prototype = new SyntaxUnit();
+MediaQuery.prototype.constructor = MediaQuery;
+function Parser(options){
+ EventTarget.call(this);
+
+
+ this.options = options || {};
+
+ this._tokenStream = null;
+}
+Parser.DEFAULT_TYPE = 0;
+Parser.COMBINATOR_TYPE = 1;
+Parser.MEDIA_FEATURE_TYPE = 2;
+Parser.MEDIA_QUERY_TYPE = 3;
+Parser.PROPERTY_NAME_TYPE = 4;
+Parser.PROPERTY_VALUE_TYPE = 5;
+Parser.PROPERTY_VALUE_PART_TYPE = 6;
+Parser.SELECTOR_TYPE = 7;
+Parser.SELECTOR_PART_TYPE = 8;
+Parser.SELECTOR_SUB_PART_TYPE = 9;
+
+Parser.prototype = function(){
+
+ var proto = new EventTarget(), //new prototype
+ prop,
+ additions = {
+ constructor: Parser,
+ DEFAULT_TYPE : 0,
+ COMBINATOR_TYPE : 1,
+ MEDIA_FEATURE_TYPE : 2,
+ MEDIA_QUERY_TYPE : 3,
+ PROPERTY_NAME_TYPE : 4,
+ PROPERTY_VALUE_TYPE : 5,
+ PROPERTY_VALUE_PART_TYPE : 6,
+ SELECTOR_TYPE : 7,
+ SELECTOR_PART_TYPE : 8,
+ SELECTOR_SUB_PART_TYPE : 9,
+
+ _stylesheet: function(){
+
+ var tokenStream = this._tokenStream,
+ charset = null,
+ count,
+ token,
+ tt;
+
+ this.fire("startstylesheet");
+ this._charset();
+
+ this._skipCruft();
+ while (tokenStream.peek() == Tokens.IMPORT_SYM){
+ this._import();
+ this._skipCruft();
+ }
+ while (tokenStream.peek() == Tokens.NAMESPACE_SYM){
+ this._namespace();
+ this._skipCruft();
+ }
+ tt = tokenStream.peek();
+ while(tt > Tokens.EOF){
+
+ try {
+
+ switch(tt){
+ case Tokens.MEDIA_SYM:
+ this._media();
+ this._skipCruft();
+ break;
+ case Tokens.PAGE_SYM:
+ this._page();
+ this._skipCruft();
+ break;
+ case Tokens.FONT_FACE_SYM:
+ this._font_face();
+ this._skipCruft();
+ break;
+ case Tokens.KEYFRAMES_SYM:
+ this._keyframes();
+ this._skipCruft();
+ break;
+ case Tokens.VIEWPORT_SYM:
+ this._viewport();
+ this._skipCruft();
+ break;
+ case Tokens.UNKNOWN_SYM: //unknown @ rule
+ tokenStream.get();
+ if (!this.options.strict){
+ this.fire({
+ type: "error",
+ error: null,
+ message: "Unknown @ rule: " + tokenStream.LT(0).value + ".",
+ line: tokenStream.LT(0).startLine,
+ col: tokenStream.LT(0).startCol
+ });
+ count=0;
+ while (tokenStream.advance([Tokens.LBRACE, Tokens.RBRACE]) == Tokens.LBRACE){
+ count++; //keep track of nesting depth
+ }
+
+ while(count){
+ tokenStream.advance([Tokens.RBRACE]);
+ count--;
+ }
+
+ } else {
+ throw new SyntaxError("Unknown @ rule.", tokenStream.LT(0).startLine, tokenStream.LT(0).startCol);
+ }
+ break;
+ case Tokens.S:
+ this._readWhitespace();
+ break;
+ default:
+ if(!this._ruleset()){
+ switch(tt){
+ case Tokens.CHARSET_SYM:
+ token = tokenStream.LT(1);
+ this._charset(false);
+ throw new SyntaxError("@charset not allowed here.", token.startLine, token.startCol);
+ case Tokens.IMPORT_SYM:
+ token = tokenStream.LT(1);
+ this._import(false);
+ throw new SyntaxError("@import not allowed here.", token.startLine, token.startCol);
+ case Tokens.NAMESPACE_SYM:
+ token = tokenStream.LT(1);
+ this._namespace(false);
+ throw new SyntaxError("@namespace not allowed here.", token.startLine, token.startCol);
+ default:
+ tokenStream.get(); //get the last token
+ this._unexpectedToken(tokenStream.token());
+ }
+
+ }
+ }
+ } catch(ex) {
+ if (ex instanceof SyntaxError && !this.options.strict){
+ this.fire({
+ type: "error",
+ error: ex,
+ message: ex.message,
+ line: ex.line,
+ col: ex.col
+ });
+ } else {
+ throw ex;
+ }
+ }
+
+ tt = tokenStream.peek();
+ }
+
+ if (tt != Tokens.EOF){
+ this._unexpectedToken(tokenStream.token());
+ }
+
+ this.fire("endstylesheet");
+ },
+
+ _charset: function(emit){
+ var tokenStream = this._tokenStream,
+ charset,
+ token,
+ line,
+ col;
+
+ if (tokenStream.match(Tokens.CHARSET_SYM)){
+ line = tokenStream.token().startLine;
+ col = tokenStream.token().startCol;
+
+ this._readWhitespace();
+ tokenStream.mustMatch(Tokens.STRING);
+
+ token = tokenStream.token();
+ charset = token.value;
+
+ this._readWhitespace();
+ tokenStream.mustMatch(Tokens.SEMICOLON);
+
+ if (emit !== false){
+ this.fire({
+ type: "charset",
+ charset:charset,
+ line: line,
+ col: col
+ });
+ }
+ }
+ },
+
+ _import: function(emit){
+
+ var tokenStream = this._tokenStream,
+ tt,
+ uri,
+ importToken,
+ mediaList = [];
+ tokenStream.mustMatch(Tokens.IMPORT_SYM);
+ importToken = tokenStream.token();
+ this._readWhitespace();
+
+ tokenStream.mustMatch([Tokens.STRING, Tokens.URI]);
+ uri = tokenStream.token().value.replace(/(?:url\()?["']([^"']+)["']\)?/, "$1");
+
+ this._readWhitespace();
+
+ mediaList = this._media_query_list();
+ tokenStream.mustMatch(Tokens.SEMICOLON);
+ this._readWhitespace();
+
+ if (emit !== false){
+ this.fire({
+ type: "import",
+ uri: uri,
+ media: mediaList,
+ line: importToken.startLine,
+ col: importToken.startCol
+ });
+ }
+
+ },
+
+ _namespace: function(emit){
+
+ var tokenStream = this._tokenStream,
+ line,
+ col,
+ prefix,
+ uri;
+ tokenStream.mustMatch(Tokens.NAMESPACE_SYM);
+ line = tokenStream.token().startLine;
+ col = tokenStream.token().startCol;
+ this._readWhitespace();
+ if (tokenStream.match(Tokens.IDENT)){
+ prefix = tokenStream.token().value;
+ this._readWhitespace();
+ }
+
+ tokenStream.mustMatch([Tokens.STRING, Tokens.URI]);
+ uri = tokenStream.token().value.replace(/(?:url\()?["']([^"']+)["']\)?/, "$1");
+
+ this._readWhitespace();
+ tokenStream.mustMatch(Tokens.SEMICOLON);
+ this._readWhitespace();
+
+ if (emit !== false){
+ this.fire({
+ type: "namespace",
+ prefix: prefix,
+ uri: uri,
+ line: line,
+ col: col
+ });
+ }
+
+ },
+
+ _media: function(){
+ var tokenStream = this._tokenStream,
+ line,
+ col,
+ mediaList;// = [];
+ tokenStream.mustMatch(Tokens.MEDIA_SYM);
+ line = tokenStream.token().startLine;
+ col = tokenStream.token().startCol;
+
+ this._readWhitespace();
+
+ mediaList = this._media_query_list();
+
+ tokenStream.mustMatch(Tokens.LBRACE);
+ this._readWhitespace();
+
+ this.fire({
+ type: "startmedia",
+ media: mediaList,
+ line: line,
+ col: col
+ });
+
+ while(true) {
+ if (tokenStream.peek() == Tokens.PAGE_SYM){
+ this._page();
+ } else if (tokenStream.peek() == Tokens.FONT_FACE_SYM){
+ this._font_face();
+ } else if (!this._ruleset()){
+ break;
+ }
+ }
+
+ tokenStream.mustMatch(Tokens.RBRACE);
+ this._readWhitespace();
+
+ this.fire({
+ type: "endmedia",
+ media: mediaList,
+ line: line,
+ col: col
+ });
+ },
+ _media_query_list: function(){
+ var tokenStream = this._tokenStream,
+ mediaList = [];
+
+
+ this._readWhitespace();
+
+ if (tokenStream.peek() == Tokens.IDENT || tokenStream.peek() == Tokens.LPAREN){
+ mediaList.push(this._media_query());
+ }
+
+ while(tokenStream.match(Tokens.COMMA)){
+ this._readWhitespace();
+ mediaList.push(this._media_query());
+ }
+
+ return mediaList;
+ },
+ _media_query: function(){
+ var tokenStream = this._tokenStream,
+ type = null,
+ ident = null,
+ token = null,
+ expressions = [];
+
+ if (tokenStream.match(Tokens.IDENT)){
+ ident = tokenStream.token().value.toLowerCase();
+ if (ident != "only" && ident != "not"){
+ tokenStream.unget();
+ ident = null;
+ } else {
+ token = tokenStream.token();
+ }
+ }
+
+ this._readWhitespace();
+
+ if (tokenStream.peek() == Tokens.IDENT){
+ type = this._media_type();
+ if (token === null){
+ token = tokenStream.token();
+ }
+ } else if (tokenStream.peek() == Tokens.LPAREN){
+ if (token === null){
+ token = tokenStream.LT(1);
+ }
+ expressions.push(this._media_expression());
+ }
+
+ if (type === null && expressions.length === 0){
+ return null;
+ } else {
+ this._readWhitespace();
+ while (tokenStream.match(Tokens.IDENT)){
+ if (tokenStream.token().value.toLowerCase() != "and"){
+ this._unexpectedToken(tokenStream.token());
+ }
+
+ this._readWhitespace();
+ expressions.push(this._media_expression());
+ }
+ }
+
+ return new MediaQuery(ident, type, expressions, token.startLine, token.startCol);
+ },
+ _media_type: function(){
+ return this._media_feature();
+ },
+ _media_expression: function(){
+ var tokenStream = this._tokenStream,
+ feature = null,
+ token,
+ expression = null;
+
+ tokenStream.mustMatch(Tokens.LPAREN);
+
+ feature = this._media_feature();
+ this._readWhitespace();
+
+ if (tokenStream.match(Tokens.COLON)){
+ this._readWhitespace();
+ token = tokenStream.LT(1);
+ expression = this._expression();
+ }
+
+ tokenStream.mustMatch(Tokens.RPAREN);
+ this._readWhitespace();
+
+ return new MediaFeature(feature, (expression ? new SyntaxUnit(expression, token.startLine, token.startCol) : null));
+ },
+ _media_feature: function(){
+ var tokenStream = this._tokenStream;
+
+ tokenStream.mustMatch(Tokens.IDENT);
+
+ return SyntaxUnit.fromToken(tokenStream.token());
+ },
+ _page: function(){
+ var tokenStream = this._tokenStream,
+ line,
+ col,
+ identifier = null,
+ pseudoPage = null;
+ tokenStream.mustMatch(Tokens.PAGE_SYM);
+ line = tokenStream.token().startLine;
+ col = tokenStream.token().startCol;
+
+ this._readWhitespace();
+
+ if (tokenStream.match(Tokens.IDENT)){
+ identifier = tokenStream.token().value;
+ if (identifier.toLowerCase() === "auto"){
+ this._unexpectedToken(tokenStream.token());
+ }
+ }
+ if (tokenStream.peek() == Tokens.COLON){
+ pseudoPage = this._pseudo_page();
+ }
+
+ this._readWhitespace();
+
+ this.fire({
+ type: "startpage",
+ id: identifier,
+ pseudo: pseudoPage,
+ line: line,
+ col: col
+ });
+
+ this._readDeclarations(true, true);
+
+ this.fire({
+ type: "endpage",
+ id: identifier,
+ pseudo: pseudoPage,
+ line: line,
+ col: col
+ });
+
+ },
+ _margin: function(){
+ var tokenStream = this._tokenStream,
+ line,
+ col,
+ marginSym = this._margin_sym();
+
+ if (marginSym){
+ line = tokenStream.token().startLine;
+ col = tokenStream.token().startCol;
+
+ this.fire({
+ type: "startpagemargin",
+ margin: marginSym,
+ line: line,
+ col: col
+ });
+
+ this._readDeclarations(true);
+
+ this.fire({
+ type: "endpagemargin",
+ margin: marginSym,
+ line: line,
+ col: col
+ });
+ return true;
+ } else {
+ return false;
+ }
+ },
+ _margin_sym: function(){
+
+ var tokenStream = this._tokenStream;
+
+ if(tokenStream.match([Tokens.TOPLEFTCORNER_SYM, Tokens.TOPLEFT_SYM,
+ Tokens.TOPCENTER_SYM, Tokens.TOPRIGHT_SYM, Tokens.TOPRIGHTCORNER_SYM,
+ Tokens.BOTTOMLEFTCORNER_SYM, Tokens.BOTTOMLEFT_SYM,
+ Tokens.BOTTOMCENTER_SYM, Tokens.BOTTOMRIGHT_SYM,
+ Tokens.BOTTOMRIGHTCORNER_SYM, Tokens.LEFTTOP_SYM,
+ Tokens.LEFTMIDDLE_SYM, Tokens.LEFTBOTTOM_SYM, Tokens.RIGHTTOP_SYM,
+ Tokens.RIGHTMIDDLE_SYM, Tokens.RIGHTBOTTOM_SYM]))
+ {
+ return SyntaxUnit.fromToken(tokenStream.token());
+ } else {
+ return null;
+ }
+
+ },
+
+ _pseudo_page: function(){
+
+ var tokenStream = this._tokenStream;
+
+ tokenStream.mustMatch(Tokens.COLON);
+ tokenStream.mustMatch(Tokens.IDENT);
+
+ return tokenStream.token().value;
+ },
+
+ _font_face: function(){
+ var tokenStream = this._tokenStream,
+ line,
+ col;
+ tokenStream.mustMatch(Tokens.FONT_FACE_SYM);
+ line = tokenStream.token().startLine;
+ col = tokenStream.token().startCol;
+
+ this._readWhitespace();
+
+ this.fire({
+ type: "startfontface",
+ line: line,
+ col: col
+ });
+
+ this._readDeclarations(true);
+
+ this.fire({
+ type: "endfontface",
+ line: line,
+ col: col
+ });
+ },
+
+ _viewport: function(){
+ var tokenStream = this._tokenStream,
+ line,
+ col;
+
+ tokenStream.mustMatch(Tokens.VIEWPORT_SYM);
+ line = tokenStream.token().startLine;
+ col = tokenStream.token().startCol;
+
+ this._readWhitespace();
+
+ this.fire({
+ type: "startviewport",
+ line: line,
+ col: col
+ });
+
+ this._readDeclarations(true);
+
+ this.fire({
+ type: "endviewport",
+ line: line,
+ col: col
+ });
+
+ },
+
+ _operator: function(inFunction){
+
+ var tokenStream = this._tokenStream,
+ token = null;
+
+ if (tokenStream.match([Tokens.SLASH, Tokens.COMMA]) ||
+ (inFunction && tokenStream.match([Tokens.PLUS, Tokens.STAR, Tokens.MINUS]))){
+ token = tokenStream.token();
+ this._readWhitespace();
+ }
+ return token ? PropertyValuePart.fromToken(token) : null;
+
+ },
+
+ _combinator: function(){
+
+ var tokenStream = this._tokenStream,
+ value = null,
+ token;
+
+ if(tokenStream.match([Tokens.PLUS, Tokens.GREATER, Tokens.TILDE])){
+ token = tokenStream.token();
+ value = new Combinator(token.value, token.startLine, token.startCol);
+ this._readWhitespace();
+ }
+
+ return value;
+ },
+
+ _unary_operator: function(){
+
+ var tokenStream = this._tokenStream;
+
+ if (tokenStream.match([Tokens.MINUS, Tokens.PLUS])){
+ return tokenStream.token().value;
+ } else {
+ return null;
+ }
+ },
+
+ _property: function(){
+
+ var tokenStream = this._tokenStream,
+ value = null,
+ hack = null,
+ tokenValue,
+ token,
+ line,
+ col;
+ if (tokenStream.peek() == Tokens.STAR && this.options.starHack){
+ tokenStream.get();
+ token = tokenStream.token();
+ hack = token.value;
+ line = token.startLine;
+ col = token.startCol;
+ }
+
+ if(tokenStream.match(Tokens.IDENT)){
+ token = tokenStream.token();
+ tokenValue = token.value;
+ if (tokenValue.charAt(0) == "_" && this.options.underscoreHack){
+ hack = "_";
+ tokenValue = tokenValue.substring(1);
+ }
+
+ value = new PropertyName(tokenValue, hack, (line||token.startLine), (col||token.startCol));
+ this._readWhitespace();
+ }
+
+ return value;
+ },
+ _ruleset: function(){
+
+ var tokenStream = this._tokenStream,
+ tt,
+ selectors;
+ try {
+ selectors = this._selectors_group();
+ } catch (ex){
+ if (ex instanceof SyntaxError && !this.options.strict){
+ this.fire({
+ type: "error",
+ error: ex,
+ message: ex.message,
+ line: ex.line,
+ col: ex.col
+ });
+ tt = tokenStream.advance([Tokens.RBRACE]);
+ if (tt == Tokens.RBRACE){
+ } else {
+ throw ex;
+ }
+
+ } else {
+ throw ex;
+ }
+ return true;
+ }
+ if (selectors){
+
+ this.fire({
+ type: "startrule",
+ selectors: selectors,
+ line: selectors[0].line,
+ col: selectors[0].col
+ });
+
+ this._readDeclarations(true);
+
+ this.fire({
+ type: "endrule",
+ selectors: selectors,
+ line: selectors[0].line,
+ col: selectors[0].col
+ });
+
+ }
+
+ return selectors;
+
+ },
+ _selectors_group: function(){
+ var tokenStream = this._tokenStream,
+ selectors = [],
+ selector;
+
+ selector = this._selector();
+ if (selector !== null){
+
+ selectors.push(selector);
+ while(tokenStream.match(Tokens.COMMA)){
+ this._readWhitespace();
+ selector = this._selector();
+ if (selector !== null){
+ selectors.push(selector);
+ } else {
+ this._unexpectedToken(tokenStream.LT(1));
+ }
+ }
+ }
+
+ return selectors.length ? selectors : null;
+ },
+ _selector: function(){
+
+ var tokenStream = this._tokenStream,
+ selector = [],
+ nextSelector = null,
+ combinator = null,
+ ws = null;
+ nextSelector = this._simple_selector_sequence();
+ if (nextSelector === null){
+ return null;
+ }
+
+ selector.push(nextSelector);
+
+ do {
+ combinator = this._combinator();
+
+ if (combinator !== null){
+ selector.push(combinator);
+ nextSelector = this._simple_selector_sequence();
+ if (nextSelector === null){
+ this._unexpectedToken(tokenStream.LT(1));
+ } else {
+ selector.push(nextSelector);
+ }
+ } else {
+ if (this._readWhitespace()){
+ ws = new Combinator(tokenStream.token().value, tokenStream.token().startLine, tokenStream.token().startCol);
+ combinator = this._combinator();
+ nextSelector = this._simple_selector_sequence();
+ if (nextSelector === null){
+ if (combinator !== null){
+ this._unexpectedToken(tokenStream.LT(1));
+ }
+ } else {
+
+ if (combinator !== null){
+ selector.push(combinator);
+ } else {
+ selector.push(ws);
+ }
+
+ selector.push(nextSelector);
+ }
+ } else {
+ break;
+ }
+
+ }
+ } while(true);
+
+ return new Selector(selector, selector[0].line, selector[0].col);
+ },
+ _simple_selector_sequence: function(){
+
+ var tokenStream = this._tokenStream,
+ elementName = null,
+ modifiers = [],
+ selectorText= "",
+ components = [
+ function(){
+ return tokenStream.match(Tokens.HASH) ?
+ new SelectorSubPart(tokenStream.token().value, "id", tokenStream.token().startLine, tokenStream.token().startCol) :
+ null;
+ },
+ this._class,
+ this._attrib,
+ this._pseudo,
+ this._negation
+ ],
+ i = 0,
+ len = components.length,
+ component = null,
+ found = false,
+ line,
+ col;
+ line = tokenStream.LT(1).startLine;
+ col = tokenStream.LT(1).startCol;
+
+ elementName = this._type_selector();
+ if (!elementName){
+ elementName = this._universal();
+ }
+
+ if (elementName !== null){
+ selectorText += elementName;
+ }
+
+ while(true){
+ if (tokenStream.peek() === Tokens.S){
+ break;
+ }
+ while(i < len && component === null){
+ component = components[i++].call(this);
+ }
+
+ if (component === null){
+ if (selectorText === ""){
+ return null;
+ } else {
+ break;
+ }
+ } else {
+ i = 0;
+ modifiers.push(component);
+ selectorText += component.toString();
+ component = null;
+ }
+ }
+
+
+ return selectorText !== "" ?
+ new SelectorPart(elementName, modifiers, selectorText, line, col) :
+ null;
+ },
+ _type_selector: function(){
+
+ var tokenStream = this._tokenStream,
+ ns = this._namespace_prefix(),
+ elementName = this._element_name();
+
+ if (!elementName){
+ if (ns){
+ tokenStream.unget();
+ if (ns.length > 1){
+ tokenStream.unget();
+ }
+ }
+
+ return null;
+ } else {
+ if (ns){
+ elementName.text = ns + elementName.text;
+ elementName.col -= ns.length;
+ }
+ return elementName;
+ }
+ },
+ _class: function(){
+
+ var tokenStream = this._tokenStream,
+ token;
+
+ if (tokenStream.match(Tokens.DOT)){
+ tokenStream.mustMatch(Tokens.IDENT);
+ token = tokenStream.token();
+ return new SelectorSubPart("." + token.value, "class", token.startLine, token.startCol - 1);
+ } else {
+ return null;
+ }
+
+ },
+ _element_name: function(){
+
+ var tokenStream = this._tokenStream,
+ token;
+
+ if (tokenStream.match(Tokens.IDENT)){
+ token = tokenStream.token();
+ return new SelectorSubPart(token.value, "elementName", token.startLine, token.startCol);
+
+ } else {
+ return null;
+ }
+ },
+ _namespace_prefix: function(){
+ var tokenStream = this._tokenStream,
+ value = "";
+ if (tokenStream.LA(1) === Tokens.PIPE || tokenStream.LA(2) === Tokens.PIPE){
+
+ if(tokenStream.match([Tokens.IDENT, Tokens.STAR])){
+ value += tokenStream.token().value;
+ }
+
+ tokenStream.mustMatch(Tokens.PIPE);
+ value += "|";
+
+ }
+
+ return value.length ? value : null;
+ },
+ _universal: function(){
+ var tokenStream = this._tokenStream,
+ value = "",
+ ns;
+
+ ns = this._namespace_prefix();
+ if(ns){
+ value += ns;
+ }
+
+ if(tokenStream.match(Tokens.STAR)){
+ value += "*";
+ }
+
+ return value.length ? value : null;
+
+ },
+ _attrib: function(){
+
+ var tokenStream = this._tokenStream,
+ value = null,
+ ns,
+ token;
+
+ if (tokenStream.match(Tokens.LBRACKET)){
+ token = tokenStream.token();
+ value = token.value;
+ value += this._readWhitespace();
+
+ ns = this._namespace_prefix();
+
+ if (ns){
+ value += ns;
+ }
+
+ tokenStream.mustMatch(Tokens.IDENT);
+ value += tokenStream.token().value;
+ value += this._readWhitespace();
+
+ if(tokenStream.match([Tokens.PREFIXMATCH, Tokens.SUFFIXMATCH, Tokens.SUBSTRINGMATCH,
+ Tokens.EQUALS, Tokens.INCLUDES, Tokens.DASHMATCH])){
+
+ value += tokenStream.token().value;
+ value += this._readWhitespace();
+
+ tokenStream.mustMatch([Tokens.IDENT, Tokens.STRING]);
+ value += tokenStream.token().value;
+ value += this._readWhitespace();
+ }
+
+ tokenStream.mustMatch(Tokens.RBRACKET);
+
+ return new SelectorSubPart(value + "]", "attribute", token.startLine, token.startCol);
+ } else {
+ return null;
+ }
+ },
+ _pseudo: function(){
+
+ var tokenStream = this._tokenStream,
+ pseudo = null,
+ colons = ":",
+ line,
+ col;
+
+ if (tokenStream.match(Tokens.COLON)){
+
+ if (tokenStream.match(Tokens.COLON)){
+ colons += ":";
+ }
+
+ if (tokenStream.match(Tokens.IDENT)){
+ pseudo = tokenStream.token().value;
+ line = tokenStream.token().startLine;
+ col = tokenStream.token().startCol - colons.length;
+ } else if (tokenStream.peek() == Tokens.FUNCTION){
+ line = tokenStream.LT(1).startLine;
+ col = tokenStream.LT(1).startCol - colons.length;
+ pseudo = this._functional_pseudo();
+ }
+
+ if (pseudo){
+ pseudo = new SelectorSubPart(colons + pseudo, "pseudo", line, col);
+ }
+ }
+
+ return pseudo;
+ },
+ _functional_pseudo: function(){
+
+ var tokenStream = this._tokenStream,
+ value = null;
+
+ if(tokenStream.match(Tokens.FUNCTION)){
+ value = tokenStream.token().value;
+ value += this._readWhitespace();
+ value += this._expression();
+ tokenStream.mustMatch(Tokens.RPAREN);
+ value += ")";
+ }
+
+ return value;
+ },
+ _expression: function(){
+
+ var tokenStream = this._tokenStream,
+ value = "";
+
+ while(tokenStream.match([Tokens.PLUS, Tokens.MINUS, Tokens.DIMENSION,
+ Tokens.NUMBER, Tokens.STRING, Tokens.IDENT, Tokens.LENGTH,
+ Tokens.FREQ, Tokens.ANGLE, Tokens.TIME,
+ Tokens.RESOLUTION, Tokens.SLASH])){
+
+ value += tokenStream.token().value;
+ value += this._readWhitespace();
+ }
+
+ return value.length ? value : null;
+
+ },
+ _negation: function(){
+
+ var tokenStream = this._tokenStream,
+ line,
+ col,
+ value = "",
+ arg,
+ subpart = null;
+
+ if (tokenStream.match(Tokens.NOT)){
+ value = tokenStream.token().value;
+ line = tokenStream.token().startLine;
+ col = tokenStream.token().startCol;
+ value += this._readWhitespace();
+ arg = this._negation_arg();
+ value += arg;
+ value += this._readWhitespace();
+ tokenStream.match(Tokens.RPAREN);
+ value += tokenStream.token().value;
+
+ subpart = new SelectorSubPart(value, "not", line, col);
+ subpart.args.push(arg);
+ }
+
+ return subpart;
+ },
+ _negation_arg: function(){
+
+ var tokenStream = this._tokenStream,
+ args = [
+ this._type_selector,
+ this._universal,
+ function(){
+ return tokenStream.match(Tokens.HASH) ?
+ new SelectorSubPart(tokenStream.token().value, "id", tokenStream.token().startLine, tokenStream.token().startCol) :
+ null;
+ },
+ this._class,
+ this._attrib,
+ this._pseudo
+ ],
+ arg = null,
+ i = 0,
+ len = args.length,
+ elementName,
+ line,
+ col,
+ part;
+
+ line = tokenStream.LT(1).startLine;
+ col = tokenStream.LT(1).startCol;
+
+ while(i < len && arg === null){
+
+ arg = args[i].call(this);
+ i++;
+ }
+ if (arg === null){
+ this._unexpectedToken(tokenStream.LT(1));
+ }
+ if (arg.type == "elementName"){
+ part = new SelectorPart(arg, [], arg.toString(), line, col);
+ } else {
+ part = new SelectorPart(null, [arg], arg.toString(), line, col);
+ }
+
+ return part;
+ },
+
+ _declaration: function(){
+
+ var tokenStream = this._tokenStream,
+ property = null,
+ expr = null,
+ prio = null,
+ error = null,
+ invalid = null,
+ propertyName= "";
+
+ property = this._property();
+ if (property !== null){
+
+ tokenStream.mustMatch(Tokens.COLON);
+ this._readWhitespace();
+
+ expr = this._expr();
+ if (!expr || expr.length === 0){
+ this._unexpectedToken(tokenStream.LT(1));
+ }
+
+ prio = this._prio();
+ propertyName = property.toString();
+ if (this.options.starHack && property.hack == "*" ||
+ this.options.underscoreHack && property.hack == "_") {
+
+ propertyName = property.text;
+ }
+
+ try {
+ this._validateProperty(propertyName, expr);
+ } catch (ex) {
+ invalid = ex;
+ }
+
+ this.fire({
+ type: "property",
+ property: property,
+ value: expr,
+ important: prio,
+ line: property.line,
+ col: property.col,
+ invalid: invalid
+ });
+
+ return true;
+ } else {
+ return false;
+ }
+ },
+
+ _prio: function(){
+
+ var tokenStream = this._tokenStream,
+ result = tokenStream.match(Tokens.IMPORTANT_SYM);
+
+ this._readWhitespace();
+ return result;
+ },
+
+ _expr: function(inFunction){
+
+ var tokenStream = this._tokenStream,
+ values = [],
+ value = null,
+ operator = null;
+
+ value = this._term();
+ if (value !== null){
+
+ values.push(value);
+
+ do {
+ operator = this._operator(inFunction);
+ if (operator){
+ values.push(operator);
+ } /*else {
+ values.push(new PropertyValue(valueParts, valueParts[0].line, valueParts[0].col));
+ valueParts = [];
+ }*/
+
+ value = this._term();
+
+ if (value === null){
+ break;
+ } else {
+ values.push(value);
+ }
+ } while(true);
+ }
+
+ return values.length > 0 ? new PropertyValue(values, values[0].line, values[0].col) : null;
+ },
+
+ _term: function(){
+
+ var tokenStream = this._tokenStream,
+ unary = null,
+ value = null,
+ token,
+ line,
+ col;
+ unary = this._unary_operator();
+ if (unary !== null){
+ line = tokenStream.token().startLine;
+ col = tokenStream.token().startCol;
+ }
+ if (tokenStream.peek() == Tokens.IE_FUNCTION && this.options.ieFilters){
+
+ value = this._ie_function();
+ if (unary === null){
+ line = tokenStream.token().startLine;
+ col = tokenStream.token().startCol;
+ }
+ } else if (tokenStream.match([Tokens.NUMBER, Tokens.PERCENTAGE, Tokens.LENGTH,
+ Tokens.ANGLE, Tokens.TIME,
+ Tokens.FREQ, Tokens.STRING, Tokens.IDENT, Tokens.URI, Tokens.UNICODE_RANGE])){
+
+ value = tokenStream.token().value;
+ if (unary === null){
+ line = tokenStream.token().startLine;
+ col = tokenStream.token().startCol;
+ }
+ this._readWhitespace();
+ } else {
+ token = this._hexcolor();
+ if (token === null){
+ if (unary === null){
+ line = tokenStream.LT(1).startLine;
+ col = tokenStream.LT(1).startCol;
+ }
+ if (value === null){
+ if (tokenStream.LA(3) == Tokens.EQUALS && this.options.ieFilters){
+ value = this._ie_function();
+ } else {
+ value = this._function();
+ }
+ }
+
+ } else {
+ value = token.value;
+ if (unary === null){
+ line = token.startLine;
+ col = token.startCol;
+ }
+ }
+
+ }
+
+ return value !== null ?
+ new PropertyValuePart(unary !== null ? unary + value : value, line, col) :
+ null;
+
+ },
+
+ _function: function(){
+
+ var tokenStream = this._tokenStream,
+ functionText = null,
+ expr = null,
+ lt;
+
+ if (tokenStream.match(Tokens.FUNCTION)){
+ functionText = tokenStream.token().value;
+ this._readWhitespace();
+ expr = this._expr(true);
+ functionText += expr;
+ if (this.options.ieFilters && tokenStream.peek() == Tokens.EQUALS){
+ do {
+
+ if (this._readWhitespace()){
+ functionText += tokenStream.token().value;
+ }
+ if (tokenStream.LA(0) == Tokens.COMMA){
+ functionText += tokenStream.token().value;
+ }
+
+ tokenStream.match(Tokens.IDENT);
+ functionText += tokenStream.token().value;
+
+ tokenStream.match(Tokens.EQUALS);
+ functionText += tokenStream.token().value;
+ lt = tokenStream.peek();
+ while(lt != Tokens.COMMA && lt != Tokens.S && lt != Tokens.RPAREN){
+ tokenStream.get();
+ functionText += tokenStream.token().value;
+ lt = tokenStream.peek();
+ }
+ } while(tokenStream.match([Tokens.COMMA, Tokens.S]));
+ }
+
+ tokenStream.match(Tokens.RPAREN);
+ functionText += ")";
+ this._readWhitespace();
+ }
+
+ return functionText;
+ },
+
+ _ie_function: function(){
+
+ var tokenStream = this._tokenStream,
+ functionText = null,
+ expr = null,
+ lt;
+ if (tokenStream.match([Tokens.IE_FUNCTION, Tokens.FUNCTION])){
+ functionText = tokenStream.token().value;
+
+ do {
+
+ if (this._readWhitespace()){
+ functionText += tokenStream.token().value;
+ }
+ if (tokenStream.LA(0) == Tokens.COMMA){
+ functionText += tokenStream.token().value;
+ }
+
+ tokenStream.match(Tokens.IDENT);
+ functionText += tokenStream.token().value;
+
+ tokenStream.match(Tokens.EQUALS);
+ functionText += tokenStream.token().value;
+ lt = tokenStream.peek();
+ while(lt != Tokens.COMMA && lt != Tokens.S && lt != Tokens.RPAREN){
+ tokenStream.get();
+ functionText += tokenStream.token().value;
+ lt = tokenStream.peek();
+ }
+ } while(tokenStream.match([Tokens.COMMA, Tokens.S]));
+
+ tokenStream.match(Tokens.RPAREN);
+ functionText += ")";
+ this._readWhitespace();
+ }
+
+ return functionText;
+ },
+
+ _hexcolor: function(){
+
+ var tokenStream = this._tokenStream,
+ token = null,
+ color;
+
+ if(tokenStream.match(Tokens.HASH)){
+
+ token = tokenStream.token();
+ color = token.value;
+ if (!/#[a-f0-9]{3,6}/i.test(color)){
+ throw new SyntaxError("Expected a hex color but found '" + color + "' at line " + token.startLine + ", col " + token.startCol + ".", token.startLine, token.startCol);
+ }
+ this._readWhitespace();
+ }
+
+ return token;
+ },
+
+ _keyframes: function(){
+ var tokenStream = this._tokenStream,
+ token,
+ tt,
+ name,
+ prefix = "";
+
+ tokenStream.mustMatch(Tokens.KEYFRAMES_SYM);
+ token = tokenStream.token();
+ if (/^@\-([^\-]+)\-/.test(token.value)) {
+ prefix = RegExp.$1;
+ }
+
+ this._readWhitespace();
+ name = this._keyframe_name();
+
+ this._readWhitespace();
+ tokenStream.mustMatch(Tokens.LBRACE);
+
+ this.fire({
+ type: "startkeyframes",
+ name: name,
+ prefix: prefix,
+ line: token.startLine,
+ col: token.startCol
+ });
+
+ this._readWhitespace();
+ tt = tokenStream.peek();
+ while(tt == Tokens.IDENT || tt == Tokens.PERCENTAGE) {
+ this._keyframe_rule();
+ this._readWhitespace();
+ tt = tokenStream.peek();
+ }
+
+ this.fire({
+ type: "endkeyframes",
+ name: name,
+ prefix: prefix,
+ line: token.startLine,
+ col: token.startCol
+ });
+
+ this._readWhitespace();
+ tokenStream.mustMatch(Tokens.RBRACE);
+
+ },
+
+ _keyframe_name: function(){
+ var tokenStream = this._tokenStream,
+ token;
+
+ tokenStream.mustMatch([Tokens.IDENT, Tokens.STRING]);
+ return SyntaxUnit.fromToken(tokenStream.token());
+ },
+
+ _keyframe_rule: function(){
+ var tokenStream = this._tokenStream,
+ token,
+ keyList = this._key_list();
+
+ this.fire({
+ type: "startkeyframerule",
+ keys: keyList,
+ line: keyList[0].line,
+ col: keyList[0].col
+ });
+
+ this._readDeclarations(true);
+
+ this.fire({
+ type: "endkeyframerule",
+ keys: keyList,
+ line: keyList[0].line,
+ col: keyList[0].col
+ });
+
+ },
+
+ _key_list: function(){
+ var tokenStream = this._tokenStream,
+ token,
+ key,
+ keyList = [];
+ keyList.push(this._key());
+
+ this._readWhitespace();
+
+ while(tokenStream.match(Tokens.COMMA)){
+ this._readWhitespace();
+ keyList.push(this._key());
+ this._readWhitespace();
+ }
+
+ return keyList;
+ },
+
+ _key: function(){
+
+ var tokenStream = this._tokenStream,
+ token;
+
+ if (tokenStream.match(Tokens.PERCENTAGE)){
+ return SyntaxUnit.fromToken(tokenStream.token());
+ } else if (tokenStream.match(Tokens.IDENT)){
+ token = tokenStream.token();
+
+ if (/from|to/i.test(token.value)){
+ return SyntaxUnit.fromToken(token);
+ }
+
+ tokenStream.unget();
+ }
+ this._unexpectedToken(tokenStream.LT(1));
+ },
+ _skipCruft: function(){
+ while(this._tokenStream.match([Tokens.S, Tokens.CDO, Tokens.CDC])){
+ }
+ },
+ _readDeclarations: function(checkStart, readMargins){
+ var tokenStream = this._tokenStream,
+ tt;
+
+
+ this._readWhitespace();
+
+ if (checkStart){
+ tokenStream.mustMatch(Tokens.LBRACE);
+ }
+
+ this._readWhitespace();
+
+ try {
+
+ while(true){
+
+ if (tokenStream.match(Tokens.SEMICOLON) || (readMargins && this._margin())){
+ } else if (this._declaration()){
+ if (!tokenStream.match(Tokens.SEMICOLON)){
+ break;
+ }
+ } else {
+ break;
+ }
+ this._readWhitespace();
+ }
+
+ tokenStream.mustMatch(Tokens.RBRACE);
+ this._readWhitespace();
+
+ } catch (ex) {
+ if (ex instanceof SyntaxError && !this.options.strict){
+ this.fire({
+ type: "error",
+ error: ex,
+ message: ex.message,
+ line: ex.line,
+ col: ex.col
+ });
+ tt = tokenStream.advance([Tokens.SEMICOLON, Tokens.RBRACE]);
+ if (tt == Tokens.SEMICOLON){
+ this._readDeclarations(false, readMargins);
+ } else if (tt != Tokens.RBRACE){
+ throw ex;
+ }
+
+ } else {
+ throw ex;
+ }
+ }
+
+ },
+ _readWhitespace: function(){
+
+ var tokenStream = this._tokenStream,
+ ws = "";
+
+ while(tokenStream.match(Tokens.S)){
+ ws += tokenStream.token().value;
+ }
+
+ return ws;
+ },
+ _unexpectedToken: function(token){
+ throw new SyntaxError("Unexpected token '" + token.value + "' at line " + token.startLine + ", col " + token.startCol + ".", token.startLine, token.startCol);
+ },
+ _verifyEnd: function(){
+ if (this._tokenStream.LA(1) != Tokens.EOF){
+ this._unexpectedToken(this._tokenStream.LT(1));
+ }
+ },
+ _validateProperty: function(property, value){
+ Validation.validate(property, value);
+ },
+
+ parse: function(input){
+ this._tokenStream = new TokenStream(input, Tokens);
+ this._stylesheet();
+ },
+
+ parseStyleSheet: function(input){
+ return this.parse(input);
+ },
+
+ parseMediaQuery: function(input){
+ this._tokenStream = new TokenStream(input, Tokens);
+ var result = this._media_query();
+ this._verifyEnd();
+ return result;
+ },
+ parsePropertyValue: function(input){
+
+ this._tokenStream = new TokenStream(input, Tokens);
+ this._readWhitespace();
+
+ var result = this._expr();
+ this._readWhitespace();
+ this._verifyEnd();
+ return result;
+ },
+ parseRule: function(input){
+ this._tokenStream = new TokenStream(input, Tokens);
+ this._readWhitespace();
+
+ var result = this._ruleset();
+ this._readWhitespace();
+ this._verifyEnd();
+ return result;
+ },
+ parseSelector: function(input){
+
+ this._tokenStream = new TokenStream(input, Tokens);
+ this._readWhitespace();
+
+ var result = this._selector();
+ this._readWhitespace();
+ this._verifyEnd();
+ return result;
+ },
+ parseStyleAttribute: function(input){
+ input += "}"; // for error recovery in _readDeclarations()
+ this._tokenStream = new TokenStream(input, Tokens);
+ this._readDeclarations();
+ }
+ };
+ for (prop in additions){
+ if (additions.hasOwnProperty(prop)){
+ proto[prop] = additions[prop];
+ }
+ }
+
+ return proto;
+}();
+var Properties = {
+ "alignment-adjust" : "auto | baseline | before-edge | text-before-edge | middle | central | after-edge | text-after-edge | ideographic | alphabetic | hanging | mathematical | <percentage> | <length>",
+ "alignment-baseline" : "baseline | use-script | before-edge | text-before-edge | after-edge | text-after-edge | central | middle | ideographic | alphabetic | hanging | mathematical",
+ "animation" : 1,
+ "animation-delay" : { multi: "<time>", comma: true },
+ "animation-direction" : { multi: "normal | alternate", comma: true },
+ "animation-duration" : { multi: "<time>", comma: true },
+ "animation-iteration-count" : { multi: "<number> | infinite", comma: true },
+ "animation-name" : { multi: "none | <ident>", comma: true },
+ "animation-play-state" : { multi: "running | paused", comma: true },
+ "animation-timing-function" : 1,
+ "-moz-animation-delay" : { multi: "<time>", comma: true },
+ "-moz-animation-direction" : { multi: "normal | alternate", comma: true },
+ "-moz-animation-duration" : { multi: "<time>", comma: true },
+ "-moz-animation-iteration-count" : { multi: "<number> | infinite", comma: true },
+ "-moz-animation-name" : { multi: "none | <ident>", comma: true },
+ "-moz-animation-play-state" : { multi: "running | paused", comma: true },
+
+ "-ms-animation-delay" : { multi: "<time>", comma: true },
+ "-ms-animation-direction" : { multi: "normal | alternate", comma: true },
+ "-ms-animation-duration" : { multi: "<time>", comma: true },
+ "-ms-animation-iteration-count" : { multi: "<number> | infinite", comma: true },
+ "-ms-animation-name" : { multi: "none | <ident>", comma: true },
+ "-ms-animation-play-state" : { multi: "running | paused", comma: true },
+
+ "-webkit-animation-delay" : { multi: "<time>", comma: true },
+ "-webkit-animation-direction" : { multi: "normal | alternate", comma: true },
+ "-webkit-animation-duration" : { multi: "<time>", comma: true },
+ "-webkit-animation-iteration-count" : { multi: "<number> | infinite", comma: true },
+ "-webkit-animation-name" : { multi: "none | <ident>", comma: true },
+ "-webkit-animation-play-state" : { multi: "running | paused", comma: true },
+
+ "-o-animation-delay" : { multi: "<time>", comma: true },
+ "-o-animation-direction" : { multi: "normal | alternate", comma: true },
+ "-o-animation-duration" : { multi: "<time>", comma: true },
+ "-o-animation-iteration-count" : { multi: "<number> | infinite", comma: true },
+ "-o-animation-name" : { multi: "none | <ident>", comma: true },
+ "-o-animation-play-state" : { multi: "running | paused", comma: true },
+
+ "appearance" : "icon | window | desktop | workspace | document | tooltip | dialog | button | push-button | hyperlink | radio-button | checkbox | menu-item | tab | menu | menubar | pull-down-menu | pop-up-menu | list-menu | radio-group | checkbox-group | outline-tree | range | field | combo-box | signature | password | normal | none | inherit",
+ "azimuth" : function (expression) {
+ var simple = "<angle> | leftwards | rightwards | inherit",
+ direction = "left-side | far-left | left | center-left | center | center-right | right | far-right | right-side",
+ behind = false,
+ valid = false,
+ part;
+
+ if (!ValidationTypes.isAny(expression, simple)) {
+ if (ValidationTypes.isAny(expression, "behind")) {
+ behind = true;
+ valid = true;
+ }
+
+ if (ValidationTypes.isAny(expression, direction)) {
+ valid = true;
+ if (!behind) {
+ ValidationTypes.isAny(expression, "behind");
+ }
+ }
+ }
+
+ if (expression.hasNext()) {
+ part = expression.next();
+ if (valid) {
+ throw new ValidationError("Expected end of value but found '" + part + "'.", part.line, part.col);
+ } else {
+ throw new ValidationError("Expected (<'azimuth'>) but found '" + part + "'.", part.line, part.col);
+ }
+ }
+ },
+ "backface-visibility" : "visible | hidden",
+ "background" : 1,
+ "background-attachment" : { multi: "<attachment>", comma: true },
+ "background-clip" : { multi: "<box>", comma: true },
+ "background-color" : "<color> | inherit",
+ "background-image" : { multi: "<bg-image>", comma: true },
+ "background-origin" : { multi: "<box>", comma: true },
+ "background-position" : { multi: "<bg-position>", comma: true },
+ "background-repeat" : { multi: "<repeat-style>" },
+ "background-size" : { multi: "<bg-size>", comma: true },
+ "baseline-shift" : "baseline | sub | super | <percentage> | <length>",
+ "behavior" : 1,
+ "binding" : 1,
+ "bleed" : "<length>",
+ "bookmark-label" : "<content> | <attr> | <string>",
+ "bookmark-level" : "none | <integer>",
+ "bookmark-state" : "open | closed",
+ "bookmark-target" : "none | <uri> | <attr>",
+ "border" : "<border-width> || <border-style> || <color>",
+ "border-bottom" : "<border-width> || <border-style> || <color>",
+ "border-bottom-color" : "<color> | inherit",
+ "border-bottom-left-radius" : "<x-one-radius>",
+ "border-bottom-right-radius" : "<x-one-radius>",
+ "border-bottom-style" : "<border-style>",
+ "border-bottom-width" : "<border-width>",
+ "border-collapse" : "collapse | separate | inherit",
+ "border-color" : { multi: "<color> | inherit", max: 4 },
+ "border-image" : 1,
+ "border-image-outset" : { multi: "<length> | <number>", max: 4 },
+ "border-image-repeat" : { multi: "stretch | repeat | round", max: 2 },
+ "border-image-slice" : function(expression) {
+
+ var valid = false,
+ numeric = "<number> | <percentage>",
+ fill = false,
+ count = 0,
+ max = 4,
+ part;
+
+ if (ValidationTypes.isAny(expression, "fill")) {
+ fill = true;
+ valid = true;
+ }
+
+ while (expression.hasNext() && count < max) {
+ valid = ValidationTypes.isAny(expression, numeric);
+ if (!valid) {
+ break;
+ }
+ count++;
+ }
+
+
+ if (!fill) {
+ ValidationTypes.isAny(expression, "fill");
+ } else {
+ valid = true;
+ }
+
+ if (expression.hasNext()) {
+ part = expression.next();
+ if (valid) {
+ throw new ValidationError("Expected end of value but found '" + part + "'.", part.line, part.col);
+ } else {
+ throw new ValidationError("Expected ([<number> | <percentage>]{1,4} && fill?) but found '" + part + "'.", part.line, part.col);
+ }
+ }
+ },
+ "border-image-source" : "<image> | none",
+ "border-image-width" : { multi: "<length> | <percentage> | <number> | auto", max: 4 },
+ "border-left" : "<border-width> || <border-style> || <color>",
+ "border-left-color" : "<color> | inherit",
+ "border-left-style" : "<border-style>",
+ "border-left-width" : "<border-width>",
+ "border-radius" : function(expression) {
+
+ var valid = false,
+ simple = "<length> | <percentage> | inherit",
+ slash = false,
+ fill = false,
+ count = 0,
+ max = 8,
+ part;
+
+ while (expression.hasNext() && count < max) {
+ valid = ValidationTypes.isAny(expression, simple);
+ if (!valid) {
+
+ if (expression.peek() == "/" && count > 0 && !slash) {
+ slash = true;
+ max = count + 5;
+ expression.next();
+ } else {
+ break;
+ }
+ }
+ count++;
+ }
+
+ if (expression.hasNext()) {
+ part = expression.next();
+ if (valid) {
+ throw new ValidationError("Expected end of value but found '" + part + "'.", part.line, part.col);
+ } else {
+ throw new ValidationError("Expected (<'border-radius'>) but found '" + part + "'.", part.line, part.col);
+ }
+ }
+ },
+ "border-right" : "<border-width> || <border-style> || <color>",
+ "border-right-color" : "<color> | inherit",
+ "border-right-style" : "<border-style>",
+ "border-right-width" : "<border-width>",
+ "border-spacing" : { multi: "<length> | inherit", max: 2 },
+ "border-style" : { multi: "<border-style>", max: 4 },
+ "border-top" : "<border-width> || <border-style> || <color>",
+ "border-top-color" : "<color> | inherit",
+ "border-top-left-radius" : "<x-one-radius>",
+ "border-top-right-radius" : "<x-one-radius>",
+ "border-top-style" : "<border-style>",
+ "border-top-width" : "<border-width>",
+ "border-width" : { multi: "<border-width>", max: 4 },
+ "bottom" : "<margin-width> | inherit",
+ "box-align" : "start | end | center | baseline | stretch", //http://www.w3.org/TR/2009/WD-css3-flexbox-20090723/
+ "box-decoration-break" : "slice |clone",
+ "box-direction" : "normal | reverse | inherit",
+ "box-flex" : "<number>",
+ "box-flex-group" : "<integer>",
+ "box-lines" : "single | multiple",
+ "box-ordinal-group" : "<integer>",
+ "box-orient" : "horizontal | vertical | inline-axis | block-axis | inherit",
+ "box-pack" : "start | end | center | justify",
+ "box-shadow" : function (expression) {
+ var result = false,
+ part;
+
+ if (!ValidationTypes.isAny(expression, "none")) {
+ Validation.multiProperty("<shadow>", expression, true, Infinity);
+ } else {
+ if (expression.hasNext()) {
+ part = expression.next();
+ throw new ValidationError("Expected end of value but found '" + part + "'.", part.line, part.col);
+ }
+ }
+ },
+ "box-sizing" : "content-box | border-box | inherit",
+ "break-after" : "auto | always | avoid | left | right | page | column | avoid-page | avoid-column",
+ "break-before" : "auto | always | avoid | left | right | page | column | avoid-page | avoid-column",
+ "break-inside" : "auto | avoid | avoid-page | avoid-column",
+ "caption-side" : "top | bottom | inherit",
+ "clear" : "none | right | left | both | inherit",
+ "clip" : 1,
+ "color" : "<color> | inherit",
+ "color-profile" : 1,
+ "column-count" : "<integer> | auto", //http://www.w3.org/TR/css3-multicol/
+ "column-fill" : "auto | balance",
+ "column-gap" : "<length> | normal",
+ "column-rule" : "<border-width> || <border-style> || <color>",
+ "column-rule-color" : "<color>",
+ "column-rule-style" : "<border-style>",
+ "column-rule-width" : "<border-width>",
+ "column-span" : "none | all",
+ "column-width" : "<length> | auto",
+ "columns" : 1,
+ "content" : 1,
+ "counter-increment" : 1,
+ "counter-reset" : 1,
+ "crop" : "<shape> | auto",
+ "cue" : "cue-after | cue-before | inherit",
+ "cue-after" : 1,
+ "cue-before" : 1,
+ "cursor" : 1,
+ "direction" : "ltr | rtl | inherit",
+ "display" : "inline | block | list-item | inline-block | table | inline-table | table-row-group | table-header-group | table-footer-group | table-row | table-column-group | table-column | table-cell | table-caption | box | inline-box | grid | inline-grid | none | inherit | -moz-box | -moz-inline-block | -moz-inline-box | -moz-inline-grid | -moz-inline-stack | -moz-inline-table | -moz-grid | -moz-grid-group | -moz-grid-line | -moz-groupbox | -moz-deck | -moz-popup | -moz-stack | -moz-marker | -webkit-box | -webkit-inline-box",
+ "dominant-baseline" : 1,
+ "drop-initial-after-adjust" : "central | middle | after-edge | text-after-edge | ideographic | alphabetic | mathematical | <percentage> | <length>",
+ "drop-initial-after-align" : "baseline | use-script | before-edge | text-before-edge | after-edge | text-after-edge | central | middle | ideographic | alphabetic | hanging | mathematical",
+ "drop-initial-before-adjust" : "before-edge | text-before-edge | central | middle | hanging | mathematical | <percentage> | <length>",
+ "drop-initial-before-align" : "caps-height | baseline | use-script | before-edge | text-before-edge | after-edge | text-after-edge | central | middle | ideographic | alphabetic | hanging | mathematical",
+ "drop-initial-size" : "auto | line | <length> | <percentage>",
+ "drop-initial-value" : "initial | <integer>",
+ "elevation" : "<angle> | below | level | above | higher | lower | inherit",
+ "empty-cells" : "show | hide | inherit",
+ "filter" : 1,
+ "fit" : "fill | hidden | meet | slice",
+ "fit-position" : 1,
+ "float" : "left | right | none | inherit",
+ "float-offset" : 1,
+ "font" : 1,
+ "font-family" : 1,
+ "font-size" : "<absolute-size> | <relative-size> | <length> | <percentage> | inherit",
+ "font-size-adjust" : "<number> | none | inherit",
+ "font-stretch" : "normal | ultra-condensed | extra-condensed | condensed | semi-condensed | semi-expanded | expanded | extra-expanded | ultra-expanded | inherit",
+ "font-style" : "normal | italic | oblique | inherit",
+ "font-variant" : "normal | small-caps | inherit",
+ "font-weight" : "normal | bold | bolder | lighter | 100 | 200 | 300 | 400 | 500 | 600 | 700 | 800 | 900 | inherit",
+ "grid-cell-stacking" : "columns | rows | layer",
+ "grid-column" : 1,
+ "grid-columns" : 1,
+ "grid-column-align" : "start | end | center | stretch",
+ "grid-column-sizing" : 1,
+ "grid-column-span" : "<integer>",
+ "grid-flow" : "none | rows | columns",
+ "grid-layer" : "<integer>",
+ "grid-row" : 1,
+ "grid-rows" : 1,
+ "grid-row-align" : "start | end | center | stretch",
+ "grid-row-span" : "<integer>",
+ "grid-row-sizing" : 1,
+ "hanging-punctuation" : 1,
+ "height" : "<margin-width> | inherit",
+ "hyphenate-after" : "<integer> | auto",
+ "hyphenate-before" : "<integer> | auto",
+ "hyphenate-character" : "<string> | auto",
+ "hyphenate-lines" : "no-limit | <integer>",
+ "hyphenate-resource" : 1,
+ "hyphens" : "none | manual | auto",
+ "icon" : 1,
+ "image-orientation" : "angle | auto",
+ "image-rendering" : 1,
+ "image-resolution" : 1,
+ "inline-box-align" : "initial | last | <integer>",
+ "left" : "<margin-width> | inherit",
+ "letter-spacing" : "<length> | normal | inherit",
+ "line-height" : "<number> | <length> | <percentage> | normal | inherit",
+ "line-break" : "auto | loose | normal | strict",
+ "line-stacking" : 1,
+ "line-stacking-ruby" : "exclude-ruby | include-ruby",
+ "line-stacking-shift" : "consider-shifts | disregard-shifts",
+ "line-stacking-strategy" : "inline-line-height | block-line-height | max-height | grid-height",
+ "list-style" : 1,
+ "list-style-image" : "<uri> | none | inherit",
+ "list-style-position" : "inside | outside | inherit",
+ "list-style-type" : "disc | circle | square | decimal | decimal-leading-zero | lower-roman | upper-roman | lower-greek | lower-latin | upper-latin | armenian | georgian | lower-alpha | upper-alpha | none | inherit",
+ "margin" : { multi: "<margin-width> | inherit", max: 4 },
+ "margin-bottom" : "<margin-width> | inherit",
+ "margin-left" : "<margin-width> | inherit",
+ "margin-right" : "<margin-width> | inherit",
+ "margin-top" : "<margin-width> | inherit",
+ "mark" : 1,
+ "mark-after" : 1,
+ "mark-before" : 1,
+ "marks" : 1,
+ "marquee-direction" : 1,
+ "marquee-play-count" : 1,
+ "marquee-speed" : 1,
+ "marquee-style" : 1,
+ "max-height" : "<length> | <percentage> | none | inherit",
+ "max-width" : "<length> | <percentage> | none | inherit",
+ "min-height" : "<length> | <percentage> | inherit",
+ "min-width" : "<length> | <percentage> | inherit",
+ "move-to" : 1,
+ "nav-down" : 1,
+ "nav-index" : 1,
+ "nav-left" : 1,
+ "nav-right" : 1,
+ "nav-up" : 1,
+ "opacity" : "<number> | inherit",
+ "orphans" : "<integer> | inherit",
+ "outline" : 1,
+ "outline-color" : "<color> | invert | inherit",
+ "outline-offset" : 1,
+ "outline-style" : "<border-style> | inherit",
+ "outline-width" : "<border-width> | inherit",
+ "overflow" : "visible | hidden | scroll | auto | inherit",
+ "overflow-style" : 1,
+ "overflow-x" : 1,
+ "overflow-y" : 1,
+ "padding" : { multi: "<padding-width> | inherit", max: 4 },
+ "padding-bottom" : "<padding-width> | inherit",
+ "padding-left" : "<padding-width> | inherit",
+ "padding-right" : "<padding-width> | inherit",
+ "padding-top" : "<padding-width> | inherit",
+ "page" : 1,
+ "page-break-after" : "auto | always | avoid | left | right | inherit",
+ "page-break-before" : "auto | always | avoid | left | right | inherit",
+ "page-break-inside" : "auto | avoid | inherit",
+ "page-policy" : 1,
+ "pause" : 1,
+ "pause-after" : 1,
+ "pause-before" : 1,
+ "perspective" : 1,
+ "perspective-origin" : 1,
+ "phonemes" : 1,
+ "pitch" : 1,
+ "pitch-range" : 1,
+ "play-during" : 1,
+ "pointer-events" : "auto | none | visiblePainted | visibleFill | visibleStroke | visible | painted | fill | stroke | all | inherit",
+ "position" : "static | relative | absolute | fixed | inherit",
+ "presentation-level" : 1,
+ "punctuation-trim" : 1,
+ "quotes" : 1,
+ "rendering-intent" : 1,
+ "resize" : 1,
+ "rest" : 1,
+ "rest-after" : 1,
+ "rest-before" : 1,
+ "richness" : 1,
+ "right" : "<margin-width> | inherit",
+ "rotation" : 1,
+ "rotation-point" : 1,
+ "ruby-align" : 1,
+ "ruby-overhang" : 1,
+ "ruby-position" : 1,
+ "ruby-span" : 1,
+ "size" : 1,
+ "speak" : "normal | none | spell-out | inherit",
+ "speak-header" : "once | always | inherit",
+ "speak-numeral" : "digits | continuous | inherit",
+ "speak-punctuation" : "code | none | inherit",
+ "speech-rate" : 1,
+ "src" : 1,
+ "stress" : 1,
+ "string-set" : 1,
+
+ "table-layout" : "auto | fixed | inherit",
+ "tab-size" : "<integer> | <length>",
+ "target" : 1,
+ "target-name" : 1,
+ "target-new" : 1,
+ "target-position" : 1,
+ "text-align" : "left | right | center | justify | inherit" ,
+ "text-align-last" : 1,
+ "text-decoration" : 1,
+ "text-emphasis" : 1,
+ "text-height" : 1,
+ "text-indent" : "<length> | <percentage> | inherit",
+ "text-justify" : "auto | none | inter-word | inter-ideograph | inter-cluster | distribute | kashida",
+ "text-outline" : 1,
+ "text-overflow" : 1,
+ "text-rendering" : "auto | optimizeSpeed | optimizeLegibility | geometricPrecision | inherit",
+ "text-shadow" : 1,
+ "text-transform" : "capitalize | uppercase | lowercase | none | inherit",
+ "text-wrap" : "normal | none | avoid",
+ "top" : "<margin-width> | inherit",
+ "transform" : 1,
+ "transform-origin" : 1,
+ "transform-style" : 1,
+ "transition" : 1,
+ "transition-delay" : 1,
+ "transition-duration" : 1,
+ "transition-property" : 1,
+ "transition-timing-function" : 1,
+ "unicode-bidi" : "normal | embed | bidi-override | inherit",
+ "user-modify" : "read-only | read-write | write-only | inherit",
+ "user-select" : "none | text | toggle | element | elements | all | inherit",
+ "vertical-align" : "auto | use-script | baseline | sub | super | top | text-top | central | middle | bottom | text-bottom | <percentage> | <length>",
+ "visibility" : "visible | hidden | collapse | inherit",
+ "voice-balance" : 1,
+ "voice-duration" : 1,
+ "voice-family" : 1,
+ "voice-pitch" : 1,
+ "voice-pitch-range" : 1,
+ "voice-rate" : 1,
+ "voice-stress" : 1,
+ "voice-volume" : 1,
+ "volume" : 1,
+ "white-space" : "normal | pre | nowrap | pre-wrap | pre-line | inherit | -pre-wrap | -o-pre-wrap | -moz-pre-wrap | -hp-pre-wrap", //http://perishablepress.com/wrapping-content/
+ "white-space-collapse" : 1,
+ "widows" : "<integer> | inherit",
+ "width" : "<length> | <percentage> | auto | inherit" ,
+ "word-break" : "normal | keep-all | break-all",
+ "word-spacing" : "<length> | normal | inherit",
+ "word-wrap" : 1,
+ "z-index" : "<integer> | auto | inherit",
+ "zoom" : "<number> | <percentage> | normal"
+};
+function PropertyName(text, hack, line, col){
+
+ SyntaxUnit.call(this, text, line, col, Parser.PROPERTY_NAME_TYPE);
+ this.hack = hack;
+
+}
+
+PropertyName.prototype = new SyntaxUnit();
+PropertyName.prototype.constructor = PropertyName;
+PropertyName.prototype.toString = function(){
+ return (this.hack ? this.hack : "") + this.text;
+};
+function PropertyValue(parts, line, col){
+
+ SyntaxUnit.call(this, parts.join(" "), line, col, Parser.PROPERTY_VALUE_TYPE);
+ this.parts = parts;
+
+}
+
+PropertyValue.prototype = new SyntaxUnit();
+PropertyValue.prototype.constructor = PropertyValue;
+function PropertyValueIterator(value){
+ this._i = 0;
+ this._parts = value.parts;
+ this._marks = [];
+ this.value = value;
+
+}
+PropertyValueIterator.prototype.count = function(){
+ return this._parts.length;
+};
+PropertyValueIterator.prototype.isFirst = function(){
+ return this._i === 0;
+};
+PropertyValueIterator.prototype.hasNext = function(){
+ return (this._i < this._parts.length);
+};
+PropertyValueIterator.prototype.mark = function(){
+ this._marks.push(this._i);
+};
+PropertyValueIterator.prototype.peek = function(count){
+ return this.hasNext() ? this._parts[this._i + (count || 0)] : null;
+};
+PropertyValueIterator.prototype.next = function(){
+ return this.hasNext() ? this._parts[this._i++] : null;
+};
+PropertyValueIterator.prototype.previous = function(){
+ return this._i > 0 ? this._parts[--this._i] : null;
+};
+PropertyValueIterator.prototype.restore = function(){
+ if (this._marks.length){
+ this._i = this._marks.pop();
+ }
+};
+function PropertyValuePart(text, line, col){
+
+ SyntaxUnit.call(this, text, line, col, Parser.PROPERTY_VALUE_PART_TYPE);
+ this.type = "unknown";
+
+ var temp;
+ if (/^([+\-]?[\d\.]+)([a-z]+)$/i.test(text)){ //dimension
+ this.type = "dimension";
+ this.value = +RegExp.$1;
+ this.units = RegExp.$2;
+ switch(this.units.toLowerCase()){
+
+ case "em":
+ case "rem":
+ case "ex":
+ case "px":
+ case "cm":
+ case "mm":
+ case "in":
+ case "pt":
+ case "pc":
+ case "ch":
+ case "vh":
+ case "vw":
+ case "vm":
+ this.type = "length";
+ break;
+
+ case "deg":
+ case "rad":
+ case "grad":
+ this.type = "angle";
+ break;
+
+ case "ms":
+ case "s":
+ this.type = "time";
+ break;
+
+ case "hz":
+ case "khz":
+ this.type = "frequency";
+ break;
+
+ case "dpi":
+ case "dpcm":
+ this.type = "resolution";
+ break;
+
+ }
+
+ } else if (/^([+\-]?[\d\.]+)%$/i.test(text)){ //percentage
+ this.type = "percentage";
+ this.value = +RegExp.$1;
+ } else if (/^([+\-]?[\d\.]+)%$/i.test(text)){ //percentage
+ this.type = "percentage";
+ this.value = +RegExp.$1;
+ } else if (/^([+\-]?\d+)$/i.test(text)){ //integer
+ this.type = "integer";
+ this.value = +RegExp.$1;
+ } else if (/^([+\-]?[\d\.]+)$/i.test(text)){ //number
+ this.type = "number";
+ this.value = +RegExp.$1;
+
+ } else if (/^#([a-f0-9]{3,6})/i.test(text)){ //hexcolor
+ this.type = "color";
+ temp = RegExp.$1;
+ if (temp.length == 3){
+ this.red = parseInt(temp.charAt(0)+temp.charAt(0),16);
+ this.green = parseInt(temp.charAt(1)+temp.charAt(1),16);
+ this.blue = parseInt(temp.charAt(2)+temp.charAt(2),16);
+ } else {
+ this.red = parseInt(temp.substring(0,2),16);
+ this.green = parseInt(temp.substring(2,4),16);
+ this.blue = parseInt(temp.substring(4,6),16);
+ }
+ } else if (/^rgb\(\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)\s*\)/i.test(text)){ //rgb() color with absolute numbers
+ this.type = "color";
+ this.red = +RegExp.$1;
+ this.green = +RegExp.$2;
+ this.blue = +RegExp.$3;
+ } else if (/^rgb\(\s*(\d+)%\s*,\s*(\d+)%\s*,\s*(\d+)%\s*\)/i.test(text)){ //rgb() color with percentages
+ this.type = "color";
+ this.red = +RegExp.$1 * 255 / 100;
+ this.green = +RegExp.$2 * 255 / 100;
+ this.blue = +RegExp.$3 * 255 / 100;
+ } else if (/^rgba\(\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)\s*,\s*([\d\.]+)\s*\)/i.test(text)){ //rgba() color with absolute numbers
+ this.type = "color";
+ this.red = +RegExp.$1;
+ this.green = +RegExp.$2;
+ this.blue = +RegExp.$3;
+ this.alpha = +RegExp.$4;
+ } else if (/^rgba\(\s*(\d+)%\s*,\s*(\d+)%\s*,\s*(\d+)%\s*,\s*([\d\.]+)\s*\)/i.test(text)){ //rgba() color with percentages
+ this.type = "color";
+ this.red = +RegExp.$1 * 255 / 100;
+ this.green = +RegExp.$2 * 255 / 100;
+ this.blue = +RegExp.$3 * 255 / 100;
+ this.alpha = +RegExp.$4;
+ } else if (/^hsl\(\s*(\d+)\s*,\s*(\d+)%\s*,\s*(\d+)%\s*\)/i.test(text)){ //hsl()
+ this.type = "color";
+ this.hue = +RegExp.$1;
+ this.saturation = +RegExp.$2 / 100;
+ this.lightness = +RegExp.$3 / 100;
+ } else if (/^hsla\(\s*(\d+)\s*,\s*(\d+)%\s*,\s*(\d+)%\s*,\s*([\d\.]+)\s*\)/i.test(text)){ //hsla() color with percentages
+ this.type = "color";
+ this.hue = +RegExp.$1;
+ this.saturation = +RegExp.$2 / 100;
+ this.lightness = +RegExp.$3 / 100;
+ this.alpha = +RegExp.$4;
+ } else if (/^url\(["']?([^\)"']+)["']?\)/i.test(text)){ //URI
+ this.type = "uri";
+ this.uri = RegExp.$1;
+ } else if (/^([^\(]+)\(/i.test(text)){
+ this.type = "function";
+ this.name = RegExp.$1;
+ this.value = text;
+ } else if (/^["'][^"']*["']/.test(text)){ //string
+ this.type = "string";
+ this.value = eval(text);
+ } else if (Colors[text.toLowerCase()]){ //named color
+ this.type = "color";
+ temp = Colors[text.toLowerCase()].substring(1);
+ this.red = parseInt(temp.substring(0,2),16);
+ this.green = parseInt(temp.substring(2,4),16);
+ this.blue = parseInt(temp.substring(4,6),16);
+ } else if (/^[\,\/]$/.test(text)){
+ this.type = "operator";
+ this.value = text;
+ } else if (/^[a-z\-\u0080-\uFFFF][a-z0-9\-\u0080-\uFFFF]*$/i.test(text)){
+ this.type = "identifier";
+ this.value = text;
+ }
+
+}
+
+PropertyValuePart.prototype = new SyntaxUnit();
+PropertyValuePart.prototype.constructor = PropertyValuePart;
+PropertyValuePart.fromToken = function(token){
+ return new PropertyValuePart(token.value, token.startLine, token.startCol);
+};
+var Pseudos = {
+ ":first-letter": 1,
+ ":first-line": 1,
+ ":before": 1,
+ ":after": 1
+};
+
+Pseudos.ELEMENT = 1;
+Pseudos.CLASS = 2;
+
+Pseudos.isElement = function(pseudo){
+ return pseudo.indexOf("::") === 0 || Pseudos[pseudo.toLowerCase()] == Pseudos.ELEMENT;
+};
+function Selector(parts, line, col){
+
+ SyntaxUnit.call(this, parts.join(" "), line, col, Parser.SELECTOR_TYPE);
+ this.parts = parts;
+ this.specificity = Specificity.calculate(this);
+
+}
+
+Selector.prototype = new SyntaxUnit();
+Selector.prototype.constructor = Selector;
+function SelectorPart(elementName, modifiers, text, line, col){
+
+ SyntaxUnit.call(this, text, line, col, Parser.SELECTOR_PART_TYPE);
+ this.elementName = elementName;
+ this.modifiers = modifiers;
+
+}
+
+SelectorPart.prototype = new SyntaxUnit();
+SelectorPart.prototype.constructor = SelectorPart;
+function SelectorSubPart(text, type, line, col){
+
+ SyntaxUnit.call(this, text, line, col, Parser.SELECTOR_SUB_PART_TYPE);
+ this.type = type;
+ this.args = [];
+
+}
+
+SelectorSubPart.prototype = new SyntaxUnit();
+SelectorSubPart.prototype.constructor = SelectorSubPart;
+function Specificity(a, b, c, d){
+ this.a = a;
+ this.b = b;
+ this.c = c;
+ this.d = d;
+}
+
+Specificity.prototype = {
+ constructor: Specificity,
+ compare: function(other){
+ var comps = ["a", "b", "c", "d"],
+ i, len;
+
+ for (i=0, len=comps.length; i < len; i++){
+ if (this[comps[i]] < other[comps[i]]){
+ return -1;
+ } else if (this[comps[i]] > other[comps[i]]){
+ return 1;
+ }
+ }
+
+ return 0;
+ },
+ valueOf: function(){
+ return (this.a * 1000) + (this.b * 100) + (this.c * 10) + this.d;
+ },
+ toString: function(){
+ return this.a + "," + this.b + "," + this.c + "," + this.d;
+ }
+
+};
+Specificity.calculate = function(selector){
+
+ var i, len,
+ part,
+ b=0, c=0, d=0;
+
+ function updateValues(part){
+
+ var i, j, len, num,
+ elementName = part.elementName ? part.elementName.text : "",
+ modifier;
+
+ if (elementName && elementName.charAt(elementName.length-1) != "*") {
+ d++;
+ }
+
+ for (i=0, len=part.modifiers.length; i < len; i++){
+ modifier = part.modifiers[i];
+ switch(modifier.type){
+ case "class":
+ case "attribute":
+ c++;
+ break;
+
+ case "id":
+ b++;
+ break;
+
+ case "pseudo":
+ if (Pseudos.isElement(modifier.text)){
+ d++;
+ } else {
+ c++;
+ }
+ break;
+
+ case "not":
+ for (j=0, num=modifier.args.length; j < num; j++){
+ updateValues(modifier.args[j]);
+ }
+ }
+ }
+ }
+
+ for (i=0, len=selector.parts.length; i < len; i++){
+ part = selector.parts[i];
+
+ if (part instanceof SelectorPart){
+ updateValues(part);
+ }
+ }
+
+ return new Specificity(0, b, c, d);
+};
+
+var h = /^[0-9a-fA-F]$/,
+ nonascii = /^[\u0080-\uFFFF]$/,
+ nl = /\n|\r\n|\r|\f/;
+
+
+function isHexDigit(c){
+ return c !== null && h.test(c);
+}
+
+function isDigit(c){
+ return c !== null && /\d/.test(c);
+}
+
+function isWhitespace(c){
+ return c !== null && /\s/.test(c);
+}
+
+function isNewLine(c){
+ return c !== null && nl.test(c);
+}
+
+function isNameStart(c){
+ return c !== null && (/[a-z_\u0080-\uFFFF\\]/i.test(c));
+}
+
+function isNameChar(c){
+ return c !== null && (isNameStart(c) || /[0-9\-\\]/.test(c));
+}
+
+function isIdentStart(c){
+ return c !== null && (isNameStart(c) || /\-\\/.test(c));
+}
+
+function mix(receiver, supplier){
+ for (var prop in supplier){
+ if (supplier.hasOwnProperty(prop)){
+ receiver[prop] = supplier[prop];
+ }
+ }
+ return receiver;
+}
+function TokenStream(input){
+ TokenStreamBase.call(this, input, Tokens);
+}
+
+TokenStream.prototype = mix(new TokenStreamBase(), {
+ _getToken: function(channel){
+
+ var c,
+ reader = this._reader,
+ token = null,
+ startLine = reader.getLine(),
+ startCol = reader.getCol();
+
+ c = reader.read();
+
+
+ while(c){
+ switch(c){
+ case "/":
+
+ if(reader.peek() == "*"){
+ token = this.commentToken(c, startLine, startCol);
+ } else {
+ token = this.charToken(c, startLine, startCol);
+ }
+ break;
+ case "|":
+ case "~":
+ case "^":
+ case "$":
+ case "*":
+ if(reader.peek() == "="){
+ token = this.comparisonToken(c, startLine, startCol);
+ } else {
+ token = this.charToken(c, startLine, startCol);
+ }
+ break;
+ case "\"":
+ case "'":
+ token = this.stringToken(c, startLine, startCol);
+ break;
+ case "#":
+ if (isNameChar(reader.peek())){
+ token = this.hashToken(c, startLine, startCol);
+ } else {
+ token = this.charToken(c, startLine, startCol);
+ }
+ break;
+ case ".":
+ if (isDigit(reader.peek())){
+ token = this.numberToken(c, startLine, startCol);
+ } else {
+ token = this.charToken(c, startLine, startCol);
+ }
+ break;
+ case "-":
+ if (reader.peek() == "-"){ //could be closing HTML-style comment
+ token = this.htmlCommentEndToken(c, startLine, startCol);
+ } else if (isNameStart(reader.peek())){
+ token = this.identOrFunctionToken(c, startLine, startCol);
+ } else {
+ token = this.charToken(c, startLine, startCol);
+ }
+ break;
+ case "!":
+ token = this.importantToken(c, startLine, startCol);
+ break;
+ case "@":
+ token = this.atRuleToken(c, startLine, startCol);
+ break;
+ case ":":
+ token = this.notToken(c, startLine, startCol);
+ break;
+ case "<":
+ token = this.htmlCommentStartToken(c, startLine, startCol);
+ break;
+ case "U":
+ case "u":
+ if (reader.peek() == "+"){
+ token = this.unicodeRangeToken(c, startLine, startCol);
+ break;
+ }
+ default:
+ if (isDigit(c)){
+ token = this.numberToken(c, startLine, startCol);
+ } else
+ if (isWhitespace(c)){
+ token = this.whitespaceToken(c, startLine, startCol);
+ } else
+ if (isIdentStart(c)){
+ token = this.identOrFunctionToken(c, startLine, startCol);
+ } else
+ {
+ token = this.charToken(c, startLine, startCol);
+ }
+
+
+
+
+
+
+ }
+ break;
+ }
+
+ if (!token && c === null){
+ token = this.createToken(Tokens.EOF,null,startLine,startCol);
+ }
+
+ return token;
+ },
+ createToken: function(tt, value, startLine, startCol, options){
+ var reader = this._reader;
+ options = options || {};
+
+ return {
+ value: value,
+ type: tt,
+ channel: options.channel,
+ hide: options.hide || false,
+ startLine: startLine,
+ startCol: startCol,
+ endLine: reader.getLine(),
+ endCol: reader.getCol()
+ };
+ },
+ atRuleToken: function(first, startLine, startCol){
+ var rule = first,
+ reader = this._reader,
+ tt = Tokens.CHAR,
+ valid = false,
+ ident,
+ c;
+ reader.mark();
+ ident = this.readName();
+ rule = first + ident;
+ tt = Tokens.type(rule.toLowerCase());
+ if (tt == Tokens.CHAR || tt == Tokens.UNKNOWN){
+ if (rule.length > 1){
+ tt = Tokens.UNKNOWN_SYM;
+ } else {
+ tt = Tokens.CHAR;
+ rule = first;
+ reader.reset();
+ }
+ }
+
+ return this.createToken(tt, rule, startLine, startCol);
+ },
+ charToken: function(c, startLine, startCol){
+ var tt = Tokens.type(c);
+
+ if (tt == -1){
+ tt = Tokens.CHAR;
+ }
+
+ return this.createToken(tt, c, startLine, startCol);
+ },
+ commentToken: function(first, startLine, startCol){
+ var reader = this._reader,
+ comment = this.readComment(first);
+
+ return this.createToken(Tokens.COMMENT, comment, startLine, startCol);
+ },
+ comparisonToken: function(c, startLine, startCol){
+ var reader = this._reader,
+ comparison = c + reader.read(),
+ tt = Tokens.type(comparison) || Tokens.CHAR;
+
+ return this.createToken(tt, comparison, startLine, startCol);
+ },
+ hashToken: function(first, startLine, startCol){
+ var reader = this._reader,
+ name = this.readName(first);
+
+ return this.createToken(Tokens.HASH, name, startLine, startCol);
+ },
+ htmlCommentStartToken: function(first, startLine, startCol){
+ var reader = this._reader,
+ text = first;
+
+ reader.mark();
+ text += reader.readCount(3);
+
+ if (text == "<!--"){
+ return this.createToken(Tokens.CDO, text, startLine, startCol);
+ } else {
+ reader.reset();
+ return this.charToken(first, startLine, startCol);
+ }
+ },
+ htmlCommentEndToken: function(first, startLine, startCol){
+ var reader = this._reader,
+ text = first;
+
+ reader.mark();
+ text += reader.readCount(2);
+
+ if (text == "-->"){
+ return this.createToken(Tokens.CDC, text, startLine, startCol);
+ } else {
+ reader.reset();
+ return this.charToken(first, startLine, startCol);
+ }
+ },
+ identOrFunctionToken: function(first, startLine, startCol){
+ var reader = this._reader,
+ ident = this.readName(first),
+ tt = Tokens.IDENT;
+ if (reader.peek() == "("){
+ ident += reader.read();
+ if (ident.toLowerCase() == "url("){
+ tt = Tokens.URI;
+ ident = this.readURI(ident);
+ if (ident.toLowerCase() == "url("){
+ tt = Tokens.FUNCTION;
+ }
+ } else {
+ tt = Tokens.FUNCTION;
+ }
+ } else if (reader.peek() == ":"){ //might be an IE function
+ if (ident.toLowerCase() == "progid"){
+ ident += reader.readTo("(");
+ tt = Tokens.IE_FUNCTION;
+ }
+ }
+
+ return this.createToken(tt, ident, startLine, startCol);
+ },
+ importantToken: function(first, startLine, startCol){
+ var reader = this._reader,
+ important = first,
+ tt = Tokens.CHAR,
+ temp,
+ c;
+
+ reader.mark();
+ c = reader.read();
+
+ while(c){
+ if (c == "/"){
+ if (reader.peek() != "*"){
+ break;
+ } else {
+ temp = this.readComment(c);
+ if (temp === ""){ //broken!
+ break;
+ }
+ }
+ } else if (isWhitespace(c)){
+ important += c + this.readWhitespace();
+ } else if (/i/i.test(c)){
+ temp = reader.readCount(8);
+ if (/mportant/i.test(temp)){
+ important += c + temp;
+ tt = Tokens.IMPORTANT_SYM;
+
+ }
+ break; //we're done
+ } else {
+ break;
+ }
+
+ c = reader.read();
+ }
+
+ if (tt == Tokens.CHAR){
+ reader.reset();
+ return this.charToken(first, startLine, startCol);
+ } else {
+ return this.createToken(tt, important, startLine, startCol);
+ }
+
+
+ },
+ notToken: function(first, startLine, startCol){
+ var reader = this._reader,
+ text = first;
+
+ reader.mark();
+ text += reader.readCount(4);
+
+ if (text.toLowerCase() == ":not("){
+ return this.createToken(Tokens.NOT, text, startLine, startCol);
+ } else {
+ reader.reset();
+ return this.charToken(first, startLine, startCol);
+ }
+ },
+ numberToken: function(first, startLine, startCol){
+ var reader = this._reader,
+ value = this.readNumber(first),
+ ident,
+ tt = Tokens.NUMBER,
+ c = reader.peek();
+
+ if (isIdentStart(c)){
+ ident = this.readName(reader.read());
+ value += ident;
+
+ if (/^em$|^ex$|^px$|^gd$|^rem$|^vw$|^vh$|^vm$|^ch$|^cm$|^mm$|^in$|^pt$|^pc$/i.test(ident)){
+ tt = Tokens.LENGTH;
+ } else if (/^deg|^rad$|^grad$/i.test(ident)){
+ tt = Tokens.ANGLE;
+ } else if (/^ms$|^s$/i.test(ident)){
+ tt = Tokens.TIME;
+ } else if (/^hz$|^khz$/i.test(ident)){
+ tt = Tokens.FREQ;
+ } else if (/^dpi$|^dpcm$/i.test(ident)){
+ tt = Tokens.RESOLUTION;
+ } else {
+ tt = Tokens.DIMENSION;
+ }
+
+ } else if (c == "%"){
+ value += reader.read();
+ tt = Tokens.PERCENTAGE;
+ }
+
+ return this.createToken(tt, value, startLine, startCol);
+ },
+ stringToken: function(first, startLine, startCol){
+ var delim = first,
+ string = first,
+ reader = this._reader,
+ prev = first,
+ tt = Tokens.STRING,
+ c = reader.read();
+
+ while(c){
+ string += c;
+ if (c == delim && prev != "\\"){
+ break;
+ }
+ if (isNewLine(reader.peek()) && c != "\\"){
+ tt = Tokens.INVALID;
+ break;
+ }
+ prev = c;
+ c = reader.read();
+ }
+ if (c === null){
+ tt = Tokens.INVALID;
+ }
+
+ return this.createToken(tt, string, startLine, startCol);
+ },
+
+ unicodeRangeToken: function(first, startLine, startCol){
+ var reader = this._reader,
+ value = first,
+ temp,
+ tt = Tokens.CHAR;
+ if (reader.peek() == "+"){
+ reader.mark();
+ value += reader.read();
+ value += this.readUnicodeRangePart(true);
+ if (value.length == 2){
+ reader.reset();
+ } else {
+
+ tt = Tokens.UNICODE_RANGE;
+ if (value.indexOf("?") == -1){
+
+ if (reader.peek() == "-"){
+ reader.mark();
+ temp = reader.read();
+ temp += this.readUnicodeRangePart(false);
+ if (temp.length == 1){
+ reader.reset();
+ } else {
+ value += temp;
+ }
+ }
+
+ }
+ }
+ }
+
+ return this.createToken(tt, value, startLine, startCol);
+ },
+ whitespaceToken: function(first, startLine, startCol){
+ var reader = this._reader,
+ value = first + this.readWhitespace();
+ return this.createToken(Tokens.S, value, startLine, startCol);
+ },
+
+ readUnicodeRangePart: function(allowQuestionMark){
+ var reader = this._reader,
+ part = "",
+ c = reader.peek();
+ while(isHexDigit(c) && part.length < 6){
+ reader.read();
+ part += c;
+ c = reader.peek();
+ }
+ if (allowQuestionMark){
+ while(c == "?" && part.length < 6){
+ reader.read();
+ part += c;
+ c = reader.peek();
+ }
+ }
+
+ return part;
+ },
+
+ readWhitespace: function(){
+ var reader = this._reader,
+ whitespace = "",
+ c = reader.peek();
+
+ while(isWhitespace(c)){
+ reader.read();
+ whitespace += c;
+ c = reader.peek();
+ }
+
+ return whitespace;
+ },
+ readNumber: function(first){
+ var reader = this._reader,
+ number = first,
+ hasDot = (first == "."),
+ c = reader.peek();
+
+
+ while(c){
+ if (isDigit(c)){
+ number += reader.read();
+ } else if (c == "."){
+ if (hasDot){
+ break;
+ } else {
+ hasDot = true;
+ number += reader.read();
+ }
+ } else {
+ break;
+ }
+
+ c = reader.peek();
+ }
+
+ return number;
+ },
+ readString: function(){
+ var reader = this._reader,
+ delim = reader.read(),
+ string = delim,
+ prev = delim,
+ c = reader.peek();
+
+ while(c){
+ c = reader.read();
+ string += c;
+ if (c == delim && prev != "\\"){
+ break;
+ }
+ if (isNewLine(reader.peek()) && c != "\\"){
+ string = "";
+ break;
+ }
+ prev = c;
+ c = reader.peek();
+ }
+ if (c === null){
+ string = "";
+ }
+
+ return string;
+ },
+ readURI: function(first){
+ var reader = this._reader,
+ uri = first,
+ inner = "",
+ c = reader.peek();
+
+ reader.mark();
+ while(c && isWhitespace(c)){
+ reader.read();
+ c = reader.peek();
+ }
+ if (c == "'" || c == "\""){
+ inner = this.readString();
+ } else {
+ inner = this.readURL();
+ }
+
+ c = reader.peek();
+ while(c && isWhitespace(c)){
+ reader.read();
+ c = reader.peek();
+ }
+ if (inner === "" || c != ")"){
+ uri = first;
+ reader.reset();
+ } else {
+ uri += inner + reader.read();
+ }
+
+ return uri;
+ },
+ readURL: function(){
+ var reader = this._reader,
+ url = "",
+ c = reader.peek();
+ while (/^[!#$%&\\*-~]$/.test(c)){
+ url += reader.read();
+ c = reader.peek();
+ }
+
+ return url;
+
+ },
+ readName: function(first){
+ var reader = this._reader,
+ ident = first || "",
+ c = reader.peek();
+
+ while(true){
+ if (c == "\\"){
+ ident += this.readEscape(reader.read());
+ c = reader.peek();
+ } else if(c && isNameChar(c)){
+ ident += reader.read();
+ c = reader.peek();
+ } else {
+ break;
+ }
+ }
+
+ return ident;
+ },
+
+ readEscape: function(first){
+ var reader = this._reader,
+ cssEscape = first || "",
+ i = 0,
+ c = reader.peek();
+
+ if (isHexDigit(c)){
+ do {
+ cssEscape += reader.read();
+ c = reader.peek();
+ } while(c && isHexDigit(c) && ++i < 6);
+ }
+
+ if (cssEscape.length == 3 && /\s/.test(c) ||
+ cssEscape.length == 7 || cssEscape.length == 1){
+ reader.read();
+ } else {
+ c = "";
+ }
+
+ return cssEscape + c;
+ },
+
+ readComment: function(first){
+ var reader = this._reader,
+ comment = first || "",
+ c = reader.read();
+
+ if (c == "*"){
+ while(c){
+ comment += c;
+ if (comment.length > 2 && c == "*" && reader.peek() == "/"){
+ comment += reader.read();
+ break;
+ }
+
+ c = reader.read();
+ }
+
+ return comment;
+ } else {
+ return "";
+ }
+
+ }
+});
+
+
+var Tokens = [
+ { name: "CDO"},
+ { name: "CDC"},
+ { name: "S", whitespace: true/*, channel: "ws"*/},
+ { name: "COMMENT", comment: true, hide: true, channel: "comment" },
+ { name: "INCLUDES", text: "~="},
+ { name: "DASHMATCH", text: "|="},
+ { name: "PREFIXMATCH", text: "^="},
+ { name: "SUFFIXMATCH", text: "$="},
+ { name: "SUBSTRINGMATCH", text: "*="},
+ { name: "STRING"},
+ { name: "IDENT"},
+ { name: "HASH"},
+ { name: "IMPORT_SYM", text: "@import"},
+ { name: "PAGE_SYM", text: "@page"},
+ { name: "MEDIA_SYM", text: "@media"},
+ { name: "FONT_FACE_SYM", text: "@font-face"},
+ { name: "CHARSET_SYM", text: "@charset"},
+ { name: "NAMESPACE_SYM", text: "@namespace"},
+ { name: "VIEWPORT_SYM", text: "@viewport"},
+ { name: "UNKNOWN_SYM" },
+ { name: "KEYFRAMES_SYM", text: [ "@keyframes", "@-webkit-keyframes", "@-moz-keyframes", "@-o-keyframes" ] },
+ { name: "IMPORTANT_SYM"},
+ { name: "LENGTH"},
+ { name: "ANGLE"},
+ { name: "TIME"},
+ { name: "FREQ"},
+ { name: "DIMENSION"},
+ { name: "PERCENTAGE"},
+ { name: "NUMBER"},
+ { name: "URI"},
+ { name: "FUNCTION"},
+ { name: "UNICODE_RANGE"},
+ { name: "INVALID"},
+ { name: "PLUS", text: "+" },
+ { name: "GREATER", text: ">"},
+ { name: "COMMA", text: ","},
+ { name: "TILDE", text: "~"},
+ { name: "NOT"},
+ { name: "TOPLEFTCORNER_SYM", text: "@top-left-corner"},
+ { name: "TOPLEFT_SYM", text: "@top-left"},
+ { name: "TOPCENTER_SYM", text: "@top-center"},
+ { name: "TOPRIGHT_SYM", text: "@top-right"},
+ { name: "TOPRIGHTCORNER_SYM", text: "@top-right-corner"},
+ { name: "BOTTOMLEFTCORNER_SYM", text: "@bottom-left-corner"},
+ { name: "BOTTOMLEFT_SYM", text: "@bottom-left"},
+ { name: "BOTTOMCENTER_SYM", text: "@bottom-center"},
+ { name: "BOTTOMRIGHT_SYM", text: "@bottom-right"},
+ { name: "BOTTOMRIGHTCORNER_SYM", text: "@bottom-right-corner"},
+ { name: "LEFTTOP_SYM", text: "@left-top"},
+ { name: "LEFTMIDDLE_SYM", text: "@left-middle"},
+ { name: "LEFTBOTTOM_SYM", text: "@left-bottom"},
+ { name: "RIGHTTOP_SYM", text: "@right-top"},
+ { name: "RIGHTMIDDLE_SYM", text: "@right-middle"},
+ { name: "RIGHTBOTTOM_SYM", text: "@right-bottom"},
+ { name: "RESOLUTION", state: "media"},
+ { name: "IE_FUNCTION" },
+ { name: "CHAR" },
+ {
+ name: "PIPE",
+ text: "|"
+ },
+ {
+ name: "SLASH",
+ text: "/"
+ },
+ {
+ name: "MINUS",
+ text: "-"
+ },
+ {
+ name: "STAR",
+ text: "*"
+ },
+
+ {
+ name: "LBRACE",
+ text: "{"
+ },
+ {
+ name: "RBRACE",
+ text: "}"
+ },
+ {
+ name: "LBRACKET",
+ text: "["
+ },
+ {
+ name: "RBRACKET",
+ text: "]"
+ },
+ {
+ name: "EQUALS",
+ text: "="
+ },
+ {
+ name: "COLON",
+ text: ":"
+ },
+ {
+ name: "SEMICOLON",
+ text: ";"
+ },
+
+ {
+ name: "LPAREN",
+ text: "("
+ },
+ {
+ name: "RPAREN",
+ text: ")"
+ },
+ {
+ name: "DOT",
+ text: "."
+ }
+];
+
+(function(){
+
+ var nameMap = [],
+ typeMap = {};
+
+ Tokens.UNKNOWN = -1;
+ Tokens.unshift({name:"EOF"});
+ for (var i=0, len = Tokens.length; i < len; i++){
+ nameMap.push(Tokens[i].name);
+ Tokens[Tokens[i].name] = i;
+ if (Tokens[i].text){
+ if (Tokens[i].text instanceof Array){
+ for (var j=0; j < Tokens[i].text.length; j++){
+ typeMap[Tokens[i].text[j]] = i;
+ }
+ } else {
+ typeMap[Tokens[i].text] = i;
+ }
+ }
+ }
+
+ Tokens.name = function(tt){
+ return nameMap[tt];
+ };
+
+ Tokens.type = function(c){
+ return typeMap[c] || -1;
+ };
+
+})();
+var Validation = {
+
+ validate: function(property, value){
+ var name = property.toString().toLowerCase(),
+ parts = value.parts,
+ expression = new PropertyValueIterator(value),
+ spec = Properties[name],
+ part,
+ valid,
+ j, count,
+ msg,
+ types,
+ last,
+ literals,
+ max, multi, group;
+
+ if (!spec) {
+ if (name.indexOf("-") !== 0){ //vendor prefixed are ok
+ throw new ValidationError("Unknown property '" + property + "'.", property.line, property.col);
+ }
+ } else if (typeof spec != "number"){
+ if (typeof spec == "string"){
+ if (spec.indexOf("||") > -1) {
+ this.groupProperty(spec, expression);
+ } else {
+ this.singleProperty(spec, expression, 1);
+ }
+
+ } else if (spec.multi) {
+ this.multiProperty(spec.multi, expression, spec.comma, spec.max || Infinity);
+ } else if (typeof spec == "function") {
+ spec(expression);
+ }
+
+ }
+
+ },
+
+ singleProperty: function(types, expression, max, partial) {
+
+ var result = false,
+ value = expression.value,
+ count = 0,
+ part;
+
+ while (expression.hasNext() && count < max) {
+ result = ValidationTypes.isAny(expression, types);
+ if (!result) {
+ break;
+ }
+ count++;
+ }
+
+ if (!result) {
+ if (expression.hasNext() && !expression.isFirst()) {
+ part = expression.peek();
+ throw new ValidationError("Expected end of value but found '" + part + "'.", part.line, part.col);
+ } else {
+ throw new ValidationError("Expected (" + types + ") but found '" + value + "'.", value.line, value.col);
+ }
+ } else if (expression.hasNext()) {
+ part = expression.next();
+ throw new ValidationError("Expected end of value but found '" + part + "'.", part.line, part.col);
+ }
+
+ },
+
+ multiProperty: function (types, expression, comma, max) {
+
+ var result = false,
+ value = expression.value,
+ count = 0,
+ sep = false,
+ part;
+
+ while(expression.hasNext() && !result && count < max) {
+ if (ValidationTypes.isAny(expression, types)) {
+ count++;
+ if (!expression.hasNext()) {
+ result = true;
+
+ } else if (comma) {
+ if (expression.peek() == ",") {
+ part = expression.next();
+ } else {
+ break;
+ }
+ }
+ } else {
+ break;
+
+ }
+ }
+
+ if (!result) {
+ if (expression.hasNext() && !expression.isFirst()) {
+ part = expression.peek();
+ throw new ValidationError("Expected end of value but found '" + part + "'.", part.line, part.col);
+ } else {
+ part = expression.previous();
+ if (comma && part == ",") {
+ throw new ValidationError("Expected end of value but found '" + part + "'.", part.line, part.col);
+ } else {
+ throw new ValidationError("Expected (" + types + ") but found '" + value + "'.", value.line, value.col);
+ }
+ }
+
+ } else if (expression.hasNext()) {
+ part = expression.next();
+ throw new ValidationError("Expected end of value but found '" + part + "'.", part.line, part.col);
+ }
+
+ },
+
+ groupProperty: function (types, expression, comma) {
+
+ var result = false,
+ value = expression.value,
+ typeCount = types.split("||").length,
+ groups = { count: 0 },
+ partial = false,
+ name,
+ part;
+
+ while(expression.hasNext() && !result) {
+ name = ValidationTypes.isAnyOfGroup(expression, types);
+ if (name) {
+ if (groups[name]) {
+ break;
+ } else {
+ groups[name] = 1;
+ groups.count++;
+ partial = true;
+
+ if (groups.count == typeCount || !expression.hasNext()) {
+ result = true;
+ }
+ }
+ } else {
+ break;
+ }
+ }
+
+ if (!result) {
+ if (partial && expression.hasNext()) {
+ part = expression.peek();
+ throw new ValidationError("Expected end of value but found '" + part + "'.", part.line, part.col);
+ } else {
+ throw new ValidationError("Expected (" + types + ") but found '" + value + "'.", value.line, value.col);
+ }
+ } else if (expression.hasNext()) {
+ part = expression.next();
+ throw new ValidationError("Expected end of value but found '" + part + "'.", part.line, part.col);
+ }
+ }
+
+
+
+};
+function ValidationError(message, line, col){
+ this.col = col;
+ this.line = line;
+ this.message = message;
+
+}
+ValidationError.prototype = new Error();
+var ValidationTypes = {
+
+ isLiteral: function (part, literals) {
+ var text = part.text.toString().toLowerCase(),
+ args = literals.split(" | "),
+ i, len, found = false;
+
+ for (i=0,len=args.length; i < len && !found; i++){
+ if (text == args[i].toLowerCase()){
+ found = true;
+ }
+ }
+
+ return found;
+ },
+
+ isSimple: function(type) {
+ return !!this.simple[type];
+ },
+
+ isComplex: function(type) {
+ return !!this.complex[type];
+ },
+ isAny: function (expression, types) {
+ var args = types.split(" | "),
+ i, len, found = false;
+
+ for (i=0,len=args.length; i < len && !found && expression.hasNext(); i++){
+ found = this.isType(expression, args[i]);
+ }
+
+ return found;
+ },
+ isAnyOfGroup: function(expression, types) {
+ var args = types.split(" || "),
+ i, len, found = false;
+
+ for (i=0,len=args.length; i < len && !found; i++){
+ found = this.isType(expression, args[i]);
+ }
+
+ return found ? args[i-1] : false;
+ },
+ isType: function (expression, type) {
+ var part = expression.peek(),
+ result = false;
+
+ if (type.charAt(0) != "<") {
+ result = this.isLiteral(part, type);
+ if (result) {
+ expression.next();
+ }
+ } else if (this.simple[type]) {
+ result = this.simple[type](part);
+ if (result) {
+ expression.next();
+ }
+ } else {
+ result = this.complex[type](expression);
+ }
+
+ return result;
+ },
+
+
+
+ simple: {
+
+ "<absolute-size>": function(part){
+ return ValidationTypes.isLiteral(part, "xx-small | x-small | small | medium | large | x-large | xx-large");
+ },
+
+ "<attachment>": function(part){
+ return ValidationTypes.isLiteral(part, "scroll | fixed | local");
+ },
+
+ "<attr>": function(part){
+ return part.type == "function" && part.name == "attr";
+ },
+
+ "<bg-image>": function(part){
+ return this["<image>"](part) || this["<gradient>"](part) || part == "none";
+ },
+
+ "<gradient>": function(part) {
+ return part.type == "function" && /^(?:\-(?:ms|moz|o|webkit)\-)?(?:repeating\-)?(?:radial\-|linear\-)?gradient/i.test(part);
+ },
+
+ "<box>": function(part){
+ return ValidationTypes.isLiteral(part, "padding-box | border-box | content-box");
+ },
+
+ "<content>": function(part){
+ return part.type == "function" && part.name == "content";
+ },
+
+ "<relative-size>": function(part){
+ return ValidationTypes.isLiteral(part, "smaller | larger");
+ },
+ "<ident>": function(part){
+ return part.type == "identifier";
+ },
+
+ "<length>": function(part){
+ if (part.type == "function" && /^(?:\-(?:ms|moz|o|webkit)\-)?calc/i.test(part)){
+ return true;
+ }else{
+ return part.type == "length" || part.type == "number" || part.type == "integer" || part == "0";
+ }
+ },
+
+ "<color>": function(part){
+ return part.type == "color" || part == "transparent";
+ },
+
+ "<number>": function(part){
+ return part.type == "number" || this["<integer>"](part);
+ },
+
+ "<integer>": function(part){
+ return part.type == "integer";
+ },
+
+ "<line>": function(part){
+ return part.type == "integer";
+ },
+
+ "<angle>": function(part){
+ return part.type == "angle";
+ },
+
+ "<uri>": function(part){
+ return part.type == "uri";
+ },
+
+ "<image>": function(part){
+ return this["<uri>"](part);
+ },
+
+ "<percentage>": function(part){
+ return part.type == "percentage" || part == "0";
+ },
+
+ "<border-width>": function(part){
+ return this["<length>"](part) || ValidationTypes.isLiteral(part, "thin | medium | thick");
+ },
+
+ "<border-style>": function(part){
+ return ValidationTypes.isLiteral(part, "none | hidden | dotted | dashed | solid | double | groove | ridge | inset | outset");
+ },
+
+ "<margin-width>": function(part){
+ return this["<length>"](part) || this["<percentage>"](part) || ValidationTypes.isLiteral(part, "auto");
+ },
+
+ "<padding-width>": function(part){
+ return this["<length>"](part) || this["<percentage>"](part);
+ },
+
+ "<shape>": function(part){
+ return part.type == "function" && (part.name == "rect" || part.name == "inset-rect");
+ },
+
+ "<time>": function(part) {
+ return part.type == "time";
+ }
+ },
+
+ complex: {
+
+ "<bg-position>": function(expression){
+ var types = this,
+ result = false,
+ numeric = "<percentage> | <length>",
+ xDir = "left | right",
+ yDir = "top | bottom",
+ count = 0,
+ hasNext = function() {
+ return expression.hasNext() && expression.peek() != ",";
+ };
+
+ while (expression.peek(count) && expression.peek(count) != ",") {
+ count++;
+ }
+
+ if (count < 3) {
+ if (ValidationTypes.isAny(expression, xDir + " | center | " + numeric)) {
+ result = true;
+ ValidationTypes.isAny(expression, yDir + " | center | " + numeric);
+ } else if (ValidationTypes.isAny(expression, yDir)) {
+ result = true;
+ ValidationTypes.isAny(expression, xDir + " | center");
+ }
+ } else {
+ if (ValidationTypes.isAny(expression, xDir)) {
+ if (ValidationTypes.isAny(expression, yDir)) {
+ result = true;
+ ValidationTypes.isAny(expression, numeric);
+ } else if (ValidationTypes.isAny(expression, numeric)) {
+ if (ValidationTypes.isAny(expression, yDir)) {
+ result = true;
+ ValidationTypes.isAny(expression, numeric);
+ } else if (ValidationTypes.isAny(expression, "center")) {
+ result = true;
+ }
+ }
+ } else if (ValidationTypes.isAny(expression, yDir)) {
+ if (ValidationTypes.isAny(expression, xDir)) {
+ result = true;
+ ValidationTypes.isAny(expression, numeric);
+ } else if (ValidationTypes.isAny(expression, numeric)) {
+ if (ValidationTypes.isAny(expression, xDir)) {
+ result = true;
+ ValidationTypes.isAny(expression, numeric);
+ } else if (ValidationTypes.isAny(expression, "center")) {
+ result = true;
+ }
+ }
+ } else if (ValidationTypes.isAny(expression, "center")) {
+ if (ValidationTypes.isAny(expression, xDir + " | " + yDir)) {
+ result = true;
+ ValidationTypes.isAny(expression, numeric);
+ }
+ }
+ }
+
+ return result;
+ },
+
+ "<bg-size>": function(expression){
+ var types = this,
+ result = false,
+ numeric = "<percentage> | <length> | auto",
+ part,
+ i, len;
+
+ if (ValidationTypes.isAny(expression, "cover | contain")) {
+ result = true;
+ } else if (ValidationTypes.isAny(expression, numeric)) {
+ result = true;
+ ValidationTypes.isAny(expression, numeric);
+ }
+
+ return result;
+ },
+
+ "<repeat-style>": function(expression){
+ var result = false,
+ values = "repeat | space | round | no-repeat",
+ part;
+
+ if (expression.hasNext()){
+ part = expression.next();
+
+ if (ValidationTypes.isLiteral(part, "repeat-x | repeat-y")) {
+ result = true;
+ } else if (ValidationTypes.isLiteral(part, values)) {
+ result = true;
+
+ if (expression.hasNext() && ValidationTypes.isLiteral(expression.peek(), values)) {
+ expression.next();
+ }
+ }
+ }
+
+ return result;
+
+ },
+
+ "<shadow>": function(expression) {
+ var result = false,
+ count = 0,
+ inset = false,
+ color = false,
+ part;
+
+ if (expression.hasNext()) {
+
+ if (ValidationTypes.isAny(expression, "inset")){
+ inset = true;
+ }
+
+ if (ValidationTypes.isAny(expression, "<color>")) {
+ color = true;
+ }
+
+ while (ValidationTypes.isAny(expression, "<length>") && count < 4) {
+ count++;
+ }
+
+
+ if (expression.hasNext()) {
+ if (!color) {
+ ValidationTypes.isAny(expression, "<color>");
+ }
+
+ if (!inset) {
+ ValidationTypes.isAny(expression, "inset");
+ }
+
+ }
+
+ result = (count >= 2 && count <= 4);
+
+ }
+
+ return result;
+ },
+
+ "<x-one-radius>": function(expression) {
+ var result = false,
+ simple = "<length> | <percentage> | inherit";
+
+ if (ValidationTypes.isAny(expression, simple)){
+ result = true;
+ ValidationTypes.isAny(expression, simple);
+ }
+
+ return result;
+ }
+ }
+};
+
+
+
+parserlib.css = {
+Colors :Colors,
+Combinator :Combinator,
+Parser :Parser,
+PropertyName :PropertyName,
+PropertyValue :PropertyValue,
+PropertyValuePart :PropertyValuePart,
+MediaFeature :MediaFeature,
+MediaQuery :MediaQuery,
+Selector :Selector,
+SelectorPart :SelectorPart,
+SelectorSubPart :SelectorSubPart,
+Specificity :Specificity,
+TokenStream :TokenStream,
+Tokens :Tokens,
+ValidationError :ValidationError
+};
+})();
+
+
+
+
+(function(){
+for(var prop in parserlib){
+exports[prop] = parserlib[prop];
+}
+})();
+var CSSLint = (function(){
+
+ var rules = [],
+ formatters = [],
+ embeddedRuleset = /\/\*csslint([^\*]*)\*\//,
+ api = new parserlib.util.EventTarget();
+
+ api.version = "0.10.0";
+ api.addRule = function(rule){
+ rules.push(rule);
+ rules[rule.id] = rule;
+ };
+ api.clearRules = function(){
+ rules = [];
+ };
+ api.getRules = function(){
+ return [].concat(rules).sort(function(a,b){
+ return a.id > b.id ? 1 : 0;
+ });
+ };
+ api.getRuleset = function() {
+ var ruleset = {},
+ i = 0,
+ len = rules.length;
+
+ while (i < len){
+ ruleset[rules[i++].id] = 1; //by default, everything is a warning
+ }
+
+ return ruleset;
+ };
+ function applyEmbeddedRuleset(text, ruleset){
+ var valueMap,
+ embedded = text && text.match(embeddedRuleset),
+ rules = embedded && embedded[1];
+
+ if (rules) {
+ valueMap = {
+ "true": 2, // true is error
+ "": 1, // blank is warning
+ "false": 0, // false is ignore
+
+ "2": 2, // explicit error
+ "1": 1, // explicit warning
+ "0": 0 // explicit ignore
+ };
+
+ rules.toLowerCase().split(",").forEach(function(rule){
+ var pair = rule.split(":"),
+ property = pair[0] || "",
+ value = pair[1] || "";
+
+ ruleset[property.trim()] = valueMap[value.trim()];
+ });
+ }
+
+ return ruleset;
+ }
+ api.addFormatter = function(formatter) {
+ formatters[formatter.id] = formatter;
+ };
+ api.getFormatter = function(formatId){
+ return formatters[formatId];
+ };
+ api.format = function(results, filename, formatId, options) {
+ var formatter = this.getFormatter(formatId),
+ result = null;
+
+ if (formatter){
+ result = formatter.startFormat();
+ result += formatter.formatResults(results, filename, options || {});
+ result += formatter.endFormat();
+ }
+
+ return result;
+ };
+ api.hasFormat = function(formatId){
+ return formatters.hasOwnProperty(formatId);
+ };
+ api.verify = function(text, ruleset){
+
+ var i = 0,
+ len = rules.length,
+ reporter,
+ lines,
+ report,
+ parser = new parserlib.css.Parser({ starHack: true, ieFilters: true,
+ underscoreHack: true, strict: false });
+ lines = text.replace(/\n\r?/g, "$split$").split('$split$');
+
+ if (!ruleset){
+ ruleset = this.getRuleset();
+ }
+
+ if (embeddedRuleset.test(text)){
+ ruleset = applyEmbeddedRuleset(text, ruleset);
+ }
+
+ reporter = new Reporter(lines, ruleset);
+
+ ruleset.errors = 2; //always report parsing errors as errors
+ for (i in ruleset){
+ if(ruleset.hasOwnProperty(i) && ruleset[i]){
+ if (rules[i]){
+ rules[i].init(parser, reporter);
+ }
+ }
+ }
+ try {
+ parser.parse(text);
+ } catch (ex) {
+ reporter.error("Fatal error, cannot continue: " + ex.message, ex.line, ex.col, {});
+ }
+
+ report = {
+ messages : reporter.messages,
+ stats : reporter.stats,
+ ruleset : reporter.ruleset
+ };
+ report.messages.sort(function (a, b){
+ if (a.rollup && !b.rollup){
+ return 1;
+ } else if (!a.rollup && b.rollup){
+ return -1;
+ } else {
+ return a.line - b.line;
+ }
+ });
+
+ return report;
+ };
+
+ return api;
+
+})();
+function Reporter(lines, ruleset){
+ this.messages = [];
+ this.stats = [];
+ this.lines = lines;
+ this.ruleset = ruleset;
+}
+
+Reporter.prototype = {
+ constructor: Reporter,
+ error: function(message, line, col, rule){
+ this.messages.push({
+ type : "error",
+ line : line,
+ col : col,
+ message : message,
+ evidence: this.lines[line-1],
+ rule : rule || {}
+ });
+ },
+ warn: function(message, line, col, rule){
+ this.report(message, line, col, rule);
+ },
+ report: function(message, line, col, rule){
+ this.messages.push({
+ type : this.ruleset[rule.id] == 2 ? "error" : "warning",
+ line : line,
+ col : col,
+ message : message,
+ evidence: this.lines[line-1],
+ rule : rule
+ });
+ },
+ info: function(message, line, col, rule){
+ this.messages.push({
+ type : "info",
+ line : line,
+ col : col,
+ message : message,
+ evidence: this.lines[line-1],
+ rule : rule
+ });
+ },
+ rollupError: function(message, rule){
+ this.messages.push({
+ type : "error",
+ rollup : true,
+ message : message,
+ rule : rule
+ });
+ },
+ rollupWarn: function(message, rule){
+ this.messages.push({
+ type : "warning",
+ rollup : true,
+ message : message,
+ rule : rule
+ });
+ },
+ stat: function(name, value){
+ this.stats[name] = value;
+ }
+};
+CSSLint._Reporter = Reporter;
+CSSLint.Util = {
+ mix: function(receiver, supplier){
+ var prop;
+
+ for (prop in supplier){
+ if (supplier.hasOwnProperty(prop)){
+ receiver[prop] = supplier[prop];
+ }
+ }
+
+ return prop;
+ },
+ indexOf: function(values, value){
+ if (values.indexOf){
+ return values.indexOf(value);
+ } else {
+ for (var i=0, len=values.length; i < len; i++){
+ if (values[i] === value){
+ return i;
+ }
+ }
+ return -1;
+ }
+ },
+ forEach: function(values, func) {
+ if (values.forEach){
+ return values.forEach(func);
+ } else {
+ for (var i=0, len=values.length; i < len; i++){
+ func(values[i], i, values);
+ }
+ }
+ }
+};
+CSSLint.addRule({
+ id: "adjoining-classes",
+ name: "Disallow adjoining classes",
+ desc: "Don't use adjoining classes.",
+ browsers: "IE6",
+ init: function(parser, reporter){
+ var rule = this;
+ parser.addListener("startrule", function(event){
+ var selectors = event.selectors,
+ selector,
+ part,
+ modifier,
+ classCount,
+ i, j, k;
+
+ for (i=0; i < selectors.length; i++){
+ selector = selectors[i];
+ for (j=0; j < selector.parts.length; j++){
+ part = selector.parts[j];
+ if (part.type == parser.SELECTOR_PART_TYPE){
+ classCount = 0;
+ for (k=0; k < part.modifiers.length; k++){
+ modifier = part.modifiers[k];
+ if (modifier.type == "class"){
+ classCount++;
+ }
+ if (classCount > 1){
+ reporter.report("Don't use adjoining classes.", part.line, part.col, rule);
+ }
+ }
+ }
+ }
+ }
+ });
+ }
+
+});
+CSSLint.addRule({
+ id: "box-model",
+ name: "Beware of broken box size",
+ desc: "Don't use width or height when using padding or border.",
+ browsers: "All",
+ init: function(parser, reporter){
+ var rule = this,
+ widthProperties = {
+ border: 1,
+ "border-left": 1,
+ "border-right": 1,
+ padding: 1,
+ "padding-left": 1,
+ "padding-right": 1
+ },
+ heightProperties = {
+ border: 1,
+ "border-bottom": 1,
+ "border-top": 1,
+ padding: 1,
+ "padding-bottom": 1,
+ "padding-top": 1
+ },
+ properties,
+ boxSizing = false;
+
+ function startRule(){
+ properties = {};
+ boxSizing = false;
+ }
+
+ function endRule(){
+ var prop, value;
+
+ if (!boxSizing) {
+ if (properties.height){
+ for (prop in heightProperties){
+ if (heightProperties.hasOwnProperty(prop) && properties[prop]){
+ value = properties[prop].value;
+ if (!(prop == "padding" && value.parts.length === 2 && value.parts[0].value === 0)){
+ reporter.report("Using height with " + prop + " can sometimes make elements larger than you expect.", properties[prop].line, properties[prop].col, rule);
+ }
+ }
+ }
+ }
+
+ if (properties.width){
+ for (prop in widthProperties){
+ if (widthProperties.hasOwnProperty(prop) && properties[prop]){
+ value = properties[prop].value;
+
+ if (!(prop == "padding" && value.parts.length === 2 && value.parts[1].value === 0)){
+ reporter.report("Using width with " + prop + " can sometimes make elements larger than you expect.", properties[prop].line, properties[prop].col, rule);
+ }
+ }
+ }
+ }
+ }
+ }
+
+ parser.addListener("startrule", startRule);
+ parser.addListener("startfontface", startRule);
+ parser.addListener("startpage", startRule);
+ parser.addListener("startpagemargin", startRule);
+ parser.addListener("startkeyframerule", startRule);
+
+ parser.addListener("property", function(event){
+ var name = event.property.text.toLowerCase();
+
+ if (heightProperties[name] || widthProperties[name]){
+ if (!/^0\S*$/.test(event.value) && !(name == "border" && event.value == "none")){
+ properties[name] = { line: event.property.line, col: event.property.col, value: event.value };
+ }
+ } else {
+ if (/^(width|height)/i.test(name) && /^(length|percentage)/.test(event.value.parts[0].type)){
+ properties[name] = 1;
+ } else if (name == "box-sizing") {
+ boxSizing = true;
+ }
+ }
+
+ });
+
+ parser.addListener("endrule", endRule);
+ parser.addListener("endfontface", endRule);
+ parser.addListener("endpage", endRule);
+ parser.addListener("endpagemargin", endRule);
+ parser.addListener("endkeyframerule", endRule);
+ }
+
+});
+CSSLint.addRule({
+ id: "box-sizing",
+ name: "Disallow use of box-sizing",
+ desc: "The box-sizing properties isn't supported in IE6 and IE7.",
+ browsers: "IE6, IE7",
+ tags: ["Compatibility"],
+ init: function(parser, reporter){
+ var rule = this;
+
+ parser.addListener("property", function(event){
+ var name = event.property.text.toLowerCase();
+
+ if (name == "box-sizing"){
+ reporter.report("The box-sizing property isn't supported in IE6 and IE7.", event.line, event.col, rule);
+ }
+ });
+ }
+
+});
+CSSLint.addRule({
+ id: "bulletproof-font-face",
+ name: "Use the bulletproof @font-face syntax",
+ desc: "Use the bulletproof @font-face syntax to avoid 404's in old IE (http://www.fontspring.com/blog/the-new-bulletproof-font-face-syntax).",
+ browsers: "All",
+ init: function(parser, reporter){
+ var rule = this,
+ count = 0,
+ fontFaceRule = false,
+ firstSrc = true,
+ ruleFailed = false,
+ line, col;
+ parser.addListener("startfontface", function(event){
+ fontFaceRule = true;
+ });
+
+ parser.addListener("property", function(event){
+ if (!fontFaceRule) {
+ return;
+ }
+
+ var propertyName = event.property.toString().toLowerCase(),
+ value = event.value.toString();
+ line = event.line;
+ col = event.col;
+ if (propertyName === 'src') {
+ var regex = /^\s?url\(['"].+\.eot\?.*['"]\)\s*format\(['"]embedded-opentype['"]\).*$/i;
+ if (!value.match(regex) && firstSrc) {
+ ruleFailed = true;
+ firstSrc = false;
+ } else if (value.match(regex) && !firstSrc) {
+ ruleFailed = false;
+ }
+ }
+
+
+ });
+ parser.addListener("endfontface", function(event){
+ fontFaceRule = false;
+
+ if (ruleFailed) {
+ reporter.report("@font-face declaration doesn't follow the fontspring bulletproof syntax.", line, col, rule);
+ }
+ });
+ }
+});
+CSSLint.addRule({
+ id: "compatible-vendor-prefixes",
+ name: "Require compatible vendor prefixes",
+ desc: "Include all compatible vendor prefixes to reach a wider range of users.",
+ browsers: "All",
+ init: function (parser, reporter) {
+ var rule = this,
+ compatiblePrefixes,
+ properties,
+ prop,
+ variations,
+ prefixed,
+ i,
+ len,
+ inKeyFrame = false,
+ arrayPush = Array.prototype.push,
+ applyTo = [];
+ compatiblePrefixes = {
+ "animation" : "webkit moz",
+ "animation-delay" : "webkit moz",
+ "animation-direction" : "webkit moz",
+ "animation-duration" : "webkit moz",
+ "animation-fill-mode" : "webkit moz",
+ "animation-iteration-count" : "webkit moz",
+ "animation-name" : "webkit moz",
+ "animation-play-state" : "webkit moz",
+ "animation-timing-function" : "webkit moz",
+ "appearance" : "webkit moz",
+ "border-end" : "webkit moz",
+ "border-end-color" : "webkit moz",
+ "border-end-style" : "webkit moz",
+ "border-end-width" : "webkit moz",
+ "border-image" : "webkit moz o",
+ "border-radius" : "webkit",
+ "border-start" : "webkit moz",
+ "border-start-color" : "webkit moz",
+ "border-start-style" : "webkit moz",
+ "border-start-width" : "webkit moz",
+ "box-align" : "webkit moz ms",
+ "box-direction" : "webkit moz ms",
+ "box-flex" : "webkit moz ms",
+ "box-lines" : "webkit ms",
+ "box-ordinal-group" : "webkit moz ms",
+ "box-orient" : "webkit moz ms",
+ "box-pack" : "webkit moz ms",
+ "box-sizing" : "webkit moz",
+ "box-shadow" : "webkit moz",
+ "column-count" : "webkit moz ms",
+ "column-gap" : "webkit moz ms",
+ "column-rule" : "webkit moz ms",
+ "column-rule-color" : "webkit moz ms",
+ "column-rule-style" : "webkit moz ms",
+ "column-rule-width" : "webkit moz ms",
+ "column-width" : "webkit moz ms",
+ "hyphens" : "epub moz",
+ "line-break" : "webkit ms",
+ "margin-end" : "webkit moz",
+ "margin-start" : "webkit moz",
+ "marquee-speed" : "webkit wap",
+ "marquee-style" : "webkit wap",
+ "padding-end" : "webkit moz",
+ "padding-start" : "webkit moz",
+ "tab-size" : "moz o",
+ "text-size-adjust" : "webkit ms",
+ "transform" : "webkit moz ms o",
+ "transform-origin" : "webkit moz ms o",
+ "transition" : "webkit moz o",
+ "transition-delay" : "webkit moz o",
+ "transition-duration" : "webkit moz o",
+ "transition-property" : "webkit moz o",
+ "transition-timing-function" : "webkit moz o",
+ "user-modify" : "webkit moz",
+ "user-select" : "webkit moz ms",
+ "word-break" : "epub ms",
+ "writing-mode" : "epub ms"
+ };
+
+
+ for (prop in compatiblePrefixes) {
+ if (compatiblePrefixes.hasOwnProperty(prop)) {
+ variations = [];
+ prefixed = compatiblePrefixes[prop].split(' ');
+ for (i = 0, len = prefixed.length; i < len; i++) {
+ variations.push('-' + prefixed[i] + '-' + prop);
+ }
+ compatiblePrefixes[prop] = variations;
+ arrayPush.apply(applyTo, variations);
+ }
+ }
+
+ parser.addListener("startrule", function () {
+ properties = [];
+ });
+
+ parser.addListener("startkeyframes", function (event) {
+ inKeyFrame = event.prefix || true;
+ });
+
+ parser.addListener("endkeyframes", function (event) {
+ inKeyFrame = false;
+ });
+
+ parser.addListener("property", function (event) {
+ var name = event.property;
+ if (CSSLint.Util.indexOf(applyTo, name.text) > -1) {
+ if (!inKeyFrame || typeof inKeyFrame != "string" ||
+ name.text.indexOf("-" + inKeyFrame + "-") !== 0) {
+ properties.push(name);
+ }
+ }
+ });
+
+ parser.addListener("endrule", function (event) {
+ if (!properties.length) {
+ return;
+ }
+
+ var propertyGroups = {},
+ i,
+ len,
+ name,
+ prop,
+ variations,
+ value,
+ full,
+ actual,
+ item,
+ propertiesSpecified;
+
+ for (i = 0, len = properties.length; i < len; i++) {
+ name = properties[i];
+
+ for (prop in compatiblePrefixes) {
+ if (compatiblePrefixes.hasOwnProperty(prop)) {
+ variations = compatiblePrefixes[prop];
+ if (CSSLint.Util.indexOf(variations, name.text) > -1) {
+ if (!propertyGroups[prop]) {
+ propertyGroups[prop] = {
+ full : variations.slice(0),
+ actual : [],
+ actualNodes: []
+ };
+ }
+ if (CSSLint.Util.indexOf(propertyGroups[prop].actual, name.text) === -1) {
+ propertyGroups[prop].actual.push(name.text);
+ propertyGroups[prop].actualNodes.push(name);
+ }
+ }
+ }
+ }
+ }
+
+ for (prop in propertyGroups) {
+ if (propertyGroups.hasOwnProperty(prop)) {
+ value = propertyGroups[prop];
+ full = value.full;
+ actual = value.actual;
+
+ if (full.length > actual.length) {
+ for (i = 0, len = full.length; i < len; i++) {
+ item = full[i];
+ if (CSSLint.Util.indexOf(actual, item) === -1) {
+ propertiesSpecified = (actual.length === 1) ? actual[0] : (actual.length == 2) ? actual.join(" and ") : actual.join(", ");
+ reporter.report("The property " + item + " is compatible with " + propertiesSpecified + " and should be included as well.", value.actualNodes[0].line, value.actualNodes[0].col, rule);
+ }
+ }
+
+ }
+ }
+ }
+ });
+ }
+});
+CSSLint.addRule({
+ id: "display-property-grouping",
+ name: "Require properties appropriate for display",
+ desc: "Certain properties shouldn't be used with certain display property values.",
+ browsers: "All",
+ init: function(parser, reporter){
+ var rule = this;
+
+ var propertiesToCheck = {
+ display: 1,
+ "float": "none",
+ height: 1,
+ width: 1,
+ margin: 1,
+ "margin-left": 1,
+ "margin-right": 1,
+ "margin-bottom": 1,
+ "margin-top": 1,
+ padding: 1,
+ "padding-left": 1,
+ "padding-right": 1,
+ "padding-bottom": 1,
+ "padding-top": 1,
+ "vertical-align": 1
+ },
+ properties;
+
+ function reportProperty(name, display, msg){
+ if (properties[name]){
+ if (typeof propertiesToCheck[name] != "string" || properties[name].value.toLowerCase() != propertiesToCheck[name]){
+ reporter.report(msg || name + " can't be used with display: " + display + ".", properties[name].line, properties[name].col, rule);
+ }
+ }
+ }
+
+ function startRule(){
+ properties = {};
+ }
+
+ function endRule(){
+
+ var display = properties.display ? properties.display.value : null;
+ if (display){
+ switch(display){
+
+ case "inline":
+ reportProperty("height", display);
+ reportProperty("width", display);
+ reportProperty("margin", display);
+ reportProperty("margin-top", display);
+ reportProperty("margin-bottom", display);
+ reportProperty("float", display, "display:inline has no effect on floated elements (but may be used to fix the IE6 double-margin bug).");
+ break;
+
+ case "block":
+ reportProperty("vertical-align", display);
+ break;
+
+ case "inline-block":
+ reportProperty("float", display);
+ break;
+
+ default:
+ if (display.indexOf("table-") === 0){
+ reportProperty("margin", display);
+ reportProperty("margin-left", display);
+ reportProperty("margin-right", display);
+ reportProperty("margin-top", display);
+ reportProperty("margin-bottom", display);
+ reportProperty("float", display);
+ }
+ }
+ }
+
+ }
+
+ parser.addListener("startrule", startRule);
+ parser.addListener("startfontface", startRule);
+ parser.addListener("startkeyframerule", startRule);
+ parser.addListener("startpagemargin", startRule);
+ parser.addListener("startpage", startRule);
+
+ parser.addListener("property", function(event){
+ var name = event.property.text.toLowerCase();
+
+ if (propertiesToCheck[name]){
+ properties[name] = { value: event.value.text, line: event.property.line, col: event.property.col };
+ }
+ });
+
+ parser.addListener("endrule", endRule);
+ parser.addListener("endfontface", endRule);
+ parser.addListener("endkeyframerule", endRule);
+ parser.addListener("endpagemargin", endRule);
+ parser.addListener("endpage", endRule);
+
+ }
+
+});
+CSSLint.addRule({
+ id: "duplicate-background-images",
+ name: "Disallow duplicate background images",
+ desc: "Every background-image should be unique. Use a common class for e.g. sprites.",
+ browsers: "All",
+ init: function(parser, reporter){
+ var rule = this,
+ stack = {};
+
+ parser.addListener("property", function(event){
+ var name = event.property.text,
+ value = event.value,
+ i, len;
+
+ if (name.match(/background/i)) {
+ for (i=0, len=value.parts.length; i < len; i++) {
+ if (value.parts[i].type == 'uri') {
+ if (typeof stack[value.parts[i].uri] === 'undefined') {
+ stack[value.parts[i].uri] = event;
+ }
+ else {
+ reporter.report("Background image '" + value.parts[i].uri + "' was used multiple times, first declared at line " + stack[value.parts[i].uri].line + ", col " + stack[value.parts[i].uri].col + ".", event.line, event.col, rule);
+ }
+ }
+ }
+ }
+ });
+ }
+});
+CSSLint.addRule({
+ id: "duplicate-properties",
+ name: "Disallow duplicate properties",
+ desc: "Duplicate properties must appear one after the other.",
+ browsers: "All",
+ init: function(parser, reporter){
+ var rule = this,
+ properties,
+ lastProperty;
+
+ function startRule(event){
+ properties = {};
+ }
+
+ parser.addListener("startrule", startRule);
+ parser.addListener("startfontface", startRule);
+ parser.addListener("startpage", startRule);
+ parser.addListener("startpagemargin", startRule);
+ parser.addListener("startkeyframerule", startRule);
+
+ parser.addListener("property", function(event){
+ var property = event.property,
+ name = property.text.toLowerCase();
+
+ if (properties[name] && (lastProperty != name || properties[name] == event.value.text)){
+ reporter.report("Duplicate property '" + event.property + "' found.", event.line, event.col, rule);
+ }
+
+ properties[name] = event.value.text;
+ lastProperty = name;
+
+ });
+
+
+ }
+
+});
+CSSLint.addRule({
+ id: "empty-rules",
+ name: "Disallow empty rules",
+ desc: "Rules without any properties specified should be removed.",
+ browsers: "All",
+ init: function(parser, reporter){
+ var rule = this,
+ count = 0;
+
+ parser.addListener("startrule", function(){
+ count=0;
+ });
+
+ parser.addListener("property", function(){
+ count++;
+ });
+
+ parser.addListener("endrule", function(event){
+ var selectors = event.selectors;
+ if (count === 0){
+ reporter.report("Rule is empty.", selectors[0].line, selectors[0].col, rule);
+ }
+ });
+ }
+
+});
+CSSLint.addRule({
+ id: "errors",
+ name: "Parsing Errors",
+ desc: "This rule looks for recoverable syntax errors.",
+ browsers: "All",
+ init: function(parser, reporter){
+ var rule = this;
+
+ parser.addListener("error", function(event){
+ reporter.error(event.message, event.line, event.col, rule);
+ });
+
+ }
+
+});
+CSSLint.addRule({
+ id: "fallback-colors",
+ name: "Require fallback colors",
+ desc: "For older browsers that don't support RGBA, HSL, or HSLA, provide a fallback color.",
+ browsers: "IE6,IE7,IE8",
+ init: function(parser, reporter){
+ var rule = this,
+ lastProperty,
+ propertiesToCheck = {
+ color: 1,
+ background: 1,
+ "border-color": 1,
+ "border-top-color": 1,
+ "border-right-color": 1,
+ "border-bottom-color": 1,
+ "border-left-color": 1,
+ border: 1,
+ "border-top": 1,
+ "border-right": 1,
+ "border-bottom": 1,
+ "border-left": 1,
+ "background-color": 1
+ },
+ properties;
+
+ function startRule(event){
+ properties = {};
+ lastProperty = null;
+ }
+
+ parser.addListener("startrule", startRule);
+ parser.addListener("startfontface", startRule);
+ parser.addListener("startpage", startRule);
+ parser.addListener("startpagemargin", startRule);
+ parser.addListener("startkeyframerule", startRule);
+
+ parser.addListener("property", function(event){
+ var property = event.property,
+ name = property.text.toLowerCase(),
+ parts = event.value.parts,
+ i = 0,
+ colorType = "",
+ len = parts.length;
+
+ if(propertiesToCheck[name]){
+ while(i < len){
+ if (parts[i].type == "color"){
+ if ("alpha" in parts[i] || "hue" in parts[i]){
+
+ if (/([^\)]+)\(/.test(parts[i])){
+ colorType = RegExp.$1.toUpperCase();
+ }
+
+ if (!lastProperty || (lastProperty.property.text.toLowerCase() != name || lastProperty.colorType != "compat")){
+ reporter.report("Fallback " + name + " (hex or RGB) should precede " + colorType + " " + name + ".", event.line, event.col, rule);
+ }
+ } else {
+ event.colorType = "compat";
+ }
+ }
+
+ i++;
+ }
+ }
+
+ lastProperty = event;
+ });
+
+ }
+
+});
+CSSLint.addRule({
+ id: "floats",
+ name: "Disallow too many floats",
+ desc: "This rule tests if the float property is used too many times",
+ browsers: "All",
+ init: function(parser, reporter){
+ var rule = this;
+ var count = 0;
+ parser.addListener("property", function(event){
+ if (event.property.text.toLowerCase() == "float" &&
+ event.value.text.toLowerCase() != "none"){
+ count++;
+ }
+ });
+ parser.addListener("endstylesheet", function(){
+ reporter.stat("floats", count);
+ if (count >= 10){
+ reporter.rollupWarn("Too many floats (" + count + "), you're probably using them for layout. Consider using a grid system instead.", rule);
+ }
+ });
+ }
+
+});
+CSSLint.addRule({
+ id: "font-faces",
+ name: "Don't use too many web fonts",
+ desc: "Too many different web fonts in the same stylesheet.",
+ browsers: "All",
+ init: function(parser, reporter){
+ var rule = this,
+ count = 0;
+
+
+ parser.addListener("startfontface", function(){
+ count++;
+ });
+
+ parser.addListener("endstylesheet", function(){
+ if (count > 5){
+ reporter.rollupWarn("Too many @font-face declarations (" + count + ").", rule);
+ }
+ });
+ }
+
+});
+CSSLint.addRule({
+ id: "font-sizes",
+ name: "Disallow too many font sizes",
+ desc: "Checks the number of font-size declarations.",
+ browsers: "All",
+ init: function(parser, reporter){
+ var rule = this,
+ count = 0;
+ parser.addListener("property", function(event){
+ if (event.property == "font-size"){
+ count++;
+ }
+ });
+ parser.addListener("endstylesheet", function(){
+ reporter.stat("font-sizes", count);
+ if (count >= 10){
+ reporter.rollupWarn("Too many font-size declarations (" + count + "), abstraction needed.", rule);
+ }
+ });
+ }
+
+});
+CSSLint.addRule({
+ id: "gradients",
+ name: "Require all gradient definitions",
+ desc: "When using a vendor-prefixed gradient, make sure to use them all.",
+ browsers: "All",
+ init: function(parser, reporter){
+ var rule = this,
+ gradients;
+
+ parser.addListener("startrule", function(){
+ gradients = {
+ moz: 0,
+ webkit: 0,
+ oldWebkit: 0,
+ o: 0
+ };
+ });
+
+ parser.addListener("property", function(event){
+
+ if (/\-(moz|o|webkit)(?:\-(?:linear|radial))\-gradient/i.test(event.value)){
+ gradients[RegExp.$1] = 1;
+ } else if (/\-webkit\-gradient/i.test(event.value)){
+ gradients.oldWebkit = 1;
+ }
+
+ });
+
+ parser.addListener("endrule", function(event){
+ var missing = [];
+
+ if (!gradients.moz){
+ missing.push("Firefox 3.6+");
+ }
+
+ if (!gradients.webkit){
+ missing.push("Webkit (Safari 5+, Chrome)");
+ }
+
+ if (!gradients.oldWebkit){
+ missing.push("Old Webkit (Safari 4+, Chrome)");
+ }
+
+ if (!gradients.o){
+ missing.push("Opera 11.1+");
+ }
+
+ if (missing.length && missing.length < 4){
+ reporter.report("Missing vendor-prefixed CSS gradients for " + missing.join(", ") + ".", event.selectors[0].line, event.selectors[0].col, rule);
+ }
+
+ });
+
+ }
+
+});
+CSSLint.addRule({
+ id: "ids",
+ name: "Disallow IDs in selectors",
+ desc: "Selectors should not contain IDs.",
+ browsers: "All",
+ init: function(parser, reporter){
+ var rule = this;
+ parser.addListener("startrule", function(event){
+ var selectors = event.selectors,
+ selector,
+ part,
+ modifier,
+ idCount,
+ i, j, k;
+
+ for (i=0; i < selectors.length; i++){
+ selector = selectors[i];
+ idCount = 0;
+
+ for (j=0; j < selector.parts.length; j++){
+ part = selector.parts[j];
+ if (part.type == parser.SELECTOR_PART_TYPE){
+ for (k=0; k < part.modifiers.length; k++){
+ modifier = part.modifiers[k];
+ if (modifier.type == "id"){
+ idCount++;
+ }
+ }
+ }
+ }
+
+ if (idCount == 1){
+ reporter.report("Don't use IDs in selectors.", selector.line, selector.col, rule);
+ } else if (idCount > 1){
+ reporter.report(idCount + " IDs in the selector, really?", selector.line, selector.col, rule);
+ }
+ }
+
+ });
+ }
+
+});
+CSSLint.addRule({
+ id: "import",
+ name: "Disallow @import",
+ desc: "Don't use @import, use <link> instead.",
+ browsers: "All",
+ init: function(parser, reporter){
+ var rule = this;
+
+ parser.addListener("import", function(event){
+ reporter.report("@import prevents parallel downloads, use <link> instead.", event.line, event.col, rule);
+ });
+
+ }
+
+});
+CSSLint.addRule({
+ id: "important",
+ name: "Disallow !important",
+ desc: "Be careful when using !important declaration",
+ browsers: "All",
+ init: function(parser, reporter){
+ var rule = this,
+ count = 0;
+ parser.addListener("property", function(event){
+ if (event.important === true){
+ count++;
+ reporter.report("Use of !important", event.line, event.col, rule);
+ }
+ });
+ parser.addListener("endstylesheet", function(){
+ reporter.stat("important", count);
+ if (count >= 10){
+ reporter.rollupWarn("Too many !important declarations (" + count + "), try to use less than 10 to avoid specificity issues.", rule);
+ }
+ });
+ }
+
+});
+CSSLint.addRule({
+ id: "known-properties",
+ name: "Require use of known properties",
+ desc: "Properties should be known (listed in CSS3 specification) or be a vendor-prefixed property.",
+ browsers: "All",
+ init: function(parser, reporter){
+ var rule = this;
+
+ parser.addListener("property", function(event){
+ var name = event.property.text.toLowerCase();
+ if (event.invalid) {
+ reporter.report(event.invalid.message, event.line, event.col, rule);
+ }
+
+ });
+ }
+
+});
+CSSLint.addRule({
+ id: "outline-none",
+ name: "Disallow outline: none",
+ desc: "Use of outline: none or outline: 0 should be limited to :focus rules.",
+ browsers: "All",
+ tags: ["Accessibility"],
+ init: function(parser, reporter){
+ var rule = this,
+ lastRule;
+
+ function startRule(event){
+ if (event.selectors){
+ lastRule = {
+ line: event.line,
+ col: event.col,
+ selectors: event.selectors,
+ propCount: 0,
+ outline: false
+ };
+ } else {
+ lastRule = null;
+ }
+ }
+
+ function endRule(event){
+ if (lastRule){
+ if (lastRule.outline){
+ if (lastRule.selectors.toString().toLowerCase().indexOf(":focus") == -1){
+ reporter.report("Outlines should only be modified using :focus.", lastRule.line, lastRule.col, rule);
+ } else if (lastRule.propCount == 1) {
+ reporter.report("Outlines shouldn't be hidden unless other visual changes are made.", lastRule.line, lastRule.col, rule);
+ }
+ }
+ }
+ }
+
+ parser.addListener("startrule", startRule);
+ parser.addListener("startfontface", startRule);
+ parser.addListener("startpage", startRule);
+ parser.addListener("startpagemargin", startRule);
+ parser.addListener("startkeyframerule", startRule);
+
+ parser.addListener("property", function(event){
+ var name = event.property.text.toLowerCase(),
+ value = event.value;
+
+ if (lastRule){
+ lastRule.propCount++;
+ if (name == "outline" && (value == "none" || value == "0")){
+ lastRule.outline = true;
+ }
+ }
+
+ });
+
+ parser.addListener("endrule", endRule);
+ parser.addListener("endfontface", endRule);
+ parser.addListener("endpage", endRule);
+ parser.addListener("endpagemargin", endRule);
+ parser.addListener("endkeyframerule", endRule);
+
+ }
+
+});
+CSSLint.addRule({
+ id: "overqualified-elements",
+ name: "Disallow overqualified elements",
+ desc: "Don't use classes or IDs with elements (a.foo or a#foo).",
+ browsers: "All",
+ init: function(parser, reporter){
+ var rule = this,
+ classes = {};
+
+ parser.addListener("startrule", function(event){
+ var selectors = event.selectors,
+ selector,
+ part,
+ modifier,
+ i, j, k;
+
+ for (i=0; i < selectors.length; i++){
+ selector = selectors[i];
+
+ for (j=0; j < selector.parts.length; j++){
+ part = selector.parts[j];
+ if (part.type == parser.SELECTOR_PART_TYPE){
+ for (k=0; k < part.modifiers.length; k++){
+ modifier = part.modifiers[k];
+ if (part.elementName && modifier.type == "id"){
+ reporter.report("Element (" + part + ") is overqualified, just use " + modifier + " without element name.", part.line, part.col, rule);
+ } else if (modifier.type == "class"){
+
+ if (!classes[modifier]){
+ classes[modifier] = [];
+ }
+ classes[modifier].push({ modifier: modifier, part: part });
+ }
+ }
+ }
+ }
+ }
+ });
+
+ parser.addListener("endstylesheet", function(){
+
+ var prop;
+ for (prop in classes){
+ if (classes.hasOwnProperty(prop)){
+ if (classes[prop].length == 1 && classes[prop][0].part.elementName){
+ reporter.report("Element (" + classes[prop][0].part + ") is overqualified, just use " + classes[prop][0].modifier + " without element name.", classes[prop][0].part.line, classes[prop][0].part.col, rule);
+ }
+ }
+ }
+ });
+ }
+
+});
+CSSLint.addRule({
+ id: "qualified-headings",
+ name: "Disallow qualified headings",
+ desc: "Headings should not be qualified (namespaced).",
+ browsers: "All",
+ init: function(parser, reporter){
+ var rule = this;
+
+ parser.addListener("startrule", function(event){
+ var selectors = event.selectors,
+ selector,
+ part,
+ i, j;
+
+ for (i=0; i < selectors.length; i++){
+ selector = selectors[i];
+
+ for (j=0; j < selector.parts.length; j++){
+ part = selector.parts[j];
+ if (part.type == parser.SELECTOR_PART_TYPE){
+ if (part.elementName && /h[1-6]/.test(part.elementName.toString()) && j > 0){
+ reporter.report("Heading (" + part.elementName + ") should not be qualified.", part.line, part.col, rule);
+ }
+ }
+ }
+ }
+ });
+ }
+
+});
+CSSLint.addRule({
+ id: "regex-selectors",
+ name: "Disallow selectors that look like regexs",
+ desc: "Selectors that look like regular expressions are slow and should be avoided.",
+ browsers: "All",
+ init: function(parser, reporter){
+ var rule = this;
+
+ parser.addListener("startrule", function(event){
+ var selectors = event.selectors,
+ selector,
+ part,
+ modifier,
+ i, j, k;
+
+ for (i=0; i < selectors.length; i++){
+ selector = selectors[i];
+ for (j=0; j < selector.parts.length; j++){
+ part = selector.parts[j];
+ if (part.type == parser.SELECTOR_PART_TYPE){
+ for (k=0; k < part.modifiers.length; k++){
+ modifier = part.modifiers[k];
+ if (modifier.type == "attribute"){
+ if (/([\~\|\^\$\*]=)/.test(modifier)){
+ reporter.report("Attribute selectors with " + RegExp.$1 + " are slow!", modifier.line, modifier.col, rule);
+ }
+ }
+
+ }
+ }
+ }
+ }
+ });
+ }
+
+});
+CSSLint.addRule({
+ id: "rules-count",
+ name: "Rules Count",
+ desc: "Track how many rules there are.",
+ browsers: "All",
+ init: function(parser, reporter){
+ var rule = this,
+ count = 0;
+ parser.addListener("startrule", function(){
+ count++;
+ });
+
+ parser.addListener("endstylesheet", function(){
+ reporter.stat("rule-count", count);
+ });
+ }
+
+});
+CSSLint.addRule({
+ id: "selector-max-approaching",
+ name: "Warn when approaching the 4095 selector limit for IE",
+ desc: "Will warn when selector count is >= 3800 selectors.",
+ browsers: "IE",
+ init: function(parser, reporter) {
+ var rule = this, count = 0;
+
+ parser.addListener('startrule', function(event) {
+ count += event.selectors.length;
+ });
+
+ parser.addListener("endstylesheet", function() {
+ if (count >= 3800) {
+ reporter.report("You have " + count + " selectors. Internet Explorer supports a maximum of 4095 selectors per stylesheet. Consider refactoring.",0,0,rule);
+ }
+ });
+ }
+
+});
+CSSLint.addRule({
+ id: "selector-max",
+ name: "Error when past the 4095 selector limit for IE",
+ desc: "Will error when selector count is > 4095.",
+ browsers: "IE",
+ init: function(parser, reporter){
+ var rule = this, count = 0;
+
+ parser.addListener('startrule',function(event) {
+ count += event.selectors.length;
+ });
+
+ parser.addListener("endstylesheet", function() {
+ if (count > 4095) {
+ reporter.report("You have " + count + " selectors. Internet Explorer supports a maximum of 4095 selectors per stylesheet. Consider refactoring.",0,0,rule);
+ }
+ });
+ }
+
+});
+CSSLint.addRule({
+ id: "shorthand",
+ name: "Require shorthand properties",
+ desc: "Use shorthand properties where possible.",
+ browsers: "All",
+ init: function(parser, reporter){
+ var rule = this,
+ prop, i, len,
+ propertiesToCheck = {},
+ properties,
+ mapping = {
+ "margin": [
+ "margin-top",
+ "margin-bottom",
+ "margin-left",
+ "margin-right"
+ ],
+ "padding": [
+ "padding-top",
+ "padding-bottom",
+ "padding-left",
+ "padding-right"
+ ]
+ };
+ for (prop in mapping){
+ if (mapping.hasOwnProperty(prop)){
+ for (i=0, len=mapping[prop].length; i < len; i++){
+ propertiesToCheck[mapping[prop][i]] = prop;
+ }
+ }
+ }
+
+ function startRule(event){
+ properties = {};
+ }
+ function endRule(event){
+
+ var prop, i, len, total;
+ for (prop in mapping){
+ if (mapping.hasOwnProperty(prop)){
+ total=0;
+
+ for (i=0, len=mapping[prop].length; i < len; i++){
+ total += properties[mapping[prop][i]] ? 1 : 0;
+ }
+
+ if (total == mapping[prop].length){
+ reporter.report("The properties " + mapping[prop].join(", ") + " can be replaced by " + prop + ".", event.line, event.col, rule);
+ }
+ }
+ }
+ }
+
+ parser.addListener("startrule", startRule);
+ parser.addListener("startfontface", startRule);
+ parser.addListener("property", function(event){
+ var name = event.property.toString().toLowerCase(),
+ value = event.value.parts[0].value;
+
+ if (propertiesToCheck[name]){
+ properties[name] = 1;
+ }
+ });
+
+ parser.addListener("endrule", endRule);
+ parser.addListener("endfontface", endRule);
+
+ }
+
+});
+CSSLint.addRule({
+ id: "star-property-hack",
+ name: "Disallow properties with a star prefix",
+ desc: "Checks for the star property hack (targets IE6/7)",
+ browsers: "All",
+ init: function(parser, reporter){
+ var rule = this;
+ parser.addListener("property", function(event){
+ var property = event.property;
+
+ if (property.hack == "*") {
+ reporter.report("Property with star prefix found.", event.property.line, event.property.col, rule);
+ }
+ });
+ }
+});
+CSSLint.addRule({
+ id: "text-indent",
+ name: "Disallow negative text-indent",
+ desc: "Checks for text indent less than -99px",
+ browsers: "All",
+ init: function(parser, reporter){
+ var rule = this,
+ textIndent,
+ direction;
+
+
+ function startRule(event){
+ textIndent = false;
+ direction = "inherit";
+ }
+ function endRule(event){
+ if (textIndent && direction != "ltr"){
+ reporter.report("Negative text-indent doesn't work well with RTL. If you use text-indent for image replacement explicitly set direction for that item to ltr.", textIndent.line, textIndent.col, rule);
+ }
+ }
+
+ parser.addListener("startrule", startRule);
+ parser.addListener("startfontface", startRule);
+ parser.addListener("property", function(event){
+ var name = event.property.toString().toLowerCase(),
+ value = event.value;
+
+ if (name == "text-indent" && value.parts[0].value < -99){
+ textIndent = event.property;
+ } else if (name == "direction" && value == "ltr"){
+ direction = "ltr";
+ }
+ });
+
+ parser.addListener("endrule", endRule);
+ parser.addListener("endfontface", endRule);
+
+ }
+
+});
+CSSLint.addRule({
+ id: "underscore-property-hack",
+ name: "Disallow properties with an underscore prefix",
+ desc: "Checks for the underscore property hack (targets IE6)",
+ browsers: "All",
+ init: function(parser, reporter){
+ var rule = this;
+ parser.addListener("property", function(event){
+ var property = event.property;
+
+ if (property.hack == "_") {
+ reporter.report("Property with underscore prefix found.", event.property.line, event.property.col, rule);
+ }
+ });
+ }
+});
+CSSLint.addRule({
+ id: "unique-headings",
+ name: "Headings should only be defined once",
+ desc: "Headings should be defined only once.",
+ browsers: "All",
+ init: function(parser, reporter){
+ var rule = this;
+
+ var headings = {
+ h1: 0,
+ h2: 0,
+ h3: 0,
+ h4: 0,
+ h5: 0,
+ h6: 0
+ };
+
+ parser.addListener("startrule", function(event){
+ var selectors = event.selectors,
+ selector,
+ part,
+ pseudo,
+ i, j;
+
+ for (i=0; i < selectors.length; i++){
+ selector = selectors[i];
+ part = selector.parts[selector.parts.length-1];
+
+ if (part.elementName && /(h[1-6])/i.test(part.elementName.toString())){
+
+ for (j=0; j < part.modifiers.length; j++){
+ if (part.modifiers[j].type == "pseudo"){
+ pseudo = true;
+ break;
+ }
+ }
+
+ if (!pseudo){
+ headings[RegExp.$1]++;
+ if (headings[RegExp.$1] > 1) {
+ reporter.report("Heading (" + part.elementName + ") has already been defined.", part.line, part.col, rule);
+ }
+ }
+ }
+ }
+ });
+
+ parser.addListener("endstylesheet", function(event){
+ var prop,
+ messages = [];
+
+ for (prop in headings){
+ if (headings.hasOwnProperty(prop)){
+ if (headings[prop] > 1){
+ messages.push(headings[prop] + " " + prop + "s");
+ }
+ }
+ }
+
+ if (messages.length){
+ reporter.rollupWarn("You have " + messages.join(", ") + " defined in this stylesheet.", rule);
+ }
+ });
+ }
+
+});
+CSSLint.addRule({
+ id: "universal-selector",
+ name: "Disallow universal selector",
+ desc: "The universal selector (*) is known to be slow.",
+ browsers: "All",
+ init: function(parser, reporter){
+ var rule = this;
+
+ parser.addListener("startrule", function(event){
+ var selectors = event.selectors,
+ selector,
+ part,
+ modifier,
+ i, j, k;
+
+ for (i=0; i < selectors.length; i++){
+ selector = selectors[i];
+
+ part = selector.parts[selector.parts.length-1];
+ if (part.elementName == "*"){
+ reporter.report(rule.desc, part.line, part.col, rule);
+ }
+ }
+ });
+ }
+
+});
+CSSLint.addRule({
+ id: "unqualified-attributes",
+ name: "Disallow unqualified attribute selectors",
+ desc: "Unqualified attribute selectors are known to be slow.",
+ browsers: "All",
+ init: function(parser, reporter){
+ var rule = this;
+
+ parser.addListener("startrule", function(event){
+
+ var selectors = event.selectors,
+ selector,
+ part,
+ modifier,
+ i, j, k;
+
+ for (i=0; i < selectors.length; i++){
+ selector = selectors[i];
+
+ part = selector.parts[selector.parts.length-1];
+ if (part.type == parser.SELECTOR_PART_TYPE){
+ for (k=0; k < part.modifiers.length; k++){
+ modifier = part.modifiers[k];
+ if (modifier.type == "attribute" && (!part.elementName || part.elementName == "*")){
+ reporter.report(rule.desc, part.line, part.col, rule);
+ }
+ }
+ }
+
+ }
+ });
+ }
+
+});
+CSSLint.addRule({
+ id: "vendor-prefix",
+ name: "Require standard property with vendor prefix",
+ desc: "When using a vendor-prefixed property, make sure to include the standard one.",
+ browsers: "All",
+ init: function(parser, reporter){
+ var rule = this,
+ properties,
+ num,
+ propertiesToCheck = {
+ "-webkit-border-radius": "border-radius",
+ "-webkit-border-top-left-radius": "border-top-left-radius",
+ "-webkit-border-top-right-radius": "border-top-right-radius",
+ "-webkit-border-bottom-left-radius": "border-bottom-left-radius",
+ "-webkit-border-bottom-right-radius": "border-bottom-right-radius",
+
+ "-o-border-radius": "border-radius",
+ "-o-border-top-left-radius": "border-top-left-radius",
+ "-o-border-top-right-radius": "border-top-right-radius",
+ "-o-border-bottom-left-radius": "border-bottom-left-radius",
+ "-o-border-bottom-right-radius": "border-bottom-right-radius",
+
+ "-moz-border-radius": "border-radius",
+ "-moz-border-radius-topleft": "border-top-left-radius",
+ "-moz-border-radius-topright": "border-top-right-radius",
+ "-moz-border-radius-bottomleft": "border-bottom-left-radius",
+ "-moz-border-radius-bottomright": "border-bottom-right-radius",
+
+ "-moz-column-count": "column-count",
+ "-webkit-column-count": "column-count",
+
+ "-moz-column-gap": "column-gap",
+ "-webkit-column-gap": "column-gap",
+
+ "-moz-column-rule": "column-rule",
+ "-webkit-column-rule": "column-rule",
+
+ "-moz-column-rule-style": "column-rule-style",
+ "-webkit-column-rule-style": "column-rule-style",
+
+ "-moz-column-rule-color": "column-rule-color",
+ "-webkit-column-rule-color": "column-rule-color",
+
+ "-moz-column-rule-width": "column-rule-width",
+ "-webkit-column-rule-width": "column-rule-width",
+
+ "-moz-column-width": "column-width",
+ "-webkit-column-width": "column-width",
+
+ "-webkit-column-span": "column-span",
+ "-webkit-columns": "columns",
+
+ "-moz-box-shadow": "box-shadow",
+ "-webkit-box-shadow": "box-shadow",
+
+ "-moz-transform" : "transform",
+ "-webkit-transform" : "transform",
+ "-o-transform" : "transform",
+ "-ms-transform" : "transform",
+
+ "-moz-transform-origin" : "transform-origin",
+ "-webkit-transform-origin" : "transform-origin",
+ "-o-transform-origin" : "transform-origin",
+ "-ms-transform-origin" : "transform-origin",
+
+ "-moz-box-sizing" : "box-sizing",
+ "-webkit-box-sizing" : "box-sizing",
+
+ "-moz-user-select" : "user-select",
+ "-khtml-user-select" : "user-select",
+ "-webkit-user-select" : "user-select"
+ };
+ function startRule(){
+ properties = {};
+ num=1;
+ }
+ function endRule(event){
+ var prop,
+ i, len,
+ standard,
+ needed,
+ actual,
+ needsStandard = [];
+
+ for (prop in properties){
+ if (propertiesToCheck[prop]){
+ needsStandard.push({ actual: prop, needed: propertiesToCheck[prop]});
+ }
+ }
+
+ for (i=0, len=needsStandard.length; i < len; i++){
+ needed = needsStandard[i].needed;
+ actual = needsStandard[i].actual;
+
+ if (!properties[needed]){
+ reporter.report("Missing standard property '" + needed + "' to go along with '" + actual + "'.", properties[actual][0].name.line, properties[actual][0].name.col, rule);
+ } else {
+ if (properties[needed][0].pos < properties[actual][0].pos){
+ reporter.report("Standard property '" + needed + "' should come after vendor-prefixed property '" + actual + "'.", properties[actual][0].name.line, properties[actual][0].name.col, rule);
+ }
+ }
+ }
+
+ }
+
+ parser.addListener("startrule", startRule);
+ parser.addListener("startfontface", startRule);
+ parser.addListener("startpage", startRule);
+ parser.addListener("startpagemargin", startRule);
+ parser.addListener("startkeyframerule", startRule);
+
+ parser.addListener("property", function(event){
+ var name = event.property.text.toLowerCase();
+
+ if (!properties[name]){
+ properties[name] = [];
+ }
+
+ properties[name].push({ name: event.property, value : event.value, pos:num++ });
+ });
+
+ parser.addListener("endrule", endRule);
+ parser.addListener("endfontface", endRule);
+ parser.addListener("endpage", endRule);
+ parser.addListener("endpagemargin", endRule);
+ parser.addListener("endkeyframerule", endRule);
+ }
+
+});
+CSSLint.addRule({
+ id: "zero-units",
+ name: "Disallow units for 0 values",
+ desc: "You don't need to specify units when a value is 0.",
+ browsers: "All",
+ init: function(parser, reporter){
+ var rule = this;
+ parser.addListener("property", function(event){
+ var parts = event.value.parts,
+ i = 0,
+ len = parts.length;
+
+ while(i < len){
+ if ((parts[i].units || parts[i].type == "percentage") && parts[i].value === 0 && parts[i].type != "time"){
+ reporter.report("Values of 0 shouldn't have units specified.", parts[i].line, parts[i].col, rule);
+ }
+ i++;
+ }
+
+ });
+
+ }
+
+});
+(function() {
+ var xmlEscape = function(str) {
+ if (!str || str.constructor !== String) {
+ return "";
+ }
+
+ return str.replace(/[\"&><]/g, function(match) {
+ switch (match) {
+ case "\"":
+ return """;
+ case "&":
+ return "&";
+ case "<":
+ return "<";
+ case ">":
+ return ">";
+ }
+ });
+ };
+
+ CSSLint.addFormatter({
+ id: "checkstyle-xml",
+ name: "Checkstyle XML format",
+ startFormat: function(){
+ return "<?xml version=\"1.0\" encoding=\"utf-8\"?><checkstyle>";
+ },
+ endFormat: function(){
+ return "</checkstyle>";
+ },
+ readError: function(filename, message) {
+ return "<file name=\"" + xmlEscape(filename) + "\"><error line=\"0\" column=\"0\" severty=\"error\" message=\"" + xmlEscape(message) + "\"></error></file>";
+ },
+ formatResults: function(results, filename, options) {
+ var messages = results.messages,
+ output = [];
+ var generateSource = function(rule) {
+ if (!rule || !('name' in rule)) {
+ return "";
+ }
+ return 'net.csslint.' + rule.name.replace(/\s/g,'');
+ };
+
+
+
+ if (messages.length > 0) {
+ output.push("<file name=\""+filename+"\">");
+ CSSLint.Util.forEach(messages, function (message, i) {
+ if (!message.rollup) {
+ output.push("<error line=\"" + message.line + "\" column=\"" + message.col + "\" severity=\"" + message.type + "\"" +
+ " message=\"" + xmlEscape(message.message) + "\" source=\"" + generateSource(message.rule) +"\"/>");
+ }
+ });
+ output.push("</file>");
+ }
+
+ return output.join("");
+ }
+ });
+
+}());
+CSSLint.addFormatter({
+ id: "compact",
+ name: "Compact, 'porcelain' format",
+ startFormat: function() {
+ return "";
+ },
+ endFormat: function() {
+ return "";
+ },
+ formatResults: function(results, filename, options) {
+ var messages = results.messages,
+ output = "";
+ options = options || {};
+ var capitalize = function(str) {
+ return str.charAt(0).toUpperCase() + str.slice(1);
+ };
+
+ if (messages.length === 0) {
+ return options.quiet ? "" : filename + ": Lint Free!";
+ }
+
+ CSSLint.Util.forEach(messages, function(message, i) {
+ if (message.rollup) {
+ output += filename + ": " + capitalize(message.type) + " - " + message.message + "\n";
+ } else {
+ output += filename + ": " + "line " + message.line +
+ ", col " + message.col + ", " + capitalize(message.type) + " - " + message.message + "\n";
+ }
+ });
+
+ return output;
+ }
+});
+CSSLint.addFormatter({
+ id: "csslint-xml",
+ name: "CSSLint XML format",
+ startFormat: function(){
+ return "<?xml version=\"1.0\" encoding=\"utf-8\"?><csslint>";
+ },
+ endFormat: function(){
+ return "</csslint>";
+ },
+ formatResults: function(results, filename, options) {
+ var messages = results.messages,
+ output = [];
+ var escapeSpecialCharacters = function(str) {
+ if (!str || str.constructor !== String) {
+ return "";
+ }
+ return str.replace(/\"/g, "'").replace(/&/g, "&").replace(/</g, "<").replace(/>/g, ">");
+ };
+
+ if (messages.length > 0) {
+ output.push("<file name=\""+filename+"\">");
+ CSSLint.Util.forEach(messages, function (message, i) {
+ if (message.rollup) {
+ output.push("<issue severity=\"" + message.type + "\" reason=\"" + escapeSpecialCharacters(message.message) + "\" evidence=\"" + escapeSpecialCharacters(message.evidence) + "\"/>");
+ } else {
+ output.push("<issue line=\"" + message.line + "\" char=\"" + message.col + "\" severity=\"" + message.type + "\"" +
+ " reason=\"" + escapeSpecialCharacters(message.message) + "\" evidence=\"" + escapeSpecialCharacters(message.evidence) + "\"/>");
+ }
+ });
+ output.push("</file>");
+ }
+
+ return output.join("");
+ }
+});
+CSSLint.addFormatter({
+ id: "junit-xml",
+ name: "JUNIT XML format",
+ startFormat: function(){
+ return "<?xml version=\"1.0\" encoding=\"utf-8\"?><testsuites>";
+ },
+ endFormat: function() {
+ return "</testsuites>";
+ },
+ formatResults: function(results, filename, options) {
+
+ var messages = results.messages,
+ output = [],
+ tests = {
+ 'error': 0,
+ 'failure': 0
+ };
+ var generateSource = function(rule) {
+ if (!rule || !('name' in rule)) {
+ return "";
+ }
+ return 'net.csslint.' + rule.name.replace(/\s/g,'');
+ };
+ var escapeSpecialCharacters = function(str) {
+
+ if (!str || str.constructor !== String) {
+ return "";
+ }
+
+ return str.replace(/\"/g, "'").replace(/</g, "<").replace(/>/g, ">");
+
+ };
+
+ if (messages.length > 0) {
+
+ messages.forEach(function (message, i) {
+ var type = message.type === 'warning' ? 'error' : message.type;
+ if (!message.rollup) {
+ output.push("<testcase time=\"0\" name=\"" + generateSource(message.rule) + "\">");
+ output.push("<" + type + " message=\"" + escapeSpecialCharacters(message.message) + "\"><![CDATA[" + message.line + ':' + message.col + ':' + escapeSpecialCharacters(message.evidence) + "]]></" + type + ">");
+ output.push("</testcase>");
+
+ tests[type] += 1;
+
+ }
+
+ });
+
+ output.unshift("<testsuite time=\"0\" tests=\"" + messages.length + "\" skipped=\"0\" errors=\"" + tests.error + "\" failures=\"" + tests.failure + "\" package=\"net.csslint\" name=\"" + filename + "\">");
+ output.push("</testsuite>");
+
+ }
+
+ return output.join("");
+
+ }
+});
+CSSLint.addFormatter({
+ id: "lint-xml",
+ name: "Lint XML format",
+ startFormat: function(){
+ return "<?xml version=\"1.0\" encoding=\"utf-8\"?><lint>";
+ },
+ endFormat: function(){
+ return "</lint>";
+ },
+ formatResults: function(results, filename, options) {
+ var messages = results.messages,
+ output = [];
+ var escapeSpecialCharacters = function(str) {
+ if (!str || str.constructor !== String) {
+ return "";
+ }
+ return str.replace(/\"/g, "'").replace(/&/g, "&").replace(/</g, "<").replace(/>/g, ">");
+ };
+
+ if (messages.length > 0) {
+
+ output.push("<file name=\""+filename+"\">");
+ CSSLint.Util.forEach(messages, function (message, i) {
+ if (message.rollup) {
+ output.push("<issue severity=\"" + message.type + "\" reason=\"" + escapeSpecialCharacters(message.message) + "\" evidence=\"" + escapeSpecialCharacters(message.evidence) + "\"/>");
+ } else {
+ output.push("<issue line=\"" + message.line + "\" char=\"" + message.col + "\" severity=\"" + message.type + "\"" +
+ " reason=\"" + escapeSpecialCharacters(message.message) + "\" evidence=\"" + escapeSpecialCharacters(message.evidence) + "\"/>");
+ }
+ });
+ output.push("</file>");
+ }
+
+ return output.join("");
+ }
+});
+CSSLint.addFormatter({
+ id: "text",
+ name: "Plain Text",
+ startFormat: function() {
+ return "";
+ },
+ endFormat: function() {
+ return "";
+ },
+ formatResults: function(results, filename, options) {
+ var messages = results.messages,
+ output = "";
+ options = options || {};
+
+ if (messages.length === 0) {
+ return options.quiet ? "" : "\n\ncsslint: No errors in " + filename + ".";
+ }
+
+ output = "\n\ncsslint: There are " + messages.length + " problems in " + filename + ".";
+ var pos = filename.lastIndexOf("/"),
+ shortFilename = filename;
+
+ if (pos === -1){
+ pos = filename.lastIndexOf("\\");
+ }
+ if (pos > -1){
+ shortFilename = filename.substring(pos+1);
+ }
+
+ CSSLint.Util.forEach(messages, function (message, i) {
+ output = output + "\n\n" + shortFilename;
+ if (message.rollup) {
+ output += "\n" + (i+1) + ": " + message.type;
+ output += "\n" + message.message;
+ } else {
+ output += "\n" + (i+1) + ": " + message.type + " at line " + message.line + ", col " + message.col;
+ output += "\n" + message.message;
+ output += "\n" + message.evidence;
+ }
+ });
+
+ return output;
+ }
+});
+
+exports.CSSLint = CSSLint;
+
+});define('ace/worker/mirror', ['require', 'exports', 'module' , 'ace/document', 'ace/lib/lang'], function(require, exports, module) {
+
+
+var Document = require("../document").Document;
+var lang = require("../lib/lang");
+
+var Mirror = exports.Mirror = function(sender) {
+ this.sender = sender;
+ var doc = this.doc = new Document("");
+
+ var deferredUpdate = this.deferredUpdate = lang.delayedCall(this.onUpdate.bind(this));
+
+ var _self = this;
+ sender.on("change", function(e) {
+ doc.applyDeltas(e.data);
+ if (_self.$timeout)
+ return deferredUpdate.schedule(_self.$timeout);
+ _self.onUpdate();
+ });
+};
+
+(function() {
+
+ this.$timeout = 500;
+
+ this.setTimeout = function(timeout) {
+ this.$timeout = timeout;
+ };
+
+ this.setValue = function(value) {
+ this.doc.setValue(value);
+ this.deferredUpdate.schedule(this.$timeout);
+ };
+
+ this.getValue = function(callbackId) {
+ this.sender.callback(this.doc.getValue(), callbackId);
+ };
+
+ this.onUpdate = function() {
+ };
+
+ this.isPending = function() {
+ return this.deferredUpdate.isPending();
+ };
+
+}).call(Mirror.prototype);
+
+});
\ No newline at end of file
--- /dev/null
+/*!
+CSS3 ColorPicker (https://github.com/gruppler/CSS3-Colorpicker)
+v1.3.2
+Copyright (c) 2011 Craig Laparo (https://plus.google.com/114746898337682206892)
+Based on "PhotoShop-like JavaScript Color Picker"
+Copyright (c) 2007 John Dyer (http://johndyer.name)
+MIT style license
+
+Permission is hereby granted, free of charge, to any person
+obtaining a copy of this software and associated documentation
+files (the "Software"), to deal in the Software without
+restriction, including without limitation the rights to use,
+copy, modify, merge, publish, distribute, sublicense, and/or sell
+copies of the Software, and to permit persons to whom the
+Software is furnished to do so, subject to the following
+conditions:
+
+The above copyright notice and this permission notice shall be
+included in all copies or substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
+OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
+HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
+WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
+FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
+OTHER DEALINGS IN THE SOFTWARE.
+*/
+
+(function($){
+
+var PROP_NAME = 'css3colorpicker';
+var mainDivId = 'css3colorpicker-div';
+var colorDivClass = 'color';
+var cpDiv = $('<div id="' + mainDivId + '"></div>');
+cpDiv.swatchContainer = $('<div id="' + mainDivId + '-swatchContainer"></div>');
+cpDiv.swatches = $('<div id="' + mainDivId + '-swatches"></div>');
+cpDiv.addSwatchButton = $('<div id="' + mainDivId + '-add-swatch-button" title="Add Current Color to Swatches" class="tooltip"></div>');
+cpDiv.colorDiv = $('<div id="' + mainDivId + '-color" title="Choose Color and Close Color Picker" class="tooltip"></div>');
+cpDiv.oldColorDiv = $('<div id="' + mainDivId + '-colorOld" title="Revert to Previous Color" class="tooltip"></div>');
+cpDiv.d1Div = $('<div id="' + mainDivId + '-1d"></div>');
+cpDiv.d1Div.control = $('<div id="' + mainDivId + '-1dControl"></div>');
+cpDiv.d1Div.colorDiv = $('<div id="' + mainDivId + '-1dColor"></div>');
+cpDiv.d1Div.gradientDiv = $('<div id="' + mainDivId + '-1dGradient"></div>');
+cpDiv.d2Div = $('<div id="' + mainDivId + '-2d"></div>');
+cpDiv.d2Div.control = $('<div id="' + mainDivId + '-2dControl"></div>');
+cpDiv.d2Div.colorDiv = $('<div id="' + mainDivId + '-2dColor"></div>');
+cpDiv.d2Div.gradientDiv = $('<div id="' + mainDivId + '-2dGradient"></div>');
+cpDiv.alphaDiv = $('<div id="' + mainDivId + '-alpha"></div>');
+cpDiv.alphaDiv.control = $('<div id="' + mainDivId + '-alphaControl"></div>');
+cpDiv.inputContainerHSB = $('<ul id="' + mainDivId + '-inputContainer-hsv" class="css3colorpicker-inputContainer"></ul>');
+cpDiv.inputContainerRGBA = $('<ul id="' + mainDivId + '-inputContainer-rgba" class="css3colorpicker-inputContainer"></ul>');
+cpDiv.inputContainerHex = $('<ul id="' + mainDivId + '-inputContainer-hex" class="css3colorpicker-inputContainer"></ul>');
+cpDiv.inputs = {
+ h: $('<input type="text" data-mode="h" id="' + mainDivId + '-h"/>'),
+ s: $('<input type="text" data-mode="s" id="' + mainDivId + '-s"/>'),
+ v: $('<input type="text" data-mode="v" id="' + mainDivId + '-v"/>'),
+ r: $('<input type="text" id="' + mainDivId + '-r"/>'),
+ g: $('<input type="text" id="' + mainDivId + '-g"/>'),
+ b: $('<input type="text" id="' + mainDivId + '-b"/>'),
+ a: $('<input type="text" id="' + mainDivId + '-a"/>'),
+ hex: $('<input type="text" id="' + mainDivId + '-hex" maxlength="8" />')
+}
+cpDiv.append(
+ $('<div id="' + mainDivId + '-container"></div>').append(
+ $('<div id="' + mainDivId + '-colorContainer"></div>').append(
+ cpDiv.colorDiv,
+ cpDiv.oldColorDiv
+ ),
+ cpDiv.d1Div.append(cpDiv.d1Div.colorDiv, cpDiv.d1Div.gradientDiv, cpDiv.d1Div.control),
+ cpDiv.d2Div.append(cpDiv.d2Div.colorDiv, cpDiv.d2Div.gradientDiv, cpDiv.d2Div.control),
+ cpDiv.alphaDiv.append(cpDiv.alphaDiv.control),
+ cpDiv.inputContainerHSB.append(
+ $('<li>H <span>°</span></li>').append(cpDiv.inputs.h),
+ $('<li>S <span>%</span></li>').append(cpDiv.inputs.s),
+ $('<li>B <span>%</span></li>').append(cpDiv.inputs.v)
+ ),
+ cpDiv.inputContainerRGBA.append(
+ $('<li>R </li>').append(cpDiv.inputs.r),
+ $('<li>G </li>').append(cpDiv.inputs.g),
+ $('<li>B </li>').append(cpDiv.inputs.b),
+ $('<li class="alpha">A <span>%</span></li>').append(cpDiv.inputs.a)
+ ),
+ cpDiv.inputContainerHex.append(
+ $('<li># </li>').append(cpDiv.inputs.hex)
+ )
+ ),
+ cpDiv.swatchContainer.append(cpDiv.swatches, cpDiv.addSwatchButton)
+);
+
+function Colorpicker(){
+ this._mainDivId = mainDivId;
+ this._colorDivClass = colorDivClass;
+
+ this._defaults = {
+ // Options
+ showAnim: true, // Fade in/out
+ duration: 200, // Fade duration
+ color: 'FFFFFF', // Default color
+ allowNull: false, // Allow an empty color value; otherwise default
+ // to the default color
+ realtime: true, // Update instantly
+ invertControls: true, // Invert color of mouse controls based on luminance
+ controlStyle: 'simple', // Mouse control theme [simple|raised|inset];
+ // separate multiple themes with a space
+ swatches: true, // [true|false] to enable/disable,
+ // or an array of hex codes to pre-fill
+ alpha: false, // [true|false] to enable/disable alpha
+ alphaHex: false, // [true|false] to enable/disable 4-byte hex
+ // in the format '#AARRGGBB'
+
+ // Events
+ beforeShow: null, // Fired before the color picker is shown
+ onClose: null, // Fired when the color picker is hidden
+ onSelect: null, // Fired when the color is set
+ onAddSwatch: null, // Fired when a new color swatch is added
+ onDeleteSwatch: null
+ };
+};
+
+$.extend(Colorpicker.prototype, {
+ cpDiv: cpDiv,
+ mode: 'h', // [h|s|v]
+ markerClassName: 'hasColorpicker',
+ controlsClassPrefix: 'controls-',
+ minLum: 50,
+ swatches: [],
+ swatchLimit: 15,
+
+
+ setDefaults: function(settings){
+ extendRemove(this._defaults, settings || {});
+ return this;
+ },
+
+ _setMode: function(mode){
+ if(['h','s','v'].indexOf(mode) >= 0){
+ this.cpDiv.removeClass('mode-' + this.mode);
+ this.cpDiv.addClass('mode-' + mode);
+ this.mode = mode;
+ $.colorpicker._updateMaps();
+ $.colorpicker._updateControls();
+ }
+ },
+
+ refresh: function(){
+ this._updateColorpicker(true);
+ return this;
+ },
+
+ color: function(args){
+ this.r = 0;
+ this.g = 0;
+ this.b = 0;
+ this.a = 1;
+
+ this.h = 0;
+ this.s = 0;
+ this.v = 0;
+ this.l = 0;
+
+ this.hex = '';
+ this.hexa = '';
+ this.rgb = 'rgb(0,0,0)';
+ this.rgba = 'rgba(0,0,0,1)';
+
+ // Floating-point
+ this._a = 1;
+ this._h = 0;
+ this._s = 0;
+ this._v = 0;
+
+ this.setRgb = function(r, g, b, a){
+ this.isNull = false;
+
+ this.r = Math.max(0, Math.min(255, Math.round(r)));
+ this.g = Math.max(0, Math.min(255, Math.round(g)));
+ this.b = Math.max(0, Math.min(255, Math.round(b)));
+ this._a = !isset(a) ? this._a || 100 : Math.max(0, Math.min(100, parseFloat(a)));
+ this.a = Math.round(this._a);
+
+ var newHsv = $.colorpicker.rgbToHsv(this);
+ this._h = newHsv.h;
+ this._s = newHsv.s;
+ this._v = newHsv.v;
+ this.h = Math.round(newHsv.h);
+ this.s = Math.round(newHsv.s);
+ this.v = Math.round(newHsv.v);
+ this.l = $.colorpicker.rgbToLum(this);
+
+ this.hex = $.colorpicker.rgbToHex(this);
+ this.hexa = $.colorpicker.rgbToHex(this);
+ this.rgb = 'rgb('+this.r+','+this.g+','+this.b+')';
+ this.rgba = 'rgba('+this.r+','+this.g+','+this.b+','+this.a/100+')';
+ };
+
+ this.setHsv = function(h, s, v, a){
+ this.isNull = false;
+
+ this._h = Math.max(0, Math.min(360, parseFloat(h)));
+ this._s = Math.max(0, Math.min(100, parseFloat(s)));
+ this._v = Math.max(0, Math.min(100, parseFloat(v)));
+ this.h = Math.round(this._h);
+ this.s = Math.round(this._s);
+ this.v = Math.round(this._v);
+ this._a = !isset(a) ? this._a || 100 : Math.max(0, Math.min(100, parseFloat(a)));
+ this.a = Math.round(this._a);
+
+ var newRgb = $.colorpicker.hsvToRgb(this);
+ this.r = Math.round(newRgb.r);
+ this.g = Math.round(newRgb.g);
+ this.b = Math.round(newRgb.b);
+ this.l = $.colorpicker.rgbToLum(this);
+
+ this.hex = $.colorpicker.rgbToHex(newRgb);
+ this.hexa = $.colorpicker.rgbToHex(newRgb);
+ this.rgb = 'rgb('+this.r+','+this.g+','+this.b+')';
+ this.rgba = 'rgba('+this.r+','+this.g+','+this.b+','+this.a/100+')';
+ };
+
+ this.setHex = function(hex){
+ this.isNull = false;
+
+ this.hexa = $.colorpicker.validateHex(hex);
+ this.hex = $.colorpicker.validateHex(hex);
+
+ var newRgb = $.colorpicker.hexToRgb(this.hexa);
+ this.r = newRgb.r;
+ this.g = newRgb.g;
+ this.b = newRgb.b;
+ this._a = newRgb.a;
+ this.a = Math.round(newRgb.a);
+
+ var newHsv = $.colorpicker.rgbToHsv(newRgb);
+ this._h = newHsv.h;
+ this._s = newHsv.s;
+ this._v = newHsv.v;
+ this.h = Math.round(newHsv.h);
+ this.s = Math.round(newHsv.s);
+ this.v = Math.round(newHsv.v);
+ this.l = $.colorpicker.rgbToLum(this);
+
+ this.rgb = 'rgb('+this.r+','+this.g+','+this.b+')';
+ this.rgba = 'rgba('+this.r+','+this.g+','+this.b+','+this.a/100+')';
+ };
+
+ if(args){
+ if('hexa' in args){
+ this.setHex(args.hexa);
+ }else if('hex' in args){
+ this.setHex(args.hex);
+ }else if('rgb' in args){
+ var rgb = args.rgb.match(/^rgba?\((\d+),\s*(\d+),\s*(\d+)(?:,\s*(0?\.?\d+))?\)/i);
+ if(rgb){
+ var a = 100;
+ if(typeof(rgb[4]) !== 'undefined'){
+ a *= rgb[4];
+ }
+ this.setRgb(rgb[1], rgb[2], rgb[3], a);
+ }
+ }else if('r' in args){
+ this.setRgb(args.r, args.g, args.b, args.a);
+ }else if('h' in args){
+ this.setHsv(args.h, args.s, args.v, args.a);
+ }
+ }
+
+ return this;
+ },
+
+ _attachColorpicker: function(target, settings){
+ var input = $(target);
+ if(input.hasClass(this.markerClassName)){
+ return;
+ }
+ input.addClass(this._colorDivClass).addClass(this.markerClassName);
+ if(!target.id){
+ this.uuid += 1;
+ target.id = 'cp' + this.uuid;
+ }
+
+ // check for settings on the control itself - in namespace 'color:'
+ var inlineSettings = null;
+ for(var attrName in this._defaults){
+ var attrValue = target.getAttribute('color:' + attrName);
+ if(attrValue){
+ inlineSettings = inlineSettings || {};
+ try{
+ inlineSettings[attrName] = eval(attrValue);
+ }catch(err){
+ inlineSettings[attrName] = attrValue;
+ }
+ }
+ }
+
+ var inst = this._newInst(input);
+ inst.settings = $.extend({}, settings || {}, inlineSettings || {});
+ if(this._get(inst, 'alpha')){
+ input.addClass('alpha')[inst.settings.alphaHex ? 'addClass' : 'removeClass']('alphaHex');
+ }else{
+ input.removeClass('alpha').removeClass('alphaHex');
+ }
+ this._setColor(inst, input.val() || input.data('color') || this._get(inst, 'color'), true);
+
+ var swatches = this._get(inst, 'swatches');
+ if(swatches){
+ this.addSwatch(swatches);
+ //this.addSwatch(inst.settings.color, true);
+ }
+
+ if(input.is("input")){
+ input.focus(function(){
+ $.colorpicker._showColorpicker(target);
+ }).keyup(function(){
+ $.colorpicker._setColor(inst, this.value);
+ $.colorpicker._updateColorpicker();
+ }).bind("setData.colorpicker", function(e, key, value) {
+ inst.settings[key] = value;
+ }).bind("getData.colorpicker", function(e, key) {
+ return $.colorpicker._get(inst, key);
+ });
+ }
+
+ input.click(function(){
+ $.colorpicker._showColorpicker(target);
+ }).bind("refresh", function(){
+ var $this = $(this);
+ var inst = $.colorpicker._getInst(this);
+ $.colorpicker._setColor(inst, input.val() || input.data('color') || $.colorpicker._get(inst, 'color').hexa, true);
+ $.colorpicker._updateColorpicker();
+ });
+ },
+
+ _setColor: function(inst, color, force){
+ if(!color || color.isNull){
+ color = new $.colorpicker.color({hex:this._defaults.color});
+ color.isNull = this._get(inst, 'allowNull');
+ }
+ if(typeof(color) == 'string' || typeof(color) == 'number'){
+ if (color.match(/^rgb/)) {
+ color = new $.colorpicker.color({rgb:color});
+ } else {
+ color = new $.colorpicker.color({hex:color});
+ }
+ }
+
+ inst.settings.color = new $.colorpicker.color({hex:color.hexa});
+ if(!this._isDragging){
+ inst.color = new $.colorpicker.color({hex:color.hexa});
+ }
+ inst.color.isNull = inst.settings.color.isNull = color.isNull;
+ this._updateTarget(inst, force);
+
+ if(!this._isLastColor(color)){
+ inst.lastColor = color.isNull ? null : color.hexa;
+ var onSelect = this._get(inst, 'onSelect');
+ if(typeof(onSelect) == 'function'){
+ onSelect(color.isNull ? null : color, inst);
+ }
+ }
+ },
+
+ _newInst: function(target){
+ var id = target[0].id.replace(/([^F-Za-z0-9_-])/g, '\\\\$1');
+ var inst = {
+ id: id,
+ input: target,
+ cpDiv: cpDiv,
+ color: new $.colorpicker.color(),
+ lastColor: null
+ };
+ target.data(PROP_NAME, inst);
+ return inst;
+ },
+
+ _checkExternalClick: function(e){
+ if(!$.colorpicker._curInst){
+ return;
+ }
+ var $target = $(e.target);
+ if($target[0].id != $.colorpicker._mainDivId &&
+ !$target.is('label[for="'+$.colorpicker._curInst.input[0].id+'"]') &&
+ $target.parents('#' + $.colorpicker._mainDivId).length == 0 &&
+ !$target.hasClass($.colorpicker.markerClassName)
+ ){
+ $.colorpicker._hideColorpicker();
+ }
+ },
+
+ _optionColorpicker: function(target, name, value){
+ var inst = this._getInst(target);
+ var show = false;
+ if(arguments.length == 2 && typeof name == 'string'){
+ return (name == 'defaults' ? $.extend({}, $.colorpicker._defaults) :
+ (inst ? (name == 'all' ? $.extend({}, inst.settings) :
+ this._get(inst, name)) : null));
+ }
+ if(inst && this._curInst == inst){
+ this._hideColorpicker(target, true);
+ show = true;
+ }
+ var settings = name || {};
+ if(typeof name == 'string'){
+ settings = {};
+ if(inst && name == 'color' && isset(value)){
+ var color = value ? new this.color({hex:value}) : new this.color({hex:this._defaults.color});
+ color.isNull = !value && this._get(inst, 'allowNull');
+ value = color;
+ this._setColor(inst, value, true);
+ this.addSwatch(value, true);
+ }
+ if(name == 'swatches' && value){
+ this.addSwatch(value);
+ }
+ settings[name] = value;
+ }
+ if(inst){
+ extendRemove(inst.settings, settings);
+ }
+ if(show){
+ this._showColorpicker(target, true);
+ }
+ },
+
+ _showColorpicker: function(input, noAnim){
+ input = input.target || input;
+ var $input = $(input);
+ if(input.disabled){
+ return;
+ }
+ var inst = $.colorpicker._getInst(input);
+ if(this._curInst && this._curInst != inst){
+ this._triggerOnClose();
+ this.cpDiv.stop(true, true);
+ }
+ this._curInst = inst;
+ inst.lastColor = inst.color.isNull ? null : inst.color.hexa;
+ var a = this._get(inst, 'alpha');
+ $.colorpicker._updateColorpicker();
+ inst.input.addClass('selected');
+
+ var showAnim = !noAnim && this._get(inst, 'showAnim');
+ var duration = this._get(inst, 'duration');
+ var postProcess = function(){
+ $.colorpicker.cpDiv.addClass('visible');
+ };
+
+ var styles = $.colorpicker._get(inst, 'controlStyle').split(/\s+/);
+ for(var i = 0; i < styles.length; i++){
+ cpDiv.addClass(this.controlsClassPrefix + styles[i]);
+ }
+ cpDiv[a?'addClass':'removeClass']('alphaOn');
+ cpDiv[this._get(inst, 'swatches')?'addClass':'removeClass']('swatchesOn');
+ this.cpDiv.oldColorDiv.data('color', inst.color.isNull ? null : inst.color.hexa).css('background-color', inst.color[a?'rgba':'rgb']);
+
+ var beforeShow = this._get(inst, 'beforeShow');
+ if(typeof(beforeShow) == 'function'){
+ beforeShow(inst.input, inst);
+ }
+
+ this._colorpickerShowing = true;
+ this.cpDiv[showAnim ? 'fadeIn' : 'show']((showAnim ? duration : null), postProcess);
+ if(!showAnim){
+ postProcess();
+ }
+
+ this._positionColorpicker();
+ },
+
+ _positionColorpicker: function(){
+ var $input = $.colorpicker._curInst.input;
+ var cpDiv = this.cpDiv;
+ var offset = $input.offset();
+ var width = cpDiv.outerWidth();
+ var height = cpDiv.defaultHeight + (this._get(this._getInst($input), 'alpha') ? cpDiv.alphaHeight : 0) + (this._get(this._getInst($input), 'swatches') ? cpDiv.swatchHeight : 0);
+ var winWidth = $(window).width();
+ var winHeight = $(window).height();
+ var margin = 10;
+ height += margin;
+ offset.left += $input.outerWidth() + margin;
+ if(offset.top + height > winHeight){
+ offset.top = winHeight - height;
+ }
+ if(offset.left + width > winWidth){
+ offset.left = winWidth - width;
+ }
+ cpDiv.css({top:0, left:0}).offset(offset);
+ },
+
+ _hideColorpicker: function(input, noAnim){
+ var inst = this._curInst;
+ if(!inst || (input && inst != this._getInst(input))){
+ return;
+ }
+ var postProcess = function(){
+ $.colorpicker._triggerOnClose();
+ $.colorpicker._curInst = null;
+ };
+ if(this._colorpickerShowing){
+ var showAnim = !noAnim && this._get(inst, 'showAnim');
+ var duration = this._get(inst, 'duration');
+ this.cpDiv[showAnim ? 'fadeOut' : 'hide']((showAnim ? duration : null), postProcess);
+ if(!showAnim){
+ postProcess();
+ }
+ this.cpDiv.removeClass('visible');
+ this._colorpickerShowing = false;
+
+ var onClose = this._get(inst, 'onClose');
+ if(typeof(onClose) == 'function'){
+ onClose(inst.color, inst);
+ }
+ }else{
+ postProcess();
+ }
+ },
+
+ _triggerOnClose: function(){
+ var inst = this._curInst;
+ if(!inst){
+ return;
+ }
+ inst.input.removeClass('selected');
+ $.colorpicker.addSwatch(inst.color, true);
+ this._setColor(inst, inst.color);
+ cpDiv.removeClass(this.controlsClassPrefix+'invert');
+
+ var styles = $.colorpicker._get(inst, 'controlStyle').split(/\s+/);
+ for(var i = 0; i < styles.length; i++){
+ cpDiv.removeClass(this.controlsClassPrefix + styles[i]);
+ }
+ },
+
+ _updateColorpicker: function(force){
+ var inst = this._curInst;
+ if(!inst){
+ return;
+ }
+ var a = this._get(inst, 'alpha');
+ this.cpDiv.colorDiv.data('color', inst.color.isNull ? null : inst.color.hexa).css('background-color', inst.color[a?'rgba':'rgb']);
+ cpDiv.d2Div.control.css('background-color', inst.color.rgb);
+ $.colorpicker._updateInputs(force);
+ $.colorpicker._updateMaps();
+ $.colorpicker._updateControls();
+ if(this._get(inst, 'realtime')){
+ this._setColor(inst, inst.color, force);
+ }
+ },
+
+ _updateTarget: function(inst, force){
+ var a = this._get(inst, 'alpha');
+ var ah = this._get(inst, 'alphaHex');
+ if(inst.color.isNull){
+ inst.input.parent().addClass('color-null');
+ }else{
+ inst.input.css({
+ backgroundColor: inst.color[a?'rgba':'rgb'],
+ color: (inst.color.l < $.colorpicker.minLum) ? '#fff' : '#000'
+ }).parent().removeClass('color-null');
+ }
+
+ inst.input.data('color', inst.color.isNull ? null : inst.color.hexa);
+ if(force || !inst.input.is(':focus')){
+ var val = inst.input.val() || '';
+ if(inst.color.isNull){
+ inst.input.val('');
+ }else{
+ inst.input.val(
+ val.indexOf('#') >= 0 ?
+ '#' + inst.color[ah?'hexa':'hex'] :
+ inst.color[ah?'hexa':'hex']
+ )
+ }
+ if(val != inst.input.val()){
+ inst.input.trigger('change');
+ }
+ }
+ },
+
+ _updateInputs: function(force){
+ var inst = this._curInst;
+ if(!inst){
+ return;
+ }
+ var ah = this._get(inst, 'alphaHex');
+ for(var i in this.cpDiv.inputs){
+ if(i && isset(inst.color[i])){
+ if(force || !this.cpDiv.inputs[i].is(':focus')){
+ if(i == 'hex'){
+ this.cpDiv.inputs[i].val(inst.color.isNull ? '' : inst.color[ah ? 'hexa' : i]);
+ }else{
+ this.cpDiv.inputs[i].val(inst.color[i]);
+ }
+ }
+ }
+ }
+ },
+
+ _updateMaps: function(){
+ var inst = this._curInst;
+ if(!inst){
+ return;
+ }
+ this.cpDiv.alphaDiv.css('background-color', inst.color.rgb);
+ switch(this.mode){
+ case 'h':
+ this.cpDiv.d1Div.gradientDiv.css('background', '');
+ this.cpDiv.d2Div.colorDiv.css('background-color', new this.color({
+ h: inst.color.h,
+ s: 100,
+ v: 100
+ }).rgb);
+ this.cpDiv.d1Div.gradientDiv.css('opacity', 1 - inst.color.v/100);
+ this.cpDiv.d1Div.colorDiv.css('opacity', inst.color.s/100);
+ this.cpDiv.d2Div.colorDiv.css('opacity', 1);
+ this.cpDiv.d2Div.gradientDiv.css('opacity', 1);
+ break;
+
+ case 's':
+ this.cpDiv.d1Div.colorDiv.css('background-color', new this.color({
+ h: inst.color.h,
+ s: 100,
+ v: 100
+ }).rgb);
+ this.cpDiv.d1Div.gradientDiv.css('opacity', 1 - inst.color.v/100);
+ this.cpDiv.d1Div.colorDiv.css('opacity', 1);
+ this.cpDiv.d2Div.colorDiv.css('opacity', inst.color.s/100);
+ this.cpDiv.d2Div.gradientDiv.css('opacity', 1);
+ break;
+
+ case 'v':
+ this.cpDiv.d1Div.gradientDiv.css('background', '');
+ this.cpDiv.d1Div.colorDiv.css('background-color', new this.color({
+ h: inst.color.h,
+ s: inst.color.s,
+ v: 100
+ }).rgb);
+ this.cpDiv.d1Div.gradientDiv.css('opacity', 1);
+ this.cpDiv.d1Div.colorDiv.css('opacity', 1);
+ this.cpDiv.d2Div.colorDiv.css('opacity', 1);
+ this.cpDiv.d2Div.gradientDiv.css('opacity', 1 - inst.color.v/100);
+ break;
+ }
+ $.colorpicker._updateControl();
+ },
+
+ _updateControls: function(){
+ if(!this._curInst || this._isDragging){
+ return;
+ }
+ var inst = this._curInst;
+
+ var x, y, z, a;
+ switch(this.mode){
+ case 'h':
+ x = inst.color._s*255/100;
+ y = 255 - inst.color._v*255/100;
+ z = 255 - inst.color._h*255/360;
+ a = inst.color._a*255/100;
+ break;
+
+ case 's':
+ x = inst.color._h*255/360;
+ y = 255 - inst.color._v*255/100;
+ z = 255 - inst.color._s*255/100;
+ a = inst.color._a*255/100;
+ break;
+
+ case 'v':
+ x = inst.color._h*255/360;
+ y = 255 - inst.color._s*255/100;
+ z = 255 - inst.color._v*255/100;
+ a = inst.color._a*255/100;
+ break;
+ }
+
+ $.colorpicker._moveControl1d(z, true);
+ $.colorpicker._moveControl2d(x, y, true);
+ $.colorpicker._moveControlAlpha(a, true);
+ },
+
+ _moveControl1d: function(z, moveOnly){
+ if(!$.colorpicker._curInst) return;
+ var inst = $.colorpicker._curInst;
+
+ cpDiv.d1Div.control.css({top: Math.max(0, Math.min(255, Math.round(z)))+'px'});
+
+ if(!moveOnly){
+ switch($.colorpicker.mode){
+ case 'h':
+ z = 360 - z*360/256;
+ break;
+
+ case 's':
+ case 'v':
+ z = 100 - z*100/256;
+ break;
+ }
+
+ inst.color['_'+$.colorpicker.mode] = z;
+ inst.color.setHsv(inst.color._h, inst.color._s, inst.color._v, inst.color.a);
+ $.colorpicker._updateColorpicker(true);
+ }
+ },
+
+ _moveControl2d: function(x, y, moveOnly){
+ if(!$.colorpicker._curInst) return;
+ var inst = $.colorpicker._curInst;
+
+ cpDiv.d2Div.control.css({
+ left: Math.max(0, Math.min(255, Math.round(x)))+'px',
+ top: Math.max(0, Math.min(255, Math.round(y)))+'px'
+ });
+
+ if(!moveOnly){
+ switch($.colorpicker.mode){
+ case 'h':
+ x = x*100/256;
+ y = 100 - y*100/256;
+ inst.color._s = x;
+ inst.color._v = y;
+ break;
+
+ case 's':
+ case 'v':
+ x = x*360/256;
+ y = 100 - y*100/256;
+ inst.color._h = x;
+ inst.color[$.colorpicker.mode == 's' ? '_v' : '_s'] = y;
+ break;
+ }
+
+ inst.color.setHsv(inst.color._h, inst.color._s, inst.color._v, inst.color.a);
+ $.colorpicker._updateColorpicker(true);
+ }
+ },
+
+ _moveControlAlpha: function(a, moveOnly){
+ if(!$.colorpicker._curInst) return;
+ var inst = $.colorpicker._curInst;
+
+ cpDiv.alphaDiv.control.css({left: Math.max(0, Math.min(255, parseInt(a)))+'px'});
+
+ if(!moveOnly){
+ a *= 100/256;
+
+ inst.color.a = a;
+ inst.color.setHsv(inst.color._h, inst.color._s, inst.color._v, inst.color.a);
+ $.colorpicker._updateColorpicker(true);
+ }
+ },
+
+ _mousemoveControl1d: function(e){
+ $.colorpicker._moveControl1d(
+ e.pageY - $.colorpicker.cpDiv.d1Div.offset().top
+ );
+ e.preventDefault();
+ return false;
+ },
+
+ _mousemoveControl2d: function(e){
+ var offset = $.colorpicker.cpDiv.d2Div.offset();
+ $.colorpicker._moveControl2d(
+ e.pageX - offset.left,
+ e.pageY - offset.top
+ );
+ e.preventDefault();
+ return false;
+ },
+
+ _mousemoveControlAlpha: function(e){
+ $.colorpicker._moveControlAlpha(
+ e.pageX - $.colorpicker.cpDiv.alphaDiv.offset().left
+ );
+ e.preventDefault();
+ return false;
+ },
+
+ _updateControl: function(){
+ if(!this._curInst || !$.colorpicker._get(this._curInst, 'invertControls')){
+ return false;
+ }
+
+ if(this._curInst.color.l < $.colorpicker.minLum){
+ cpDiv.addClass(this.controlsClassPrefix+'invert');
+ }else{
+ cpDiv.removeClass(this.controlsClassPrefix+'invert');
+ }
+ },
+
+ _submit: function(color, isSwatch){
+ var inst = this._curInst;
+ if(!inst){
+ return;
+ }
+
+ if(!isset(color)){
+ var color = inst.color,
+ isNull = color.isNull && this._get(inst, 'allowNull');
+ }else if(!color){
+ var isNull = this._get(inst, 'allowNull');
+ color = this._defaults.color;
+ }
+
+ if(typeof(color) == 'string' || typeof(color) == 'number'){
+ color = new this.color({hex:color});
+ if(!this._get(inst, 'alpha')){
+ color.a = color._a = 100;
+ }
+ }else{
+ color = new this.color({hex:color[this._get(inst, 'alpha') ? 'hexa' : 'hex']});
+ }
+ color.isNull = isNull;
+
+ if(this._isCurrentColor(color)){
+ $.colorpicker._hideColorpicker();
+ isSwatch = true;
+ }else{
+ $.colorpicker._setColor(inst, color, true);
+ $.colorpicker._updateColorpicker(true);
+ }
+
+ $.colorpicker.addSwatch(color, isSwatch);
+ },
+
+ _isCurrentColor: function(color){
+ var inst = this._curInst;
+ if(!inst){
+ return;
+ }
+ if(!color || color.isNull){
+ return inst.settings.color.isNull && inst.color.isNull;
+ }
+ if(typeof(color) == 'string' || typeof(color) == 'number'){
+ color = new this.color({hex:color});
+ }
+ return this._get(inst, 'alpha') ? (
+ color.hexa == inst.settings.color.hexa &&
+ color.hexa == inst.color.hexa
+ ) : (
+ color.hex == inst.settings.color.hex &&
+ color.hex == inst.color.hex
+ );
+ },
+
+ _isLastColor: function(color){
+ var inst = this._curInst;
+ if(!inst){
+ return;
+ }
+ if(!color || color.isNull){
+ return inst.lastColor === null;
+ }
+ var lastColor = new this.color({hex: inst.lastColor});
+
+ if(typeof(color) == 'string' || typeof(color) == 'number'){
+ color = new this.color({hex:color});
+ }
+ return this._get(inst, 'alpha')
+ ? color.hexa == lastColor.hexa
+ : color.hex == lastColor.hex;
+ },
+
+ addSwatch: function(color, newOnly){
+ var inst = this._curInst;
+ if(inst && !this._get(inst, 'swatches') || !color || color.isNull){
+ return false;
+ }
+ if(typeof(color) == 'string' || typeof(color) == 'number'){
+ color = new this.color({hex:color});
+ }
+ if(color.hexa){
+ var index = this.swatches.indexOf(color.hexa);
+ if(index < 0){
+ this.swatches.unshift(color.hexa);
+ var swatch = $('<div/>')
+ .addClass('swatch')
+ .attr('title', 'Right-click to delete swatch')
+ .data('color', color.hexa)
+ .css({
+ backgroundColor: color.rgb,
+ width: 0,
+ opacity: 0
+ })
+ .append($('<div/>').css('background', color.rgba));
+ window.setTimeout(function(){
+ swatch.css({
+ width: '',
+ opacity: 1
+ });
+ },0);
+ this.cpDiv.swatches.prepend(swatch);
+ }else{
+ if(newOnly){
+ return false;
+ }
+ this.swatches.splice(index, 1);
+ this.swatches.unshift(color.hexa);
+ this.cpDiv.swatches.prepend(this.cpDiv.swatches.children().eq(index));
+ }
+ if(this.swatchLimit){
+ this.swatches = this.swatches.slice(0, this.swatchLimit);
+ }
+
+ var onAddSwatch = inst ?
+ this._get(inst, 'onAddSwatch'):
+ this._defaults.onAddSwatch;
+ if(typeof(onAddSwatch) == 'function'){
+ onAddSwatch(color, this.swatches);
+ }
+ }else if(color.length && color[0]){
+ for(var i = color.length - 1; i >= 0; i--){
+ this.addSwatch(color[i]);
+ }
+ }
+ return this;
+ },
+
+ deleteSwatch: function(swatch) {
+
+ var swatch = $(swatch);
+
+ if ( typeof swatch != 'object' || !swatch || !swatch.length )
+ return false;
+
+ this.swatches.splice(this.swatches.indexOf(swatch.data('color')), 1);
+
+ /* Fire callback */
+ var inst = this._curInst;
+
+ var onDeleteSwatch = inst ?
+ this._get(inst, 'onDeleteSwatch'):
+ this._defaults.onDeleteSwatch;
+
+ if ( typeof(onDeleteSwatch) == 'function' )
+ onDeleteSwatch(swatch.data('color'), this.swatches);
+
+ /* Remove swatch element */
+ swatch.remove();
+
+ },
+
+ clearSwatches: function(){
+ this.swatches = [];
+ this.cpDiv.swatches.empty();
+ return this;
+ },
+
+ _useSwatch: function(e){
+ $.colorpicker._setColor($.colorpicker._curInst, $(this).data('color'));
+ $.colorpicker._updateColorpicker();
+ e.preventDefault();
+ return false;
+ },
+
+ _get: function(inst, key){
+ return isset(inst.settings[key]) ? inst.settings[key] : this._defaults[key];
+ },
+
+ _getInst: function(target){
+ try{
+ return $(target).data(PROP_NAME);
+ }catch(e){
+ throw 'Missing instance data for this colorpicker';
+ }
+ },
+
+ // Color functions
+
+ hexToRgb: function(hex){
+ hex = this.validateHex(hex);
+
+ var r='00', g='00', b='00';
+
+ if(hex.length == 6){
+ a = 'FF';
+ r = hex.substring(0,2);
+ g = hex.substring(2,4);
+ b = hex.substring(4,6);
+ }
+ if(hex.length == 8){
+ a = hex.substring(0,2);
+ r = hex.substring(2,4);
+ g = hex.substring(4,6);
+ b = hex.substring(6,8);
+ }
+
+ return { r:this.hexToInt(r), g:this.hexToInt(g), b:this.hexToInt(b), a:(100*this.hexToInt(a)/255) };
+ },
+
+ _hexRegExp: /[a-f0-9]{0,2}([a-f0-9]{6})|[a-f0-9]?([a-f0-9]{3})/i,
+ _hexaRegExp: /([a-f0-9]{8}|[a-f0-9]{6}|[a-f0-9]{4}|[a-f0-9]{3})/i,
+
+ validateHex: function(hex){
+ if(!hex) return false;
+ hex = (''+hex).match(this._hexaRegExp);
+ hex = hex ? (hex[1] || hex[2]) : ('00000000');
+
+ hex = hex.toUpperCase();
+ if(hex.length == 3){
+ hex = hex.split('');
+ hex = [hex[0],hex[0],hex[1],hex[1],hex[2],hex[2]].join('');
+ }
+ if(hex.length == 4){
+ hex = hex.split('');
+ hex = [hex[0],hex[0],hex[1],hex[1],hex[2],hex[2],hex[3],hex[3]].join('');
+ }
+ if(hex.length != 8){
+ hex = 'FF'+hex;
+ }
+
+ /* If 100% alpha then remove the FF from beginning of hex to normalize things */
+ if ( hex.substring(0, 2) == 'FF' )
+ hex = hex.substring(2, 8);
+
+ return hex;
+ },
+
+ rgbToHex: function(rgb){
+
+ var alphaHex = (this.intToHex(Math.round(rgb.a*255/100)));
+
+ /* If 100% alpha then don't make it an rgba hex, just KISS (http://en.wikipedia.org/wiki/KISS_principle), yo */
+ if ( alphaHex == 'FF' )
+ alphaHex = '';
+
+ var rgbHex = this.intToHex(rgb.r) + this.intToHex(rgb.g) + this.intToHex(rgb.b);
+
+ return alphaHex + rgbHex;
+ },
+
+ intToHex: function(dec){
+ var result = (parseInt(dec).toString(16));
+ if(result.length == 1)
+ result = ("0" + result);
+ return result.toUpperCase();
+ },
+
+ hexToInt: function(hex){
+ return(parseInt(hex,16));
+ },
+
+ rgbToLum: function(rgb){
+ return Math.abs(Math.round((0.2126*rgb.r + 0.7152*rgb.g + 0.0722*rgb.b)/2.55));
+ },
+
+ rgbToHsv: function(rgb){
+ var r = rgb.r / 255;
+ var g = rgb.g / 255;
+ var b = rgb.b / 255;
+
+ hsv = {h:0, s:0, v:0, a:(isset(rgb._a) ? rgb._a : rgb.a)};
+
+ var min = 0
+ var max = 0;
+
+ if(r >= g && r >= b){
+ max = r;
+ min = (g > b) ? b : g;
+ }else if(g >= b && g >= r){
+ max = g;
+ min = (r > b) ? b : r;
+ }else{
+ max = b;
+ min = (g > r) ? r : g;
+ }
+
+ hsv.v = max;
+ hsv.s = (max) ? ((max - min) / max) : 0;
+
+ if(!hsv.s){
+ hsv.h = 0;
+ }else{
+ delta = max - min;
+ if(r == max){
+ hsv.h = (g - b) / delta;
+ }else if(g == max){
+ hsv.h = 2 + (b - r) / delta;
+ }else{
+ hsv.h = 4 + (r - g) / delta;
+ }
+
+ hsv.h = hsv.h * 60;
+ if(hsv.h < 0){
+ hsv.h += 360;
+ }
+ }
+
+ hsv.s = Math.abs(hsv.s * 100);
+ hsv.v = Math.abs(hsv.v * 100);
+
+ return hsv;
+ },
+
+ hsvToRgb: function(hsv){
+
+ rgb = {r:0, g:0, b:0, a:(isset(hsv._a) ? hsv._a : hsv.a)};
+
+ var h = isset(hsv._h) ? hsv._h : hsv.h;
+ var s = isset(hsv._s) ? hsv._s : hsv.s;
+ var v = isset(hsv._v) ? hsv._v : hsv.v;
+
+ if(s == 0){
+ if(v == 0){
+ rgb.r = rgb.g = rgb.b = 0;
+ }else{
+ rgb.r = rgb.g = rgb.b = Math.abs(v * 255 / 100);
+ }
+ }else{
+ if(h == 360){
+ h = 0;
+ }
+ h /= 60;
+
+ // 100 scale
+ s = s/100;
+ v = v/100;
+
+ var i = parseInt(h);
+ var f = h - i;
+ var p = v * (1 - s);
+ var q = v * (1 - (s * f));
+ var t = v * (1 - (s * (1 - f)));
+ switch (i){
+ case 0:
+ rgb.r = v;
+ rgb.g = t;
+ rgb.b = p;
+ break;
+ case 1:
+ rgb.r = q;
+ rgb.g = v;
+ rgb.b = p;
+ break;
+ case 2:
+ rgb.r = p;
+ rgb.g = v;
+ rgb.b = t;
+ break;
+ case 3:
+ rgb.r = p;
+ rgb.g = q;
+ rgb.b = v;
+ break;
+ case 4:
+ rgb.r = t;
+ rgb.g = p;
+ rgb.b = v;
+ break;
+ case 5:
+ rgb.r = v;
+ rgb.g = p;
+ rgb.b = q;
+ break;
+ }
+
+ rgb.r = Math.abs(Math.round(rgb.r * 255));
+ rgb.g = Math.abs(Math.round(rgb.g * 255));
+ rgb.b = Math.abs(Math.round(rgb.b * 255));
+ }
+
+ return rgb;
+ }
+});
+
+$.fn.colorpicker = function(options){
+ if(!this.length){
+ return this;
+ }
+
+ if(!$.colorpicker.initialized){
+ $(document).mousedown($.colorpicker._checkExternalClick)
+ .find('body').append($.colorpicker.cpDiv.hide())
+ .find('#'+mainDivId+'-'+$.colorpicker.mode).closest('li').addClass('selected');
+
+ for(var i in cpDiv.inputs){
+ if(i){
+ var $input = $(cpDiv.inputs[i]);
+ if($input.data('mode')){
+ $input.focus(function(){
+ var $this = $(this);
+ $this.closest('li').addClass('selected')
+ .siblings('.selected').removeClass('selected');
+ $.colorpicker._setMode($this.data('mode'));
+ }).closest('li').click(function(){
+ $(this).find('input').focus();
+ });
+ }
+
+ $input.blur(function(){
+ $.colorpicker._updateInputs();
+ });
+
+ switch(i){
+ case 'h':
+ case 's':
+ case 'v':
+ case 'a':
+ $input.keydown(function(e){
+ if(!$.colorpicker._curInst) return;
+ var $this = $(this);
+ var inst = $.colorpicker._curInst;
+ switch(e.keyCode){
+ case 38:
+ case 40:
+ $this.val(parseInt($this.val()) + (e.shiftKey ? 10 : 1) * (e.keyCode == 40 ? -1 : 1));
+ inst.color.setHsv(cpDiv.inputs.h.val(), cpDiv.inputs.s.val(), cpDiv.inputs.v.val(), cpDiv.inputs.a.val());
+ $.colorpicker._updateColorpicker(true);
+ break;
+
+ case 13:
+ $.colorpicker._submit();
+ break;
+
+ default:
+ return;
+ }
+ }).keyup(function(){
+ if(!$.colorpicker._curInst) return;
+ $.colorpicker._curInst.color.setHsv(cpDiv.inputs.h.val(), cpDiv.inputs.s.val(), cpDiv.inputs.v.val(), cpDiv.inputs.a.val());
+ $.colorpicker._updateColorpicker();
+ });
+ break;
+
+ case 'r':
+ case 'g':
+ case 'b':
+ $input.keydown(function(e){
+ if(!$.colorpicker._curInst) return;
+ var $this = $(this);
+ var inst = $.colorpicker._curInst;
+ switch(e.keyCode){
+ case 38:
+ case 40:
+ $this.val(parseInt($this.val()) + (e.shiftKey ? 10 : 1) * (e.keyCode == 40 ? -1 : 1));
+ inst.color.setRgb(cpDiv.inputs.r.val(), cpDiv.inputs.g.val(), cpDiv.inputs.b.val(), cpDiv.inputs.a.val());
+ $.colorpicker._updateColorpicker(true);
+ break;
+
+ case 13:
+ $.colorpicker._submit();
+ break;
+
+ default:
+ return;
+ }
+ }).keyup(function(){
+ if(!$.colorpicker._curInst) return;
+ $.colorpicker._curInst.color.setRgb(cpDiv.inputs.r.val(), cpDiv.inputs.g.val(), cpDiv.inputs.b.val(), cpDiv.inputs.a.val());
+ $.colorpicker._updateColorpicker();
+ });
+ break;
+
+ case 'hex':
+ $input.keydown(function(e){
+ if(!$.colorpicker._curInst) return;
+ switch(e.keyCode){
+ case 13:
+ $.colorpicker._submit();
+ break;
+
+ default:
+ return;
+ }
+ }).keyup(function(){
+ var inst = $.colorpicker._curInst;
+ if(!inst) return;
+ if(!cpDiv.inputs.hex.val()){
+ inst.color = new $.colorpicker.color({hex: $.colorpicker._defaults.color});
+ inst.color.isNull = $.colorpicker._get(inst, 'allowNull');
+ $.colorpicker._updateColorpicker();
+ }else{
+ inst.color.setHex(cpDiv.inputs.hex.val());
+ $.colorpicker._updateColorpicker();
+ }
+ });
+ break;
+ }
+ }
+ }
+
+
+ /* Swatches */
+ /* Add Swatch */
+ cpDiv.addSwatchButton.mousedown(function(e) {
+ $.colorpicker.addSwatch($.colorpicker._curInst.color);
+ });
+
+ /* Use swatch */
+ cpDiv.swatches.delegate('.swatch', 'click', function(e) {
+
+ /* Proxy that way useSwatch has the right this object */
+ var useSwatch = $.proxy($.colorpicker._useSwatch, this);
+ useSwatch(e);
+
+ e.preventDefault();
+
+ });
+
+ /* Delete swatch */
+
+ cpDiv.swatches.delegate('.swatch', 'contextmenu', function(e) {
+
+ if ( confirm('Are you sure you wish to delete this swatch?') )
+ $.colorpicker.deleteSwatch(this);
+
+ e.preventDefault();
+ return false;
+
+ });
+
+
+
+ cpDiv.oldColorDiv.mousedown($.colorpicker._useSwatch);
+ cpDiv.colorDiv.mousedown(function(e){
+ $.colorpicker._submit($(this).data('color'));
+ e.preventDefault();
+ return false;
+ });
+
+ cpDiv.defaultHeight = cpDiv.outerHeight();
+ cpDiv.addClass('swatchesOn');
+ cpDiv.swatchHeight = cpDiv.outerHeight() - cpDiv.defaultHeight;
+ cpDiv.removeClass('swatchesOn').addClass('alphaOn');
+ cpDiv.alphaHeight = cpDiv.outerHeight() - cpDiv.defaultHeight;
+ cpDiv.removeClass('alphaOn');
+
+ cpDiv.d1Div.mousedown(function(e){
+ $.colorpicker._isDragging = true;
+ $.colorpicker._mousemoveControl1d(e);
+ $(document).bind('mousemove', $.colorpicker._mousemoveControl1d);
+ return false;
+ })
+ cpDiv.d2Div.mousedown(function(e){
+ $.colorpicker._isDragging = true;
+ $.colorpicker._mousemoveControl2d(e);
+ $(document).bind('mousemove', $.colorpicker._mousemoveControl2d);
+ return false;
+ })
+ cpDiv.alphaDiv.mousedown(function(e){
+ $.colorpicker._isDragging = true;
+ $.colorpicker._mousemoveControlAlpha(e);
+ $(document).bind('mousemove', $.colorpicker._mousemoveControlAlpha);
+ return false;
+ })
+ $(document).mouseup(function(){
+ $(document)
+ .unbind('mousemove', $.colorpicker._mousemoveControl1d)
+ .unbind('mousemove', $.colorpicker._mousemoveControl2d)
+ .unbind('mousemove', $.colorpicker._mousemoveControlAlpha);
+ $.colorpicker._isDragging = false;
+ return false;
+ });
+ $(window).resize(function(){
+ if($.colorpicker._colorpickerShowing){
+ $.colorpicker._positionColorpicker();
+ }
+ })
+
+ $.colorpicker._setMode($.colorpicker.mode);
+
+ $.colorpicker.initialized = true;
+ }
+
+ var otherArgs = Array.prototype.slice.call(arguments, 1);
+ if(options == 'option' && arguments.length == 2 && typeof arguments[1] == 'string'){
+ return $.colorpicker['_' + options + 'Colorpicker'].
+ apply($.colorpicker, [this[0]].concat(otherArgs));
+ }
+ return this.each(function(){
+ typeof options == 'string' ?
+ $.colorpicker['_' + options + 'Colorpicker'].
+ apply($.colorpicker, [this].concat(otherArgs)) :
+ $.colorpicker._attachColorpicker(this, options);
+ });
+};
+
+function extendRemove(target, props) {
+ $.extend(target, props);
+ for(var name in props){
+ if(props[name] == null || props[name] == undefined){
+ target[name] = props[name];
+ }
+ }
+ return target;
+};
+
+function isset(x){
+ return x !== undefined;
+}
+
+$.colorpicker = new Colorpicker();
+$.colorpicker.initialized = false;
+$.colorpicker.uuid = new Date().getTime();
+
+})(jQuery);
\ No newline at end of file
--- /dev/null
+/*
+ JS Stylesheet Library
+ Created by Chris Jean
+ Licensed under GPL v2
+
+ Version 0.1
+*/
+function ITStylesheet(args, action) {
+
+ if('undefined' !== typeof args.document) {
+ this.document = args.document;
+ delete args.document;
+ }
+
+ this.property_dom_names = {};
+ this.property_standard_names = {};
+ this.converted_rgb_values = {};
+
+ this.args = ('undefined' !== typeof args) ? args : {};
+ this.action = ('undefined' !== typeof action) ? action : 'load';
+
+ this.init = function() {
+ if('find' === this.action)
+ this._find_stylesheet();
+ else
+ this._load_stylesheet();
+ }
+
+
+ this._load_stylesheet = function() {
+ args = this.args;
+
+ var new_style_node;
+
+ if('undefined' !== typeof args.href) {
+ new_style_node = this.document.createElement('link');
+ new_style_node.href = args.href;
+
+ this.type = 'link';
+ }
+ else {
+ new_style_node = this.document.createElement('style');
+
+ this.type = 'style';
+ }
+
+ new_style_node.type = 'text/css';
+
+ if('undefined' !== typeof args.title)
+ new_style_node.title = args.title;
+ if('undefined' !== typeof args.rel)
+ new_style_node.rel = args.rel;
+ if('undefined' !== typeof args.media)
+ new_style_node.media = args.media;
+
+ if(('undefined' !== typeof args.href) && ('undefined' === typeof args.rel))
+ new_style_node.rel = 'stylesheet';
+
+
+ var content = '';
+
+ if('undefined' !== typeof args.content) {
+ content = args.content;
+ delete args.content;
+ }
+
+ /* Give stylesheet a random ID that way we can find it later */
+ var randomID = Math.floor((Math.random() * 1000)) + 1;
+
+ /* Create stylesheet/link */
+ this.$stylesheet_node = jQuery(new_style_node).insertBefore($i('style#live-css-holder')).addClass('ITStylesheet').attr('id', 'itstylesheet-' + randomID);
+ this.stylesheet_node = this.$stylesheet_node[0];
+
+ /* Loop through this.document.styleSheets to find the newly added stylesheet */
+ var self = this;
+
+ jQuery.each(this.document.styleSheets, function(index, CSSStylesheet) {
+
+ if ( typeof CSSStylesheet.ownerNode.id == 'undefined' || !CSSStylesheet.ownerNode.id || CSSStylesheet.ownerNode.id != 'itstylesheet-' + randomID )
+ return;
+
+ self.stylesheet = CSSStylesheet;
+
+ return false;
+
+ });
+
+ this._find_rules();
+
+ if('' !== content)
+ this.set_rules(content);
+ }
+
+ this._find_stylesheet = function() {
+ args = this.args;
+
+ for(var i = 0; i < this.document.styleSheets.length; i++) {
+
+ if(('undefined' !== typeof args.href) && typeof this.document.styleSheets[i].href == 'string' && this.document.styleSheets[i].href.indexOf(args.href) === -1)
+ continue;
+ if(('undefined' !== typeof args.title) && (args.title !== this.document.styleSheets[i].title))
+ continue;
+ if(('undefined' !== typeof args.rel) && (args.rel !== this.document.styleSheets[i].rel))
+ continue;
+ if(('undefined' !== typeof args.media) && (args.media !== this.document.styleSheets[i].media))
+ continue;
+ if(('undefined' !== typeof args.type) && (args.type !== this.document.styleSheets[i].type))
+ continue;
+ if(('undefined' !== typeof args.disabled) && (args.disabled !== this.document.styleSheets[i].disabled))
+ continue;
+
+ this.type = 'link';
+
+ this.stylesheet = this.document.styleSheets[i];
+ this._find_rules();
+ break;
+ }
+ }
+
+ this._find_rules = function() {
+
+ if(('undefined' === typeof this.stylesheet))
+ return;
+
+ if(this.stylesheet.cssRules)
+ this.rules = this.stylesheet.cssRules;
+ else
+ this.rules = this.stylesheet.rules;
+
+ }
+
+ this._get_style_from_declarations = function(declarations) {
+ var style = '';
+
+ for(property in declarations)
+ style += property + ':' + declarations[property] + '; ';
+
+ return style;
+ }
+
+ this._get_rules_obj_from_string = function(rules_string) {
+ var rules = {};
+
+ var rule_matches = rules_string.match(/\s*[^{;]+\s*{\s*[^{}]+\s*}/g);
+ if(-1 === rule_matches)
+ return rules;
+
+ for(var i = 0; i < rule_matches.length; i++) {
+ var rule_parts = rule_matches[i].match(/\s*([^{;]+)\s*{\s*([^{}]+)\s*}/);
+ rules[rule_parts[1]] = rule_parts[2];
+ }
+
+ return rules;
+ }
+
+ this._get_property_dom_name = function(css_property) {
+ if('undefined' !== typeof this.property_dom_names[css_property])
+ return this.property_dom_names[css_property];
+
+ var property_parts = css_property.split('-');
+
+ var property = property_parts.shift();
+
+ while(property_parts.length > 0) {
+ var part = property_parts.shift();
+ part = part.charAt(0).toUpperCase() + part.substr(1);
+
+ property += part;
+ }
+
+ this.property_dom_names[css_property] = property;
+
+ return property;
+ }
+
+ this._get_property_standard_name = function(css_property) {
+ if('undefined' !== typeof this.property_standard_names[css_property])
+ return this.property_standard_names[css_property];
+
+ var property = css_property;
+
+ if('padding-right-value' === css_property)
+ property = 'padding-right';
+ else if('padding-left-value' === css_property)
+ property = 'padding-left';
+ else if('margin-right-value' === css_property)
+ property = 'margin-right';
+ else if('margin-left-value' === css_property)
+ property = 'margin-left';
+
+ this.property_standard_names[css_property] = property;
+
+ return property;
+ }
+
+ this._delete_rule_at_index = function(index) {
+ if(this.stylesheet.deleteRule)
+ this.stylesheet.deleteRule(index);
+ else
+ this.stylesheet.removeRule(index);
+ }
+
+ this._get_stylesheet_rules = function(stylesheet) {
+ if(stylesheet.cssRules)
+ return stylesheet.cssRules;
+ return stylesheet.rules;
+ }
+
+ this._get_stylesheet_rules_object = function(stylesheet) {
+ var raw_rules = this._get_stylesheet_rules(stylesheet);
+
+ var declarations = {};
+ var selectors = [];
+
+ for(var i = 0; i < raw_rules.length; i++) {
+ declarations[raw_rules[i].selectorText] = this._get_rule_declarations_object(raw_rules[i]);
+ selectors.push(raw_rules[i].selectorText);
+ }
+
+ selectors.sort();
+
+ var rules = {};
+
+ for(var i = 0; i < selectors.length; i++)
+ rules[selectors[i]] = declarations[selectors[i]];
+
+ return rules;
+ }
+
+ this._get_rule_declarations_object = function(rule_or_node) {
+ var declarations = {};
+
+ var style_obj;
+
+ if(rule_or_node.style)
+ style_obj = rule_or_node.style;
+ else
+ style_obj = rule_or_node;
+
+ var properties = [];
+ for(var i = 0; i < style_obj.length; i++)
+ properties.push(style_obj[i]);
+ properties.sort();
+
+ for(var i = 0; i < properties.length; i++) {
+ var property = this._get_property_standard_name(properties[i]);
+
+ if('undefined' !== typeof style_obj[property])
+ declarations[property] = style_obj[property];
+ else
+ declarations[property] = style_obj[this._get_property_dom_name(property)];
+ }
+
+ return declarations;
+ }
+
+
+ this.get_rule_index = function(selector) {
+ if('undefined' === typeof selector)
+ return false;
+
+ indexes = new Array();
+
+ if(!this.rules)
+ this._find_rules();
+ if(!this.rules)
+ return false;
+
+ if('undefined' !== typeof this.rules[selector])
+ return selector;
+
+
+ for(var i = 0; i < this.rules.length; i++) {
+ if(typeof this.rules[i].selectorText == 'string' && this.rules[i].selectorText.toLowerCase() == selector.toLowerCase())
+ indexes.push(i);
+ }
+
+ if(indexes.length !== 0){
+ return indexes[indexes.length-1];
+ }
+
+ return false;
+ }
+
+ this.get_rule = function(selector) {
+ if('undefined' === typeof selector)
+ return false;
+
+ var index = this.get_rule_index(selector);
+
+ if((false === index) || ('undefined' === typeof this.rules[index]))
+ return false;
+
+ return this.rules[index];
+ }
+
+ this.add_rule = function(selector, declarations) {
+ return this.update_rule(selector, declarations);
+ }
+
+ this.update_rule = function(selectors_raw, declarations, split_selectors) {
+ if(('undefined' === typeof this.rules) || ('undefined' === typeof selectors_raw))
+ return false;
+ if('undefined' === typeof declarations )
+ declarations = {};
+ if('undefined' === typeof split_selectors)
+ split_selectors = false;
+
+ if(split_selectors){
+ var selectors = selectors_raw.split(',');
+ } else {
+ var selectors = new Array(selectors_raw);
+ }
+
+ var rules = [];
+
+ for(var i = 0; i < selectors.length; i++) {
+ var selector = selectors[i];
+
+ if('undefined' === typeof selector)
+ continue;
+
+ var rule = this.get_rule(selector);
+
+ try {
+ if(false === rule) {
+ var rule_index = this.rules.length;
+ string_declarations = ('string' === typeof declarations) ? declarations : this._get_style_from_declarations(declarations);
+
+ if(this.stylesheet.addRule)
+ this.stylesheet.addRule(selector, string_declarations, rule_index);
+ else
+ this.stylesheet.insertRule(selector + ' {' + string_declarations + '}', rule_index);
+
+ rule = this.rules[rule_index];
+ }
+ else {
+ for(property in declarations) {
+ if(rule.style.setAttribute)
+ rule.style.setAttribute(property, declarations[property]);
+ else
+ rule.style.setProperty(property, declarations[property], null);
+ }
+ }
+
+ rules.push(rule);
+ }
+ catch(error) {}
+ }
+
+ return rules;
+ }
+
+ this.delete_all_rules = function() {
+ while(this.rules.length > 0)
+ this._delete_rule_at_index(0);
+ }
+
+ this.delete_rule = function(selector) {
+ var index = this.get_rule_index(selector);
+
+ if(false === index)
+ return false;
+
+ this._delete_rule_at_index(index);
+
+ return true;
+ }
+
+ this.delete_rule_property = function(selector, property) {
+ var tempObject = {};
+ tempObject[property] = null;
+
+ this.update_rule(selector, tempObject);
+ }
+
+ this._convert_rgb_to_hex = function(rgb) {
+ if('undefined' !== typeof this.converted_rgb_values[rgb])
+ return this.converted_rgb_values[rgb];
+
+ var digits = /rgb\(\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)\s*\)/.exec(rgb);
+
+ var red = parseInt(digits[1]);
+ var green = parseInt(digits[2]);
+ var blue = parseInt(digits[3]);
+
+ var hex_raw = blue | (green << 8) | (red << 16);
+
+ hex = hex_raw.toString(16).toUpperCase();
+
+ while(hex.length < 6)
+ hex = '0' + hex;
+
+ this.converted_rgb_values[rgb] = '#' + hex;
+
+ return '#' + hex;
+ }
+
+ this.get_stylesheet_text = function() {
+ var rules = this._get_stylesheet_rules_object(this.stylesheet);
+
+ var stylesheet = '';
+ var rgb_regex = /^rgb\(\s*\d+\s*,\s*\d+\s*,\s*\d+\s*\)/;
+
+ for(selector in rules) {
+ var properties = '';
+ for(property in rules[selector]) {
+ var value = rules[selector][property];
+
+ if('undefined' === typeof value)
+ continue;
+
+ if(rgb_regex.test(value))
+ value = this._convert_rgb_to_hex(value);
+
+ properties += "\t" + property + ": " + value + ";\n";
+ }
+
+ if('' === properties)
+ continue;
+
+ if('' !== stylesheet)
+ stylesheet += "\n";
+ stylesheet += selector + " {\n" + properties + '}';
+ }
+
+ return stylesheet;
+ }
+
+ this.get_computed_style = function(node) {
+ if(window.getComputedStyle)
+ return window.getComputedStyle(node, '');
+ return node.currentStyle;
+ }
+
+ this.set_rules = function(new_style_rules) {
+ this.delete_all_rules();
+
+ if('string' === typeof new_style_rules)
+ new_style_rules = this._get_rules_obj_from_string(new_style_rules);
+
+ for(selector in new_style_rules)
+ this.update_rule(selector, new_style_rules[selector]);
+ }
+
+
+ this.init();
+
+ return true;
+}
\ No newline at end of file
--- /dev/null
+/**
+ * jQuery Cookie plugin
+ *
+ * Copyright (c) 2010 Klaus Hartl (stilbuero.de)
+ * Dual licensed under the MIT and GPL licenses:
+ * http://www.opensource.org/licenses/mit-license.php
+ * http://www.gnu.org/licenses/gpl.html
+ *
+ */
+jQuery.cookie = function (key, value, options) {
+
+ // key and at least value given, set cookie...
+ if (arguments.length > 1 && String(value) !== "[object Object]") {
+ options = jQuery.extend({}, options);
+
+ if (value === null || value === undefined) {
+ options.expires = -1;
+ }
+
+ if (typeof options.expires === 'number') {
+ var days = options.expires, t = options.expires = new Date();
+ t.setDate(t.getDate() + days);
+ }
+
+ value = String(value);
+
+ return (document.cookie = [
+ encodeURIComponent(key), '=',
+ options.raw ? value : encodeURIComponent(value),
+ options.expires ? '; expires=' + options.expires.toUTCString() : '', // use expires attribute, max-age is not supported by IE
+ options.path ? '; path=' + options.path : '',
+ options.domain ? '; domain=' + options.domain : '',
+ options.secure ? '; secure' : ''
+ ].join(''));
+ }
+
+ // key and possibly options given, get cookie...
+ options = value || {};
+ var result, decode = options.raw ? function (s) { return s; } : decodeURIComponent;
+ return (result = new RegExp('(?:^|; )' + encodeURIComponent(key) + '=([^;]*)').exec(document.cookie)) ? decode(result[1]) : null;
+};
\ No newline at end of file
--- /dev/null
+/*
+ * ________ ________
+ * ______(_)_____ ____ __________________ __ _____________________ ______(_)_______
+ * _____ /_ __ `/ / / / _ \_ ___/_ / / / ___ __ \ _ \__ __ \ _____ /__ ___/
+ * ____ / / /_/ // /_/ // __/ / _ /_/ /____ /_/ / __/_ /_/ /______ / _(__ )
+ * ___ / \__, / \__,_/ \___//_/ _\__, /_(_) .___/\___/_ .___/_(_)__ / /____/
+ * /___/ /_/ /____/ /_/ /_/ /___/
+ *
+ * http://pep.briangonzalez.org
+ * Kinetic drag for mobile/desktop.
+ *
+ * Copyright (c) 2013 Brian Gonzalez
+ * Licensed under the MIT license.
+ *
+ * Title generated using "Speed" @
+ * http://patorjk.com/software/taag/#p=display&f=Speed&t=jquery.pep.js
+ */
+
+;(function ( $, window, undefined ) {
+
+ "use strict";
+
+ // create the defaults once
+ var pluginName = 'pep';
+ var defaults = {
+
+ // Options
+ // ----------------------------------------------------------------------------------------------
+ // See ** https://github.com/briangonzalez/jquery.pep.js ** for fully documented options.
+ // It was too hard to manage options here and in the readme.
+ // ----------------------------------------------------------------------------------------------
+ initiate: function(){},
+ start: function(){},
+ drag: function(){},
+ stop: function(){},
+ rest: function(){},
+ moveTo: false,
+ callIfNotStarted: ['stop', 'rest'],
+ startThreshold: [0,0],
+ grid: [1,1],
+ debug: false,
+ activeClass: 'pep-active',
+ multiplier: 1,
+ velocityMultiplier: 2.5,
+ shouldPreventDefault: true,
+ allowDragEventPropagation: true,
+ stopEvents: '',
+ hardwareAccelerate: true,
+ useCSSTranslation: true,
+ disableSelect: true,
+ cssEaseString: "cubic-bezier(0.190, 1.000, 0.220, 1.000)",
+ cssEaseDuration: 1000,
+ shouldEase: true,
+ droppable: false,
+ droppableActiveClass: 'pep-dpa',
+ overlapFunction: false,
+ constrainTo: false,
+ removeMargins: true,
+ place: true,
+ deferPlacement: false,
+ axis: null,
+ forceNonCSS3Movement: false,
+ elementsWithInteraction: 'input',
+ revert: false,
+ revertAfter: 'stop',
+ revertIf: function(){ return true; }
+ };
+
+ // ---------------------------------
+ // ----- Our main Pep object -----
+ // ---------------------------------
+ function Pep( el, options ) {
+
+ this.name = pluginName;
+
+ // reference to our DOM object
+ // and it's jQuery equivalent.
+ this.el = el;
+ this.$el = $(el);
+
+ // merge in defaults
+ this.options = $.extend( {}, defaults, options) ;
+
+ // store document/body so we don't need to keep grabbing them
+ // throughout the code
+ this.$document = $(this.$el[0].ownerDocument);
+ this.$body = this.$document.find('body');
+
+ // Create our triggers based on touch/click device
+ this.moveTrigger = "MSPointerMove touchmove mousemove";
+ this.startTrigger = "MSPointerDown touchstart mousedown";
+ this.stopTrigger = "MSPointerUp touchend mouseup";
+ this.startTriggerArray = this.startTrigger.split(' ');
+ this.moveTriggerArray = this.moveTrigger.split(' ');
+ this.stopTriggerArray = this.stopTrigger.split(' ');
+ this.stopEvents = [ this.stopTrigger, this.options.stopEvents ].join(' ');
+
+ if ( this.options.constrainTo === 'window' )
+ this.$container = this.$document;
+ else if ( this.options.constrainTo && (this.options.constrainTo !== 'parent') )
+ this.$container = $(this.options.constrainTo);
+ else
+ this.$container = this.$el.parent();
+
+ // IE need this
+ if ( this.isPointerEventCompatible() )
+ this.applyMSDefaults();
+
+ this.CSSEaseHash = this.getCSSEaseHash();
+ this.scale = 1;
+ this.started = false;
+ this.disabled = false;
+ this.resetVelocityQueue();
+
+ this.init();
+ }
+
+ // init();
+ // initialization logic
+ // you already have access to the DOM el and the options via the instance,
+ // e.g., this.el and this.options
+ Pep.prototype.init = function () {
+
+ if ( this.options.debug )
+ this.buildDebugDiv();
+
+ if ( this.options.disableSelect )
+ this.disableSelect();
+
+ // position the parent & place the object, if necessary.
+ if ( this.options.place && !this.options.deferPlacement ) {
+ this.positionParent();
+ this.placeObject();
+ }
+
+ this.ev = {}; // to store our event movements
+ this.pos = {}; // to store positions
+ this.subscribe();
+ };
+
+ // subscribe();
+ // useful in the event we want to programmatically
+ // interact with our Pep object.
+ // e.g.: $('#pep').trigger('stop')
+ Pep.prototype.subscribe = function () {
+ var self = this;
+
+ // Subscribe to our start event
+ this.$el.on( this.startTrigger, function(ev){
+ self.handleStart(ev);
+ });
+
+ // Prevent start events from being gobbled by elements that should allow user interaction
+ this.$el.on( this.startTrigger, this.options.elementsWithInteraction, function(ev){
+ ev.stopPropagation();
+ });
+
+ // Subscribe to our stop event
+ this.$document.on( this.stopEvents, function(ev) {
+ self.handleStop(ev);
+ });
+
+ // Subscribe to our move event
+ this.$document.on( this.moveTrigger, function(ev){
+ self.moveEvent = ev;
+ });
+ };
+
+ // handleStart();
+ // once this.startTrigger occurs, handle all of the logic
+ // that must go on. This is where Pep's heavy lifting is done.
+ Pep.prototype.handleStart = function(ev) {
+ var self = this;
+
+ // only continue chugging if our start event is a valid move event.
+ if ( this.isValidMoveEvent(ev) && !this.disabled ){
+
+ // IE10 Hack. Me not happy.
+ if ( this.isPointerEventCompatible() && ev.preventManipulation )
+ ev.preventManipulation();
+
+ // normalize event
+ ev = this.normalizeEvent(ev);
+
+ // position the parent & place the object, if necessary.
+ if ( this.options.place && this.options.deferPlacement ) {
+ this.positionParent();
+ this.placeObject();
+ }
+
+ // log it
+ this.log({ type: 'event', event: ev.type });
+
+ // hardware accelerate, if necessary.
+ if ( this.options.hardwareAccelerate && !this.hardwareAccelerated ) {
+ this.hardwareAccelerate();
+ this.hardwareAccelerated = true;
+ }
+
+ // fire user's initiate event.
+ var shouldContinue = this.options.initiate.call(this, ev, this);
+ if ( shouldContinue === false )
+ return;
+
+
+ // cancel the rest timeout
+ clearTimeout( this.restTimeout );
+
+ // add active class and reset css animation, if necessary
+ this.$el.addClass( this.options.activeClass );
+ this.removeCSSEasing();
+
+ // store event's x & y values for later use
+ this.startX = this.ev.x = ev.pep.x;
+ this.startY = this.ev.y = ev.pep.y;
+
+ // store initial offset.
+ this.initialPosition = this.initialPosition || this.$el.position();
+
+ // store the initial touch/click event, used to calculate the inital delta values.
+ this.startEvent = this.moveEvent = ev;
+
+ // make object active, so watchMoveLoop starts looping.
+ this.active = true;
+
+ // preventDefault(), is necessary
+ if ( this.options.shouldPreventDefault )
+ ev.preventDefault();
+
+ // allow / disallow event bubbling
+ if ( !this.options.allowDragEventPropagation )
+ ev.stopPropagation();
+
+ // animation loop to ensure we don't fire
+ // too many unneccessary repaints
+ (function watchMoveLoop(){
+ if ( !self.active ) return;
+ self.handleMove();
+ self.requestAnimationFrame( watchMoveLoop );
+ })($, self);
+
+ }
+ };
+
+ // handleMove();
+ // the logic for when the move events occur
+ Pep.prototype.handleMove = function() {
+
+ // setup our event object
+ if ( typeof(this.moveEvent) === 'undefined' )
+ return;
+
+ // get our move event's x & y
+ var ev = this.normalizeEvent( this.moveEvent );
+ var curX = window.parseInt(ev.pep.x / this.options.grid[0]) * this.options.grid[0];
+ var curY = window.parseInt(ev.pep.y / this.options.grid[1]) * this.options.grid[1];
+
+ // last in, first out (LIFO) queue to help us manage velocity
+ this.addToLIFO( { time: ev.timeStamp, x: curX, y: curY } );
+
+ // calculate values necessary to moving
+ var dx, dy;
+
+ if ( $.inArray( ev.type, this.startTriggerArray ) > -1 ){
+ dx = 0;
+ dy = 0;
+ } else{
+ dx = curX - this.ev.x;
+ dy = curY - this.ev.y;
+ }
+
+ this.dx = dx;
+ this.dy = dy;
+ this.ev.x = curX;
+ this.ev.y = curY;
+
+ // no movement in either direction -- so return
+ if (dx === 0 && dy === 0){
+ this.log({ type: 'event', event: '** stopped **' });
+ return;
+ }
+
+ // check if object has moved past X/Y thresholds
+ // if so, fire users start event
+ var initialDx = Math.abs(this.startX - curX);
+ var initialDy = Math.abs(this.startY - curY);
+ if ( !this.started && ( initialDx > this.options.startThreshold[0] || initialDy > this.options.startThreshold[1] ) ){
+ this.started = true;
+ this.$el.addClass('pep-start');
+ this.options.start.call(this, this.startEvent, this);
+ }
+
+ // Calculate our drop regions
+ if ( this.options.droppable ) {
+ this.calculateActiveDropRegions();
+ }
+
+ // fire user's drag event.
+ var continueDrag = this.options.drag.call(this, ev, this);
+
+ if ( continueDrag === false ) {
+ this.resetVelocityQueue();
+ return;
+ }
+
+ // log the move trigger & event position
+ this.log({ type: 'event', event: ev.type });
+ this.log({ type: 'event-coords', x: this.ev.x, y: this.ev.y });
+ this.log({ type: 'velocity' });
+
+ var hash = this.handleConstraint(dx, dy);
+ var xOp, yOp;
+
+ // if using not using CSS transforms, move object via absolute position
+ if ( typeof this.options.moveTo === 'function') {
+ xOp = ( dx >= 0 ) ? "+=" + Math.abs(dx/this.scale)*this.options.multiplier : "-=" + Math.abs(dx/this.scale)*this.options.multiplier;
+ yOp = ( dy >= 0 ) ? "+=" + Math.abs(dy/this.scale)*this.options.multiplier : "-=" + Math.abs(dy/this.scale)*this.options.multiplier;
+
+ if ( this.options.constrainTo ) {
+ xOp = (hash.x !== false) ? hash.x : xOp;
+ yOp = (hash.y !== false) ? hash.y : yOp;
+ }
+
+ // only move along single axis, if necessary
+ if ( this.options.axis === 'x' ) yOp = hash.y;
+ if ( this.options.axis === 'y' ) xOp = hash.x;
+
+ this.options.moveTo.call(this, xOp, yOp);
+ } else if ( !this.shouldUseCSSTranslation() ){
+ xOp = ( dx >= 0 ) ? "+=" + Math.abs(dx/this.scale)*this.options.multiplier : "-=" + Math.abs(dx/this.scale)*this.options.multiplier;
+ yOp = ( dy >= 0 ) ? "+=" + Math.abs(dy/this.scale)*this.options.multiplier : "-=" + Math.abs(dy/this.scale)*this.options.multiplier;
+
+ if ( this.options.constrainTo ) {
+ xOp = (hash.x !== false) ? hash.x : xOp;
+ yOp = (hash.y !== false) ? hash.y : yOp;
+ }
+
+ // only move along single axis, if necessary
+ if ( this.options.axis === 'x' ) yOp = hash.y;
+ if ( this.options.axis === 'y' ) xOp = hash.x;
+
+ this.moveTo(xOp, yOp);
+ }
+ else {
+
+ dx = (dx/this.scale)*this.options.multiplier;
+ dy = (dy/this.scale)*this.options.multiplier;
+
+ if ( this.options.constrainTo ) {
+ dx = (hash.x === false) ? dx : 0 ;
+ dy = (hash.y === false) ? dy : 0 ;
+ }
+
+ // only move along single axis, if necessary
+ if ( this.options.axis === 'x' ) dy = 0;
+ if ( this.options.axis === 'y' ) dx = 0;
+
+ this.moveToUsingTransforms( dx, dy );
+ }
+ };
+
+ // handleStop();
+ // the logic for when the stop events occur
+ Pep.prototype.handleStop = function(ev) {
+
+ // no need to handle stop event if we're not active
+ if (!this.active)
+ return;
+
+ // log it
+ this.log({ type: 'event', event: ev.type });
+
+ // make object inactive, so watchMoveLoop returns
+ this.active = false;
+
+ // remove our start class
+ this.$el.removeClass('pep-start')
+ .addClass('pep-ease');
+
+ // Calculate our drop regions
+ if ( this.options.droppable ) {
+ this.calculateActiveDropRegions();
+ }
+
+ // fire user's stop event.
+ if ( this.started || (!this.started && $.inArray('stop', this.options.callIfNotStarted) > -1 ) ) {
+ this.options.stop.call(this, ev, this);
+ }
+
+ // ease the object, if necessary.
+ if (this.options.shouldEase) {
+ this.ease(ev, this.started);
+ } else {
+ this.removeActiveClass();
+ }
+
+ if ( this.options.revert && (this.options.revertAfter === 'stop' || !this.options.shouldEase) && ( this.options.revertIf && this.options.revertIf() ) ) {
+ this.revert();
+ }
+
+ // this must be set to false after
+ // the user's stop event is called, so the dev
+ // has access to it.
+ this.started = false;
+
+ // reset the velocity queue
+ this.resetVelocityQueue();
+
+ };
+
+ // ease();
+ // used in conjunction with the LIFO queue
+ // to ease the object after stop
+ Pep.prototype.ease = function(ev, started){
+
+ var pos = this.$el.position();
+ var vel = this.velocity();
+ var dt = this.dt;
+ var x = (vel.x/this.scale) * this.options.multiplier;
+ var y = (vel.y/this.scale) * this.options.multiplier;
+
+ var hash = this.handleConstraint(x, y, true);
+
+ // ✪ Apply the CSS3 animation easing magic ✪
+ if ( this.cssAnimationsSupported() )
+ this.$el.css( this.getCSSEaseHash() );
+
+ var xOp = ( vel.x > 0 ) ? "+=" + x : "-=" + Math.abs(x);
+ var yOp = ( vel.y > 0 ) ? "+=" + y : "-=" + Math.abs(y);
+
+ if ( this.options.constrainTo ) {
+ xOp = (hash.x !== false) ? hash.x : xOp;
+ yOp = (hash.y !== false) ? hash.y : yOp;
+ }
+
+ if ( this.options.axis === 'x' ) yOp = "+=0";
+ if ( this.options.axis === 'y' ) xOp = "+=0";
+
+ // ease it via JS, the last true tells it to animate.
+ var jsAnimateFallback = !this.cssAnimationsSupported() || this.options.forceNonCSS3Movement;
+ if (typeof this.options.moveTo === 'function') {
+ this.options.moveTo.call(this, xOp, yOp);
+ } else {
+ this.moveTo(xOp, yOp, jsAnimateFallback);
+ }
+
+ // when the rest occurs, remove active class and call
+ // user's rest event.
+ var self = this;
+ this.restTimeout = setTimeout( function(){
+
+ // Calculate our drop regions
+ if ( self.options.droppable ) {
+ self.calculateActiveDropRegions();
+ }
+
+ // call users rest event.
+ if ( started || ( !started && $.inArray('rest', self.options.callIfNotStarted) > -1 ) ) {
+ self.options.rest.call(self, ev, self);
+ }
+
+ // revert thy self!
+ // if ( this.options.revert && this.options.revertIf() && (this.options.revertAfter === 'stop' || !this.options.shouldEase) ) {
+ if ( self.options.revert && (self.options.revertAfter === 'ease' && self.options.shouldEase) && ( self.options.revertIf && self.options.revertIf() ) ) {
+ self.revert();
+ }
+
+ // remove active class
+ self.removeActiveClass();
+
+ }, this.options.cssEaseDuration );
+
+ };
+
+ // normalizeEvent()
+ Pep.prototype.normalizeEvent = function(ev) {
+ ev.pep = {};
+
+ if ( this.isPointerEventCompatible() || !this.isTouch(ev) ) {
+
+ if ( ev.pageX ) {
+ ev.pep.x = ev.pageX;
+ ev.pep.y = ev.pageY;
+ } else {
+ ev.pep.x = ev.originalEvent.pageX;
+ ev.pep.y = ev.originalEvent.pageY;
+ }
+
+ ev.pep.type = ev.type;
+
+ }
+ else {
+ ev.pep.x = ev.originalEvent.touches[0].pageX;
+ ev.pep.y = ev.originalEvent.touches[0].pageY;
+ ev.pep.type = ev.type;
+ }
+
+ return ev;
+ };
+
+ // resetVelocityQueue()
+ //
+ Pep.prototype.resetVelocityQueue = function() {
+ this.velocityQueue = new Array(5);
+ };
+
+ // moveTo();
+ // move the object to an x and/or y value
+ // using jQuery's .css function -- this fxn uses the
+ // .css({top: "+=20", left: "-=30"}) syntax
+ Pep.prototype.moveTo = function(x,y, animate) {
+
+ this.log({ type: 'delta', x: x, y: y });
+ if ( animate ) {
+ this.$el.animate({ top: y, left: x }, this.options.cssEaseDuration/2, 'easeOutQuad', {queue: false});
+ } else{
+ this.$el.stop(true, false).css({ top: y , left: x });
+ }
+
+ };
+
+ // moveToUsingTransforms();
+ // move the object to an x and/or y value
+ Pep.prototype.moveToUsingTransforms = function(x,y) {
+
+ // Check for our initial values if we don't have them.
+ var matrixArray = this.matrixToArray( this.matrixString() );
+ if ( !this.cssX )
+ this.cssX = this.xTranslation( matrixArray );
+
+ if ( !this.cssY )
+ this.cssY = this.yTranslation( matrixArray );
+
+ // CSS3 transforms are additive from current position
+ this.cssX = this.cssX + x;
+ this.cssY = this.cssY + y;
+
+ this.log({ type: 'delta', x: x, y: y });
+
+ matrixArray[4] = this.cssX;
+ matrixArray[5] = this.cssY;
+
+ this.translation = this.arrayToMatrix( matrixArray );
+ this.transform( this.translation );
+ };
+
+ Pep.prototype.transform = function(value) {
+ this.$el.css({
+ '-webkit-transform': value,
+ '-moz-transform': value,
+ '-ms-transform': value,
+ '-o-transform': value,
+ 'transform': value });
+ };
+
+ Pep.prototype.xTranslation = function(matrixArray) {
+ matrixArray = matrixArray || this.matrixToArray( this.matrixString() );
+ return parseInt(matrixArray[4], 10);
+ };
+
+ Pep.prototype.yTranslation = function(matrixArray) {
+ matrixArray = matrixArray || this.matrixToArray( this.matrixString() );
+ return parseInt(matrixArray[5], 10);
+ };
+
+
+ // 3 helper functions for working with the
+ // objects CSS3 transforms
+ // matrixString
+ // matrixToArray
+ // arrayToMatrix
+ Pep.prototype.matrixString = function() {
+
+ var validMatrix = function(o){
+ return !( !o || o === 'none' || o.indexOf('matrix') < 0 );
+ };
+
+ var matrix = "matrix(1, 0, 0, 1, 0, 0)";
+
+ if ( validMatrix( this.$el.css('-webkit-transform') ) )
+ matrix = this.$el.css('-webkit-transform');
+
+ if ( validMatrix( this.$el.css('-moz-transform') ) )
+ matrix = this.$el.css('-moz-transform');
+
+ if ( validMatrix( this.$el.css('-ms-transform') ) )
+ matrix = this.$el.css('-ms-transform');
+
+ if ( validMatrix( this.$el.css('-o-transform') ) )
+ matrix = this.$el.css('-o-transform');
+
+ if ( validMatrix( this.$el.css('transform') ) )
+ matrix = this.$el.css('transform');
+
+ return matrix;
+ };
+
+ Pep.prototype.matrixToArray = function(str) {
+ return str.split('(')[1].split(')')[0].split(',');
+ };
+
+ Pep.prototype.arrayToMatrix = function(array) {
+ return "matrix(" + array.join(',') + ")";
+ };
+
+ // addToLIFO();
+ // a Last-In/First-Out array of the 5 most recent
+ // velocity points, which is used for easing
+ Pep.prototype.addToLIFO = function(val){
+ // last in, first out
+ var arr = this.velocityQueue;
+ arr = arr.slice(1, arr.length);
+ arr.push(val);
+ this.velocityQueue = arr;
+ };
+
+ // velocity();
+ // using the LIFO, calculate velocity and return
+ // velocity in each direction (x & y)
+ Pep.prototype.velocity = function(){
+ var sumX = 0;
+ var sumY = 0;
+
+ for ( var i = 0; i < this.velocityQueue.length -1; i++ ){
+ if ( this.velocityQueue[i] ){
+ sumX += (this.velocityQueue[i+1].x - this.velocityQueue[i].x);
+ sumY += (this.velocityQueue[i+1].y - this.velocityQueue[i].y);
+ this.dt = ( this.velocityQueue[i+1].time - this.velocityQueue[i].time );
+ }
+ }
+
+ // return velocity in each direction.
+ return { x: sumX*this.options.velocityMultiplier, y: sumY*this.options.velocityMultiplier};
+ };
+
+ Pep.prototype.revert = function() {
+ if ( this.shouldUseCSSTranslation() ){
+ this.moveToUsingTransforms(-this.xTranslation(),-this.yTranslation());
+ }
+
+ this.moveTo(this.initialPosition.left, this.initialPosition.top);
+ };
+
+ // requestAnimationFrame();
+ // requestAnimationFrame Polyfill
+ // More info:
+ // http://paulirish.com/2011/requestanimationframe-for-smart-animating/
+ Pep.prototype.requestAnimationFrame = function(callback) {
+ return window.requestAnimationFrame && window.requestAnimationFrame(callback) ||
+ window.webkitRequestAnimationFrame && window.webkitRequestAnimationFrame(callback) ||
+ window.mozRequestAnimationFrame && window.mozRequestAnimationFrame(callback) ||
+ window.oRequestAnimationFrame && window.mozRequestAnimationFrame(callback) ||
+ window.msRequestAnimationFrame && window.msRequestAnimationFrame(callback) ||
+ window.setTimeout(callback, 1000 / 60);
+ };
+
+ // positionParent();
+ // add the right positioning to the parent object
+ Pep.prototype.positionParent = function() {
+
+ if ( !this.options.constrainTo || this.parentPositioned )
+ return;
+
+ this.parentPositioned = true;
+
+ // make `relative` parent if necessary
+ if ( this.options.constrainTo === 'parent' ) {
+ this.$container.css({ position: 'relative' });
+ } else if ( this.options.constrainTo === 'window' &&
+ this.$container.get(0).nodeName !== "#document" &&
+ this.$container.css('position') !== 'static' )
+ {
+ this.$container.css({ position: 'static' });
+ }
+
+ };
+
+ // placeObject();
+ // add the right positioning to the object
+ Pep.prototype.placeObject = function() {
+
+ if ( this.objectPlaced )
+ return;
+
+ this.objectPlaced = true;
+
+ this.offset = (this.options.constrainTo === 'parent' || this.hasNonBodyRelative() ) ?
+ this.$el.position() : this.$el.offset();
+
+ // better to leave absolute position alone if
+ // it already has one.
+ if ( parseInt( this.$el.css('left'), 10 ) )
+ this.offset.left = this.$el.css('left');
+
+ if ( parseInt( this.$el.css('top'), 10 ) )
+ this.offset.top = this.$el.css('top');
+
+ if ( this.options.removeMargins )
+ this.$el.css({margin: 0});
+
+ this.$el.css({
+ position: 'absolute',
+ top: this.offset.top,
+ left: this.offset.left
+ });
+
+ };
+
+ // hasNonBodyRelative()
+ // returns true if any parent other than the body
+ // has relative positioning
+ Pep.prototype.hasNonBodyRelative = function() {
+ return this.$el.parents().filter(function() {
+ var $this = $(this);
+ return $this.is('body') || $this.css('position') === 'relative';
+ }).length > 1;
+ };
+
+ // setScale()
+ // set the scale of the object being moved.
+ Pep.prototype.setScale = function(val) {
+ this.scale = val;
+ };
+
+ // setMultiplier()
+ // set the multiplier of the object being moved.
+ Pep.prototype.setMultiplier = function(val) {
+ this.options.multiplier = val;
+ };
+
+ // removeCSSEasing();
+ // remove CSS easing properties, if necessary
+ Pep.prototype.removeCSSEasing = function() {
+ if ( this.cssAnimationsSupported() )
+ this.$el.css( this.getCSSEaseHash(true) );
+ };
+
+ // disableSelect();
+ // add the property which causes the object
+ // to not be selected user drags over text areas
+ Pep.prototype.disableSelect = function() {
+
+ this.$el.css({
+ '-webkit-touch-callout' : 'none',
+ '-webkit-user-select' : 'none',
+ '-khtml-user-select' : 'none',
+ '-moz-user-select' : 'none',
+ '-ms-user-select' : 'none',
+ 'user-select' : 'none'
+ });
+
+ };
+
+ // removeActiveClass()
+ // Removes the active class.
+ Pep.prototype.removeActiveClass = function() {
+ this.$el.removeClass( [this.options.activeClass, 'pep-ease'].join(' ') );
+ };
+
+ // handleConstraint();
+ // returns a hash of where to move to
+ // when we constrain to parent/window
+ Pep.prototype.handleConstraint = function(dx, dy, accountForTranslation) {
+ var self = this;
+ var pos = this.$el.position();
+ this.pos.x = pos.left;
+ this.pos.y = pos.top;
+
+ var hash = { x: false, y: false };
+
+ var upperYLimit, upperXLimit, lowerXLimit, lowerYLimit;
+
+ // log our positions
+ this.log({ type: "pos-coords", x: this.pos.x, y: this.pos.y});
+
+ if ( $.isArray( this.options.constrainTo ) ) {
+
+ if ( this.options.constrainTo[3] !== undefined && this.options.constrainTo[1] !== undefined ) {
+ upperXLimit = this.options.constrainTo[1] === false ? Infinity : this.options.constrainTo[1];
+ lowerXLimit = this.options.constrainTo[3] === false ? -Infinity : this.options.constrainTo[3];
+ }
+ if ( this.options.constrainTo[0] !== false && this.options.constrainTo[2] !== false ) {
+ upperYLimit = this.options.constrainTo[2] === false ? Infinity : this.options.constrainTo[2];
+ lowerYLimit = this.options.constrainTo[0] === false ? -Infinity : this.options.constrainTo[0];
+ }
+
+ // is our object trying to move outside lower X & Y limits?
+ if ( this.pos.x + dx < lowerXLimit) hash.x = lowerXLimit;
+ if ( this.pos.y + dy < lowerYLimit) hash.y = lowerYLimit;
+
+ } else if ( typeof this.options.constrainTo === 'string' ) {
+ lowerXLimit = 0;
+ lowerYLimit = 0;
+ upperXLimit = this.$container.width() - this.$el.outerWidth();
+ upperYLimit = this.$container.height() - this.$el.outerHeight();
+
+ // is our object trying to move outside lower X & Y limits?
+ this.$el.each(function() {
+
+ if ( $(this).position().left + dx < 0 )
+ hash.x = 0;
+
+ if ( $(this).position().top + dy < 0 )
+ hash.y = 0;
+
+ });
+
+ //Is the cursor outside of the bounding of the container?
+ var containerBounding = this.$container[0].getBoundingClientRect();
+ var isInsideContainer = ( this.ev.x > containerBounding.left &&
+ this.ev.x < containerBounding.right &&
+ this.ev.y > containerBounding.top + $(this.$el[0].ownerDocument).scrollTop() &&
+ this.ev.y < containerBounding.bottom + $(this.$el[0].ownerDocument).scrollTop() )
+
+ if ( !isInsideContainer ) {
+ hash.x = lowerXLimit;
+ hash.y = lowerYLimit;
+ }
+
+ }
+
+ // is our object trying to move outside upper X & Y limits?
+ this.$el.each(function() {
+
+ upperXLimit = self.$container.width() - $(this).outerWidth();
+ upperYLimit = self.$container.height() - $(this).outerHeight();
+
+ if ( $(this).position().left + dx > upperXLimit )
+ hash.x = upperXLimit;
+
+ if ( $(this).position().top + dy > upperYLimit )
+ hash.y = upperYLimit;
+
+ });
+
+ // Account for translation, which makes movement a little tricky.
+ if ( this.shouldUseCSSTranslation() && accountForTranslation ){
+ if (hash.x === lowerXLimit && this.xTranslation() ) hash.x = lowerXLimit - this.xTranslation();
+ if (hash.x === upperXLimit && this.xTranslation() ) hash.x = upperXLimit - this.xTranslation();
+
+ if (hash.y === lowerYLimit && this.yTranslation() ) hash.y = lowerYLimit - this.yTranslation();
+ if (hash.y === upperYLimit && this.yTranslation() ) hash.y = upperYLimit - this.yTranslation();
+ }
+
+ return hash;
+ };
+
+ // getCSSEaseHash();
+ // returns a hash of params used in conjunction
+ // with this.options.cssEaseString
+ Pep.prototype.getCSSEaseHash = function(reset){
+ if ( typeof(reset) === 'undefined' ) reset = false;
+
+ var cssEaseString;
+ if (reset){
+ cssEaseString = '';
+ } else if ( this.CSSEaseHash ) {
+ return this.CSSEaseHash;
+ } else {
+ cssEaseString = ['all', this.options.cssEaseDuration + 'ms', this.options.cssEaseString].join(' ');
+ }
+
+ return {
+ '-webkit-transition' : cssEaseString, // chrome, safari, etc.
+ '-moz-transition' : cssEaseString, // firefox
+ '-ms-transition' : cssEaseString, // microsoft
+ '-o-transition' : cssEaseString, // opera
+ 'transition' : cssEaseString // future
+ };
+ };
+
+ // calculateActiveDropRegions()
+ // sets parent droppables of this.
+ Pep.prototype.calculateActiveDropRegions = function() {
+ var self = this;
+ this.activeDropRegions = [];
+
+ $.each( $(this.options.droppable), function(idx, el){
+ var $el = $(el);
+ if ( self.isOverlapping($el, self.$el) ){
+ $el.addClass(self.options.droppableActiveClass);
+ self.activeDropRegions.push($el);
+ } else {
+ $el.removeClass(self.options.droppableActiveClass);
+ }
+ });
+
+ };
+
+ // isOverlapping();
+ // returns true if element a over
+ Pep.prototype.isOverlapping = function($a,$b) {
+
+ if ( this.options.overlapFunction ) {
+ return this.options.overlapFunction($a,$b);
+ }
+
+ var rect1 = $a[0].getBoundingClientRect();
+ var rect2 = $b[0].getBoundingClientRect();
+
+ return !( rect1.right < rect2.left ||
+ rect1.left > rect2.right ||
+ rect1.bottom < rect2.top ||
+ rect1.top > rect2.bottom );
+ };
+
+ // isTouch();
+ // returns whether or not event is a touch event
+ Pep.prototype.isTouch = function(ev){
+ return ev.type.search('touch') > -1;
+ };
+
+ // isPointerEventCompatible();
+ // return whether or note our device is pointer
+ // event compatible; typically means where on a
+ // touch Win8 device
+ Pep.prototype.isPointerEventCompatible = function() {
+ return ("MSPointerEvent" in window);
+ };
+
+ // applyMSDefaults();
+ Pep.prototype.applyMSDefaults = function(first_argument) {
+ this.$el.css({
+ '-ms-touch-action' : 'none',
+ 'touch-action' : 'none',
+ '-ms-scroll-chaining': 'none',
+ '-ms-scroll-limit': '0 0 0 0'
+ });
+ };
+
+ // isValidMoveEvent();
+ // returns true if we're on a non-touch device -- or --
+ // if the event is **single** touch event on a touch device
+ Pep.prototype.isValidMoveEvent = function(ev){
+ return ( !this.isTouch(ev) || ( this.isTouch(ev) && ev.originalEvent.touches && ev.originalEvent.touches.length === 1 ) );
+ };
+
+ // shouldUseCSSTranslation();
+ // return true if we should use CSS transforms for move the object
+ Pep.prototype.shouldUseCSSTranslation = function() {
+
+ if ( typeof(this.useCSSTranslation) !== "undefined" )
+ return this.useCSSTranslation;
+
+ var useCSSTranslation = false;
+
+ if ( !this.options.useCSSTranslation || ( typeof(Modernizr) !== "undefined" && !Modernizr.csstransforms)){
+ useCSSTranslation = false;
+ }
+ else{
+ useCSSTranslation = true;
+ }
+
+ this.useCSSTranslation = useCSSTranslation;
+ return useCSSTranslation;
+ };
+
+ // cssAnimationsSupported():
+ // returns true if the browser supports CSS animations
+ // which are used for easing..
+ Pep.prototype.cssAnimationsSupported = function() {
+
+ if ( typeof(this.cssAnimationsSupport) !== "undefined" ){
+ return this.cssAnimationsSupport;
+ }
+
+ // If the page has Modernizr, let them do the heavy lifting.
+ if ( ( typeof(Modernizr) !== "undefined" && Modernizr.cssanimations) ){
+ this.cssAnimationsSupport = true;
+ return true;
+ }
+
+ var animation = false,
+ elm = document.createElement('div'),
+ animationstring = 'animation',
+ keyframeprefix = '',
+ domPrefixes = 'Webkit Moz O ms Khtml'.split(' '),
+ pfx = '';
+
+ if( elm.style.animationName ) { animation = true; }
+
+ if( animation === false ) {
+ for( var i = 0; i < domPrefixes.length; i++ ) {
+ if( elm.style[ domPrefixes[i] + 'AnimationName' ] !== undefined ) {
+ pfx = domPrefixes[ i ];
+ animationstring = pfx + 'Animation';
+ keyframeprefix = '-' + pfx.toLowerCase() + '-';
+ animation = true;
+ break;
+ }
+ }
+ }
+
+ this.cssAnimationsSupport = animation;
+ return animation;
+ };
+
+ // hardwareAccelerate();
+ // add fool-proof CSS3 hardware acceleration.
+ Pep.prototype.hardwareAccelerate = function() {
+ this.$el.css({
+ '-webkit-perspective': 1000,
+ 'perspective': 1000,
+ '-webkit-backface-visibility': 'hidden',
+ 'backface-visibility': 'hidden'
+ });
+ };
+
+ // getMovementValues();
+ // returns object pos, event position, and velocity in each direction.
+ Pep.prototype.getMovementValues = function() {
+ return { ev: this.ev, pos: this.pos, velocity: this.velocity() };
+ };
+
+ // buildDebugDiv();
+ // Create a little div in the lower right corner of the window
+ // for extra info about the object currently moving
+ Pep.prototype.buildDebugDiv = function() {
+
+ // Build the debugDiv and it's inner HTML -- if necessary
+ var $debugDiv;
+ if ( $('#pep-debug').length === 0 ){
+ $debugDiv = $('<div></div>');
+ $debugDiv
+ .attr('id', 'pep-debug')
+ .append("<div style='font-weight:bold; background: red; color: white;'>DEBUG MODE</div>")
+ .append("<div id='pep-debug-event'>no event</div>")
+ .append("<div id='pep-debug-ev-coords'>event coords: <span class='pep-x'>-</span>, <span class='pep-y'>-</span></div>")
+ .append("<div id='pep-debug-pos-coords'>position coords: <span class='pep-x'>-</span>, <span class='pep-y'>-</span></div>")
+ .append("<div id='pep-debug-velocity'>velocity: <span class='pep-x'>-</span>, <span class='pep-y'>-</span></div>")
+ .append("<div id='pep-debug-delta'>Δ movement: <span class='pep-x'>-</span>, <span class='pep-y'>-</span></div>")
+ .css({
+ position: 'fixed',
+ bottom: 5,
+ right: 5,
+ zIndex: 99999,
+ textAlign: 'right',
+ fontFamily: 'Arial, sans',
+ fontSize: 10,
+ border: '1px solid #DDD',
+ padding: '3px',
+ background: 'white',
+ color: '#333'
+ });
+ }
+
+ var self = this;
+ setTimeout(function(){
+ self.debugElements = {
+ $event: $("#pep-debug-event"),
+ $velocityX: $("#pep-debug-velocity .pep-x"),
+ $velocityY: $("#pep-debug-velocity .pep-y"),
+ $dX: $("#pep-debug-delta .pep-x"),
+ $dY: $("#pep-debug-delta .pep-y"),
+ $evCoordsX: $("#pep-debug-ev-coords .pep-x"),
+ $evCoordsY: $("#pep-debug-ev-coords .pep-y"),
+ $posCoordsX: $("#pep-debug-pos-coords .pep-x"),
+ $posCoordsY: $("#pep-debug-pos-coords .pep-y")
+ };
+ }, 0);
+
+ $('body').append( $debugDiv );
+ };
+
+ // log()
+ Pep.prototype.log = function(opts) {
+ if ( !this.options.debug ) return;
+
+ switch (opts.type){
+ case "event":
+ this.debugElements.$event.text(opts.event);
+ break;
+ case "pos-coords":
+ this.debugElements.$posCoordsX.text(opts.x);
+ this.debugElements.$posCoordsY.text(opts.y);
+ break;
+ case "event-coords":
+ this.debugElements.$evCoordsX.text(opts.x);
+ this.debugElements.$evCoordsY.text(opts.y);
+ break;
+ case "delta":
+ this.debugElements.$dX.text(opts.x);
+ this.debugElements.$dY.text(opts.y);
+ break;
+ case "velocity":
+ var vel = this.velocity();
+ this.debugElements.$velocityX.text( Math.round(vel.x) );
+ this.debugElements.$velocityY.text( Math.round(vel.y) );
+ break;
+ }
+ };
+
+ // toggle()
+ // toggle the pep object
+ Pep.prototype.toggle = function(on) {
+ if ( typeof(on) === "undefined"){
+ this.disabled = !this.disabled;
+ }
+ else {
+ this.disabled = !on;
+ }
+ };
+
+ // *** Special Easings functions ***
+ // Used for JS easing fallback
+ // We can use any of these for a
+ // good intertia ease
+ $.extend($.easing,
+ {
+ easeOutQuad: function (x, t, b, c, d) {
+ return -c *(t/=d)*(t-2) + b;
+ },
+ easeOutCirc: function (x, t, b, c, d) {
+ return c * Math.sqrt(1 - (t=t/d-1)*t) + b;
+ },
+ easeOutExpo: function (x, t, b, c, d) {
+ return (t===d) ? b+c : c * (-Math.pow(2, -10 * t/d) + 1) + b;
+ }
+ });
+
+ // wrap it
+ // A really lightweight plugin wrapper around the constructor,
+ // preventing against multiple instantiations.
+ $.fn[pluginName] = function ( options ) {
+ return this.each(function () {
+ if (!$.data(this, 'plugin_' + pluginName)) {
+ var pepObj = new Pep( this, options );
+ $.data(this, 'plugin_' + pluginName, pepObj);
+ $.pep.peps.push(pepObj);
+ }
+ });
+ };
+
+ // The _ ___ ___
+ // /_\ | _ \_ _|
+ // / _ \| _/| |
+ // /_/ \_\_| |___|
+ //
+ $.pep = {};
+ $.pep.peps = [];
+ $.pep.toggleAll = function(on){
+ $.each(this.peps, function(index, pepObj){
+ pepObj.toggle(on);
+ });
+ };
+
+ $.pep.unbind = function($obj){
+ var pep = $obj.data('plugin_' + pluginName);
+
+ if ( typeof pep === 'undefined' )
+ return;
+
+ pep.toggle(false);
+ $obj.removeData('plugin_' + pluginName);
+ };
+
+}(jQuery, window));
\ No newline at end of file
--- /dev/null
+/* qTip2 v2.2.0 tips viewport | qtip2.com | Licensed MIT, GPL | Mon Dec 16 2013 11:39:27 */
+
+!function(a,b,c){!function(a){"use strict";"function"==typeof define&&define.amd?define(["jquery"],a):jQuery&&!jQuery.fn.qtip&&a(jQuery)}(function(d){"use strict";function e(a,b,c,e){this.id=c,this.target=a,this.tooltip=E,this.elements={target:a},this._id=R+"-"+c,this.timers={img:{}},this.options=b,this.plugins={},this.cache={event:{},target:d(),disabled:D,attr:e,onTooltip:D,lastClass:""},this.rendered=this.destroyed=this.disabled=this.waiting=this.hiddenDuringWait=this.positioning=this.triggering=D}function f(a){return a===E||"object"!==d.type(a)}function g(a){return!(d.isFunction(a)||a&&a.attr||a.length||"object"===d.type(a)&&(a.jquery||a.then))}function h(a){var b,c,e,h;return f(a)?D:(f(a.metadata)&&(a.metadata={type:a.metadata}),"content"in a&&(b=a.content,f(b)||b.jquery||b.done?b=a.content={text:c=g(b)?D:b}:c=b.text,"ajax"in b&&(e=b.ajax,h=e&&e.once!==D,delete b.ajax,b.text=function(a,b){var f=c||d(this).attr(b.options.content.attr)||"Loading...",g=d.ajax(d.extend({},e,{context:b})).then(e.success,E,e.error).then(function(a){return a&&h&&b.set("content.text",a),a},function(a,c,d){b.destroyed||0===a.status||b.set("content.text",c+": "+d)});return h?f:(b.set("content.text",f),g)}),"title"in b&&(f(b.title)||(b.button=b.title.button,b.title=b.title.text),g(b.title||D)&&(b.title=D))),"position"in a&&f(a.position)&&(a.position={my:a.position,at:a.position}),"show"in a&&f(a.show)&&(a.show=a.show.jquery?{target:a.show}:a.show===C?{ready:C}:{event:a.show}),"hide"in a&&f(a.hide)&&(a.hide=a.hide.jquery?{target:a.hide}:{event:a.hide}),"style"in a&&f(a.style)&&(a.style={classes:a.style}),d.each(Q,function(){this.sanitize&&this.sanitize(a)}),a)}function i(a,b){for(var c,d=0,e=a,f=b.split(".");e=e[f[d++]];)d<f.length&&(c=e);return[c||a,f.pop()]}function j(a,b){var c,d,e;for(c in this.checks)for(d in this.checks[c])(e=new RegExp(d,"i").exec(a))&&(b.push(e),("builtin"===c||this.plugins[c])&&this.checks[c][d].apply(this.plugins[c]||this,b))}function k(a){return U.concat("").join(a?"-"+a+" ":" ")}function l(c){return c&&{type:c.type,pageX:c.pageX,pageY:c.pageY,target:c.target,relatedTarget:c.relatedTarget,scrollX:c.scrollX||a.pageXOffset||b.body.scrollLeft||b.documentElement.scrollLeft,scrollY:c.scrollY||a.pageYOffset||b.body.scrollTop||b.documentElement.scrollTop}||{}}function m(a,b){return b>0?setTimeout(d.proxy(a,this),b):(a.call(this),void 0)}function n(a){return this.tooltip.hasClass(_)?D:(clearTimeout(this.timers.show),clearTimeout(this.timers.hide),this.timers.show=m.call(this,function(){this.toggle(C,a)},this.options.show.delay),void 0)}function o(a){if(this.tooltip.hasClass(_))return D;var b=d(a.relatedTarget),c=b.closest(V)[0]===this.tooltip[0],e=b[0]===this.options.show.target[0];if(clearTimeout(this.timers.show),clearTimeout(this.timers.hide),this!==b[0]&&"mouse"===this.options.position.target&&c||this.options.hide.fixed&&/mouse(out|leave|move)/.test(a.type)&&(c||e))try{a.preventDefault(),a.stopImmediatePropagation()}catch(f){}else this.timers.hide=m.call(this,function(){this.toggle(D,a)},this.options.hide.delay,this)}function p(a){return this.tooltip.hasClass(_)||!this.options.hide.inactive?D:(clearTimeout(this.timers.inactive),this.timers.inactive=m.call(this,function(){this.hide(a)},this.options.hide.inactive),void 0)}function q(a){this.rendered&&this.tooltip[0].offsetWidth>0&&this.reposition(a)}function r(a,c,e){d(b.body).delegate(a,(c.split?c:c.join(gb+" "))+gb,function(){var a=x.api[d.attr(this,T)];a&&!a.disabled&&e.apply(a,arguments)})}function s(a,c,f){var g,i,j,k,l,m=d(b.body),n=a[0]===b?m:a,o=a.metadata?a.metadata(f.metadata):E,p="html5"===f.metadata.type&&o?o[f.metadata.name]:E,q=a.data(f.metadata.name||"qtipopts");try{q="string"==typeof q?d.parseJSON(q):q}catch(r){}if(k=d.extend(C,{},x.defaults,f,"object"==typeof q?h(q):E,h(p||o)),i=k.position,k.id=c,"boolean"==typeof k.content.text){if(j=a.attr(k.content.attr),k.content.attr===D||!j)return D;k.content.text=j}if(i.container.length||(i.container=m),i.target===D&&(i.target=n),k.show.target===D&&(k.show.target=n),k.show.solo===C&&(k.show.solo=i.container.closest("body")),k.hide.target===D&&(k.hide.target=n),k.position.viewport===C&&(k.position.viewport=i.container),i.container=i.container.eq(0),i.at=new z(i.at,C),i.my=new z(i.my),a.data(R))if(k.overwrite)a.qtip("destroy",!0);else if(k.overwrite===D)return D;return a.attr(S,c),k.suppress&&(l=a.attr("title"))&&a.removeAttr("title").attr(bb,l).attr("title",""),g=new e(a,k,c,!!j),a.data(R,g),a.one("remove.qtip-"+c+" removeqtip.qtip-"+c,function(){var a;(a=d(this).data(R))&&a.destroy(!0)}),g}function t(a){return a.charAt(0).toUpperCase()+a.slice(1)}function u(a,b){var d,e,f=b.charAt(0).toUpperCase()+b.slice(1),g=(b+" "+rb.join(f+" ")+f).split(" "),h=0;if(qb[b])return a.css(qb[b]);for(;d=g[h++];)if((e=a.css(d))!==c)return qb[b]=d,e}function v(a,b){return Math.ceil(parseFloat(u(a,b)))}function w(a,b){this._ns="tip",this.options=b,this.offset=b.offset,this.size=[b.width,b.height],this.init(this.qtip=a)}var x,y,z,A,B,C=!0,D=!1,E=null,F="x",G="y",H="width",I="height",J="top",K="left",L="bottom",M="right",N="center",O="flipinvert",P="shift",Q={},R="qtip",S="data-hasqtip",T="data-qtip-id",U=["ui-widget","ui-tooltip"],V="."+R,W="click dblclick mousedown mouseup mousemove mouseleave mouseenter".split(" "),X=R+"-fixed",Y=R+"-default",Z=R+"-focus",$=R+"-hover",_=R+"-disabled",ab="_replacedByqTip",bb="oldtitle",cb={ie:function(){for(var a=3,c=b.createElement("div");(c.innerHTML="<!--[if gt IE "+ ++a+"]><i></i><![endif]-->")&&c.getElementsByTagName("i")[0];);return a>4?a:0/0}(),iOS:parseFloat((""+(/CPU.*OS ([0-9_]{1,5})|(CPU like).*AppleWebKit.*Mobile/i.exec(navigator.userAgent)||[0,""])[1]).replace("undefined","3_2").replace("_",".").replace("_",""))||D};y=e.prototype,y._when=function(a){return d.when.apply(d,a)},y.render=function(a){if(this.rendered||this.destroyed)return this;var b,c=this,e=this.options,f=this.cache,g=this.elements,h=e.content.text,i=e.content.title,j=e.content.button,k=e.position,l=("."+this._id+" ",[]);return d.attr(this.target[0],"aria-describedby",this._id),this.tooltip=g.tooltip=b=d("<div/>",{id:this._id,"class":[R,Y,e.style.classes,R+"-pos-"+e.position.my.abbrev()].join(" "),width:e.style.width||"",height:e.style.height||"",tracking:"mouse"===k.target&&k.adjust.mouse,role:"alert","aria-live":"polite","aria-atomic":D,"aria-describedby":this._id+"-content","aria-hidden":C}).toggleClass(_,this.disabled).attr(T,this.id).data(R,this).appendTo(k.container).append(g.content=d("<div />",{"class":R+"-content",id:this._id+"-content","aria-atomic":C})),this.rendered=-1,this.positioning=C,i&&(this._createTitle(),d.isFunction(i)||l.push(this._updateTitle(i,D))),j&&this._createButton(),d.isFunction(h)||l.push(this._updateContent(h,D)),this.rendered=C,this._setWidget(),d.each(Q,function(a){var b;"render"===this.initialize&&(b=this(c))&&(c.plugins[a]=b)}),this._unassignEvents(),this._assignEvents(),this._when(l).then(function(){c._trigger("render"),c.positioning=D,c.hiddenDuringWait||!e.show.ready&&!a||c.toggle(C,f.event,D),c.hiddenDuringWait=D}),x.api[this.id]=this,this},y.destroy=function(a){function b(){if(!this.destroyed){this.destroyed=C;var a=this.target,b=a.attr(bb);this.rendered&&this.tooltip.stop(1,0).find("*").remove().end().remove(),d.each(this.plugins,function(){this.destroy&&this.destroy()}),clearTimeout(this.timers.show),clearTimeout(this.timers.hide),this._unassignEvents(),a.removeData(R).removeAttr(T).removeAttr(S).removeAttr("aria-describedby"),this.options.suppress&&b&&a.attr("title",b).removeAttr(bb),this._unbind(a),this.options=this.elements=this.cache=this.timers=this.plugins=this.mouse=E,delete x.api[this.id]}}return this.destroyed?this.target:(a===C&&"hide"!==this.triggering||!this.rendered?b.call(this):(this.tooltip.one("tooltiphidden",d.proxy(b,this)),!this.triggering&&this.hide()),this.target)},A=y.checks={builtin:{"^id$":function(a,b,c,e){var f=c===C?x.nextid:c,g=R+"-"+f;f!==D&&f.length>0&&!d("#"+g).length?(this._id=g,this.rendered&&(this.tooltip[0].id=this._id,this.elements.content[0].id=this._id+"-content",this.elements.title[0].id=this._id+"-title")):a[b]=e},"^prerender":function(a,b,c){c&&!this.rendered&&this.render(this.options.show.ready)},"^content.text$":function(a,b,c){this._updateContent(c)},"^content.attr$":function(a,b,c,d){this.options.content.text===this.target.attr(d)&&this._updateContent(this.target.attr(c))},"^content.title$":function(a,b,c){return c?(c&&!this.elements.title&&this._createTitle(),this._updateTitle(c),void 0):this._removeTitle()},"^content.button$":function(a,b,c){this._updateButton(c)},"^content.title.(text|button)$":function(a,b,c){this.set("content."+b,c)},"^position.(my|at)$":function(a,b,c){"string"==typeof c&&(a[b]=new z(c,"at"===b))},"^position.container$":function(a,b,c){this.rendered&&this.tooltip.appendTo(c)},"^show.ready$":function(a,b,c){c&&(!this.rendered&&this.render(C)||this.toggle(C))},"^style.classes$":function(a,b,c,d){this.rendered&&this.tooltip.removeClass(d).addClass(c)},"^style.(width|height)":function(a,b,c){this.rendered&&this.tooltip.css(b,c)},"^style.widget|content.title":function(){this.rendered&&this._setWidget()},"^style.def":function(a,b,c){this.rendered&&this.tooltip.toggleClass(Y,!!c)},"^events.(render|show|move|hide|focus|blur)$":function(a,b,c){this.rendered&&this.tooltip[(d.isFunction(c)?"":"un")+"bind"]("tooltip"+b,c)},"^(show|hide|position).(event|target|fixed|inactive|leave|distance|viewport|adjust)":function(){if(this.rendered){var a=this.options.position;this.tooltip.attr("tracking","mouse"===a.target&&a.adjust.mouse),this._unassignEvents(),this._assignEvents()}}}},y.get=function(a){if(this.destroyed)return this;var b=i(this.options,a.toLowerCase()),c=b[0][b[1]];return c.precedance?c.string():c};var db=/^position\.(my|at|adjust|target|container|viewport)|style|content|show\.ready/i,eb=/^prerender|show\.ready/i;y.set=function(a,b){if(this.destroyed)return this;{var c,e=this.rendered,f=D,g=this.options;this.checks}return"string"==typeof a?(c=a,a={},a[c]=b):a=d.extend({},a),d.each(a,function(b,c){if(e&&eb.test(b))return delete a[b],void 0;var h,j=i(g,b.toLowerCase());h=j[0][j[1]],j[0][j[1]]=c&&c.nodeType?d(c):c,f=db.test(b)||f,a[b]=[j[0],j[1],c,h]}),h(g),this.positioning=C,d.each(a,d.proxy(j,this)),this.positioning=D,this.rendered&&this.tooltip[0].offsetWidth>0&&f&&this.reposition("mouse"===g.position.target?E:this.cache.event),this},y._update=function(a,b){var c=this,e=this.cache;return this.rendered&&a?(d.isFunction(a)&&(a=a.call(this.elements.target,e.event,this)||""),d.isFunction(a.then)?(e.waiting=C,a.then(function(a){return e.waiting=D,c._update(a,b)},E,function(a){return c._update(a,b)})):a===D||!a&&""!==a?D:(a.jquery&&a.length>0?b.empty().append(a.css({display:"block",visibility:"visible"})):b.html(a),this._waitForContent(b).then(function(a){a.images&&a.images.length&&c.rendered&&c.tooltip[0].offsetWidth>0&&c.reposition(e.event,!a.length)}))):D},y._waitForContent=function(a){var b=this.cache;return b.waiting=C,(d.fn.imagesLoaded?a.imagesLoaded():d.Deferred().resolve([])).done(function(){b.waiting=D}).promise()},y._updateContent=function(a,b){this._update(a,this.elements.content,b)},y._updateTitle=function(a,b){this._update(a,this.elements.title,b)===D&&this._removeTitle(D)},y._createTitle=function(){var a=this.elements,b=this._id+"-title";a.titlebar&&this._removeTitle(),a.titlebar=d("<div />",{"class":R+"-titlebar "+(this.options.style.widget?k("header"):"")}).append(a.title=d("<div />",{id:b,"class":R+"-title","aria-atomic":C})).insertBefore(a.content).delegate(".qtip-close","mousedown keydown mouseup keyup mouseout",function(a){d(this).toggleClass("ui-state-active ui-state-focus","down"===a.type.substr(-4))}).delegate(".qtip-close","mouseover mouseout",function(a){d(this).toggleClass("ui-state-hover","mouseover"===a.type)}),this.options.content.button&&this._createButton()},y._removeTitle=function(a){var b=this.elements;b.title&&(b.titlebar.remove(),b.titlebar=b.title=b.button=E,a!==D&&this.reposition())},y.reposition=function(c,e){if(!this.rendered||this.positioning||this.destroyed)return this;this.positioning=C;var f,g,h=this.cache,i=this.tooltip,j=this.options.position,k=j.target,l=j.my,m=j.at,n=j.viewport,o=j.container,p=j.adjust,q=p.method.split(" "),r=i.outerWidth(D),s=i.outerHeight(D),t=0,u=0,v=i.css("position"),w={left:0,top:0},x=i[0].offsetWidth>0,y=c&&"scroll"===c.type,z=d(a),A=o[0].ownerDocument,B=this.mouse;if(d.isArray(k)&&2===k.length)m={x:K,y:J},w={left:k[0],top:k[1]};else if("mouse"===k)m={x:K,y:J},!B||!B.pageX||!p.mouse&&c&&c.pageX?c&&c.pageX||((!p.mouse||this.options.show.distance)&&h.origin&&h.origin.pageX?c=h.origin:(!c||c&&("resize"===c.type||"scroll"===c.type))&&(c=h.event)):c=B,"static"!==v&&(w=o.offset()),A.body.offsetWidth!==(a.innerWidth||A.documentElement.clientWidth)&&(g=d(b.body).offset()),w={left:c.pageX-w.left+(g&&g.left||0),top:c.pageY-w.top+(g&&g.top||0)},p.mouse&&y&&B&&(w.left-=(B.scrollX||0)-z.scrollLeft(),w.top-=(B.scrollY||0)-z.scrollTop());else{if("event"===k?c&&c.target&&"scroll"!==c.type&&"resize"!==c.type?h.target=d(c.target):c.target||(h.target=this.elements.target):"event"!==k&&(h.target=d(k.jquery?k:this.elements.target)),k=h.target,k=d(k).eq(0),0===k.length)return this;k[0]===b||k[0]===a?(t=cb.iOS?a.innerWidth:k.width(),u=cb.iOS?a.innerHeight:k.height(),k[0]===a&&(w={top:(n||k).scrollTop(),left:(n||k).scrollLeft()})):Q.imagemap&&k.is("area")?f=Q.imagemap(this,k,m,Q.viewport?q:D):Q.svg&&k&&k[0].ownerSVGElement?f=Q.svg(this,k,m,Q.viewport?q:D):(t=k.outerWidth(D),u=k.outerHeight(D),w=k.offset()),f&&(t=f.width,u=f.height,g=f.offset,w=f.position),w=this.reposition.offset(k,w,o),(cb.iOS>3.1&&cb.iOS<4.1||cb.iOS>=4.3&&cb.iOS<4.33||!cb.iOS&&"fixed"===v)&&(w.left-=z.scrollLeft(),w.top-=z.scrollTop()),(!f||f&&f.adjustable!==D)&&(w.left+=m.x===M?t:m.x===N?t/2:0,w.top+=m.y===L?u:m.y===N?u/2:0)}return w.left+=p.x+(l.x===M?-r:l.x===N?-r/2:0),w.top+=p.y+(l.y===L?-s:l.y===N?-s/2:0),Q.viewport?(w.adjusted=Q.viewport(this,w,j,t,u,r,s),g&&w.adjusted.left&&(w.left+=g.left),g&&w.adjusted.top&&(w.top+=g.top)):w.adjusted={left:0,top:0},this._trigger("move",[w,n.elem||n],c)?(delete w.adjusted,e===D||!x||isNaN(w.left)||isNaN(w.top)||"mouse"===k||!d.isFunction(j.effect)?i.css(w):d.isFunction(j.effect)&&(j.effect.call(i,this,d.extend({},w)),i.queue(function(a){d(this).css({opacity:"",height:""}),cb.ie&&this.style.removeAttribute("filter"),a()})),this.positioning=D,this):this},y.reposition.offset=function(a,c,e){function f(a,b){c.left+=b*a.scrollLeft(),c.top+=b*a.scrollTop()}if(!e[0])return c;var g,h,i,j,k=d(a[0].ownerDocument),l=!!cb.ie&&"CSS1Compat"!==b.compatMode,m=e[0];do"static"!==(h=d.css(m,"position"))&&("fixed"===h?(i=m.getBoundingClientRect(),f(k,-1)):(i=d(m).position(),i.left+=parseFloat(d.css(m,"borderLeftWidth"))||0,i.top+=parseFloat(d.css(m,"borderTopWidth"))||0),c.left-=i.left+(parseFloat(d.css(m,"marginLeft"))||0),c.top-=i.top+(parseFloat(d.css(m,"marginTop"))||0),g||"hidden"===(j=d.css(m,"overflow"))||"visible"===j||(g=d(m)));while(m=m.offsetParent);return g&&(g[0]!==k[0]||l)&&f(g,1),c};var fb=(z=y.reposition.Corner=function(a,b){a=(""+a).replace(/([A-Z])/," $1").replace(/middle/gi,N).toLowerCase(),this.x=(a.match(/left|right/i)||a.match(/center/)||["inherit"])[0].toLowerCase(),this.y=(a.match(/top|bottom|center/i)||["inherit"])[0].toLowerCase(),this.forceY=!!b;var c=a.charAt(0);this.precedance="t"===c||"b"===c?G:F}).prototype;fb.invert=function(a,b){this[a]=this[a]===K?M:this[a]===M?K:b||this[a]},fb.string=function(){var a=this.x,b=this.y;return a===b?a:this.precedance===G||this.forceY&&"center"!==b?b+" "+a:a+" "+b},fb.abbrev=function(){var a=this.string().split(" ");return a[0].charAt(0)+(a[1]&&a[1].charAt(0)||"")},fb.clone=function(){return new z(this.string(),this.forceY)},y.toggle=function(a,c){var e=this.cache,f=this.options,g=this.tooltip;if(c){if(/over|enter/.test(c.type)&&/out|leave/.test(e.event.type)&&f.show.target.add(c.target).length===f.show.target.length&&g.has(c.relatedTarget).length)return this;e.event=l(c)}if(this.waiting&&!a&&(this.hiddenDuringWait=C),!this.rendered)return a?this.render(1):this;if(this.destroyed||this.disabled)return this;var h,i,j,k=a?"show":"hide",m=this.options[k],n=(this.options[a?"hide":"show"],this.options.position),o=this.options.content,p=this.tooltip.css("width"),q=this.tooltip.is(":visible"),r=a||1===m.target.length,s=!c||m.target.length<2||e.target[0]===c.target;return(typeof a).search("boolean|number")&&(a=!q),h=!g.is(":animated")&&q===a&&s,i=h?E:!!this._trigger(k,[90]),this.destroyed?this:(i!==D&&a&&this.focus(c),!i||h?this:(d.attr(g[0],"aria-hidden",!a),a?(e.origin=l(this.mouse),d.isFunction(o.text)&&this._updateContent(o.text,D),d.isFunction(o.title)&&this._updateTitle(o.title,D),!B&&"mouse"===n.target&&n.adjust.mouse&&(d(b).bind("mousemove."+R,this._storeMouse),B=C),p||g.css("width",g.outerWidth(D)),this.reposition(c,arguments[2]),p||g.css("width",""),m.solo&&("string"==typeof m.solo?d(m.solo):d(V,m.solo)).not(g).not(m.target).qtip("hide",d.Event("tooltipsolo"))):(clearTimeout(this.timers.show),delete e.origin,B&&!d(V+'[tracking="true"]:visible',m.solo).not(g).length&&(d(b).unbind("mousemove."+R),B=D),this.blur(c)),j=d.proxy(function(){a?(cb.ie&&g[0].style.removeAttribute("filter"),g.css("overflow",""),"string"==typeof m.autofocus&&d(this.options.show.autofocus,g).focus(),this.options.show.target.trigger("qtip-"+this.id+"-inactive")):g.css({display:"",visibility:"",opacity:"",left:"",top:""}),this._trigger(a?"visible":"hidden")},this),m.effect===D||r===D?(g[k](),j()):d.isFunction(m.effect)?(g.stop(1,1),m.effect.call(g,this),g.queue("fx",function(a){j(),a()})):g.fadeTo(90,a?1:0,j),a&&m.target.trigger("qtip-"+this.id+"-inactive"),this))},y.show=function(a){return this.toggle(C,a)},y.hide=function(a){return this.toggle(D,a)},y.focus=function(a){if(!this.rendered||this.destroyed)return this;var b=d(V),c=this.tooltip,e=parseInt(c[0].style.zIndex,10),f=x.zindex+b.length;return c.hasClass(Z)||this._trigger("focus",[f],a)&&(e!==f&&(b.each(function(){this.style.zIndex>e&&(this.style.zIndex=this.style.zIndex-1)}),b.filter("."+Z).qtip("blur",a)),c.addClass(Z)[0].style.zIndex=f),this},y.blur=function(a){return!this.rendered||this.destroyed?this:(this.tooltip.removeClass(Z),this._trigger("blur",[this.tooltip.css("zIndex")],a),this)},y.disable=function(a){return this.destroyed?this:("toggle"===a?a=!(this.rendered?this.tooltip.hasClass(_):this.disabled):"boolean"!=typeof a&&(a=C),this.rendered&&this.tooltip.toggleClass(_,a).attr("aria-disabled",a),this.disabled=!!a,this)},y.enable=function(){return this.disable(D)},y._createButton=function(){var a=this,b=this.elements,c=b.tooltip,e=this.options.content.button,f="string"==typeof e,g=f?e:"Close tooltip";b.button&&b.button.remove(),b.button=e.jquery?e:d("<a />",{"class":"qtip-close "+(this.options.style.widget?"":R+"-icon"),title:g,"aria-label":g}).prepend(d("<span />",{"class":"ui-icon ui-icon-close",html:"×"})),b.button.appendTo(b.titlebar||c).attr("role","button").click(function(b){return c.hasClass(_)||a.hide(b),D})},y._updateButton=function(a){if(!this.rendered)return D;var b=this.elements.button;a?this._createButton():b.remove()},y._setWidget=function(){var a=this.options.style.widget,b=this.elements,c=b.tooltip,d=c.hasClass(_);c.removeClass(_),_=a?"ui-state-disabled":"qtip-disabled",c.toggleClass(_,d),c.toggleClass("ui-helper-reset "+k(),a).toggleClass(Y,this.options.style.def&&!a),b.content&&b.content.toggleClass(k("content"),a),b.titlebar&&b.titlebar.toggleClass(k("header"),a),b.button&&b.button.toggleClass(R+"-icon",!a)},y._storeMouse=function(a){(this.mouse=l(a)).type="mousemove"},y._bind=function(a,b,c,e,f){var g="."+this._id+(e?"-"+e:"");b.length&&d(a).bind((b.split?b:b.join(g+" "))+g,d.proxy(c,f||this))},y._unbind=function(a,b){d(a).unbind("."+this._id+(b?"-"+b:""))};var gb="."+R;d(function(){r(V,["mouseenter","mouseleave"],function(a){var b="mouseenter"===a.type,c=d(a.currentTarget),e=d(a.relatedTarget||a.target),f=this.options;b?(this.focus(a),c.hasClass(X)&&!c.hasClass(_)&&clearTimeout(this.timers.hide)):"mouse"===f.position.target&&f.hide.event&&f.show.target&&!e.closest(f.show.target[0]).length&&this.hide(a),c.toggleClass($,b)}),r("["+T+"]",W,p)}),y._trigger=function(a,b,c){var e=d.Event("tooltip"+a);return e.originalEvent=c&&d.extend({},c)||this.cache.event||E,this.triggering=a,this.tooltip.trigger(e,[this].concat(b||[])),this.triggering=D,!e.isDefaultPrevented()},y._bindEvents=function(a,b,c,e,f,g){if(e.add(c).length===e.length){var h=[];b=d.map(b,function(b){var c=d.inArray(b,a);return c>-1?(h.push(a.splice(c,1)[0]),void 0):b}),h.length&&this._bind(c,h,function(a){var b=this.rendered?this.tooltip[0].offsetWidth>0:!1;(b?g:f).call(this,a)})}this._bind(c,a,f),this._bind(e,b,g)},y._assignInitialEvents=function(a){function b(a){return this.disabled||this.destroyed?D:(this.cache.event=l(a),this.cache.target=a?d(a.target):[c],clearTimeout(this.timers.show),this.timers.show=m.call(this,function(){this.render("object"==typeof a||e.show.ready)},e.show.delay),void 0)}var e=this.options,f=e.show.target,g=e.hide.target,h=e.show.event?d.trim(""+e.show.event).split(" "):[],i=e.hide.event?d.trim(""+e.hide.event).split(" "):[];/mouse(over|enter)/i.test(e.show.event)&&!/mouse(out|leave)/i.test(e.hide.event)&&i.push("mouseleave"),this._bind(f,"mousemove",function(a){this._storeMouse(a),this.cache.onTarget=C}),this._bindEvents(h,i,f,g,b,function(){clearTimeout(this.timers.show)}),(e.show.ready||e.prerender)&&b.call(this,a)},y._assignEvents=function(){var c=this,e=this.options,f=e.position,g=this.tooltip,h=e.show.target,i=e.hide.target,j=f.container,k=f.viewport,l=d(b),m=(d(b.body),d(a)),r=e.show.event?d.trim(""+e.show.event).split(" "):[],s=e.hide.event?d.trim(""+e.hide.event).split(" "):[];d.each(e.events,function(a,b){c._bind(g,"toggle"===a?["tooltipshow","tooltiphide"]:["tooltip"+a],b,null,g)}),/mouse(out|leave)/i.test(e.hide.event)&&"window"===e.hide.leave&&this._bind(l,["mouseout","blur"],function(a){/select|option/.test(a.target.nodeName)||a.relatedTarget||this.hide(a)}),e.hide.fixed?i=i.add(g.addClass(X)):/mouse(over|enter)/i.test(e.show.event)&&this._bind(i,"mouseleave",function(){clearTimeout(this.timers.show)}),(""+e.hide.event).indexOf("unfocus")>-1&&this._bind(j.closest("html"),["mousedown","touchstart"],function(a){var b=d(a.target),c=this.rendered&&!this.tooltip.hasClass(_)&&this.tooltip[0].offsetWidth>0,e=b.parents(V).filter(this.tooltip[0]).length>0;b[0]===this.target[0]||b[0]===this.tooltip[0]||e||this.target.has(b[0]).length||!c||this.hide(a)}),"number"==typeof e.hide.inactive&&(this._bind(h,"qtip-"+this.id+"-inactive",p),this._bind(i.add(g),x.inactiveEvents,p,"-inactive")),this._bindEvents(r,s,h,i,n,o),this._bind(h.add(g),"mousemove",function(a){if("number"==typeof e.hide.distance){var b=this.cache.origin||{},c=this.options.hide.distance,d=Math.abs;(d(a.pageX-b.pageX)>=c||d(a.pageY-b.pageY)>=c)&&this.hide(a)}this._storeMouse(a)}),"mouse"===f.target&&f.adjust.mouse&&(e.hide.event&&this._bind(h,["mouseenter","mouseleave"],function(a){this.cache.onTarget="mouseenter"===a.type}),this._bind(l,"mousemove",function(a){this.rendered&&this.cache.onTarget&&!this.tooltip.hasClass(_)&&this.tooltip[0].offsetWidth>0&&this.reposition(a)})),(f.adjust.resize||k.length)&&this._bind(d.event.special.resize?k:m,"resize",q),f.adjust.scroll&&this._bind(m.add(f.container),"scroll",q)},y._unassignEvents=function(){var c=[this.options.show.target[0],this.options.hide.target[0],this.rendered&&this.tooltip[0],this.options.position.container[0],this.options.position.viewport[0],this.options.position.container.closest("html")[0],a,b];this._unbind(d([]).pushStack(d.grep(c,function(a){return"object"==typeof a})))},x=d.fn.qtip=function(a,b,e){var f=(""+a).toLowerCase(),g=E,i=d.makeArray(arguments).slice(1),j=i[i.length-1],k=this[0]?d.data(this[0],R):E;return!arguments.length&&k||"api"===f?k:"string"==typeof a?(this.each(function(){var a=d.data(this,R);if(!a)return C;if(j&&j.timeStamp&&(a.cache.event=j),!b||"option"!==f&&"options"!==f)a[f]&&a[f].apply(a,i);else{if(e===c&&!d.isPlainObject(b))return g=a.get(b),D;a.set(b,e)}}),g!==E?g:this):"object"!=typeof a&&arguments.length?void 0:(k=h(d.extend(C,{},a)),this.each(function(a){var b,c;return c=d.isArray(k.id)?k.id[a]:k.id,c=!c||c===D||c.length<1||x.api[c]?x.nextid++:c,b=s(d(this),c,k),b===D?C:(x.api[c]=b,d.each(Q,function(){"initialize"===this.initialize&&this(b)}),b._assignInitialEvents(j),void 0)}))},d.qtip=e,x.api={},d.each({attr:function(a,b){if(this.length){var c=this[0],e="title",f=d.data(c,"qtip");if(a===e&&f&&"object"==typeof f&&f.options.suppress)return arguments.length<2?d.attr(c,bb):(f&&f.options.content.attr===e&&f.cache.attr&&f.set("content.text",b),this.attr(bb,b))}return d.fn["attr"+ab].apply(this,arguments)},clone:function(a){var b=(d([]),d.fn["clone"+ab].apply(this,arguments));return a||b.filter("["+bb+"]").attr("title",function(){return d.attr(this,bb)}).removeAttr(bb),b}},function(a,b){if(!b||d.fn[a+ab])return C;var c=d.fn[a+ab]=d.fn[a];d.fn[a]=function(){return b.apply(this,arguments)||c.apply(this,arguments)}}),d.ui||(d["cleanData"+ab]=d.cleanData,d.cleanData=function(a){for(var b,c=0;(b=d(a[c])).length;c++)if(b.attr(S))try{b.triggerHandler("removeqtip")}catch(e){}d["cleanData"+ab].apply(this,arguments)}),x.version="2.2.0",x.nextid=0,x.inactiveEvents=W,x.zindex=15e3,x.defaults={prerender:D,id:D,overwrite:C,suppress:C,content:{text:C,attr:"title",title:D,button:D},position:{my:"top left",at:"bottom right",target:D,container:D,viewport:D,adjust:{x:0,y:0,mouse:C,scroll:C,resize:C,method:"flipinvert flipinvert"},effect:function(a,b){d(this).animate(b,{duration:200,queue:D})}},show:{target:D,event:"mouseenter",effect:C,delay:90,solo:D,ready:D,autofocus:D},hide:{target:D,event:"mouseleave",effect:C,delay:0,fixed:D,inactive:D,leave:"window",distance:D},style:{classes:"",widget:D,width:D,height:D,def:C},events:{render:E,move:E,show:E,hide:E,toggle:E,visible:E,hidden:E,focus:E,blur:E}};var hb,ib="margin",jb="border",kb="color",lb="background-color",mb="transparent",nb=" !important",ob=!!b.createElement("canvas").getContext,pb=/rgba?\(0, 0, 0(, 0)?\)|transparent|#123456/i,qb={},rb=["Webkit","O","Moz","ms"];if(ob)var sb=a.devicePixelRatio||1,tb=function(){var a=b.createElement("canvas").getContext("2d");return a.backingStorePixelRatio||a.webkitBackingStorePixelRatio||a.mozBackingStorePixelRatio||a.msBackingStorePixelRatio||a.oBackingStorePixelRatio||1}(),ub=sb/tb;else var vb=function(a,b,c){return"<qtipvml:"+a+' xmlns="urn:schemas-microsoft.com:vml" class="qtip-vml" '+(b||"")+' style="behavior: url(#default#VML); '+(c||"")+'" />'};d.extend(w.prototype,{init:function(a){var b,c;c=this.element=a.elements.tip=d("<div />",{"class":R+"-tip"}).prependTo(a.tooltip),ob?(b=d("<canvas />").appendTo(this.element)[0].getContext("2d"),b.lineJoin="miter",b.miterLimit=1e5,b.save()):(b=vb("shape",'coordorigin="0,0"',"position:absolute;"),this.element.html(b+b),a._bind(d("*",c).add(c),["click","mousedown"],function(a){a.stopPropagation()},this._ns)),a._bind(a.tooltip,"tooltipmove",this.reposition,this._ns,this),this.create()},_swapDimensions:function(){this.size[0]=this.options.height,this.size[1]=this.options.width},_resetDimensions:function(){this.size[0]=this.options.width,this.size[1]=this.options.height},_useTitle:function(a){var b=this.qtip.elements.titlebar;return b&&(a.y===J||a.y===N&&this.element.position().top+this.size[1]/2+this.options.offset<b.outerHeight(C))},_parseCorner:function(a){var b=this.qtip.options.position.my;return a===D||b===D?a=D:a===C?a=new z(b.string()):a.string||(a=new z(a),a.fixed=C),a},_parseWidth:function(a,b,c){var d=this.qtip.elements,e=jb+t(b)+"Width";return(c?v(c,e):v(d.content,e)||v(this._useTitle(a)&&d.titlebar||d.content,e)||v(d.tooltip,e))||0},_parseRadius:function(a){var b=this.qtip.elements,c=jb+t(a.y)+t(a.x)+"Radius";return cb.ie<9?0:v(this._useTitle(a)&&b.titlebar||b.content,c)||v(b.tooltip,c)||0},_invalidColour:function(a,b,c){var d=a.css(b);return!d||c&&d===a.css(c)||pb.test(d)?D:d},_parseColours:function(a){var b=this.qtip.elements,c=this.element.css("cssText",""),e=jb+t(a[a.precedance])+t(kb),f=this._useTitle(a)&&b.titlebar||b.content,g=this._invalidColour,h=[];return h[0]=g(c,lb)||g(f,lb)||g(b.content,lb)||g(b.tooltip,lb)||c.css(lb),h[1]=g(c,e,kb)||g(f,e,kb)||g(b.content,e,kb)||g(b.tooltip,e,kb)||b.tooltip.css(e),d("*",c).add(c).css("cssText",lb+":"+mb+nb+";"+jb+":0"+nb+";"),h},_calculateSize:function(a){var b,c,d,e=a.precedance===G,f=this.options.width,g=this.options.height,h="c"===a.abbrev(),i=(e?f:g)*(h?.5:1),j=Math.pow,k=Math.round,l=Math.sqrt(j(i,2)+j(g,2)),m=[this.border/i*l,this.border/g*l];return m[2]=Math.sqrt(j(m[0],2)-j(this.border,2)),m[3]=Math.sqrt(j(m[1],2)-j(this.border,2)),b=l+m[2]+m[3]+(h?0:m[0]),c=b/l,d=[k(c*f),k(c*g)],e?d:d.reverse()},_calculateTip:function(a,b,c){c=c||1,b=b||this.size;var d=b[0]*c,e=b[1]*c,f=Math.ceil(d/2),g=Math.ceil(e/2),h={br:[0,0,d,e,d,0],bl:[0,0,d,0,0,e],tr:[0,e,d,0,d,e],tl:[0,0,0,e,d,e],tc:[0,e,f,0,d,e],bc:[0,0,d,0,f,e],rc:[0,0,d,g,0,e],lc:[d,0,d,e,0,g]};return h.lt=h.br,h.rt=h.bl,h.lb=h.tr,h.rb=h.tl,h[a.abbrev()]},_drawCoords:function(a,b){a.beginPath(),a.moveTo(b[0],b[1]),a.lineTo(b[2],b[3]),a.lineTo(b[4],b[5]),a.closePath()},create:function(){var a=this.corner=(ob||cb.ie)&&this._parseCorner(this.options.corner);return(this.enabled=!!this.corner&&"c"!==this.corner.abbrev())&&(this.qtip.cache.corner=a.clone(),this.update()),this.element.toggle(this.enabled),this.corner},update:function(b,c){if(!this.enabled)return this;var e,f,g,h,i,j,k,l,m=this.qtip.elements,n=this.element,o=n.children(),p=this.options,q=this.size,r=p.mimic,s=Math.round;b||(b=this.qtip.cache.corner||this.corner),r===D?r=b:(r=new z(r),r.precedance=b.precedance,"inherit"===r.x?r.x=b.x:"inherit"===r.y?r.y=b.y:r.x===r.y&&(r[b.precedance]=b[b.precedance])),f=r.precedance,b.precedance===F?this._swapDimensions():this._resetDimensions(),e=this.color=this._parseColours(b),e[1]!==mb?(l=this.border=this._parseWidth(b,b[b.precedance]),p.border&&1>l&&!pb.test(e[1])&&(e[0]=e[1]),this.border=l=p.border!==C?p.border:l):this.border=l=0,k=this.size=this._calculateSize(b),n.css({width:k[0],height:k[1],lineHeight:k[1]+"px"}),j=b.precedance===G?[s(r.x===K?l:r.x===M?k[0]-q[0]-l:(k[0]-q[0])/2),s(r.y===J?k[1]-q[1]:0)]:[s(r.x===K?k[0]-q[0]:0),s(r.y===J?l:r.y===L?k[1]-q[1]-l:(k[1]-q[1])/2)],ob?(g=o[0].getContext("2d"),g.restore(),g.save(),g.clearRect(0,0,6e3,6e3),h=this._calculateTip(r,q,ub),i=this._calculateTip(r,this.size,ub),o.attr(H,k[0]*ub).attr(I,k[1]*ub),o.css(H,k[0]).css(I,k[1]),this._drawCoords(g,i),g.fillStyle=e[1],g.fill(),g.translate(j[0]*ub,j[1]*ub),this._drawCoords(g,h),g.fillStyle=e[0],g.fill()):(h=this._calculateTip(r),h="m"+h[0]+","+h[1]+" l"+h[2]+","+h[3]+" "+h[4]+","+h[5]+" xe",j[2]=l&&/^(r|b)/i.test(b.string())?8===cb.ie?2:1:0,o.css({coordsize:k[0]+l+" "+(k[1]+l),antialias:""+(r.string().indexOf(N)>-1),left:j[0]-j[2]*Number(f===F),top:j[1]-j[2]*Number(f===G),width:k[0]+l,height:k[1]+l}).each(function(a){var b=d(this);b[b.prop?"prop":"attr"]({coordsize:k[0]+l+" "+(k[1]+l),path:h,fillcolor:e[0],filled:!!a,stroked:!a}).toggle(!(!l&&!a)),!a&&b.html(vb("stroke",'weight="'+2*l+'px" color="'+e[1]+'" miterlimit="1000" joinstyle="miter"'))})),a.opera&&setTimeout(function(){m.tip.css({display:"inline-block",visibility:"visible"})},1),c!==D&&this.calculate(b,k)},calculate:function(a,b){if(!this.enabled)return D;var c,e,f=this,g=this.qtip.elements,h=this.element,i=this.options.offset,j=(g.tooltip.hasClass("ui-widget"),{});return a=a||this.corner,c=a.precedance,b=b||this._calculateSize(a),e=[a.x,a.y],c===F&&e.reverse(),d.each(e,function(d,e){var h,k,l;e===N?(h=c===G?K:J,j[h]="50%",j[ib+"-"+h]=-Math.round(b[c===G?0:1]/2)+i):(h=f._parseWidth(a,e,g.tooltip),k=f._parseWidth(a,e,g.content),l=f._parseRadius(a),j[e]=Math.max(-f.border,d?k:i+(l>h?l:-h)))}),j[a[c]]-=b[c===F?0:1],h.css({margin:"",top:"",bottom:"",left:"",right:""}).css(j),j
+},reposition:function(a,b,d){function e(a,b,c,d,e){a===P&&j.precedance===b&&k[d]&&j[c]!==N?j.precedance=j.precedance===F?G:F:a!==P&&k[d]&&(j[b]=j[b]===N?k[d]>0?d:e:j[b]===d?e:d)}function f(a,b,e){j[a]===N?p[ib+"-"+b]=o[a]=g[ib+"-"+b]-k[b]:(h=g[e]!==c?[k[b],-g[b]]:[-k[b],g[b]],(o[a]=Math.max(h[0],h[1]))>h[0]&&(d[b]-=k[b],o[b]=D),p[g[e]!==c?e:b]=o[a])}if(this.enabled){var g,h,i=b.cache,j=this.corner.clone(),k=d.adjusted,l=b.options.position.adjust.method.split(" "),m=l[0],n=l[1]||l[0],o={left:D,top:D,x:0,y:0},p={};this.corner.fixed!==C&&(e(m,F,G,K,M),e(n,G,F,J,L),j.string()===i.corner.string()||i.cornerTop===k.top&&i.cornerLeft===k.left||this.update(j,D)),g=this.calculate(j),g.right!==c&&(g.left=-g.right),g.bottom!==c&&(g.top=-g.bottom),g.user=this.offset,(o.left=m===P&&!!k.left)&&f(F,K,M),(o.top=n===P&&!!k.top)&&f(G,J,L),this.element.css(p).toggle(!(o.x&&o.y||j.x===N&&o.y||j.y===N&&o.x)),d.left-=g.left.charAt?g.user:m!==P||o.top||!o.left&&!o.top?g.left+this.border:0,d.top-=g.top.charAt?g.user:n!==P||o.left||!o.left&&!o.top?g.top+this.border:0,i.cornerLeft=k.left,i.cornerTop=k.top,i.corner=j.clone()}},destroy:function(){this.qtip._unbind(this.qtip.tooltip,this._ns),this.qtip.elements.tip&&this.qtip.elements.tip.find("*").remove().end().remove()}}),hb=Q.tip=function(a){return new w(a,a.options.style.tip)},hb.initialize="render",hb.sanitize=function(a){if(a.style&&"tip"in a.style){var b=a.style.tip;"object"!=typeof b&&(b=a.style.tip={corner:b}),/string|boolean/i.test(typeof b.corner)||(b.corner=C)}},A.tip={"^position.my|style.tip.(corner|mimic|border)$":function(){this.create(),this.qtip.reposition()},"^style.tip.(height|width)$":function(a){this.size=[a.width,a.height],this.update(),this.qtip.reposition()},"^content.title|style.(classes|widget)$":function(){this.update()}},d.extend(C,x.defaults,{style:{tip:{corner:C,mimic:D,width:6,height:6,border:C,offset:0}}}),Q.viewport=function(c,d,e,f,g,h,i){function j(a,b,c,e,f,g,h,i,j){var k=d[f],m=v[a],t=w[a],u=c===P,x=m===f?j:m===g?-j:-j/2,y=t===f?i:t===g?-i:-i/2,z=r[f]+s[f]-(o?0:n[f]),A=z-k,B=k+j-(h===H?p:q)-z,C=x-(v.precedance===a||m===v[b]?y:0)-(t===N?i/2:0);return u?(C=(m===f?1:-1)*x,d[f]+=A>0?A:B>0?-B:0,d[f]=Math.max(-n[f]+s[f],k-C,Math.min(Math.max(-n[f]+s[f]+(h===H?p:q),k+C),d[f],"center"===m?k-x:1e9))):(e*=c===O?2:0,A>0&&(m!==f||B>0)?(d[f]-=C+e,l.invert(a,f)):B>0&&(m!==g||A>0)&&(d[f]-=(m===N?-C:C)+e,l.invert(a,g)),d[f]<r&&-d[f]>B&&(d[f]=k,l=v.clone())),d[f]-k}var k,l,m,n,o,p,q,r,s,t=e.target,u=c.elements.tooltip,v=e.my,w=e.at,x=e.adjust,y=x.method.split(" "),z=y[0],A=y[1]||y[0],B=e.viewport,C=e.container,E=c.cache,Q={left:0,top:0};return B.jquery&&t[0]!==a&&t[0]!==b.body&&"none"!==x.method?(n=C.offset()||Q,o="static"===C.css("position"),k="fixed"===u.css("position"),p=B[0]===a?B.width():B.outerWidth(D),q=B[0]===a?B.height():B.outerHeight(D),r={left:k?0:B.scrollLeft(),top:k?0:B.scrollTop()},s=B.offset()||Q,("shift"!==z||"shift"!==A)&&(l=v.clone()),Q={left:"none"!==z?j(F,G,z,x.x,K,M,H,f,h):0,top:"none"!==A?j(G,F,A,x.y,J,L,I,g,i):0},l&&E.lastClass!==(m=R+"-pos-"+l.abbrev())&&u.removeClass(c.cache.lastClass).addClass(c.cache.lastClass=m),Q):Q}})}(window,document);
+//# sourceMappingURL=http://cdnjs.cloudflare.com/ajax/libs/qtip2/2.2.0//var/www/qtip2/build/tmp/tmp-9404f1j0t40/jquery.qtip.min.map
\ No newline at end of file
--- /dev/null
+/**
+ * jQuery.ScrollTo - Easy element scrolling using jQuery.
+ * Copyright (c) 2007-2009 Ariel Flesler - aflesler(at)gmail(dot)com | http://flesler.blogspot.com
+ * Dual licensed under MIT and GPL.
+ * Date: 5/25/2009
+ * @author Ariel Flesler
+ * @version 1.4.2
+ *
+ * http://flesler.blogspot.com/2007/10/jqueryscrollto.html
+ */
+;(function(d){var k=d.scrollTo=function(a,i,e){d(window).scrollTo(a,i,e)};k.defaults={axis:'xy',duration:parseFloat(d.fn.jquery)>=1.3?0:1};k.window=function(a){return d(window)._scrollable()};d.fn._scrollable=function(){return this.map(function(){var a=this,i=!a.nodeName||d.inArray(a.nodeName.toLowerCase(),['iframe','#document','html','body'])!=-1;if(!i)return a;var e=(a.contentWindow||a).document||a.ownerDocument||a;return d.browser.safari||e.compatMode=='BackCompat'?e.body:e.documentElement})};d.fn.scrollTo=function(n,j,b){if(typeof j=='object'){b=j;j=0}if(typeof b=='function')b={onAfter:b};if(n=='max')n=9e9;b=d.extend({},k.defaults,b);j=j||b.speed||b.duration;b.queue=b.queue&&b.axis.length>1;if(b.queue)j/=2;b.offset=p(b.offset);b.over=p(b.over);return this._scrollable().each(function(){var q=this,r=d(q),f=n,s,g={},u=r.is('html,body');switch(typeof f){case'number':case'string':if(/^([+-]=)?\d+(\.\d+)?(px|%)?$/.test(f)){f=p(f);break}f=d(f,this);case'object':if(f.is||f.style)s=(f=d(f)).offset()}d.each(b.axis.split(''),function(a,i){var e=i=='x'?'Left':'Top',h=e.toLowerCase(),c='scroll'+e,l=q[c],m=k.max(q,i);if(s){g[c]=s[h]+(u?0:l-r.offset()[h]);if(b.margin){g[c]-=parseInt(f.css('margin'+e))||0;g[c]-=parseInt(f.css('border'+e+'Width'))||0}g[c]+=b.offset[h]||0;if(b.over[h])g[c]+=f[i=='x'?'width':'height']()*b.over[h]}else{var o=f[h];g[c]=o.slice&&o.slice(-1)=='%'?parseFloat(o)/100*m:o}if(/^\d+$/.test(g[c]))g[c]=g[c]<=0?0:Math.min(g[c],m);if(!a&&b.queue){if(l!=g[c])t(b.onAfterFirst);delete g[c]}});t(b.onAfter);function t(a){r.animate(g,j,b.easing,a&&function(){a.call(this,n,b)})}}).end()};k.max=function(a,i){var e=i=='x'?'Width':'Height',h='scroll'+e;if(!d(a).is('html,body'))return a[h]-d(a)[e.toLowerCase()]();var c='client'+e,l=a.ownerDocument.documentElement,m=a.ownerDocument.body;return Math.max(l[h],m[h])-Math.min(l[c],m[c])};function p(a){return typeof a=='object'?a:{top:a,left:a}}})(jQuery);
\ No newline at end of file
--- /dev/null
+/*
+ * Tabby jQuery plugin version 0.12
+ *
+ * Ted Devito - http://teddevito.com/demos/textarea.html
+ *
+ * Copyright (c) 2009 Ted Devito
+ */
+ (function(d){d.fn.tabby=function(f){var g=d.extend({},d.fn.tabby.defaults,f);var h=d.fn.tabby.pressed;return this.each(function(){$this=d(this);var i=d.meta?d.extend({},g,$this.data()):g;$this.bind("keydown",function(k){var j=d.fn.tabby.catch_kc(k);if(16==j){h.shft=true}if(17==j){h.ctrl=true;setTimeout("$.fn.tabby.pressed.ctrl = false;",1000)}if(18==j){h.alt=true;setTimeout("$.fn.tabby.pressed.alt = false;",1000)}if(9==j&&!h.ctrl&&!h.alt){k.preventDefault;h.last=j;setTimeout("$.fn.tabby.pressed.last = null;",0);e(d(k.target).get(0),h.shft,i);return false}}).bind("keyup",function(j){if(16==d.fn.tabby.catch_kc(j)){h.shft=false}}).bind("blur",function(j){if(9==h.last){d(j.target).one("focus",function(k){h.last=null}).get(0).focus()}})})};d.fn.tabby.catch_kc=function(f){return f.keyCode?f.keyCode:f.charCode?f.charCode:f.which};d.fn.tabby.pressed={shft:false,ctrl:false,alt:false,last:null};function b(f){if(window.console&&window.console.log){window.console.log("textarea count: "+f.size())}}function e(i,h,g){var f=i.scrollTop;if(i.setSelectionRange){a(i,h,g)}else{if(document.selection){c(i,h,g)}}i.scrollTop=f}d.fn.tabby.defaults={tabString:String.fromCharCode(9)};function a(j,f,u){var t=j.selectionStart;var r=j.selectionEnd;if(t==r){if(f){if(t-u.tabString==j.value.substring(t-u.tabString.length,t)){j.value=j.value.substring(0,t-u.tabString.length)+j.value.substring(t);j.focus();j.setSelectionRange(t-u.tabString.length,t-u.tabString.length)}else{if(t-u.tabString==j.value.substring(t,t+u.tabString.length)){j.value=j.value.substring(0,t)+j.value.substring(t+u.tabString.length);j.focus();j.setSelectionRange(t,t)}}}else{j.value=j.value.substring(0,t)+u.tabString+j.value.substring(t);j.focus();j.setSelectionRange(t+u.tabString.length,t+u.tabString.length)}}else{while(t<j.value.length&&j.value.charAt(t).match(/[ \t]/)){t++}var v=j.value.split("\n");var s=new Array();var l=0;var h=0;var g=false;for(var n in v){h=l+v[n].length;s.push({start:l,end:h,selected:(l<=t&&h>t)||(h>=r&&l<r)||(l>t&&h<r)});l=h+1}var k=0;for(var n in s){if(s[n].selected){var q=s[n].start+k;if(f&&u.tabString==j.value.substring(q,q+u.tabString.length)){j.value=j.value.substring(0,q)+j.value.substring(q+u.tabString.length);k-=u.tabString.length}else{if(!f){j.value=j.value.substring(0,q)+u.tabString+j.value.substring(q);k+=u.tabString.length}}}}j.focus();var p=t+((k>0)?u.tabString.length:(k<0)?-u.tabString.length:0);var m=r+k;j.setSelectionRange(p,m)}}function c(q,w,f){var p=document.selection.createRange();if(q==p.parentElement()){if(""==p.text){if(w){var l=p.getBookmark();p.moveStart("character",-f.tabString.length);if(f.tabString==p.text){p.text=""}else{p.moveToBookmark(l);p.moveEnd("character",f.tabString.length);if(f.tabString==p.text){p.text=""}}p.collapse(true);p.select()}else{p.text=f.tabString;p.collapse(false);p.select()}}else{var k=p.text;var n=k.length;var u=k.split("\r\n");var z=document.body.createTextRange();z.moveToElementText(q);z.setEndPoint("EndToStart",p);var m=z.text;var x=m.split("\r\n");var r=m.length;var y=document.body.createTextRange();y.moveToElementText(q);y.setEndPoint("StartToEnd",p);var v=y.text;var g=document.body.createTextRange();g.moveToElementText(q);g.setEndPoint("StartToEnd",z);var s=g.text;var h=d(q).html();d("#r3").text(r+" + "+n+" + "+v.length+" = "+h.length);if((r+s.length)<h.length){x.push("");r+=2;if(w&&f.tabString==u[0].substring(0,f.tabString.length)){u[0]=u[0].substring(f.tabString.length)}else{if(!w){u[0]=f.tabString+u[0]}}}else{if(w&&f.tabString==x[x.length-1].substring(0,f.tabString.length)){x[x.length-1]=x[x.length-1].substring(f.tabString.length)}else{if(!w){x[x.length-1]=f.tabString+x[x.length-1]}}}for(var t=1;t<u.length;t++){if(w&&f.tabString==u[t].substring(0,f.tabString.length)){u[t]=u[t].substring(f.tabString.length)}else{if(!w){u[t]=f.tabString+u[t]}}}if(1==x.length&&0==r){if(w&&f.tabString==u[0].substring(0,f.tabString.length)){u[0]=u[0].substring(f.tabString.length)}else{if(!w){u[0]=f.tabString+u[0]}}}if((r+n+v.length)<h.length){u.push("");n+=2}z.text=x.join("\r\n");p.text=u.join("\r\n");var j=document.body.createTextRange();j.moveToElementText(q);if(0<r){j.setEndPoint("StartToEnd",z)}else{j.setEndPoint("StartToStart",z)}j.setEndPoint("EndToEnd",p);j.select()}}}})(jQuery);
\ No newline at end of file
--- /dev/null
+// @author Rich Adams <rich@richadams.me>
+
+// Implements a tap and hold functionality. If you click/tap and release, it will trigger a normal
+// click event. But if you click/tap and hold for 1s (default), it will trigger a taphold event instead.
+
+;(function($)
+{
+ // Default options
+ var defaults = {
+ duration: 1000, // ms
+ clickHandler: null
+ }
+
+ // When start of a taphold event is triggered.
+ function startHandler(event)
+ {
+ var $elem = jQuery(this);
+
+ // Merge the defaults and any user defined settings.
+ settings = jQuery.extend({}, defaults, event.data);
+
+ // If object also has click handler, store it and unbind. Taphold will trigger the
+ // click itself, rather than normal propagation.
+ if (typeof $elem.data("events") != "undefined"
+ && typeof $elem.data("events").click != "undefined")
+ {
+ // Find the one without a namespace defined.
+ for (var c in $elem.data("events").click)
+ {
+ if ($elem.data("events").click[c].namespace == "")
+ {
+ var handler = $elem.data("events").click[c].handler
+ $elem.data("taphold_click_handler", handler);
+ $elem.unbind("click", handler);
+ break;
+ }
+ }
+ }
+ // Otherwise, if a custom click handler was explicitly defined, then store it instead.
+ else if (typeof settings.clickHandler == "function")
+ {
+ $elem.data("taphold_click_handler", settings.clickHandler);
+ }
+
+ // Reset the flags
+ $elem.data("taphold_triggered", false); // If a hold was triggered
+ $elem.data("taphold_clicked", false); // If a click was triggered
+ $elem.data("taphold_cancelled", false); // If event has been cancelled.
+
+ // Set the timer for the hold event.
+ $elem.data("taphold_timer",
+ setTimeout(function()
+ {
+ // If event hasn't been cancelled/clicked already, then go ahead and trigger the hold.
+ if (!$elem.data("taphold_cancelled")
+ && !$elem.data("taphold_clicked"))
+ {
+ // Trigger the hold event, and set the flag to say it's been triggered.
+ $elem.trigger(jQuery.extend(event, jQuery.Event("taphold")));
+ $elem.data("taphold_triggered", true);
+ }
+ }, settings.duration));
+ }
+
+ // When user ends a tap or click, decide what we should do.
+ function stopHandler(event)
+ {
+ var $elem = jQuery(this);
+
+ // If taphold has been cancelled, then we're done.
+ if ($elem.data("taphold_cancelled")) { return; }
+
+ // Clear the hold timer. If it hasn't already triggered, then it's too late anyway.
+ clearTimeout($elem.data("taphold_timer"));
+
+ // If hold wasn't triggered and not already clicked, then was a click event.
+ if (!$elem.data("taphold_triggered")
+ && !$elem.data("taphold_clicked"))
+ {
+ // If click handler, trigger it.
+ if (typeof $elem.data("taphold_click_handler") == "function")
+ {
+ $elem.data("taphold_click_handler")(jQuery.extend(event, jQuery.Event("click")));
+ }
+
+ // Set flag to say we've triggered the click event.
+ $elem.data("taphold_clicked", true);
+ }
+ }
+
+ // If a user prematurely leaves the boundary of the object we're working on.
+ function leaveHandler(event)
+ {
+ // Cancel the event.
+ $(this).data("taphold_cancelled", true);
+ }
+
+ // Determine if touch events are supported.
+ var touchSupported = ("ontouchstart" in window) // Most browsers
+ || ("onmsgesturechange" in window); // Mircosoft
+
+ var taphold = $.event.special.taphold =
+ {
+ setup: function(data)
+ {
+ $(this).bind((touchSupported ? "touchstart" : "mousedown"), data, startHandler)
+ .bind((touchSupported ? "touchend" : "mouseup"), stopHandler)
+ .bind((touchSupported ? "touchmove" : "mouseleave"), leaveHandler);
+ },
+ teardown: function(namespaces)
+ {
+ $(this).unbind((touchSupported ? "touchstart" : "mousedown"), startHandler)
+ .unbind((touchSupported ? "touchend" : "mouseup"), stopHandler)
+ .unbind((touchSupported ? "touchmove" : "mouseleave"), leaveHandler);
+ }
+ };
+})(jQuery);
\ No newline at end of file
--- /dev/null
+/*! jQuery UI - v1.10.2 - 2013-03-14
+* http://jqueryui.com
+* Copyright 2013 jQuery Foundation and other contributors; Licensed MIT */
+(function(e,t){function i(t,i){var a,n,r,o=t.nodeName.toLowerCase();return"area"===o?(a=t.parentNode,n=a.name,t.href&&n&&"map"===a.nodeName.toLowerCase()?(r=e("img[usemap=#"+n+"]")[0],!!r&&s(r)):!1):(/input|select|textarea|button|object/.test(o)?!t.disabled:"a"===o?t.href||i:i)&&s(t)}function s(t){return e.expr.filters.visible(t)&&!e(t).parents().addBack().filter(function(){return"hidden"===e.css(this,"visibility")}).length}var a=0,n=/^ui-id-\d+$/;e.ui=e.ui||{},e.extend(e.ui,{version:"1.10.2",keyCode:{BACKSPACE:8,COMMA:188,DELETE:46,DOWN:40,END:35,ENTER:13,ESCAPE:27,HOME:36,LEFT:37,NUMPAD_ADD:107,NUMPAD_DECIMAL:110,NUMPAD_DIVIDE:111,NUMPAD_ENTER:108,NUMPAD_MULTIPLY:106,NUMPAD_SUBTRACT:109,PAGE_DOWN:34,PAGE_UP:33,PERIOD:190,RIGHT:39,SPACE:32,TAB:9,UP:38}}),e.fn.extend({focus:function(t){return function(i,s){return"number"==typeof i?this.each(function(){var t=this;setTimeout(function(){e(t).focus(),s&&s.call(t)},i)}):t.apply(this,arguments)}}(e.fn.focus),scrollParent:function(){var t;return t=e.ui.ie&&/(static|relative)/.test(this.css("position"))||/absolute/.test(this.css("position"))?this.parents().filter(function(){return/(relative|absolute|fixed)/.test(e.css(this,"position"))&&/(auto|scroll)/.test(e.css(this,"overflow")+e.css(this,"overflow-y")+e.css(this,"overflow-x"))}).eq(0):this.parents().filter(function(){return/(auto|scroll)/.test(e.css(this,"overflow")+e.css(this,"overflow-y")+e.css(this,"overflow-x"))}).eq(0),/fixed/.test(this.css("position"))||!t.length?e(document):t},zIndex:function(i){if(i!==t)return this.css("zIndex",i);if(this.length)for(var s,a,n=e(this[0]);n.length&&n[0]!==document;){if(s=n.css("position"),("absolute"===s||"relative"===s||"fixed"===s)&&(a=parseInt(n.css("zIndex"),10),!isNaN(a)&&0!==a))return a;n=n.parent()}return 0},uniqueId:function(){return this.each(function(){this.id||(this.id="ui-id-"+ ++a)})},removeUniqueId:function(){return this.each(function(){n.test(this.id)&&e(this).removeAttr("id")})}}),e.extend(e.expr[":"],{data:e.expr.createPseudo?e.expr.createPseudo(function(t){return function(i){return!!e.data(i,t)}}):function(t,i,s){return!!e.data(t,s[3])},focusable:function(t){return i(t,!isNaN(e.attr(t,"tabindex")))},tabbable:function(t){var s=e.attr(t,"tabindex"),a=isNaN(s);return(a||s>=0)&&i(t,!a)}}),e("<a>").outerWidth(1).jquery||e.each(["Width","Height"],function(i,s){function a(t,i,s,a){return e.each(n,function(){i-=parseFloat(e.css(t,"padding"+this))||0,s&&(i-=parseFloat(e.css(t,"border"+this+"Width"))||0),a&&(i-=parseFloat(e.css(t,"margin"+this))||0)}),i}var n="Width"===s?["Left","Right"]:["Top","Bottom"],r=s.toLowerCase(),o={innerWidth:e.fn.innerWidth,innerHeight:e.fn.innerHeight,outerWidth:e.fn.outerWidth,outerHeight:e.fn.outerHeight};e.fn["inner"+s]=function(i){return i===t?o["inner"+s].call(this):this.each(function(){e(this).css(r,a(this,i)+"px")})},e.fn["outer"+s]=function(t,i){return"number"!=typeof t?o["outer"+s].call(this,t):this.each(function(){e(this).css(r,a(this,t,!0,i)+"px")})}}),e.fn.addBack||(e.fn.addBack=function(e){return this.add(null==e?this.prevObject:this.prevObject.filter(e))}),e("<a>").data("a-b","a").removeData("a-b").data("a-b")&&(e.fn.removeData=function(t){return function(i){return arguments.length?t.call(this,e.camelCase(i)):t.call(this)}}(e.fn.removeData)),e.ui.ie=!!/msie [\w.]+/.exec(navigator.userAgent.toLowerCase()),e.support.selectstart="onselectstart"in document.createElement("div"),e.fn.extend({disableSelection:function(){return this.bind((e.support.selectstart?"selectstart":"mousedown")+".ui-disableSelection",function(e){e.preventDefault()})},enableSelection:function(){return this.unbind(".ui-disableSelection")}}),e.extend(e.ui,{plugin:{add:function(t,i,s){var a,n=e.ui[t].prototype;for(a in s)n.plugins[a]=n.plugins[a]||[],n.plugins[a].push([i,s[a]])},call:function(e,t,i){var s,a=e.plugins[t];if(a&&e.element[0].parentNode&&11!==e.element[0].parentNode.nodeType)for(s=0;a.length>s;s++)e.options[a[s][0]]&&a[s][1].apply(e.element,i)}},hasScroll:function(t,i){if("hidden"===e(t).css("overflow"))return!1;var s=i&&"left"===i?"scrollLeft":"scrollTop",a=!1;return t[s]>0?!0:(t[s]=1,a=t[s]>0,t[s]=0,a)}})})(jQuery);
+
+
+/*! jQuery UI - v1.10.2 - 2013-03-14
+* http://jqueryui.com
+* Copyright 2013 jQuery Foundation and other contributors; Licensed MIT */
+(function(e,t){var i=0,s=Array.prototype.slice,n=e.cleanData;e.cleanData=function(t){for(var i,s=0;null!=(i=t[s]);s++)try{e(i).triggerHandler("remove")}catch(a){}n(t)},e.widget=function(i,s,n){var a,r,o,h,l={},u=i.split(".")[0];i=i.split(".")[1],a=u+"-"+i,n||(n=s,s=e.Widget),e.expr[":"][a.toLowerCase()]=function(t){return!!e.data(t,a)},e[u]=e[u]||{},r=e[u][i],o=e[u][i]=function(e,i){return this._createWidget?(arguments.length&&this._createWidget(e,i),t):new o(e,i)},e.extend(o,r,{version:n.version,_proto:e.extend({},n),_childConstructors:[]}),h=new s,h.options=e.widget.extend({},h.options),e.each(n,function(i,n){return e.isFunction(n)?(l[i]=function(){var e=function(){return s.prototype[i].apply(this,arguments)},t=function(e){return s.prototype[i].apply(this,e)};return function(){var i,s=this._super,a=this._superApply;return this._super=e,this._superApply=t,i=n.apply(this,arguments),this._super=s,this._superApply=a,i}}(),t):(l[i]=n,t)}),o.prototype=e.widget.extend(h,{widgetEventPrefix:r?h.widgetEventPrefix:i},l,{constructor:o,namespace:u,widgetName:i,widgetFullName:a}),r?(e.each(r._childConstructors,function(t,i){var s=i.prototype;e.widget(s.namespace+"."+s.widgetName,o,i._proto)}),delete r._childConstructors):s._childConstructors.push(o),e.widget.bridge(i,o)},e.widget.extend=function(i){for(var n,a,r=s.call(arguments,1),o=0,h=r.length;h>o;o++)for(n in r[o])a=r[o][n],r[o].hasOwnProperty(n)&&a!==t&&(i[n]=e.isPlainObject(a)?e.isPlainObject(i[n])?e.widget.extend({},i[n],a):e.widget.extend({},a):a);return i},e.widget.bridge=function(i,n){var a=n.prototype.widgetFullName||i;e.fn[i]=function(r){var o="string"==typeof r,h=s.call(arguments,1),l=this;return r=!o&&h.length?e.widget.extend.apply(null,[r].concat(h)):r,o?this.each(function(){var s,n=e.data(this,a);return n?e.isFunction(n[r])&&"_"!==r.charAt(0)?(s=n[r].apply(n,h),s!==n&&s!==t?(l=s&&s.jquery?l.pushStack(s.get()):s,!1):t):e.error("no such method '"+r+"' for "+i+" widget instance"):e.error("cannot call methods on "+i+" prior to initialization; "+"attempted to call method '"+r+"'")}):this.each(function(){var t=e.data(this,a);t?t.option(r||{})._init():e.data(this,a,new n(r,this))}),l}},e.Widget=function(){},e.Widget._childConstructors=[],e.Widget.prototype={widgetName:"widget",widgetEventPrefix:"",defaultElement:"<div>",options:{disabled:!1,create:null},_createWidget:function(t,s){s=e(s||this.defaultElement||this)[0],this.element=e(s),this.uuid=i++,this.eventNamespace="."+this.widgetName+this.uuid,this.options=e.widget.extend({},this.options,this._getCreateOptions(),t),this.bindings=e(),this.hoverable=e(),this.focusable=e(),s!==this&&(e.data(s,this.widgetFullName,this),this._on(!0,this.element,{remove:function(e){e.target===s&&this.destroy()}}),this.document=e(s.style?s.ownerDocument:s.document||s),this.window=e(this.document[0].defaultView||this.document[0].parentWindow)),this._create(),this._trigger("create",null,this._getCreateEventData()),this._init()},_getCreateOptions:e.noop,_getCreateEventData:e.noop,_create:e.noop,_init:e.noop,destroy:function(){this._destroy(),this.element.unbind(this.eventNamespace).removeData(this.widgetName).removeData(this.widgetFullName).removeData(e.camelCase(this.widgetFullName)),this.widget().unbind(this.eventNamespace).removeAttr("aria-disabled").removeClass(this.widgetFullName+"-disabled "+"ui-state-disabled"),this.bindings.unbind(this.eventNamespace),this.hoverable.removeClass("ui-state-hover"),this.focusable.removeClass("ui-state-focus")},_destroy:e.noop,widget:function(){return this.element},option:function(i,s){var n,a,r,o=i;if(0===arguments.length)return e.widget.extend({},this.options);if("string"==typeof i)if(o={},n=i.split("."),i=n.shift(),n.length){for(a=o[i]=e.widget.extend({},this.options[i]),r=0;n.length-1>r;r++)a[n[r]]=a[n[r]]||{},a=a[n[r]];if(i=n.pop(),s===t)return a[i]===t?null:a[i];a[i]=s}else{if(s===t)return this.options[i]===t?null:this.options[i];o[i]=s}return this._setOptions(o),this},_setOptions:function(e){var t;for(t in e)this._setOption(t,e[t]);return this},_setOption:function(e,t){return this.options[e]=t,"disabled"===e&&(this.widget().toggleClass(this.widgetFullName+"-disabled ui-state-disabled",!!t).attr("aria-disabled",t),this.hoverable.removeClass("ui-state-hover"),this.focusable.removeClass("ui-state-focus")),this},enable:function(){return this._setOption("disabled",!1)},disable:function(){return this._setOption("disabled",!0)},_on:function(i,s,n){var a,r=this;"boolean"!=typeof i&&(n=s,s=i,i=!1),n?(s=a=e(s),this.bindings=this.bindings.add(s)):(n=s,s=this.element,a=this.widget()),e.each(n,function(n,o){function h(){return i||r.options.disabled!==!0&&!e(this).hasClass("ui-state-disabled")?("string"==typeof o?r[o]:o).apply(r,arguments):t}"string"!=typeof o&&(h.guid=o.guid=o.guid||h.guid||e.guid++);var l=n.match(/^(\w+)\s*(.*)$/),u=l[1]+r.eventNamespace,c=l[2];c?a.delegate(c,u,h):s.bind(u,h)})},_off:function(e,t){t=(t||"").split(" ").join(this.eventNamespace+" ")+this.eventNamespace,e.unbind(t).undelegate(t)},_delay:function(e,t){function i(){return("string"==typeof e?s[e]:e).apply(s,arguments)}var s=this;return setTimeout(i,t||0)},_hoverable:function(t){this.hoverable=this.hoverable.add(t),this._on(t,{mouseenter:function(t){e(t.currentTarget).addClass("ui-state-hover")},mouseleave:function(t){e(t.currentTarget).removeClass("ui-state-hover")}})},_focusable:function(t){this.focusable=this.focusable.add(t),this._on(t,{focusin:function(t){e(t.currentTarget).addClass("ui-state-focus")},focusout:function(t){e(t.currentTarget).removeClass("ui-state-focus")}})},_trigger:function(t,i,s){var n,a,r=this.options[t];if(s=s||{},i=e.Event(i),i.type=(t===this.widgetEventPrefix?t:this.widgetEventPrefix+t).toLowerCase(),i.target=this.element[0],a=i.originalEvent)for(n in a)n in i||(i[n]=a[n]);return this.element.trigger(i,s),!(e.isFunction(r)&&r.apply(this.element[0],[i].concat(s))===!1||i.isDefaultPrevented())}},e.each({show:"fadeIn",hide:"fadeOut"},function(t,i){e.Widget.prototype["_"+t]=function(s,n,a){"string"==typeof n&&(n={effect:n});var r,o=n?n===!0||"number"==typeof n?i:n.effect||i:t;n=n||{},"number"==typeof n&&(n={duration:n}),r=!e.isEmptyObject(n),n.complete=a,n.delay&&s.delay(n.delay),r&&e.effects&&e.effects.effect[o]?s[t](n):o!==t&&s[o]?s[o](n.duration,n.easing,a):s.queue(function(i){e(this)[t](),a&&a.call(s[0]),i()})}})})(jQuery);
+
+/*!
+ * jQuery UI Mouse 1.10.0
+ * http://jqueryui.com
+ *
+ * Copyright 2013 jQuery Foundation and other contributors
+ * Released under the MIT license.
+ * http://jquery.org/license
+ *
+ * http://api.jqueryui.com/mouse/
+ *
+ * Depends:
+ * jquery.ui.widget.js
+ */
+(function( $, undefined ) {
+
+var mouseHandled = false;
+$( document ).mouseup( function() {
+ mouseHandled = false;
+});
+
+$.widget("ui.mouse", {
+ version: "1.10.0",
+ options: {
+ cancel: "input,textarea,button,select,option",
+ distance: 1,
+ delay: 0
+ },
+ _mouseInit: function() {
+ var that = this;
+
+ this.element
+ .bind("mousedown."+this.widgetName, function(event) {
+ return that._mouseDown(event);
+ })
+ .bind("click."+this.widgetName, function(event) {
+ if (true === $.data(event.target, that.widgetName + ".preventClickEvent")) {
+ $.removeData(event.target, that.widgetName + ".preventClickEvent");
+ event.stopImmediatePropagation();
+ return false;
+ }
+ });
+
+ this.document.mouseup( function( e ) {
+ mouseHandled = false;
+ });
+
+ this.started = false;
+ },
+
+ // TODO: make sure destroying one instance of mouse doesn't mess with
+ // other instances of mouse
+ _mouseDestroy: function() {
+ this.element.unbind("."+this.widgetName);
+ if ( this._mouseMoveDelegate ) {
+ $(this.document)
+ .unbind("mousemove."+this.widgetName, this._mouseMoveDelegate)
+ .unbind("mouseup."+this.widgetName, this._mouseUpDelegate);
+ }
+ },
+
+ _mouseDown: function(event) {
+
+ // don't let more than one widget handle mouseStart
+ //if( mouseHandled ) { return; }
+
+ // we may have missed mouseup (out of window)
+ (this._mouseStarted && this._mouseUp(event));
+
+ this._mouseDownEvent = event;
+
+ var that = this,
+ btnIsLeft = (event.which === 1),
+ // event.target.nodeName works around a bug in IE 8 with
+ // disabled inputs (#7620)
+ elIsCancel = (typeof this.options.cancel === "string" && event.target.nodeName ? $(event.target).closest(this.options.cancel).length : false);
+ if (!btnIsLeft || elIsCancel || !this._mouseCapture(event)) {
+ return true;
+ }
+
+ this.mouseDelayMet = !this.options.delay;
+ if (!this.mouseDelayMet) {
+ this._mouseDelayTimer = setTimeout(function() {
+ that.mouseDelayMet = true;
+ }, this.options.delay);
+ }
+
+ if (this._mouseDistanceMet(event) && this._mouseDelayMet(event)) {
+ this._mouseStarted = (this._mouseStart(event) !== false);
+ if (!this._mouseStarted) {
+ event.preventDefault();
+ return true;
+ }
+ }
+
+ // Click event may never have fired (Gecko & Opera)
+ if (true === $.data(event.target, this.widgetName + ".preventClickEvent")) {
+ $.removeData(event.target, this.widgetName + ".preventClickEvent");
+ }
+
+ // these delegates are required to keep context
+ this._mouseMoveDelegate = function(event) {
+ return that._mouseMove(event);
+ };
+ this._mouseUpDelegate = function(event) {
+ return that._mouseUp(event);
+ };
+ $(this.document)
+ .bind("mousemove."+this.widgetName, this._mouseMoveDelegate)
+ .bind("mouseup."+this.widgetName, this._mouseUpDelegate);
+
+ event.preventDefault();
+
+ mouseHandled = true;
+ return true;
+ },
+
+ _mouseMove: function(event) {
+ // IE mouseup check - mouseup happened when mouse was out of window
+ if ($.ui.ie && ( !document.documentMode || document.documentMode < 9 ) && !event.button) {
+ return this._mouseUp(event);
+ }
+
+ if (this._mouseStarted) {
+ this._mouseDrag(event);
+ return event.preventDefault();
+ }
+
+ if (this._mouseDistanceMet(event) && this._mouseDelayMet(event)) {
+ this._mouseStarted =
+ (this._mouseStart(this._mouseDownEvent, event) !== false);
+ (this._mouseStarted ? this._mouseDrag(event) : this._mouseUp(event));
+ }
+
+ return !this._mouseStarted;
+ },
+
+ _mouseUp: function(event) {
+ $(this.document)
+ .unbind("mousemove."+this.widgetName, this._mouseMoveDelegate)
+ .unbind("mouseup."+this.widgetName, this._mouseUpDelegate);
+
+ if (this._mouseStarted) {
+ this._mouseStarted = false;
+
+ if (event.target === this._mouseDownEvent.target) {
+ $.data(event.target, this.widgetName + ".preventClickEvent", true);
+ }
+
+ this._mouseStop(event);
+ }
+
+ return false;
+ },
+
+ _mouseDistanceMet: function(event) {
+ return (Math.max(
+ Math.abs(this._mouseDownEvent.pageX - event.pageX),
+ Math.abs(this._mouseDownEvent.pageY - event.pageY)
+ ) >= this.options.distance
+ );
+ },
+
+ _mouseDelayMet: function(/* event */) {
+ return this.mouseDelayMet;
+ },
+
+ // These are placeholder methods, to be overriden by extending plugin
+ _mouseStart: function(/* event */) {},
+ _mouseDrag: function(/* event */) {},
+ _mouseStop: function(/* event */) {},
+ _mouseCapture: function(/* event */) { return true; }
+});
+
+})(jQuery);
+
+
+/*! jQuery UI - v1.10.0 - 2013-01-17
+* http://jqueryui.com
+* Includes: jquery.ui.position.js
+* Copyright 2013 jQuery Foundation and other contributors; Licensed MIT */
+(function(e,t){function h(e,t,n){return[parseInt(e[0],10)*(l.test(e[0])?t/100:1),parseInt(e[1],10)*(l.test(e[1])?n/100:1)]}function p(t,n){return parseInt(e.css(t,n),10)||0}function d(t){var n=t[0];return n.nodeType===9?{width:t.width(),height:t.height(),offset:{top:0,left:0}}:e.isWindow(n)?{width:t.width(),height:t.height(),offset:{top:t.scrollTop(),left:t.scrollLeft()}}:n.preventDefault?{width:0,height:0,offset:{top:n.pageY,left:n.pageX}}:{width:t.outerWidth(),height:t.outerHeight(),offset:t.offset()}}e.ui=e.ui||{};var n,r=Math.max,i=Math.abs,s=Math.round,o=/left|center|right/,u=/top|center|bottom/,a=/[\+\-]\d+%?/,f=/^\w+/,l=/%$/,c=e.fn.position;e.position={scrollbarWidth:function(){if(n!==t)return n;var r,i,s=e("<div style='display:block;width:50px;height:50px;overflow:hidden;'><div style='height:100px;width:auto;'></div></div>"),o=s.children()[0];return e("body").append(s),r=o.offsetWidth,s.css("overflow","scroll"),i=o.offsetWidth,r===i&&(i=s[0].clientWidth),s.remove(),n=r-i},getScrollInfo:function(t){var n=t.isWindow?"":t.element.css("overflow-x"),r=t.isWindow?"":t.element.css("overflow-y"),i=n==="scroll"||n==="auto"&&t.width<t.element[0].scrollWidth,s=r==="scroll"||r==="auto"&&t.height<t.element[0].scrollHeight;return{width:i?e.position.scrollbarWidth():0,height:s?e.position.scrollbarWidth():0}},getWithinInfo:function(t){var n=e(t||window),r=e.isWindow(n[0]);return{element:n,isWindow:r,offset:n.offset()||{left:0,top:0},scrollLeft:n.scrollLeft(),scrollTop:n.scrollTop(),width:r?n.width():n.outerWidth(),height:r?n.height():n.outerHeight()}}},e.fn.position=function(t){if(!t||!t.of)return c.apply(this,arguments);t=e.extend({},t);var n,l,v,m,g,y,b=e(t.of),w=e.position.getWithinInfo(t.within),E=e.position.getScrollInfo(w),S=(t.collision||"flip").split(" "),x={};return y=d(b),b[0].preventDefault&&(t.at="left top"),l=y.width,v=y.height,m=y.offset,g=e.extend({},m),e.each(["my","at"],function(){var e=(t[this]||"").split(" "),n,r;e.length===1&&(e=o.test(e[0])?e.concat(["center"]):u.test(e[0])?["center"].concat(e):["center","center"]),e[0]=o.test(e[0])?e[0]:"center",e[1]=u.test(e[1])?e[1]:"center",n=a.exec(e[0]),r=a.exec(e[1]),x[this]=[n?n[0]:0,r?r[0]:0],t[this]=[f.exec(e[0])[0],f.exec(e[1])[0]]}),S.length===1&&(S[1]=S[0]),t.at[0]==="right"?g.left+=l:t.at[0]==="center"&&(g.left+=l/2),t.at[1]==="bottom"?g.top+=v:t.at[1]==="center"&&(g.top+=v/2),n=h(x.at,l,v),g.left+=n[0],g.top+=n[1],this.each(function(){var o,u,a=e(this),f=a.outerWidth(),c=a.outerHeight(),d=p(this,"marginLeft"),y=p(this,"marginTop"),T=f+d+p(this,"marginRight")+E.width,N=c+y+p(this,"marginBottom")+E.height,C=e.extend({},g),k=h(x.my,a.outerWidth(),a.outerHeight());t.my[0]==="right"?C.left-=f:t.my[0]==="center"&&(C.left-=f/2),t.my[1]==="bottom"?C.top-=c:t.my[1]==="center"&&(C.top-=c/2),C.left+=k[0],C.top+=k[1],e.support.offsetFractions||(C.left=s(C.left),C.top=s(C.top)),o={marginLeft:d,marginTop:y},e.each(["left","top"],function(r,i){e.ui.position[S[r]]&&e.ui.position[S[r]][i](C,{targetWidth:l,targetHeight:v,elemWidth:f,elemHeight:c,collisionPosition:o,collisionWidth:T,collisionHeight:N,offset:[n[0]+k[0],n[1]+k[1]],my:t.my,at:t.at,within:w,elem:a})}),t.using&&(u=function(e){var n=m.left-C.left,s=n+l-f,o=m.top-C.top,u=o+v-c,h={target:{element:b,left:m.left,top:m.top,width:l,height:v},element:{element:a,left:C.left,top:C.top,width:f,height:c},horizontal:s<0?"left":n>0?"right":"center",vertical:u<0?"top":o>0?"bottom":"middle"};l<f&&i(n+s)<l&&(h.horizontal="center"),v<c&&i(o+u)<v&&(h.vertical="middle"),r(i(n),i(s))>r(i(o),i(u))?h.important="horizontal":h.important="vertical",t.using.call(this,e,h)}),a.offset(e.extend(C,{using:u}))})},e.ui.position={fit:{left:function(e,t){var n=t.within,i=n.isWindow?n.scrollLeft:n.offset.left,s=n.width,o=e.left-t.collisionPosition.marginLeft,u=i-o,a=o+t.collisionWidth-s-i,f;t.collisionWidth>s?u>0&&a<=0?(f=e.left+u+t.collisionWidth-s-i,e.left+=u-f):a>0&&u<=0?e.left=i:u>a?e.left=i+s-t.collisionWidth:e.left=i:u>0?e.left+=u:a>0?e.left-=a:e.left=r(e.left-o,e.left)},top:function(e,t){var n=t.within,i=n.isWindow?n.scrollTop:n.offset.top,s=t.within.height,o=e.top-t.collisionPosition.marginTop,u=i-o,a=o+t.collisionHeight-s-i,f;t.collisionHeight>s?u>0&&a<=0?(f=e.top+u+t.collisionHeight-s-i,e.top+=u-f):a>0&&u<=0?e.top=i:u>a?e.top=i+s-t.collisionHeight:e.top=i:u>0?e.top+=u:a>0?e.top-=a:e.top=r(e.top-o,e.top)}},flip:{left:function(e,t){var n=t.within,r=n.offset.left+n.scrollLeft,s=n.width,o=n.isWindow?n.scrollLeft:n.offset.left,u=e.left-t.collisionPosition.marginLeft,a=u-o,f=u+t.collisionWidth-s-o,l=t.my[0]==="left"?-t.elemWidth:t.my[0]==="right"?t.elemWidth:0,c=t.at[0]==="left"?t.targetWidth:t.at[0]==="right"?-t.targetWidth:0,h=-2*t.offset[0],p,d;if(a<0){p=e.left+l+c+h+t.collisionWidth-s-r;if(p<0||p<i(a))e.left+=l+c+h}else if(f>0){d=e.left-t.collisionPosition.marginLeft+l+c+h-o;if(d>0||i(d)<f)e.left+=l+c+h}},top:function(e,t){var n=t.within,r=n.offset.top+n.scrollTop,s=n.height,o=n.isWindow?n.scrollTop:n.offset.top,u=e.top-t.collisionPosition.marginTop,a=u-o,f=u+t.collisionHeight-s-o,l=t.my[1]==="top",c=l?-t.elemHeight:t.my[1]==="bottom"?t.elemHeight:0,h=t.at[1]==="top"?t.targetHeight:t.at[1]==="bottom"?-t.targetHeight:0,p=-2*t.offset[1],d,v;a<0?(v=e.top+c+h+p+t.collisionHeight-s-r,e.top+c+h+p>a&&(v<0||v<i(a))&&(e.top+=c+h+p)):f>0&&(d=e.top-t.collisionPosition.marginTop+c+h+p-o,e.top+c+h+p>f&&(d>0||i(d)<f)&&(e.top+=c+h+p))}},flipfit:{left:function(){e.ui.position.flip.left.apply(this,arguments),e.ui.position.fit.left.apply(this,arguments)},top:function(){e.ui.position.flip.top.apply(this,arguments),e.ui.position.fit.top.apply(this,arguments)}}},function(){var t,n,r,i,s,o=document.getElementsByTagName("body")[0],u=document.createElement("div");t=document.createElement(o?"div":"body"),r={visibility:"hidden",width:0,height:0,border:0,margin:0,background:"none"},o&&e.extend(r,{position:"absolute",left:"-1000px",top:"-1000px"});for(s in r)t.style[s]=r[s];t.appendChild(u),n=o||document.documentElement,n.insertBefore(t,n.firstChild),u.style.cssText="position: absolute; left: 10.7432222px;",i=e(u).offset().left,e.support.offsetFractions=i>10&&i<11,t.innerHTML="",n.removeChild(t)}()})(jQuery);
+
+
+/*!
+ * jQuery UI Draggable 1.10.1
+ * http://jqueryui.com
+ *
+ * Copyright 2013 jQuery Foundation and other contributors
+ * Released under the MIT license.
+ * http://jquery.org/license
+ *
+ * http://api.jqueryui.com/draggable/
+ *
+ * Depends:
+ * jquery.ui.core.js
+ * jquery.ui.mouse.js
+ * jquery.ui.widget.js
+ */
+(function( $, undefined ) {
+
+$.widget("ui.draggable", $.ui.mouse, {
+ version: "1.10.1",
+ widgetEventPrefix: "drag",
+ options: {
+ addClasses: true,
+ appendTo: "parent",
+ axis: false,
+ connectToSortable: false,
+ containment: false,
+ cursor: "auto",
+ cursorAt: false,
+ grid: false,
+ handle: false,
+ helper: "original",
+ iframeFix: false,
+ opacity: false,
+ refreshPositions: false,
+ revert: false,
+ revertDuration: 500,
+ scope: "default",
+ scroll: true,
+ scrollSensitivity: 20,
+ scrollSpeed: 20,
+ snap: false,
+ snapMode: "both",
+ snapTolerance: 20,
+ stack: false,
+ zIndex: false,
+
+ // callbacks
+ drag: null,
+ start: null,
+ stop: null
+ },
+ _create: function() {
+
+ if (this.options.helper === "original" && !(/^(?:r|a|f)/).test(this.element.css("position"))) {
+ this.element[0].style.position = "relative";
+ }
+ if (this.options.addClasses){
+ this.element.addClass("ui-draggable");
+ }
+ if (this.options.disabled){
+ this.element.addClass("ui-draggable-disabled");
+ }
+
+ this._mouseInit();
+
+ },
+
+ _destroy: function() {
+ this.element.removeClass( "ui-draggable ui-draggable-dragging ui-draggable-disabled" );
+ this._mouseDestroy();
+ },
+
+ _mouseCapture: function(event) {
+
+ var o = this.options;
+
+ // among others, prevent a drag on a resizable-handle
+ if (this.helper || o.disabled || $(event.target).closest(".ui-resizable-handle").length > 0) {
+ return false;
+ }
+
+ //Quit if we're not on a valid handle
+ this.handle = this._getHandle(event);
+ if (!this.handle) {
+ return false;
+ }
+
+ $(o.iframeFix === true ? "iframe" : o.iframeFix).each(function() {
+ $("<div class='ui-draggable-iframeFix' style='background: #fff;'></div>")
+ .css({
+ width: this.offsetWidth+"px", height: this.offsetHeight+"px",
+ position: "absolute", opacity: "0.001", zIndex: 1000
+ })
+ .css($(this).offset())
+ .appendTo("body");
+ });
+
+ return true;
+
+ },
+
+ _mouseStart: function(event) {
+
+ var o = this.options;
+
+ //Create and append the visible helper
+ this.helper = this._createHelper(event);
+
+ this.helper.addClass("ui-draggable-dragging");
+
+ //Cache the helper size
+ this._cacheHelperProportions();
+
+ //If ddmanager is used for droppables, set the global draggable
+ if($.ui.ddmanager) {
+ $.ui.ddmanager.current = this;
+ }
+
+ /*
+ * - Position generation -
+ * This block generates everything position related - it's the core of draggables.
+ */
+
+ //Cache the margins of the original element
+ this._cacheMargins();
+
+ //Store the helper's css position
+ this.cssPosition = this.helper.css("position");
+ this.scrollParent = this.helper.scrollParent();
+
+ //The element's absolute position on the page minus margins
+ this.offset = this.positionAbs = this.element.offset();
+ this.offset = {
+ top: this.offset.top - this.margins.top,
+ left: this.offset.left - this.margins.left
+ };
+
+ $.extend(this.offset, {
+ click: { //Where the click happened, relative to the element
+ left: event.pageX - this.offset.left,
+ top: event.pageY - this.offset.top
+ },
+ parent: this._getParentOffset(),
+ relative: this._getRelativeOffset() //This is a relative to absolute position minus the actual position calculation - only used for relative positioned helper
+ });
+
+ //Generate the original position
+ this.originalPosition = this.position = this._generatePosition(event);
+ this.originalPageX = event.pageX;
+ this.originalPageY = event.pageY;
+
+ //Adjust the mouse offset relative to the helper if "cursorAt" is supplied
+ (o.cursorAt && this._adjustOffsetFromHelper(o.cursorAt));
+
+ //Set a containment if given in the options
+ if(o.containment) {
+ this._setContainment();
+ }
+
+ //Trigger event + callbacks
+ if(this._trigger("start", event) === false) {
+ this._clear();
+ return false;
+ }
+
+ //Recache the helper size
+ this._cacheHelperProportions();
+
+ //Prepare the droppable offsets
+ if ($.ui.ddmanager && !o.dropBehaviour) {
+ $.ui.ddmanager.prepareOffsets(this, event);
+ }
+
+
+ this._mouseDrag(event, true); //Execute the drag once - this causes the helper not to be visible before getting its correct position
+
+ //If the ddmanager is used for droppables, inform the manager that dragging has started (see #5003)
+ if ( $.ui.ddmanager ) {
+ $.ui.ddmanager.dragStart(this, event);
+ }
+
+ return true;
+ },
+
+ _mouseDrag: function(event, noPropagation) {
+
+ //Compute the helpers position
+ this.position = this._generatePosition(event);
+ this.positionAbs = this._convertPositionTo("absolute");
+
+ if(!this.options.axis || this.options.axis !== "y") {
+ this.helper[0].style.left = this.position.left+"px";
+ }
+ if(!this.options.axis || this.options.axis !== "x") {
+ this.helper[0].style.top = this.position.top+"px";
+ }
+
+ //Call plugins and callbacks and use the resulting position if something is returned
+ if (!noPropagation) {
+ var ui = this._uiHash();
+ if(this._trigger("drag", event, ui) === false) {
+ this._mouseUp({});
+ return false;
+ }
+ }
+
+ if($.ui.ddmanager) {
+ $.ui.ddmanager.drag(this, event);
+ }
+
+ return false;
+ },
+
+ _mouseStop: function(event) {
+
+ //If we are using droppables, inform the manager about the drop
+ var element,
+ that = this,
+ elementInDom = false,
+ dropped = false;
+ if ($.ui.ddmanager && !this.options.dropBehaviour) {
+ dropped = $.ui.ddmanager.drop(this, event);
+ }
+
+ //if a drop comes from outside (a sortable)
+ if(this.dropped) {
+ dropped = this.dropped;
+ this.dropped = false;
+ }
+
+ //if the original element is no longer in the DOM don't bother to continue (see #8269)
+ element = this.element[0];
+ while ( element && (element = element.parentNode) ) {
+ if (element === this.document.get(0) ) {
+ elementInDom = true;
+ }
+ }
+ if ( !elementInDom && this.options.helper === "original" ) {
+ return false;
+ }
+
+ if((this.options.revert === "invalid" && !dropped) || (this.options.revert === "valid" && dropped) || this.options.revert === true || ($.isFunction(this.options.revert) && this.options.revert.call(this.element, dropped))) {
+ $(this.helper).animate(this.originalPosition, parseInt(this.options.revertDuration, 10), function() {
+ if(that._trigger("stop", event) !== false) {
+ that._clear();
+ }
+ });
+ } else {
+ if(this._trigger("stop", event) !== false) {
+ this._clear();
+ }
+ }
+
+ return false;
+ },
+
+ _mouseUp: function(event) {
+ //Remove frame helpers
+ $("div.ui-draggable-iframeFix").each(function() {
+ this.parentNode.removeChild(this);
+ });
+
+ //If the ddmanager is used for droppables, inform the manager that dragging has stopped (see #5003)
+ if( $.ui.ddmanager ) {
+ $.ui.ddmanager.dragStop(this, event);
+ }
+
+ return $.ui.mouse.prototype._mouseUp.call(this, event);
+ },
+
+ cancel: function() {
+
+ if(this.helper.is(".ui-draggable-dragging")) {
+ this._mouseUp({});
+ } else {
+ this._clear();
+ }
+
+ return this;
+
+ },
+
+ _getHandle: function(event) {
+
+ var handle = !this.options.handle || !$(this.options.handle, this.element).length ? true : false;
+ $(this.options.handle, this.element)
+ .find("*")
+ .addBack()
+ .each(function() {
+ if(this === event.target) {
+ handle = true;
+ }
+ });
+
+ return handle;
+
+ },
+
+ _createHelper: function(event) {
+
+ var o = this.options,
+ helper = $.isFunction(o.helper) ? $(o.helper.apply(this.element[0], [event])) : (o.helper === "clone" ? this.element.clone().removeAttr("id") : this.element);
+
+ if(!helper.parents("body").length) {
+ helper.appendTo((o.appendTo === "parent" ? this.element[0].parentNode : o.appendTo));
+ }
+
+ if(helper[0] !== this.element[0] && !(/(fixed|absolute)/).test(helper.css("position"))) {
+ helper.css("position", "absolute");
+ }
+
+ return helper;
+
+ },
+
+ _adjustOffsetFromHelper: function(obj) {
+ if (typeof obj === "string") {
+ obj = obj.split(" ");
+ }
+ if ($.isArray(obj)) {
+ obj = {left: +obj[0], top: +obj[1] || 0};
+ }
+ if ("left" in obj) {
+ this.offset.click.left = obj.left + this.margins.left;
+ }
+ if ("right" in obj) {
+ this.offset.click.left = this.helperProportions.width - obj.right + this.margins.left;
+ }
+ if ("top" in obj) {
+ this.offset.click.top = obj.top + this.margins.top;
+ }
+ if ("bottom" in obj) {
+ this.offset.click.top = this.helperProportions.height - obj.bottom + this.margins.top;
+ }
+ },
+
+ _getParentOffset: function() {
+
+ //Get the offsetParent and cache its position
+ this.offsetParent = this.helper.offsetParent();
+ var po = this.offsetParent.offset();
+
+ // This is a special case where we need to modify a offset calculated on start, since the following happened:
+ // 1. The position of the helper is absolute, so it's position is calculated based on the next positioned parent
+ // 2. The actual offset parent is a child of the scroll parent, and the scroll parent isn't the document, which means that
+ // the scroll is included in the initial calculation of the offset of the parent, and never recalculated upon drag
+ if(this.cssPosition === "absolute" && this.scrollParent[0] !== document && $.contains(this.scrollParent[0], this.offsetParent[0])) {
+ po.left += this.scrollParent.scrollLeft();
+ po.top += this.scrollParent.scrollTop();
+ }
+
+ //This needs to be actually done for all browsers, since pageX/pageY includes this information
+ //Ugly IE fix
+ if((this.offsetParent[0] === document.body) ||
+ (this.offsetParent[0].tagName && this.offsetParent[0].tagName.toLowerCase() === "html" && $.ui.ie)) {
+ po = { top: 0, left: 0 };
+ }
+
+ return {
+ top: po.top + (parseInt(this.offsetParent.css("borderTopWidth"),10) || 0),
+ left: po.left + (parseInt(this.offsetParent.css("borderLeftWidth"),10) || 0)
+ };
+
+ },
+
+ _getRelativeOffset: function() {
+
+ if(this.cssPosition === "relative") {
+ var p = this.element.position();
+ return {
+ top: p.top - (parseInt(this.helper.css("top"),10) || 0) + this.scrollParent.scrollTop(),
+ left: p.left - (parseInt(this.helper.css("left"),10) || 0) + this.scrollParent.scrollLeft()
+ };
+ } else {
+ return { top: 0, left: 0 };
+ }
+
+ },
+
+ _cacheMargins: function() {
+ this.margins = {
+ left: (parseInt(this.element.css("marginLeft"),10) || 0),
+ top: (parseInt(this.element.css("marginTop"),10) || 0),
+ right: (parseInt(this.element.css("marginRight"),10) || 0),
+ bottom: (parseInt(this.element.css("marginBottom"),10) || 0)
+ };
+ },
+
+ _cacheHelperProportions: function() {
+ this.helperProportions = {
+ width: this.helper.outerWidth(),
+ height: this.helper.outerHeight()
+ };
+ },
+
+ _setContainment: function() {
+
+ var over, c, ce,
+ o = this.options;
+
+ if(o.containment === "parent") {
+ o.containment = this.helper[0].parentNode;
+ }
+ if(o.containment === "document" || o.containment === "window") {
+ this.containment = [
+ o.containment === "document" ? 0 : $(window).scrollLeft() - this.offset.relative.left - this.offset.parent.left,
+ o.containment === "document" ? 0 : $(window).scrollTop() - this.offset.relative.top - this.offset.parent.top,
+ (o.containment === "document" ? 0 : $(window).scrollLeft()) + $(o.containment === "document" ? document : window).width() - this.helperProportions.width - this.margins.left,
+ (o.containment === "document" ? 0 : $(window).scrollTop()) + ($(o.containment === "document" ? document : window).height() || document.body.parentNode.scrollHeight) - this.helperProportions.height - this.margins.top
+ ];
+ }
+
+ if(!(/^(document|window|parent)$/).test(o.containment) && o.containment.constructor !== Array) {
+ c = $(o.containment);
+ ce = c[0];
+
+ if(!ce) {
+ return;
+ }
+
+ over = ($(ce).css("overflow") !== "hidden");
+
+ this.containment = [
+ (parseInt($(ce).css("borderLeftWidth"),10) || 0) + (parseInt($(ce).css("paddingLeft"),10) || 0),
+ (parseInt($(ce).css("borderTopWidth"),10) || 0) + (parseInt($(ce).css("paddingTop"),10) || 0),
+ (over ? Math.max(ce.scrollWidth,ce.offsetWidth) : ce.offsetWidth) - (parseInt($(ce).css("borderLeftWidth"),10) || 0) - (parseInt($(ce).css("paddingRight"),10) || 0) - this.helperProportions.width - this.margins.left - this.margins.right,
+ (over ? Math.max(ce.scrollHeight,ce.offsetHeight) : ce.offsetHeight) - (parseInt($(ce).css("borderTopWidth"),10) || 0) - (parseInt($(ce).css("paddingBottom"),10) || 0) - this.helperProportions.height - this.margins.top - this.margins.bottom
+ ];
+ this.relative_container = c;
+
+ } else if(o.containment.constructor === Array) {
+ this.containment = o.containment;
+ }
+
+ },
+
+ _convertPositionTo: function(d, pos) {
+
+ if(!pos) {
+ pos = this.position;
+ }
+
+ var mod = d === "absolute" ? 1 : -1,
+ scroll = this.cssPosition === "absolute" && !(this.scrollParent[0] !== document && $.contains(this.scrollParent[0], this.offsetParent[0])) ? this.offsetParent : this.scrollParent, scrollIsRootNode = (/(html|body)/i).test(scroll[0].tagName);
+
+ return {
+ top: (
+ pos.top + // The absolute mouse position
+ this.offset.relative.top * mod + // Only for relative positioned nodes: Relative offset from element to offset parent
+ this.offset.parent.top * mod - // The offsetParent's offset without borders (offset + border)
+ ( ( this.cssPosition === "fixed" ? -this.scrollParent.scrollTop() : ( scrollIsRootNode ? 0 : scroll.scrollTop() ) ) * mod)
+ ),
+ left: (
+ pos.left + // The absolute mouse position
+ this.offset.relative.left * mod + // Only for relative positioned nodes: Relative offset from element to offset parent
+ this.offset.parent.left * mod - // The offsetParent's offset without borders (offset + border)
+ ( ( this.cssPosition === "fixed" ? -this.scrollParent.scrollLeft() : scrollIsRootNode ? 0 : scroll.scrollLeft() ) * mod)
+ )
+ };
+
+ },
+
+ _generatePosition: function(event) {
+
+ var containment, co, top, left,
+ o = this.options,
+ scroll = this.cssPosition === "absolute" && !(this.scrollParent[0] !== document && $.contains(this.scrollParent[0], this.offsetParent[0])) ? this.offsetParent : this.scrollParent,
+ scrollIsRootNode = (/(html|body)/i).test(scroll[0].tagName),
+ pageX = event.pageX,
+ pageY = event.pageY;
+
+ /*
+ * - Position constraining -
+ * Constrain the position to a mix of grid, containment.
+ */
+
+ if(this.originalPosition) { //If we are not dragging yet, we won't check for options
+ if(this.containment) {
+ if (this.relative_container){
+ co = this.relative_container.offset();
+ containment = [ this.containment[0] + co.left,
+ this.containment[1] + co.top,
+ this.containment[2] + co.left,
+ this.containment[3] + co.top ];
+ }
+ else {
+ containment = this.containment;
+ }
+
+ if(event.pageX - this.offset.click.left < containment[0]) {
+ pageX = containment[0] + this.offset.click.left;
+ }
+ if(event.pageY - this.offset.click.top < containment[1]) {
+ pageY = containment[1] + this.offset.click.top;
+ }
+ if(event.pageX - this.offset.click.left > containment[2]) {
+ pageX = containment[2] + this.offset.click.left;
+ }
+ if(event.pageY - this.offset.click.top > containment[3]) {
+ pageY = containment[3] + this.offset.click.top;
+ }
+ }
+
+ if(o.grid) {
+ //Check for grid elements set to 0 to prevent divide by 0 error causing invalid argument errors in IE (see ticket #6950)
+ top = o.grid[1] ? this.originalPageY + Math.round((pageY - this.originalPageY) / o.grid[1]) * o.grid[1] : this.originalPageY;
+ pageY = containment ? ((top - this.offset.click.top >= containment[1] || top - this.offset.click.top > containment[3]) ? top : ((top - this.offset.click.top >= containment[1]) ? top - o.grid[1] : top + o.grid[1])) : top;
+
+ left = o.grid[0] ? this.originalPageX + Math.round((pageX - this.originalPageX) / o.grid[0]) * o.grid[0] : this.originalPageX;
+ pageX = containment ? ((left - this.offset.click.left >= containment[0] || left - this.offset.click.left > containment[2]) ? left : ((left - this.offset.click.left >= containment[0]) ? left - o.grid[0] : left + o.grid[0])) : left;
+ }
+
+ }
+
+ return {
+ top: (
+ pageY - // The absolute mouse position
+ this.offset.click.top - // Click offset (relative to the element)
+ this.offset.relative.top - // Only for relative positioned nodes: Relative offset from element to offset parent
+ this.offset.parent.top + // The offsetParent's offset without borders (offset + border)
+ ( ( this.cssPosition === "fixed" ? -this.scrollParent.scrollTop() : ( scrollIsRootNode ? 0 : scroll.scrollTop() ) ))
+ ),
+ left: (
+ pageX - // The absolute mouse position
+ this.offset.click.left - // Click offset (relative to the element)
+ this.offset.relative.left - // Only for relative positioned nodes: Relative offset from element to offset parent
+ this.offset.parent.left + // The offsetParent's offset without borders (offset + border)
+ ( ( this.cssPosition === "fixed" ? -this.scrollParent.scrollLeft() : scrollIsRootNode ? 0 : scroll.scrollLeft() ))
+ )
+ };
+
+ },
+
+ _clear: function() {
+ this.helper.removeClass("ui-draggable-dragging");
+ if(this.helper[0] !== this.element[0] && !this.cancelHelperRemoval) {
+ this.helper.remove();
+ }
+ this.helper = null;
+ this.cancelHelperRemoval = false;
+ },
+
+ // From now on bulk stuff - mainly helpers
+
+ _trigger: function(type, event, ui) {
+ ui = ui || this._uiHash();
+ $.ui.plugin.call(this, type, [event, ui]);
+ //The absolute position has to be recalculated after plugins
+ if(type === "drag") {
+ this.positionAbs = this._convertPositionTo("absolute");
+ }
+ return $.Widget.prototype._trigger.call(this, type, event, ui);
+ },
+
+ plugins: {},
+
+ _uiHash: function() {
+ return {
+ helper: this.helper,
+ position: this.position,
+ originalPosition: this.originalPosition,
+ offset: this.positionAbs
+ };
+ }
+
+});
+
+$.ui.plugin.add("draggable", "connectToSortable", {
+ start: function(event, ui) {
+
+ var inst = $(this).data("ui-draggable"), o = inst.options,
+ uiSortable = $.extend({}, ui, { item: inst.element });
+ inst.sortables = [];
+ $(o.connectToSortable).each(function() {
+ var sortable = $.data(this, "ui-sortable");
+ if (sortable && !sortable.options.disabled) {
+ inst.sortables.push({
+ instance: sortable,
+ shouldRevert: sortable.options.revert
+ });
+ sortable.refreshPositions(); // Call the sortable's refreshPositions at drag start to refresh the containerCache since the sortable container cache is used in drag and needs to be up to date (this will ensure it's initialised as well as being kept in step with any changes that might have happened on the page).
+ sortable._trigger("activate", event, uiSortable);
+ }
+ });
+
+ },
+ stop: function(event, ui) {
+
+ //If we are still over the sortable, we fake the stop event of the sortable, but also remove helper
+ var inst = $(this).data("ui-draggable"),
+ uiSortable = $.extend({}, ui, { item: inst.element });
+
+ $.each(inst.sortables, function() {
+ if(this.instance.isOver) {
+
+ this.instance.isOver = 0;
+
+ inst.cancelHelperRemoval = true; //Don't remove the helper in the draggable instance
+ this.instance.cancelHelperRemoval = false; //Remove it in the sortable instance (so sortable plugins like revert still work)
+
+ //The sortable revert is supported, and we have to set a temporary dropped variable on the draggable to support revert: "valid/invalid"
+ if(this.shouldRevert) {
+ this.instance.options.revert = true;
+ }
+
+ //Trigger the stop of the sortable
+ this.instance._mouseStop(event);
+
+ this.instance.options.helper = this.instance.options._helper;
+
+ //If the helper has been the original item, restore properties in the sortable
+ if(inst.options.helper === "original") {
+ this.instance.currentItem.css({ top: "auto", left: "auto" });
+ }
+
+ } else {
+ this.instance.cancelHelperRemoval = false; //Remove the helper in the sortable instance
+ this.instance._trigger("deactivate", event, uiSortable);
+ }
+
+ });
+
+ },
+ drag: function(event, ui) {
+
+ var inst = $(this).data("ui-draggable"), that = this;
+
+ $.each(inst.sortables, function() {
+
+ var innermostIntersecting = false,
+ thisSortable = this;
+
+ //Copy over some variables to allow calling the sortable's native _intersectsWith
+ this.instance.positionAbs = inst.positionAbs;
+ this.instance.helperProportions = inst.helperProportions;
+ this.instance.offset.click = inst.offset.click;
+
+ if(this.instance._intersectsWith(this.instance.containerCache)) {
+ innermostIntersecting = true;
+ $.each(inst.sortables, function () {
+ this.instance.positionAbs = inst.positionAbs;
+ this.instance.helperProportions = inst.helperProportions;
+ this.instance.offset.click = inst.offset.click;
+ if (this !== thisSortable &&
+ this.instance._intersectsWith(this.instance.containerCache) &&
+ $.contains(thisSortable.instance.element[0], this.instance.element[0])
+ ) {
+ innermostIntersecting = false;
+ }
+ return innermostIntersecting;
+ });
+ }
+
+
+ if(innermostIntersecting) {
+ //If it intersects, we use a little isOver variable and set it once, so our move-in stuff gets fired only once
+ if(!this.instance.isOver) {
+
+ this.instance.isOver = 1;
+ //Now we fake the start of dragging for the sortable instance,
+ //by cloning the list group item, appending it to the sortable and using it as inst.currentItem
+ //We can then fire the start event of the sortable with our passed browser event, and our own helper (so it doesn't create a new one)
+ this.instance.currentItem = $(that).clone().removeAttr("id").appendTo(this.instance.element).data("ui-sortable-item", true);
+ this.instance.options._helper = this.instance.options.helper; //Store helper option to later restore it
+ this.instance.options.helper = function() { return ui.helper[0]; };
+
+ event.target = this.instance.currentItem[0];
+ this.instance._mouseCapture(event, true);
+ this.instance._mouseStart(event, true, true);
+
+ //Because the browser event is way off the new appended portlet, we modify a couple of variables to reflect the changes
+ this.instance.offset.click.top = inst.offset.click.top;
+ this.instance.offset.click.left = inst.offset.click.left;
+ this.instance.offset.parent.left -= inst.offset.parent.left - this.instance.offset.parent.left;
+ this.instance.offset.parent.top -= inst.offset.parent.top - this.instance.offset.parent.top;
+
+ inst._trigger("toSortable", event);
+ inst.dropped = this.instance.element; //draggable revert needs that
+ //hack so receive/update callbacks work (mostly)
+ inst.currentItem = inst.element;
+ this.instance.fromOutside = inst;
+
+ }
+
+ //Provided we did all the previous steps, we can fire the drag event of the sortable on every draggable drag, when it intersects with the sortable
+ if(this.instance.currentItem) {
+ this.instance._mouseDrag(event);
+ }
+
+ } else {
+
+ //If it doesn't intersect with the sortable, and it intersected before,
+ //we fake the drag stop of the sortable, but make sure it doesn't remove the helper by using cancelHelperRemoval
+ if(this.instance.isOver) {
+
+ this.instance.isOver = 0;
+ this.instance.cancelHelperRemoval = true;
+
+ //Prevent reverting on this forced stop
+ this.instance.options.revert = false;
+
+ // The out event needs to be triggered independently
+ this.instance._trigger("out", event, this.instance._uiHash(this.instance));
+
+ this.instance._mouseStop(event, true);
+ this.instance.options.helper = this.instance.options._helper;
+
+ //Now we remove our currentItem, the list group clone again, and the placeholder, and animate the helper back to it's original size
+ this.instance.currentItem.remove();
+ if(this.instance.placeholder) {
+ this.instance.placeholder.remove();
+ }
+
+ inst._trigger("fromSortable", event);
+ inst.dropped = false; //draggable revert needs that
+ }
+
+ }
+
+ });
+
+ }
+});
+
+$.ui.plugin.add("draggable", "cursor", {
+ start: function() {
+ var t = $("body"), o = $(this).data("ui-draggable").options;
+ if (t.css("cursor")) {
+ o._cursor = t.css("cursor");
+ }
+ t.css("cursor", o.cursor);
+ },
+ stop: function() {
+ var o = $(this).data("ui-draggable").options;
+ if (o._cursor) {
+ $("body").css("cursor", o._cursor);
+ }
+ }
+});
+
+$.ui.plugin.add("draggable", "opacity", {
+ start: function(event, ui) {
+ var t = $(ui.helper), o = $(this).data("ui-draggable").options;
+ if(t.css("opacity")) {
+ o._opacity = t.css("opacity");
+ }
+ t.css("opacity", o.opacity);
+ },
+ stop: function(event, ui) {
+ var o = $(this).data("ui-draggable").options;
+ if(o._opacity) {
+ $(ui.helper).css("opacity", o._opacity);
+ }
+ }
+});
+
+$.ui.plugin.add("draggable", "scroll", {
+ start: function() {
+ var i = $(this).data("ui-draggable");
+ if(i.scrollParent[0] !== document && i.scrollParent[0].tagName !== "HTML") {
+ i.overflowOffset = i.scrollParent.offset();
+ }
+ },
+ drag: function( event ) {
+
+ var i = $(this).data("ui-draggable"), o = i.options, scrolled = false;
+
+ if(i.scrollParent[0] !== document && i.scrollParent[0].tagName !== "HTML") {
+
+ if(!o.axis || o.axis !== "x") {
+ if((i.overflowOffset.top + i.scrollParent[0].offsetHeight) - event.pageY < o.scrollSensitivity) {
+ i.scrollParent[0].scrollTop = scrolled = i.scrollParent[0].scrollTop + o.scrollSpeed;
+ } else if(event.pageY - i.overflowOffset.top < o.scrollSensitivity) {
+ i.scrollParent[0].scrollTop = scrolled = i.scrollParent[0].scrollTop - o.scrollSpeed;
+ }
+ }
+
+ if(!o.axis || o.axis !== "y") {
+ if((i.overflowOffset.left + i.scrollParent[0].offsetWidth) - event.pageX < o.scrollSensitivity) {
+ i.scrollParent[0].scrollLeft = scrolled = i.scrollParent[0].scrollLeft + o.scrollSpeed;
+ } else if(event.pageX - i.overflowOffset.left < o.scrollSensitivity) {
+ i.scrollParent[0].scrollLeft = scrolled = i.scrollParent[0].scrollLeft - o.scrollSpeed;
+ }
+ }
+
+ } else {
+
+ if(!o.axis || o.axis !== "x") {
+ if(event.pageY - $(document).scrollTop() < o.scrollSensitivity) {
+ scrolled = $(document).scrollTop($(document).scrollTop() - o.scrollSpeed);
+ } else if($(window).height() - (event.pageY - $(document).scrollTop()) < o.scrollSensitivity) {
+ scrolled = $(document).scrollTop($(document).scrollTop() + o.scrollSpeed);
+ }
+ }
+
+ if(!o.axis || o.axis !== "y") {
+ if(event.pageX - $(document).scrollLeft() < o.scrollSensitivity) {
+ scrolled = $(document).scrollLeft($(document).scrollLeft() - o.scrollSpeed);
+ } else if($(window).width() - (event.pageX - $(document).scrollLeft()) < o.scrollSensitivity) {
+ scrolled = $(document).scrollLeft($(document).scrollLeft() + o.scrollSpeed);
+ }
+ }
+
+ }
+
+ if(scrolled !== false && $.ui.ddmanager && !o.dropBehaviour) {
+ $.ui.ddmanager.prepareOffsets(i, event);
+ }
+
+ }
+});
+
+$.ui.plugin.add("draggable", "snap", {
+ start: function() {
+
+ var i = $(this).data("ui-draggable"),
+ o = i.options;
+
+ i.snapElements = [];
+
+ $(o.snap.constructor !== String ? ( o.snap.items || ":data(ui-draggable)" ) : o.snap).each(function() {
+ var $t = $(this),
+ $o = $t.offset();
+ if(this !== i.element[0]) {
+ i.snapElements.push({
+ item: this,
+ width: $t.outerWidth(), height: $t.outerHeight(),
+ top: $o.top, left: $o.left
+ });
+ }
+ });
+
+ },
+ drag: function(event, ui) {
+
+ var ts, bs, ls, rs, l, r, t, b, i, first,
+ inst = $(this).data("ui-draggable"),
+ o = inst.options,
+ d = o.snapTolerance,
+ x1 = ui.offset.left, x2 = x1 + inst.helperProportions.width,
+ y1 = ui.offset.top, y2 = y1 + inst.helperProportions.height;
+
+ for (i = inst.snapElements.length - 1; i >= 0; i--){
+
+ l = inst.snapElements[i].left;
+ r = l + inst.snapElements[i].width;
+ t = inst.snapElements[i].top;
+ b = t + inst.snapElements[i].height;
+
+ //Yes, I know, this is insane ;)
+ if(!((l-d < x1 && x1 < r+d && t-d < y1 && y1 < b+d) || (l-d < x1 && x1 < r+d && t-d < y2 && y2 < b+d) || (l-d < x2 && x2 < r+d && t-d < y1 && y1 < b+d) || (l-d < x2 && x2 < r+d && t-d < y2 && y2 < b+d))) {
+ if(inst.snapElements[i].snapping) {
+ (inst.options.snap.release && inst.options.snap.release.call(inst.element, event, $.extend(inst._uiHash(), { snapItem: inst.snapElements[i].item })));
+ }
+ inst.snapElements[i].snapping = false;
+ continue;
+ }
+
+ if(o.snapMode !== "inner") {
+ ts = Math.abs(t - y2) <= d;
+ bs = Math.abs(b - y1) <= d;
+ ls = Math.abs(l - x2) <= d;
+ rs = Math.abs(r - x1) <= d;
+ if(ts) {
+ ui.position.top = inst._convertPositionTo("relative", { top: t - inst.helperProportions.height, left: 0 }).top - inst.margins.top;
+ }
+ if(bs) {
+ ui.position.top = inst._convertPositionTo("relative", { top: b, left: 0 }).top - inst.margins.top;
+ }
+ if(ls) {
+ ui.position.left = inst._convertPositionTo("relative", { top: 0, left: l - inst.helperProportions.width }).left - inst.margins.left;
+ }
+ if(rs) {
+ ui.position.left = inst._convertPositionTo("relative", { top: 0, left: r }).left - inst.margins.left;
+ }
+ }
+
+ first = (ts || bs || ls || rs);
+
+ if(o.snapMode !== "outer") {
+ ts = Math.abs(t - y1) <= d;
+ bs = Math.abs(b - y2) <= d;
+ ls = Math.abs(l - x1) <= d;
+ rs = Math.abs(r - x2) <= d;
+ if(ts) {
+ ui.position.top = inst._convertPositionTo("relative", { top: t, left: 0 }).top - inst.margins.top;
+ }
+ if(bs) {
+ ui.position.top = inst._convertPositionTo("relative", { top: b - inst.helperProportions.height, left: 0 }).top - inst.margins.top;
+ }
+ if(ls) {
+ ui.position.left = inst._convertPositionTo("relative", { top: 0, left: l }).left - inst.margins.left;
+ }
+ if(rs) {
+ ui.position.left = inst._convertPositionTo("relative", { top: 0, left: r - inst.helperProportions.width }).left - inst.margins.left;
+ }
+ }
+
+ if(!inst.snapElements[i].snapping && (ts || bs || ls || rs || first)) {
+ (inst.options.snap.snap && inst.options.snap.snap.call(inst.element, event, $.extend(inst._uiHash(), { snapItem: inst.snapElements[i].item })));
+ }
+ inst.snapElements[i].snapping = (ts || bs || ls || rs || first);
+
+ }
+
+ }
+});
+
+$.ui.plugin.add("draggable", "stack", {
+ start: function() {
+ var min,
+ o = this.data("ui-draggable").options,
+ group = $.makeArray($(o.stack)).sort(function(a,b) {
+ return (parseInt($(a).css("zIndex"),10) || 0) - (parseInt($(b).css("zIndex"),10) || 0);
+ });
+
+ if (!group.length) { return; }
+
+ min = parseInt($(group[0]).css("zIndex"), 10) || 0;
+ $(group).each(function(i) {
+ $(this).css("zIndex", min + i);
+ });
+ this.css("zIndex", (min + group.length));
+ }
+});
+
+$.ui.plugin.add("draggable", "zIndex", {
+ start: function(event, ui) {
+ var t = $(ui.helper), o = $(this).data("ui-draggable").options;
+ if(t.css("zIndex")) {
+ o._zIndex = t.css("zIndex");
+ }
+ t.css("zIndex", o.zIndex);
+ },
+ stop: function(event, ui) {
+ var o = $(this).data("ui-draggable").options;
+ if(o._zIndex) {
+ $(ui.helper).css("zIndex", o._zIndex);
+ }
+ }
+});
+
+})(jQuery);
+
+
+
+/*! jQuery UI - v1.10.0 - 2013-01-17
+* http://jqueryui.com
+* Includes: jquery.ui.droppable.js
+* Copyright 2013 jQuery Foundation and other contributors; Licensed MIT */
+/*!
+ * jQuery UI Droppable 1.10.1
+ * http://jqueryui.com
+ *
+ * Copyright 2013 jQuery Foundation and other contributors
+ * Released under the MIT license.
+ * http://jquery.org/license
+ *
+ * http://api.jqueryui.com/droppable/
+ *
+ * Depends:
+ * jquery.ui.core.js
+ * jquery.ui.widget.js
+ * jquery.ui.mouse.js
+ * jquery.ui.draggable.js
+ */
+(function( $, undefined ) {
+
+function isOverAxis( x, reference, size ) {
+ return ( x > reference ) && ( x < ( reference + size ) );
+}
+
+$.widget("ui.droppable", {
+ version: "1.10.1",
+ widgetEventPrefix: "drop",
+ options: {
+ accept: "*",
+ activeClass: false,
+ addClasses: true,
+ greedy: false,
+ hoverClass: false,
+ scope: "default",
+ tolerance: "intersect",
+
+ // callbacks
+ activate: null,
+ deactivate: null,
+ drop: null,
+ out: null,
+ over: null
+ },
+ _create: function() {
+
+ var o = this.options,
+ accept = o.accept;
+
+ this.isover = false;
+ this.isout = true;
+
+ this.accept = $.isFunction(accept) ? accept : function(d) {
+ return d.is(accept);
+ };
+
+ //Store the droppable's proportions
+ this.proportions = { width: this.element[0].offsetWidth, height: this.element[0].offsetHeight };
+
+ // Add the reference and positions to the manager
+ $.ui.ddmanager.droppables[o.scope] = $.ui.ddmanager.droppables[o.scope] || [];
+ $.ui.ddmanager.droppables[o.scope].push(this);
+
+ (o.addClasses && this.element.addClass("ui-droppable"));
+
+ },
+
+ _destroy: function() {
+ var i = 0,
+ drop = $.ui.ddmanager.droppables[this.options.scope];
+
+ for ( ; i < drop.length; i++ ) {
+ if ( drop[i] === this ) {
+ drop.splice(i, 1);
+ }
+ }
+
+ this.element.removeClass("ui-droppable ui-droppable-disabled");
+ },
+
+ _setOption: function(key, value) {
+
+ if(key === "accept") {
+ this.accept = $.isFunction(value) ? value : function(d) {
+ return d.is(value);
+ };
+ }
+ $.Widget.prototype._setOption.apply(this, arguments);
+ },
+
+ _activate: function(event) {
+ var draggable = $.ui.ddmanager.current;
+ if(this.options.activeClass) {
+ this.element.addClass(this.options.activeClass);
+ }
+ if(draggable){
+ this._trigger("activate", event, this.ui(draggable));
+ }
+ },
+
+ _deactivate: function(event) {
+ var draggable = $.ui.ddmanager.current;
+ if(this.options.activeClass) {
+ this.element.removeClass(this.options.activeClass);
+ }
+ if(draggable){
+ this._trigger("deactivate", event, this.ui(draggable));
+ }
+ },
+
+ _over: function(event) {
+
+ var draggable = $.ui.ddmanager.current;
+
+ // Bail if draggable and droppable are same element
+ if (!draggable || (draggable.currentItem || draggable.element)[0] === this.element[0]) {
+ return;
+ }
+
+ if (this.accept.call(this.element[0],(draggable.currentItem || draggable.element))) {
+ if(this.options.hoverClass) {
+ this.element.addClass(this.options.hoverClass);
+ }
+ this._trigger("over", event, this.ui(draggable));
+ }
+
+ },
+
+ _out: function(event) {
+
+ var draggable = $.ui.ddmanager.current;
+
+ // Bail if draggable and droppable are same element
+ if (!draggable || (draggable.currentItem || draggable.element)[0] === this.element[0]) {
+ return;
+ }
+
+ if (this.accept.call(this.element[0],(draggable.currentItem || draggable.element))) {
+ if(this.options.hoverClass) {
+ this.element.removeClass(this.options.hoverClass);
+ }
+ this._trigger("out", event, this.ui(draggable));
+ }
+
+ },
+
+ _drop: function(event,custom) {
+
+ var draggable = custom || $.ui.ddmanager.current,
+ childrenIntersection = false;
+
+ // Bail if draggable and droppable are same element
+ if (!draggable || (draggable.currentItem || draggable.element)[0] === this.element[0]) {
+ return false;
+ }
+
+ this.element.find(":data(ui-droppable)").not(".ui-draggable-dragging").each(function() {
+ var inst = $.data(this, "ui-droppable");
+ if(
+ inst.options.greedy &&
+ !inst.options.disabled &&
+ inst.options.scope === draggable.options.scope &&
+ inst.accept.call(inst.element[0], (draggable.currentItem || draggable.element)) &&
+ $.ui.intersect(draggable, $.extend(inst, { offset: inst.element.offset() }), inst.options.tolerance, event)
+ ) { childrenIntersection = true; return false; }
+ });
+ if(childrenIntersection) {
+ return false;
+ }
+
+ if(this.accept.call(this.element[0],(draggable.currentItem || draggable.element))) {
+ if(this.options.activeClass) {
+ this.element.removeClass(this.options.activeClass);
+ }
+ if(this.options.hoverClass) {
+ this.element.removeClass(this.options.hoverClass);
+ }
+ this._trigger("drop", event, this.ui(draggable));
+ return this.element;
+ }
+
+ return false;
+
+ },
+
+ ui: function(c) {
+ return {
+ draggable: (c.currentItem || c.element),
+ helper: c.helper,
+ position: c.position,
+ offset: c.positionAbs
+ };
+ }
+
+});
+
+$.ui.intersect = function(draggable, droppable, toleranceMode, event) {
+
+ if (!droppable.offset) {
+ return false;
+ }
+
+ var draggableLeft, draggableTop,
+ x1 = (draggable.positionAbs || draggable.position.absolute).left, x2 = x1 + draggable.helperProportions.width,
+ y1 = (draggable.positionAbs || draggable.position.absolute).top, y2 = y1 + draggable.helperProportions.height,
+ l = droppable.offset.left, r = l + droppable.proportions.width,
+ t = droppable.offset.top, b = t + droppable.proportions.height;
+
+ switch (toleranceMode) {
+ case "fit":
+ return (l <= x1 && x2 <= r && t <= y1 && y2 <= b);
+ case "intersect":
+ return (l < x1 + (draggable.helperProportions.width / 2) && // Right Half
+ x2 - (draggable.helperProportions.width / 2) < r && // Left Half
+ t < y1 + (draggable.helperProportions.height / 2) && // Bottom Half
+ y2 - (draggable.helperProportions.height / 2) < b ); // Top Half
+ case "pointer":
+ draggableLeft = event.pageX;
+ draggableTop = event.pageY;
+ return isOverAxis( draggableTop, t, droppable.proportions.height ) && isOverAxis( draggableLeft, l, droppable.proportions.width );
+ case "touch":
+ return (
+ (y1 >= t && y1 <= b) || // Top edge touching
+ (y2 >= t && y2 <= b) || // Bottom edge touching
+ (y1 < t && y2 > b) // Surrounded vertically
+ ) && (
+ (x1 >= l && x1 <= r) || // Left edge touching
+ (x2 >= l && x2 <= r) || // Right edge touching
+ (x1 < l && x2 > r) // Surrounded horizontally
+ );
+ default:
+ return false;
+ }
+
+};
+
+/*
+ This manager tracks offsets of draggables and droppables
+*/
+$.ui.ddmanager = {
+ current: null,
+ droppables: { "default": [] },
+ prepareOffsets: function(t, event) {
+
+ var i, j,
+ m = $.ui.ddmanager.droppables[t.options.scope] || [],
+ type = event ? event.type : null, // workaround for #2317
+ list = (t.currentItem || t.element).find(":data(ui-droppable)").addBack();
+
+ droppablesLoop: for (i = 0; i < m.length; i++) {
+
+ //No disabled and non-accepted
+ if(m[i].options.disabled || (t && !m[i].accept.call(m[i].element[0],(t.currentItem || t.element)))) {
+ continue;
+ }
+
+ // Filter out elements in the current dragged item
+ for (j=0; j < list.length; j++) {
+ if(list[j] === m[i].element[0]) {
+ m[i].proportions.height = 0;
+ continue droppablesLoop;
+ }
+ }
+
+ m[i].visible = m[i].element.css("display") !== "none";
+ if(!m[i].visible) {
+ continue;
+ }
+
+ //Activate the droppable if used directly from draggables
+ if(type === "mousedown") {
+ m[i]._activate.call(m[i], event);
+ }
+
+ m[i].offset = m[i].element.offset();
+ m[i].proportions = { width: m[i].element[0].offsetWidth, height: m[i].element[0].offsetHeight };
+
+ }
+
+ },
+ drop: function(draggable, event) {
+
+ var dropped = false;
+ $.each($.ui.ddmanager.droppables[draggable.options.scope] || [], function() {
+
+ if(!this.options) {
+ return;
+ }
+ if (!this.options.disabled && this.visible && $.ui.intersect(draggable, this, this.options.tolerance, event)) {
+ dropped = this._drop.call(this, event) || dropped;
+ }
+
+ if (!this.options.disabled && this.visible && this.accept.call(this.element[0],(draggable.currentItem || draggable.element))) {
+ this.isout = true;
+ this.isover = false;
+ this._deactivate.call(this, event);
+ }
+
+ });
+ return dropped;
+
+ },
+ dragStart: function( draggable, event ) {
+ //Listen for scrolling so that if the dragging causes scrolling the position of the droppables can be recalculated (see #5003)
+ draggable.element.parentsUntil( "body" ).bind( "scroll.droppable", function() {
+ if( !draggable.options.refreshPositions ) {
+ $.ui.ddmanager.prepareOffsets( draggable, event );
+ }
+ });
+ },
+ drag: function(draggable, event) {
+
+ //If you have a highly dynamic page, you might try this option. It renders positions every time you move the mouse.
+ if(draggable.options.refreshPositions) {
+ $.ui.ddmanager.prepareOffsets(draggable, event);
+ }
+
+ //Run through all droppables and check their positions based on specific tolerance options
+ $.each($.ui.ddmanager.droppables[draggable.options.scope] || [], function() {
+
+ if(this.options.disabled || this.greedyChild || !this.visible) {
+ return;
+ }
+
+ var parentInstance, scope, parent,
+ intersects = $.ui.intersect(draggable, this, this.options.tolerance, event),
+ c = !intersects && this.isover ? "isout" : (intersects && !this.isover ? "isover" : null);
+ if(!c) {
+ return;
+ }
+
+ if (this.options.greedy) {
+ // find droppable parents with same scope
+ scope = this.options.scope;
+ parent = this.element.parents(":data(ui-droppable)").filter(function () {
+ return $.data(this, "ui-droppable").options.scope === scope;
+ });
+
+ if (parent.length) {
+ parentInstance = $.data(parent[0], "ui-droppable");
+ parentInstance.greedyChild = (c === "isover");
+ }
+ }
+
+ // we just moved into a greedy child
+ if (parentInstance && c === "isover") {
+ parentInstance.isover = false;
+ parentInstance.isout = true;
+ parentInstance._out.call(parentInstance, event);
+ }
+
+ this[c] = true;
+ this[c === "isout" ? "isover" : "isout"] = false;
+ this[c === "isover" ? "_over" : "_out"].call(this, event);
+
+ // we just moved out of a greedy child
+ if (parentInstance && c === "isout") {
+ parentInstance.isout = false;
+ parentInstance.isover = true;
+ parentInstance._over.call(parentInstance, event);
+ }
+ });
+
+ },
+ dragStop: function( draggable, event ) {
+ draggable.element.parentsUntil( "body" ).unbind( "scroll.droppable" );
+ //Call prepareOffsets one final time since IE does not fire return scroll events when overflow was caused by drag (see #5003)
+ if( !draggable.options.refreshPositions ) {
+ $.ui.ddmanager.prepareOffsets( draggable, event );
+ }
+ }
+};
+
+})(jQuery);
+
+
+
+/*! jQuery UI - v1.10.0 - 2013-01-17
+* http://jqueryui.com
+* Includes: jquery.ui.resizable.js
+* Copyright 2013 jQuery Foundation and other contributors; Licensed MIT */
+(function(e,t){function n(e){return parseInt(e,10)||0}function r(e){return!isNaN(parseInt(e,10))}e.widget("ui.resizable",e.ui.mouse,{version:"1.10.0",widgetEventPrefix:"resize",options:{alsoResize:!1,animate:!1,animateDuration:"slow",animateEasing:"swing",aspectRatio:!1,autoHide:!1,containment:!1,ghost:!1,grid:!1,handles:"e,s,se",helper:!1,maxHeight:null,maxWidth:null,minHeight:10,minWidth:10,zIndex:90,resize:null,start:null,stop:null},_create:function(){var t,n,r,i,s,o=this,u=this.options;this.element.addClass("ui-resizable"),e.extend(this,{_aspectRatio:!!u.aspectRatio,aspectRatio:u.aspectRatio,originalElement:this.element,_proportionallyResizeElements:[],_helper:u.helper||u.ghost||u.animate?u.helper||"ui-resizable-helper":null}),this.element[0].nodeName.match(/canvas|textarea|input|select|button|img/i)&&(this.element.wrap(e("<div class='ui-wrapper' style='overflow: hidden;'></div>").css({position:this.element.css("position"),width:this.element.outerWidth(),height:this.element.outerHeight(),top:this.element.css("top"),left:this.element.css("left")})),this.element=this.element.parent().data("ui-resizable",this.element.data("ui-resizable")),this.elementIsWrapper=!0,this.element.css({marginLeft:this.originalElement.css("marginLeft"),marginTop:this.originalElement.css("marginTop"),marginRight:this.originalElement.css("marginRight"),marginBottom:this.originalElement.css("marginBottom")}),this.originalElement.css({marginLeft:0,marginTop:0,marginRight:0,marginBottom:0}),this.originalResizeStyle=this.originalElement.css("resize"),this.originalElement.css("resize","none"),this._proportionallyResizeElements.push(this.originalElement.css({position:"static",zoom:1,display:"block"})),this.originalElement.css({margin:this.originalElement.css("margin")}),this._proportionallyResize()),this.handles=u.handles||(e(".ui-resizable-handle",this.element).length?{n:".ui-resizable-n",e:".ui-resizable-e",s:".ui-resizable-s",w:".ui-resizable-w",se:".ui-resizable-se",sw:".ui-resizable-sw",ne:".ui-resizable-ne",nw:".ui-resizable-nw"}:"e,s,se");if(this.handles.constructor===String){this.handles==="all"&&(this.handles="n,e,s,w,se,sw,ne,nw"),t=this.handles.split(","),this.handles={};for(n=0;n<t.length;n++)r=e.trim(t[n]),s="ui-resizable-"+r,i=e("<div class='ui-resizable-handle "+s+"'></div>"),i.css({zIndex:u.zIndex}),"se"===r&&i.addClass("ui-icon ui-icon-gripsmall-diagonal-se"),this.handles[r]=".ui-resizable-"+r,this.element.append(i)}this._renderAxis=function(t){var n,r,i,s;t=t||this.element;for(n in this.handles){this.handles[n].constructor===String&&(this.handles[n]=e(this.handles[n],this.element).show()),this.elementIsWrapper&&this.originalElement[0].nodeName.match(/textarea|input|select|button/i)&&(r=e(this.handles[n],this.element),s=/sw|ne|nw|se|n|s/.test(n)?r.outerHeight():r.outerWidth(),i=["padding",/ne|nw|n/.test(n)?"Top":/se|sw|s/.test(n)?"Bottom":/^e$/.test(n)?"Right":"Left"].join(""),t.css(i,s),this._proportionallyResize());if(!e(this.handles[n]).length)continue}},this._renderAxis(this.element),this._handles=e(".ui-resizable-handle",this.element).disableSelection(),this._handles.mouseover(function(){o.resizing||(this.className&&(i=this.className.match(/ui-resizable-(se|sw|ne|nw|n|e|s|w)/i)),o.axis=i&&i[1]?i[1]:"se")}),u.autoHide&&(this._handles.hide(),e(this.element).addClass("ui-resizable-autohide").mouseenter(function(){if(u.disabled)return;e(this).removeClass("ui-resizable-autohide"),o._handles.show()}).mouseleave(function(){if(u.disabled)return;o.resizing||(e(this).addClass("ui-resizable-autohide"),o._handles.hide())})),this._mouseInit()},_destroy:function(){this._mouseDestroy();var t,n=function(t){e(t).removeClass("ui-resizable ui-resizable-disabled ui-resizable-resizing").removeData("resizable").removeData("ui-resizable").unbind(".resizable").find(".ui-resizable-handle").remove()};return this.elementIsWrapper&&(n(this.element),t=this.element,this.originalElement.css({position:t.css("position"),width:t.outerWidth(),height:t.outerHeight(),top:t.css("top"),left:t.css("left")}).insertAfter(t),t.remove()),this.originalElement.css("resize",this.originalResizeStyle),n(this.originalElement),this},_mouseCapture:function(t){var n,r,i=!1;for(n in this.handles){r=e(this.handles[n])[0];if(r===t.target||e.contains(r,t.target))i=!0}return!this.options.disabled&&i},_mouseStart:function(t){var r,i,s,o=this.options,u=this.element.position(),a=this.element;return this.resizing=!0,/absolute/.test(a.css("position"))?a.css({position:"absolute",top:a.css("top"),left:a.css("left")}):a.is(".ui-draggable")&&a.css({position:"absolute",top:u.top,left:u.left}),this._renderProxy(),r=n(this.helper.css("left")),i=n(this.helper.css("top")),o.containment&&(r+=e(o.containment).scrollLeft()||0,i+=e(o.containment).scrollTop()||0),this.offset=this.helper.offset(),this.position={left:r,top:i},this.size=this._helper?{width:a.outerWidth(),height:a.outerHeight()}:{width:a.width(),height:a.height()},this.originalSize=this._helper?{width:a.outerWidth(),height:a.outerHeight()}:{width:a.width(),height:a.height()},this.originalPosition={left:r,top:i},this.sizeDiff={width:a.outerWidth()-a.width(),height:a.outerHeight()-a.height()},this.originalMousePosition={left:t.pageX,top:t.pageY},this.aspectRatio=typeof o.aspectRatio=="number"?o.aspectRatio:this.originalSize.width/this.originalSize.height||1,s=e(".ui-resizable-"+this.axis).css("cursor"),e("body").css("cursor",s==="auto"?this.axis+"-resize":s),a.addClass("ui-resizable-resizing"),this._propagate("start",t),!0},_mouseDrag:function(t){var n,r=this.helper,i={},s=this.originalMousePosition,o=this.axis,u=this.position.top,a=this.position.left,f=this.size.width,l=this.size.height,c=t.pageX-s.left||0,h=t.pageY-s.top||0,p=this._change[o];if(!p)return!1;n=p.apply(this,[t,c,h]),this._updateVirtualBoundaries(t.shiftKey);if(this._aspectRatio||t.shiftKey)n=this._updateRatio(n,t);return n=this._respectSize(n,t),this._updateCache(n),this._propagate("resize",t),this.position.top!==u&&(i.top=this.position.top+"px"),this.position.left!==a&&(i.left=this.position.left+"px"),this.size.width!==f&&(i.width=this.size.width+"px"),this.size.height!==l&&(i.height=this.size.height+"px"),r.css(i),!this._helper&&this._proportionallyResizeElements.length&&this._proportionallyResize(),e.isEmptyObject(i)||this._trigger("resize",t,this.ui()),!1},_mouseStop:function(t){this.resizing=!1;var n,r,i,s,o,u,a,f=this.options,l=this;return this._helper&&(n=this._proportionallyResizeElements,r=n.length&&/textarea/i.test(n[0].nodeName),i=r&&e.ui.hasScroll(n[0],"left")?0:l.sizeDiff.height,s=r?0:l.sizeDiff.width,o={width:l.helper.width()-s,height:l.helper.height()-i},u=parseInt(l.element.css("left"),10)+(l.position.left-l.originalPosition.left)||null,a=parseInt(l.element.css("top"),10)+(l.position.top-l.originalPosition.top)||null,f.animate||this.element.css(e.extend(o,{top:a,left:u})),l.helper.height(l.size.height),l.helper.width(l.size.width),this._helper&&!f.animate&&this._proportionallyResize()),e("body").css("cursor","auto"),this.element.removeClass("ui-resizable-resizing"),this._propagate("stop",t),this._helper&&this.helper.remove(),!1},_updateVirtualBoundaries:function(e){var t,n,i,s,o,u=this.options;o={minWidth:r(u.minWidth)?u.minWidth:0,maxWidth:r(u.maxWidth)?u.maxWidth:Infinity,minHeight:r(u.minHeight)?u.minHeight:0,maxHeight:r(u.maxHeight)?u.maxHeight:Infinity};if(this._aspectRatio||e)t=o.minHeight*this.aspectRatio,i=o.minWidth/this.aspectRatio,n=o.maxHeight*this.aspectRatio,s=o.maxWidth/this.aspectRatio,t>o.minWidth&&(o.minWidth=t),i>o.minHeight&&(o.minHeight=i),n<o.maxWidth&&(o.maxWidth=n),s<o.maxHeight&&(o.maxHeight=s);this._vBoundaries=o},_updateCache:function(e){this.offset=this.helper.offset(),r(e.left)&&(this.position.left=e.left),r(e.top)&&(this.position.top=e.top),r(e.height)&&(this.size.height=e.height),r(e.width)&&(this.size.width=e.width)},_updateRatio:function(e){var t=this.position,n=this.size,i=this.axis;return r(e.height)?e.width=e.height*this.aspectRatio:r(e.width)&&(e.height=e.width/this.aspectRatio),i==="sw"&&(e.left=t.left+(n.width-e.width),e.top=null),i==="nw"&&(e.top=t.top+(n.height-e.height),e.left=t.left+(n.width-e.width)),e},_respectSize:function(e){var t=this._vBoundaries,n=this.axis,i=r(e.width)&&t.maxWidth&&t.maxWidth<e.width,s=r(e.height)&&t.maxHeight&&t.maxHeight<e.height,o=r(e.width)&&t.minWidth&&t.minWidth>e.width,u=r(e.height)&&t.minHeight&&t.minHeight>e.height,a=this.originalPosition.left+this.originalSize.width,f=this.position.top+this.size.height,l=/sw|nw|w/.test(n),c=/nw|ne|n/.test(n);return o&&(e.width=t.minWidth),u&&(e.height=t.minHeight),i&&(e.width=t.maxWidth),s&&(e.height=t.maxHeight),o&&l&&(e.left=a-t.minWidth),i&&l&&(e.left=a-t.maxWidth),u&&c&&(e.top=f-t.minHeight),s&&c&&(e.top=f-t.maxHeight),!e.width&&!e.height&&!e.left&&e.top?e.top=null:!e.width&&!e.height&&!e.top&&e.left&&(e.left=null),e},_proportionallyResize:function(){if(!this._proportionallyResizeElements.length)return;var e,t,n,r,i,s=this.helper||this.element;for(e=0;e<this._proportionallyResizeElements.length;e++){i=this._proportionallyResizeElements[e];if(!this.borderDif){this.borderDif=[],n=[i.css("borderTopWidth"),i.css("borderRightWidth"),i.css("borderBottomWidth"),i.css("borderLeftWidth")],r=[i.css("paddingTop"),i.css("paddingRight"),i.css("paddingBottom"),i.css("paddingLeft")];for(t=0;t<n.length;t++)this.borderDif[t]=(parseInt(n[t],10)||0)+(parseInt(r[t],10)||0)}i.css({height:s.height()-this.borderDif[0]-this.borderDif[2]||0,width:s.width()-this.borderDif[1]-this.borderDif[3]||0})}},_renderProxy:function(){var t=this.element,n=this.options;this.elementOffset=t.offset(),this._helper?(this.helper=this.helper||e("<div style='overflow:hidden;'></div>"),this.helper.addClass(this._helper).css({width:this.element.outerWidth()-1,height:this.element.outerHeight()-1,position:"absolute",left:this.elementOffset.left+"px",top:this.elementOffset.top+"px",zIndex:++n.zIndex}),this.helper.appendTo("body").disableSelection()):this.helper=this.element},_change:{e:function(e,t){return{width:this.originalSize.width+t}},w:function(e,t){var n=this.originalSize,r=this.originalPosition;return{left:r.left+t,width:n.width-t}},n:function(e,t,n){var r=this.originalSize,i=this.originalPosition;return{top:i.top+n,height:r.height-n}},s:function(e,t,n){return{height:this.originalSize.height+n}},se:function(t,n,r){return e.extend(this._change.s.apply(this,arguments),this._change.e.apply(this,[t,n,r]))},sw:function(t,n,r){return e.extend(this._change.s.apply(this,arguments),this._change.w.apply(this,[t,n,r]))},ne:function(t,n,r){return e.extend(this._change.n.apply(this,arguments),this._change.e.apply(this,[t,n,r]))},nw:function(t,n,r){return e.extend(this._change.n.apply(this,arguments),this._change.w.apply(this,[t,n,r]))}},_propagate:function(t,n){e.ui.plugin.call(this,t,[n,this.ui()]),t!=="resize"&&this._trigger(t,n,this.ui())},plugins:{},ui:function(){return{originalElement:this.originalElement,element:this.element,helper:this.helper,position:this.position,size:this.size,originalSize:this.originalSize,originalPosition:this.originalPosition}}}),e.ui.plugin.add("resizable","animate",{stop:function(t){var n=e(this).data("ui-resizable"),r=n.options,i=n._proportionallyResizeElements,s=i.length&&/textarea/i.test(i[0].nodeName),o=s&&e.ui.hasScroll(i[0],"left")?0:n.sizeDiff.height,u=s?0:n.sizeDiff.width,a={width:n.size.width-u,height:n.size.height-o},f=parseInt(n.element.css("left"),10)+(n.position.left-n.originalPosition.left)||null,l=parseInt(n.element.css("top"),10)+(n.position.top-n.originalPosition.top)||null;n.element.animate(e.extend(a,l&&f?{top:l,left:f}:{}),{duration:r.animateDuration,easing:r.animateEasing,step:function(){var r={width:parseInt(n.element.css("width"),10),height:parseInt(n.element.css("height"),10),top:parseInt(n.element.css("top"),10),left:parseInt(n.element.css("left"),10)};i&&i.length&&e(i[0]).css({width:r.width,height:r.height}),n._updateCache(r),n._propagate("resize",t)}})}}),e.ui.plugin.add("resizable","containment",{start:function(){var t,r,i,s,o,u,a,f=e(this).data("ui-resizable"),l=f.options,c=f.element,h=l.containment,p=h instanceof e?h.get(0):/parent/.test(h)?c.parent().get(0):h;if(!p)return;f.containerElement=e(p),/document/.test(h)||h===document?(f.containerOffset={left:0,top:0},f.containerPosition={left:0,top:0},f.parentData={element:e(document),left:0,top:0,width:e(document).width(),height:e(document).height()||document.body.parentNode.scrollHeight}):(t=e(p),r=[],e(["Top","Right","Left","Bottom"]).each(function(e,i){r[e]=n(t.css("padding"+i))}),f.containerOffset=t.offset(),f.containerPosition=t.position(),f.containerSize={height:t.innerHeight()-r[3],width:t.innerWidth()-r[1]},i=f.containerOffset,s=f.containerSize.height,o=f.containerSize.width,u=e.ui.hasScroll(p,"left")?p.scrollWidth:o,a=e.ui.hasScroll(p)?p.scrollHeight:s,f.parentData={element:p,left:i.left,top:i.top,width:u,height:a})},resize:function(t){var n,r,i,s,o=e(this).data("ui-resizable"),u=o.options,a=o.containerOffset,f=o.position,l=o._aspectRatio||t.shiftKey,c={top:0,left:0},h=o.containerElement;h[0]!==document&&/static/.test(h.css("position"))&&(c=a),f.left<(o._helper?a.left:0)&&(o.size.width=o.size.width+(o._helper?o.position.left-a.left:o.position.left-c.left),l&&(o.size.height=o.size.width/o.aspectRatio),o.position.left=u.helper?a.left:0),f.top<(o._helper?a.top:0)&&(o.size.height=o.size.height+(o._helper?o.position.top-a.top:o.position.top),l&&(o.size.width=o.size.height*o.aspectRatio),o.position.top=o._helper?a.top:0),o.offset.left=o.parentData.left+o.position.left,o.offset.top=o.parentData.top+o.position.top,n=Math.abs((o._helper?o.offset.left-c.left:o.offset.left-c.left)+o.sizeDiff.width),r=Math.abs((o._helper?o.offset.top-c.top:o.offset.top-a.top)+o.sizeDiff.height),i=o.containerElement.get(0)===o.element.parent().get(0),s=/relative|absolute/.test(o.containerElement.css("position")),i&&s&&(n-=o.parentData.left),n+o.size.width>=o.parentData.width&&(o.size.width=o.parentData.width-n,l&&(o.size.height=o.size.width/o.aspectRatio)),r+o.size.height>=o.parentData.height&&(o.size.height=o.parentData.height-r,l&&(o.size.width=o.size.height*o.aspectRatio))},stop:function(){var t=e(this).data("ui-resizable"),n=t.options,r=t.containerOffset,i=t.containerPosition,s=t.containerElement,o=e(t.helper),u=o.offset(),a=o.outerWidth()-t.sizeDiff.width,f=o.outerHeight()-t.sizeDiff.height;t._helper&&!n.animate&&/relative/.test(s.css("position"))&&e(this).css({left:u.left-i.left-r.left,width:a,height:f}),t._helper&&!n.animate&&/static/.test(s.css("position"))&&e(this).css({left:u.left-i.left-r.left,width:a,height:f})}}),e.ui.plugin.add("resizable","alsoResize",{start:function(){var t=e(this).data("ui-resizable"),n=t.options,r=function(t){e(t).each(function(){var t=e(this);t.data("ui-resizable-alsoresize",{width:parseInt(t.width(),10),height:parseInt(t.height(),10),left:parseInt(t.css("left"),10),top:parseInt(t.css("top"),10)})})};typeof n.alsoResize=="object"&&!n.alsoResize.parentNode?n.alsoResize.length?(n.alsoResize=n.alsoResize[0],r(n.alsoResize)):e.each(n.alsoResize,function(e){r(e)}):r(n.alsoResize)},resize:function(t,n){var r=e(this).data("ui-resizable"),i=r.options,s=r.originalSize,o=r.originalPosition,u={height:r.size.height-s.height||0,width:r.size.width-s.width||0,top:r.position.top-o.top||0,left:r.position.left-o.left||0},a=function(t,r){e(t).each(function(){var t=e(this),i=e(this).data("ui-resizable-alsoresize"),s={},o=r&&r.length?r:t.parents(n.originalElement[0]).length?["width","height"]:["width","height","top","left"];e.each(o,function(e,t){var n=(i[t]||0)+(u[t]||0);n&&n>=0&&(s[t]=n||null)}),t.css(s)})};typeof i.alsoResize=="object"&&!i.alsoResize.nodeType?e.each(i.alsoResize,function(e,t){a(e,t)}):a(i.alsoResize)},stop:function(){e(this).removeData("resizable-alsoresize")}}),e.ui.plugin.add("resizable","ghost",{start:function(){var t=e(this).data("ui-resizable"),n=t.options,r=t.size;t.ghost=t.originalElement.clone(),t.ghost.css({opacity:.25,display:"block",position:"relative",height:r.height,width:r.width,margin:0,left:0,top:0}).addClass("ui-resizable-ghost").addClass(typeof n.ghost=="string"?n.ghost:""),t.ghost.appendTo(t.helper)},resize:function(){var t=e(this).data("ui-resizable");t.ghost&&t.ghost.css({position:"relative",height:t.size.height,width:t.size.width})},stop:function(){var t=e(this).data("ui-resizable");t.ghost&&t.helper&&t.helper.get(0).removeChild(t.ghost.get(0))}}),e.ui.plugin.add("resizable","grid",{resize:function(){var t=e(this).data("ui-resizable"),n=t.options,r=t.size,i=t.originalSize,s=t.originalPosition,o=t.axis,u=typeof n.grid=="number"?[n.grid,n.grid]:n.grid,a=u[0]||1,f=u[1]||1,l=Math.round((r.width-i.width)/a)*a,c=Math.round((r.height-i.height)/f)*f,h=i.width+l,p=i.height+c,d=n.maxWidth&&n.maxWidth<h,v=n.maxHeight&&n.maxHeight<p,m=n.minWidth&&n.minWidth>h,g=n.minHeight&&n.minHeight>p;n.grid=u,m&&(h+=a),g&&(p+=f),d&&(h-=a),v&&(p-=f),/^(se|s|e)$/.test(o)?(t.size.width=h,t.size.height=p):/^(ne)$/.test(o)?(t.size.width=h,t.size.height=p,t.position.top=s.top-c):/^(sw)$/.test(o)?(t.size.width=h,t.size.height=p,t.position.left=s.left-l):(t.size.width=h,t.size.height=p,t.position.top=s.top-c,t.position.left=s.left-l)}})})(jQuery);
+
+
+/*! jQuery UI Sortables - v1.10.2 - 2013-03-14
+* http://jqueryui.com
+* Copyright 2013 jQuery Foundation and other contributors; Licensed MIT */
+(function(t){function e(t,e,i){return t>e&&e+i>t}function i(t){return/left|right/.test(t.css("float"))||/inline|table-cell/.test(t.css("display"))}t.widget("ui.sortable",t.ui.mouse,{version:"1.10.2",widgetEventPrefix:"sort",ready:!1,options:{appendTo:"parent",axis:!1,connectWith:!1,containment:!1,cursor:"auto",cursorAt:!1,dropOnEmpty:!0,forcePlaceholderSize:!1,forceHelperSize:!1,grid:!1,handle:!1,helper:"original",items:"> *",opacity:!1,placeholder:!1,revert:!1,scroll:!0,scrollSensitivity:20,scrollSpeed:20,scope:"default",tolerance:"intersect",zIndex:1e3,activate:null,beforeStop:null,change:null,deactivate:null,out:null,over:null,receive:null,remove:null,sort:null,start:null,stop:null,update:null},_create:function(){var t=this.options;this.containerCache={},this.element.addClass("ui-sortable"),this.refresh(),this.floating=this.items.length?"x"===t.axis||i(this.items[0].item):!1,this.offset=this.element.offset(),this._mouseInit(),this.ready=!0},_destroy:function(){this.element.removeClass("ui-sortable ui-sortable-disabled"),this._mouseDestroy();for(var t=this.items.length-1;t>=0;t--)this.items[t].item.removeData(this.widgetName+"-item");return this},_setOption:function(e,i){"disabled"===e?(this.options[e]=i,this.widget().toggleClass("ui-sortable-disabled",!!i)):t.Widget.prototype._setOption.apply(this,arguments)},_mouseCapture:function(e,i){var s=null,n=!1,a=this;return this.reverting?!1:this.options.disabled||"static"===this.options.type?!1:(this._refreshItems(e),t(e.target).parents().each(function(){return t.data(this,a.widgetName+"-item")===a?(s=t(this),!1):undefined}),t.data(e.target,a.widgetName+"-item")===a&&(s=t(e.target)),s?!this.options.handle||i||(t(this.options.handle,s).find("*").addBack().each(function(){this===e.target&&(n=!0)}),n)?(this.currentItem=s,this._removeCurrentsFromItems(),!0):!1:!1)},_mouseStart:function(e,i,s){var n,a,o=this.options;if(this.currentContainer=this,this.refreshPositions(),this.helper=this._createHelper(e),this._cacheHelperProportions(),this._cacheMargins(),this.scrollParent=this.helper.scrollParent(),this.offset=this.currentItem.offset(),this.offset={top:this.offset.top-this.margins.top,left:this.offset.left-this.margins.left},t.extend(this.offset,{click:{left:e.pageX-this.offset.left,top:e.pageY-this.offset.top},parent:this._getParentOffset(),relative:this._getRelativeOffset()}),this.helper.css("position","absolute"),this.cssPosition=this.helper.css("position"),this.originalPosition=this._generatePosition(e),this.originalPageX=e.pageX,this.originalPageY=e.pageY,o.cursorAt&&this._adjustOffsetFromHelper(o.cursorAt),this.domPosition={prev:this.currentItem.prev()[0],parent:this.currentItem.parent()[0]},this.helper[0]!==this.currentItem[0]&&this.currentItem.hide(),this._createPlaceholder(),o.containment&&this._setContainment(),o.cursor&&"auto"!==o.cursor&&(a=this.document.find("body"),this.storedCursor=a.css("cursor"),a.css("cursor",o.cursor),this.storedStylesheet=t("<style>*{ cursor: "+o.cursor+" !important; }</style>").appendTo(a)),o.opacity&&(this.helper.css("opacity")&&(this._storedOpacity=this.helper.css("opacity")),this.helper.css("opacity",o.opacity)),o.zIndex&&(this.helper.css("zIndex")&&(this._storedZIndex=this.helper.css("zIndex")),this.helper.css("zIndex",o.zIndex)),this.scrollParent[0]!==document&&"HTML"!==this.scrollParent[0].tagName&&(this.overflowOffset=this.scrollParent.offset()),this._trigger("start",e,this._uiHash()),this._preserveHelperProportions||this._cacheHelperProportions(),!s)for(n=this.containers.length-1;n>=0;n--)this.containers[n]._trigger("activate",e,this._uiHash(this));return t.ui.ddmanager&&(t.ui.ddmanager.current=this),t.ui.ddmanager&&!o.dropBehaviour&&t.ui.ddmanager.prepareOffsets(this,e),this.dragging=!0,this.helper.addClass("ui-sortable-helper"),this._mouseDrag(e),!0},_mouseDrag:function(e){var i,s,n,a,o=this.options,r=!1;for(this.position=this._generatePosition(e),this.positionAbs=this._convertPositionTo("absolute"),this.lastPositionAbs||(this.lastPositionAbs=this.positionAbs),this.options.scroll&&(this.scrollParent[0]!==document&&"HTML"!==this.scrollParent[0].tagName?(this.overflowOffset.top+this.scrollParent[0].offsetHeight-e.pageY<o.scrollSensitivity?this.scrollParent[0].scrollTop=r=this.scrollParent[0].scrollTop+o.scrollSpeed:e.pageY-this.overflowOffset.top<o.scrollSensitivity&&(this.scrollParent[0].scrollTop=r=this.scrollParent[0].scrollTop-o.scrollSpeed),this.overflowOffset.left+this.scrollParent[0].offsetWidth-e.pageX<o.scrollSensitivity?this.scrollParent[0].scrollLeft=r=this.scrollParent[0].scrollLeft+o.scrollSpeed:e.pageX-this.overflowOffset.left<o.scrollSensitivity&&(this.scrollParent[0].scrollLeft=r=this.scrollParent[0].scrollLeft-o.scrollSpeed)):(e.pageY-t(document).scrollTop()<o.scrollSensitivity?r=t(document).scrollTop(t(document).scrollTop()-o.scrollSpeed):t(window).height()-(e.pageY-t(document).scrollTop())<o.scrollSensitivity&&(r=t(document).scrollTop(t(document).scrollTop()+o.scrollSpeed)),e.pageX-t(document).scrollLeft()<o.scrollSensitivity?r=t(document).scrollLeft(t(document).scrollLeft()-o.scrollSpeed):t(window).width()-(e.pageX-t(document).scrollLeft())<o.scrollSensitivity&&(r=t(document).scrollLeft(t(document).scrollLeft()+o.scrollSpeed))),r!==!1&&t.ui.ddmanager&&!o.dropBehaviour&&t.ui.ddmanager.prepareOffsets(this,e)),this.positionAbs=this._convertPositionTo("absolute"),this.options.axis&&"y"===this.options.axis||(this.helper[0].style.left=this.position.left+"px"),this.options.axis&&"x"===this.options.axis||(this.helper[0].style.top=this.position.top+"px"),i=this.items.length-1;i>=0;i--)if(s=this.items[i],n=s.item[0],a=this._intersectsWithPointer(s),a&&s.instance===this.currentContainer&&n!==this.currentItem[0]&&this.placeholder[1===a?"next":"prev"]()[0]!==n&&!t.contains(this.placeholder[0],n)&&("semi-dynamic"===this.options.type?!t.contains(this.element[0],n):!0)){if(this.direction=1===a?"down":"up","pointer"!==this.options.tolerance&&!this._intersectsWithSides(s))break;this._rearrange(e,s),this._trigger("change",e,this._uiHash());break}return this._contactContainers(e),t.ui.ddmanager&&t.ui.ddmanager.drag(this,e),this._trigger("sort",e,this._uiHash()),this.lastPositionAbs=this.positionAbs,!1},_mouseStop:function(e,i){if(e){if(t.ui.ddmanager&&!this.options.dropBehaviour&&t.ui.ddmanager.drop(this,e),this.options.revert){var s=this,n=this.placeholder.offset(),a=this.options.axis,o={};a&&"x"!==a||(o.left=n.left-this.offset.parent.left-this.margins.left+(this.offsetParent[0]===document.body?0:this.offsetParent[0].scrollLeft)),a&&"y"!==a||(o.top=n.top-this.offset.parent.top-this.margins.top+(this.offsetParent[0]===document.body?0:this.offsetParent[0].scrollTop)),this.reverting=!0,t(this.helper).animate(o,parseInt(this.options.revert,10)||500,function(){s._clear(e)})}else this._clear(e,i);return!1}},cancel:function(){if(this.dragging){this._mouseUp({target:null}),"original"===this.options.helper?this.currentItem.css(this._storedCSS).removeClass("ui-sortable-helper"):this.currentItem.show();for(var e=this.containers.length-1;e>=0;e--)this.containers[e]._trigger("deactivate",null,this._uiHash(this)),this.containers[e].containerCache.over&&(this.containers[e]._trigger("out",null,this._uiHash(this)),this.containers[e].containerCache.over=0)}return this.placeholder&&(this.placeholder[0].parentNode&&this.placeholder[0].parentNode.removeChild(this.placeholder[0]),"original"!==this.options.helper&&this.helper&&this.helper[0].parentNode&&this.helper.remove(),t.extend(this,{helper:null,dragging:!1,reverting:!1,_noFinalSort:null}),this.domPosition.prev?t(this.domPosition.prev).after(this.currentItem):t(this.domPosition.parent).prepend(this.currentItem)),this},serialize:function(e){var i=this._getItemsAsjQuery(e&&e.connected),s=[];return e=e||{},t(i).each(function(){var i=(t(e.item||this).attr(e.attribute||"id")||"").match(e.expression||/(.+)[\-=_](.+)/);i&&s.push((e.key||i[1]+"[]")+"="+(e.key&&e.expression?i[1]:i[2]))}),!s.length&&e.key&&s.push(e.key+"="),s.join("&")},toArray:function(e){var i=this._getItemsAsjQuery(e&&e.connected),s=[];return e=e||{},i.each(function(){s.push(t(e.item||this).attr(e.attribute||"id")||"")}),s},_intersectsWith:function(t){var e=this.positionAbs.left,i=e+this.helperProportions.width,s=this.positionAbs.top,n=s+this.helperProportions.height,a=t.left,o=a+t.width,r=t.top,h=r+t.height,l=this.offset.click.top,c=this.offset.click.left,u=s+l>r&&h>s+l&&e+c>a&&o>e+c;return"pointer"===this.options.tolerance||this.options.forcePointerForContainers||"pointer"!==this.options.tolerance&&this.helperProportions[this.floating?"width":"height"]>t[this.floating?"width":"height"]?u:e+this.helperProportions.width/2>a&&o>i-this.helperProportions.width/2&&s+this.helperProportions.height/2>r&&h>n-this.helperProportions.height/2},_intersectsWithPointer:function(t){var i="x"===this.options.axis||e(this.positionAbs.top+this.offset.click.top,t.top,t.height),s="y"===this.options.axis||e(this.positionAbs.left+this.offset.click.left,t.left,t.width),n=i&&s,a=this._getDragVerticalDirection(),o=this._getDragHorizontalDirection();return n?this.floating?o&&"right"===o||"down"===a?2:1:a&&("down"===a?2:1):!1},_intersectsWithSides:function(t){var i=e(this.positionAbs.top+this.offset.click.top,t.top+t.height/2,t.height),s=e(this.positionAbs.left+this.offset.click.left,t.left+t.width/2,t.width),n=this._getDragVerticalDirection(),a=this._getDragHorizontalDirection();return this.floating&&a?"right"===a&&s||"left"===a&&!s:n&&("down"===n&&i||"up"===n&&!i)},_getDragVerticalDirection:function(){var t=this.positionAbs.top-this.lastPositionAbs.top;return 0!==t&&(t>0?"down":"up")},_getDragHorizontalDirection:function(){var t=this.positionAbs.left-this.lastPositionAbs.left;return 0!==t&&(t>0?"right":"left")},refresh:function(t){return this._refreshItems(t),this.refreshPositions(),this},_connectWith:function(){var t=this.options;return t.connectWith.constructor===String?[t.connectWith]:t.connectWith},_getItemsAsjQuery:function(e){var i,s,n,a,o=[],r=[],h=this._connectWith();if(h&&e)for(i=h.length-1;i>=0;i--)for(n=t(h[i]),s=n.length-1;s>=0;s--)a=t.data(n[s],this.widgetFullName),a&&a!==this&&!a.options.disabled&&r.push([t.isFunction(a.options.items)?a.options.items.call(a.element):t(a.options.items,a.element).not(".ui-sortable-helper").not(".ui-sortable-placeholder"),a]);for(r.push([t.isFunction(this.options.items)?this.options.items.call(this.element,null,{options:this.options,item:this.currentItem}):t(this.options.items,this.element).not(".ui-sortable-helper").not(".ui-sortable-placeholder"),this]),i=r.length-1;i>=0;i--)r[i][0].each(function(){o.push(this)});return t(o)},_removeCurrentsFromItems:function(){var e=this.currentItem.find(":data("+this.widgetName+"-item)");this.items=t.grep(this.items,function(t){for(var i=0;e.length>i;i++)if(e[i]===t.item[0])return!1;return!0})},_refreshItems:function(e){this.items=[],this.containers=[this];var i,s,n,a,o,r,h,l,c=this.items,u=[[t.isFunction(this.options.items)?this.options.items.call(this.element[0],e,{item:this.currentItem}):t(this.options.items,this.element),this]],d=this._connectWith();if(d&&this.ready)for(i=d.length-1;i>=0;i--)for(n=t(d[i]),s=n.length-1;s>=0;s--)a=t.data(n[s],this.widgetFullName),a&&a!==this&&!a.options.disabled&&(u.push([t.isFunction(a.options.items)?a.options.items.call(a.element[0],e,{item:this.currentItem}):t(a.options.items,a.element),a]),this.containers.push(a));for(i=u.length-1;i>=0;i--)for(o=u[i][1],r=u[i][0],s=0,l=r.length;l>s;s++)h=t(r[s]),h.data(this.widgetName+"-item",o),c.push({item:h,instance:o,width:0,height:0,left:0,top:0})},refreshPositions:function(e){this.offsetParent&&this.helper&&(this.offset.parent=this._getParentOffset());var i,s,n,a;for(i=this.items.length-1;i>=0;i--)s=this.items[i],s.instance!==this.currentContainer&&this.currentContainer&&s.item[0]!==this.currentItem[0]||(n=this.options.toleranceElement?t(this.options.toleranceElement,s.item):s.item,e||(s.width=n.outerWidth(),s.height=n.outerHeight()),a=n.offset(),s.left=a.left,s.top=a.top);if(this.options.custom&&this.options.custom.refreshContainers)this.options.custom.refreshContainers.call(this);else for(i=this.containers.length-1;i>=0;i--)a=this.containers[i].element.offset(),this.containers[i].containerCache.left=a.left,this.containers[i].containerCache.top=a.top,this.containers[i].containerCache.width=this.containers[i].element.outerWidth(),this.containers[i].containerCache.height=this.containers[i].element.outerHeight();return this},_createPlaceholder:function(e){e=e||this;var i,s=e.options;s.placeholder&&s.placeholder.constructor!==String||(i=s.placeholder,s.placeholder={element:function(){var s=e.currentItem[0].nodeName.toLowerCase(),n=t(e.document[0].createElement(s)).addClass(i||e.currentItem[0].className+" ui-sortable-placeholder").removeClass("ui-sortable-helper");return"tr"===s?n.append("<td colspan='99'> </td>"):"img"===s&&n.attr("src",e.currentItem.attr("src")),i||n.css("visibility","hidden"),n},update:function(t,n){(!i||s.forcePlaceholderSize)&&(n.height()||n.height(e.currentItem.innerHeight()-parseInt(e.currentItem.css("paddingTop")||0,10)-parseInt(e.currentItem.css("paddingBottom")||0,10)),n.width()||n.width(e.currentItem.innerWidth()-parseInt(e.currentItem.css("paddingLeft")||0,10)-parseInt(e.currentItem.css("paddingRight")||0,10)))}}),e.placeholder=t(s.placeholder.element.call(e.element,e.currentItem)),e.currentItem.after(e.placeholder),s.placeholder.update(e,e.placeholder)},_contactContainers:function(s){var n,a,o,r,h,l,c,u,d,p,f=null,m=null;for(n=this.containers.length-1;n>=0;n--)if(!t.contains(this.currentItem[0],this.containers[n].element[0]))if(this._intersectsWith(this.containers[n].containerCache)){if(f&&t.contains(this.containers[n].element[0],f.element[0]))continue;f=this.containers[n],m=n}else this.containers[n].containerCache.over&&(this.containers[n]._trigger("out",s,this._uiHash(this)),this.containers[n].containerCache.over=0);if(f)if(1===this.containers.length)this.containers[m].containerCache.over||(this.containers[m]._trigger("over",s,this._uiHash(this)),this.containers[m].containerCache.over=1);else{for(o=1e4,r=null,p=f.floating||i(this.currentItem),h=p?"left":"top",l=p?"width":"height",c=this.positionAbs[h]+this.offset.click[h],a=this.items.length-1;a>=0;a--)t.contains(this.containers[m].element[0],this.items[a].item[0])&&this.items[a].item[0]!==this.currentItem[0]&&(!p||e(this.positionAbs.top+this.offset.click.top,this.items[a].top,this.items[a].height))&&(u=this.items[a].item.offset()[h],d=!1,Math.abs(u-c)>Math.abs(u+this.items[a][l]-c)&&(d=!0,u+=this.items[a][l]),o>Math.abs(u-c)&&(o=Math.abs(u-c),r=this.items[a],this.direction=d?"up":"down"));if(!r&&!this.options.dropOnEmpty)return;if(this.currentContainer===this.containers[m])return;r?this._rearrange(s,r,null,!0):this._rearrange(s,null,this.containers[m].element,!0),this._trigger("change",s,this._uiHash()),this.containers[m]._trigger("change",s,this._uiHash(this)),this.currentContainer=this.containers[m],this.options.placeholder.update(this.currentContainer,this.placeholder),this.containers[m]._trigger("over",s,this._uiHash(this)),this.containers[m].containerCache.over=1}},_createHelper:function(e){var i=this.options,s=t.isFunction(i.helper)?t(i.helper.apply(this.element[0],[e,this.currentItem])):"clone"===i.helper?this.currentItem.clone():this.currentItem;return s.parents("body").length||t("parent"!==i.appendTo?i.appendTo:this.currentItem[0].parentNode)[0].appendChild(s[0]),s[0]===this.currentItem[0]&&(this._storedCSS={width:this.currentItem[0].style.width,height:this.currentItem[0].style.height,position:this.currentItem.css("position"),top:this.currentItem.css("top"),left:this.currentItem.css("left")}),(!s[0].style.width||i.forceHelperSize)&&s.width(this.currentItem.width()),(!s[0].style.height||i.forceHelperSize)&&s.height(this.currentItem.height()),s},_adjustOffsetFromHelper:function(e){"string"==typeof e&&(e=e.split(" ")),t.isArray(e)&&(e={left:+e[0],top:+e[1]||0}),"left"in e&&(this.offset.click.left=e.left+this.margins.left),"right"in e&&(this.offset.click.left=this.helperProportions.width-e.right+this.margins.left),"top"in e&&(this.offset.click.top=e.top+this.margins.top),"bottom"in e&&(this.offset.click.top=this.helperProportions.height-e.bottom+this.margins.top)},_getParentOffset:function(){this.offsetParent=this.helper.offsetParent();var e=this.offsetParent.offset();return"absolute"===this.cssPosition&&this.scrollParent[0]!==document&&t.contains(this.scrollParent[0],this.offsetParent[0])&&(e.left+=this.scrollParent.scrollLeft(),e.top+=this.scrollParent.scrollTop()),(this.offsetParent[0]===document.body||this.offsetParent[0].tagName&&"html"===this.offsetParent[0].tagName.toLowerCase()&&t.ui.ie)&&(e={top:0,left:0}),{top:e.top+(parseInt(this.offsetParent.css("borderTopWidth"),10)||0),left:e.left+(parseInt(this.offsetParent.css("borderLeftWidth"),10)||0)}},_getRelativeOffset:function(){if("relative"===this.cssPosition){var t=this.currentItem.position();return{top:t.top-(parseInt(this.helper.css("top"),10)||0)+this.scrollParent.scrollTop(),left:t.left-(parseInt(this.helper.css("left"),10)||0)+this.scrollParent.scrollLeft()}}return{top:0,left:0}},_cacheMargins:function(){this.margins={left:parseInt(this.currentItem.css("marginLeft"),10)||0,top:parseInt(this.currentItem.css("marginTop"),10)||0}},_cacheHelperProportions:function(){this.helperProportions={width:this.helper.outerWidth(),height:this.helper.outerHeight()}},_setContainment:function(){var e,i,s,n=this.options;"parent"===n.containment&&(n.containment=this.helper[0].parentNode),("document"===n.containment||"window"===n.containment)&&(this.containment=[0-this.offset.relative.left-this.offset.parent.left,0-this.offset.relative.top-this.offset.parent.top,t("document"===n.containment?document:window).width()-this.helperProportions.width-this.margins.left,(t("document"===n.containment?document:window).height()||document.body.parentNode.scrollHeight)-this.helperProportions.height-this.margins.top]),/^(document|window|parent)$/.test(n.containment)||(e=t(n.containment)[0],i=t(n.containment).offset(),s="hidden"!==t(e).css("overflow"),this.containment=[i.left+(parseInt(t(e).css("borderLeftWidth"),10)||0)+(parseInt(t(e).css("paddingLeft"),10)||0)-this.margins.left,i.top+(parseInt(t(e).css("borderTopWidth"),10)||0)+(parseInt(t(e).css("paddingTop"),10)||0)-this.margins.top,i.left+(s?Math.max(e.scrollWidth,e.offsetWidth):e.offsetWidth)-(parseInt(t(e).css("borderLeftWidth"),10)||0)-(parseInt(t(e).css("paddingRight"),10)||0)-this.helperProportions.width-this.margins.left,i.top+(s?Math.max(e.scrollHeight,e.offsetHeight):e.offsetHeight)-(parseInt(t(e).css("borderTopWidth"),10)||0)-(parseInt(t(e).css("paddingBottom"),10)||0)-this.helperProportions.height-this.margins.top])},_convertPositionTo:function(e,i){i||(i=this.position);var s="absolute"===e?1:-1,n="absolute"!==this.cssPosition||this.scrollParent[0]!==document&&t.contains(this.scrollParent[0],this.offsetParent[0])?this.scrollParent:this.offsetParent,a=/(html|body)/i.test(n[0].tagName);return{top:i.top+this.offset.relative.top*s+this.offset.parent.top*s-("fixed"===this.cssPosition?-this.scrollParent.scrollTop():a?0:n.scrollTop())*s,left:i.left+this.offset.relative.left*s+this.offset.parent.left*s-("fixed"===this.cssPosition?-this.scrollParent.scrollLeft():a?0:n.scrollLeft())*s}},_generatePosition:function(e){var i,s,n=this.options,a=e.pageX,o=e.pageY,r="absolute"!==this.cssPosition||this.scrollParent[0]!==document&&t.contains(this.scrollParent[0],this.offsetParent[0])?this.scrollParent:this.offsetParent,h=/(html|body)/i.test(r[0].tagName);return"relative"!==this.cssPosition||this.scrollParent[0]!==document&&this.scrollParent[0]!==this.offsetParent[0]||(this.offset.relative=this._getRelativeOffset()),this.originalPosition&&(this.containment&&(e.pageX-this.offset.click.left<this.containment[0]&&(a=this.containment[0]+this.offset.click.left),e.pageY-this.offset.click.top<this.containment[1]&&(o=this.containment[1]+this.offset.click.top),e.pageX-this.offset.click.left>this.containment[2]&&(a=this.containment[2]+this.offset.click.left),e.pageY-this.offset.click.top>this.containment[3]&&(o=this.containment[3]+this.offset.click.top)),n.grid&&(i=this.originalPageY+Math.round((o-this.originalPageY)/n.grid[1])*n.grid[1],o=this.containment?i-this.offset.click.top>=this.containment[1]&&i-this.offset.click.top<=this.containment[3]?i:i-this.offset.click.top>=this.containment[1]?i-n.grid[1]:i+n.grid[1]:i,s=this.originalPageX+Math.round((a-this.originalPageX)/n.grid[0])*n.grid[0],a=this.containment?s-this.offset.click.left>=this.containment[0]&&s-this.offset.click.left<=this.containment[2]?s:s-this.offset.click.left>=this.containment[0]?s-n.grid[0]:s+n.grid[0]:s)),{top:o-this.offset.click.top-this.offset.relative.top-this.offset.parent.top+("fixed"===this.cssPosition?-this.scrollParent.scrollTop():h?0:r.scrollTop()),left:a-this.offset.click.left-this.offset.relative.left-this.offset.parent.left+("fixed"===this.cssPosition?-this.scrollParent.scrollLeft():h?0:r.scrollLeft())}},_rearrange:function(t,e,i,s){i?i[0].appendChild(this.placeholder[0]):e.item[0].parentNode.insertBefore(this.placeholder[0],"down"===this.direction?e.item[0]:e.item[0].nextSibling),this.counter=this.counter?++this.counter:1;var n=this.counter;this._delay(function(){n===this.counter&&this.refreshPositions(!s)})},_clear:function(t,e){this.reverting=!1;var i,s=[];if(!this._noFinalSort&&this.currentItem.parent().length&&this.placeholder.before(this.currentItem),this._noFinalSort=null,this.helper[0]===this.currentItem[0]){for(i in this._storedCSS)("auto"===this._storedCSS[i]||"static"===this._storedCSS[i])&&(this._storedCSS[i]="");this.currentItem.css(this._storedCSS).removeClass("ui-sortable-helper")}else this.currentItem.show();for(this.fromOutside&&!e&&s.push(function(t){this._trigger("receive",t,this._uiHash(this.fromOutside))}),!this.fromOutside&&this.domPosition.prev===this.currentItem.prev().not(".ui-sortable-helper")[0]&&this.domPosition.parent===this.currentItem.parent()[0]||e||s.push(function(t){this._trigger("update",t,this._uiHash())}),this!==this.currentContainer&&(e||(s.push(function(t){this._trigger("remove",t,this._uiHash())}),s.push(function(t){return function(e){t._trigger("receive",e,this._uiHash(this))}}.call(this,this.currentContainer)),s.push(function(t){return function(e){t._trigger("update",e,this._uiHash(this))}}.call(this,this.currentContainer)))),i=this.containers.length-1;i>=0;i--)e||s.push(function(t){return function(e){t._trigger("deactivate",e,this._uiHash(this))}}.call(this,this.containers[i])),this.containers[i].containerCache.over&&(s.push(function(t){return function(e){t._trigger("out",e,this._uiHash(this))}}.call(this,this.containers[i])),this.containers[i].containerCache.over=0);if(this.storedCursor&&(this.document.find("body").css("cursor",this.storedCursor),this.storedStylesheet.remove()),this._storedOpacity&&this.helper.css("opacity",this._storedOpacity),this._storedZIndex&&this.helper.css("zIndex","auto"===this._storedZIndex?"":this._storedZIndex),this.dragging=!1,this.cancelHelperRemoval){if(!e){for(this._trigger("beforeStop",t,this._uiHash()),i=0;s.length>i;i++)s[i].call(this,t);this._trigger("stop",t,this._uiHash())}return this.fromOutside=!1,!1}if(e||this._trigger("beforeStop",t,this._uiHash()),this.placeholder[0].parentNode.removeChild(this.placeholder[0]),this.helper[0]!==this.currentItem[0]&&this.helper.remove(),this.helper=null,!e){for(i=0;s.length>i;i++)s[i].call(this,t);this._trigger("stop",t,this._uiHash())}return this.fromOutside=!1,!0},_trigger:function(){t.Widget.prototype._trigger.apply(this,arguments)===!1&&this.cancel()},_uiHash:function(e){var i=e||this;return{helper:i.helper,placeholder:i.placeholder||t([]),position:i.position,originalPosition:i.originalPosition,offset:i.positionAbs,item:i.currentItem,sender:e?e.element:null}}})})(jQuery);
+
+
+
+/*! jQuery UI - v1.10.2 - 2013-03-14
+* http://jqueryui.com
+* Copyright 2013 jQuery Foundation and other contributors; Licensed MIT */
+(function(t,e){function i(){return++n}function s(t){return t.hash.length>1&&decodeURIComponent(t.href.replace(a,""))===decodeURIComponent(location.href.replace(a,""))}var n=0,a=/#.*$/;t.widget("ui.tabs",{version:"1.10.2",delay:300,options:{active:null,collapsible:!1,event:"click",heightStyle:"content",hide:null,show:null,activate:null,beforeActivate:null,beforeLoad:null,load:null},_create:function(){var e=this,i=this.options;this.running=!1,this.element.addClass("ui-tabs ui-widget ui-widget-content ui-corner-all").toggleClass("ui-tabs-collapsible",i.collapsible).delegate(".ui-tabs-nav > li","mousedown"+this.eventNamespace,function(e){t(this).is(".ui-state-disabled")&&e.preventDefault()}).delegate(".ui-tabs-anchor","focus"+this.eventNamespace,function(){t(this).closest("li").is(".ui-state-disabled")&&this.blur()}),this._processTabs(),i.active=this._initialActive(),t.isArray(i.disabled)&&(i.disabled=t.unique(i.disabled.concat(t.map(this.tabs.filter(".ui-state-disabled"),function(t){return e.tabs.index(t)}))).sort()),this.active=this.options.active!==!1&&this.anchors.length?this._findActive(i.active):t(),this._refresh(),this.active.length&&this.load(i.active)},_initialActive:function(){var i=this.options.active,s=this.options.collapsible,n=location.hash.substring(1);return null===i&&(n&&this.tabs.each(function(s,a){return t(a).attr("aria-controls")===n?(i=s,!1):e}),null===i&&(i=this.tabs.index(this.tabs.filter(".ui-tabs-active"))),(null===i||-1===i)&&(i=this.tabs.length?0:!1)),i!==!1&&(i=this.tabs.index(this.tabs.eq(i)),-1===i&&(i=s?!1:0)),!s&&i===!1&&this.anchors.length&&(i=0),i},_getCreateEventData:function(){return{tab:this.active,panel:this.active.length?this._getPanelForTab(this.active):t()}},_tabKeydown:function(i){var s=t(this.document[0].activeElement).closest("li"),n=this.tabs.index(s),a=!0;if(!this._handlePageNav(i)){switch(i.keyCode){case t.ui.keyCode.RIGHT:case t.ui.keyCode.DOWN:n++;break;case t.ui.keyCode.UP:case t.ui.keyCode.LEFT:a=!1,n--;break;case t.ui.keyCode.END:n=this.anchors.length-1;break;case t.ui.keyCode.HOME:n=0;break;case t.ui.keyCode.SPACE:return i.preventDefault(),clearTimeout(this.activating),this._activate(n),e;case t.ui.keyCode.ENTER:return i.preventDefault(),clearTimeout(this.activating),this._activate(n===this.options.active?!1:n),e;default:return}i.preventDefault(),clearTimeout(this.activating),n=this._focusNextTab(n,a),i.ctrlKey||(s.attr("aria-selected","false"),this.tabs.eq(n).attr("aria-selected","true"),this.activating=this._delay(function(){this.option("active",n)},this.delay))}},_panelKeydown:function(e){this._handlePageNav(e)||e.ctrlKey&&e.keyCode===t.ui.keyCode.UP&&(e.preventDefault(),this.active.focus())},_handlePageNav:function(i){return i.altKey&&i.keyCode===t.ui.keyCode.PAGE_UP?(this._activate(this._focusNextTab(this.options.active-1,!1)),!0):i.altKey&&i.keyCode===t.ui.keyCode.PAGE_DOWN?(this._activate(this._focusNextTab(this.options.active+1,!0)),!0):e},_findNextTab:function(e,i){function s(){return e>n&&(e=0),0>e&&(e=n),e}for(var n=this.tabs.length-1;-1!==t.inArray(s(),this.options.disabled);)e=i?e+1:e-1;return e},_focusNextTab:function(t,e){return t=this._findNextTab(t,e),this.tabs.eq(t).focus(),t},_setOption:function(t,i){return"active"===t?(this._activate(i),e):"disabled"===t?(this._setupDisabled(i),e):(this._super(t,i),"collapsible"===t&&(this.element.toggleClass("ui-tabs-collapsible",i),i||this.options.active!==!1||this._activate(0)),"event"===t&&this._setupEvents(i),"heightStyle"===t&&this._setupHeightStyle(i),e)},_tabId:function(t){return t.attr("aria-controls")||"ui-tabs-"+i()},_sanitizeSelector:function(t){return t?t.replace(/[!"$%&'()*+,.\/:;<=>?@\[\]\^`{|}~]/g,"\\$&"):""},refresh:function(){var e=this.options,i=this.tablist.children(":has(a[href])");e.disabled=t.map(i.filter(".ui-state-disabled"),function(t){return i.index(t)}),this._processTabs(),e.active!==!1&&this.anchors.length?this.active.length&&!t.contains(this.tablist[0],this.active[0])?this.tabs.length===e.disabled.length?(e.active=!1,this.active=t()):this._activate(this._findNextTab(Math.max(0,e.active-1),!1)):e.active=this.tabs.index(this.active):(e.active=!1,this.active=t()),this._refresh()},_refresh:function(){this._setupDisabled(this.options.disabled),this._setupEvents(this.options.event),this._setupHeightStyle(this.options.heightStyle),this.tabs.not(this.active).attr({"aria-selected":"false",tabIndex:-1}),this.panels.not(this._getPanelForTab(this.active)).hide().attr({"aria-expanded":"false","aria-hidden":"true"}),this.active.length?(this.active.addClass("ui-tabs-active ui-state-active").attr({"aria-selected":"true",tabIndex:0}),this._getPanelForTab(this.active).show().attr({"aria-expanded":"true","aria-hidden":"false"})):this.tabs.eq(0).attr("tabIndex",0)},_processTabs:function(){var e=this;this.tablist=this._getList().addClass("ui-tabs-nav ui-helper-reset ui-helper-clearfix ui-widget-header ui-corner-all").attr("role","tablist"),this.tabs=this.tablist.find("> li:has(a[href])").addClass("ui-state-default ui-corner-top").attr({role:"tab",tabIndex:-1}),this.anchors=this.tabs.map(function(){return t("a",this)[0]}).addClass("ui-tabs-anchor").attr({role:"presentation",tabIndex:-1}),this.panels=t(),this.anchors.each(function(i,n){var a,o,r,h=t(n).uniqueId().attr("id"),l=t(n).closest("li"),u=l.attr("aria-controls");s(n)?(a=n.hash,o=e.element.find(e._sanitizeSelector(a))):(r=e._tabId(l),a="#"+r,o=e.element.find(a),o.length||(o=e._createPanel(r),o.insertAfter(e.panels[i-1]||e.tablist)),o.attr("aria-live","polite")),o.length&&(e.panels=e.panels.add(o)),u&&l.data("ui-tabs-aria-controls",u),l.attr({"aria-controls":a.substring(1),"aria-labelledby":h}),o.attr("aria-labelledby",h)}),this.panels.addClass("ui-tabs-panel ui-widget-content ui-corner-bottom").attr("role","tabpanel")},_getList:function(){return this.element.find("ol,ul").eq(0)},_createPanel:function(e){return t("<div>").attr("id",e).addClass("ui-tabs-panel ui-widget-content ui-corner-bottom").data("ui-tabs-destroy",!0)},_setupDisabled:function(e){t.isArray(e)&&(e.length?e.length===this.anchors.length&&(e=!0):e=!1);for(var i,s=0;i=this.tabs[s];s++)e===!0||-1!==t.inArray(s,e)?t(i).addClass("ui-state-disabled").attr("aria-disabled","true"):t(i).removeClass("ui-state-disabled").removeAttr("aria-disabled");this.options.disabled=e},_setupEvents:function(e){var i={click:function(t){t.preventDefault()}};e&&t.each(e.split(" "),function(t,e){i[e]="_eventHandler"}),this._off(this.anchors.add(this.tabs).add(this.panels)),this._on(this.anchors,i),this._on(this.tabs,{keydown:"_tabKeydown"}),this._on(this.panels,{keydown:"_panelKeydown"}),this._focusable(this.tabs),this._hoverable(this.tabs)},_setupHeightStyle:function(e){var i,s=this.element.parent();"fill"===e?(i=s.height(),i-=this.element.outerHeight()-this.element.height(),this.element.siblings(":visible").each(function(){var e=t(this),s=e.css("position");"absolute"!==s&&"fixed"!==s&&(i-=e.outerHeight(!0))}),this.element.children().not(this.panels).each(function(){i-=t(this).outerHeight(!0)}),this.panels.each(function(){t(this).height(Math.max(0,i-t(this).innerHeight()+t(this).height()))}).css("overflow","auto")):"auto"===e&&(i=0,this.panels.each(function(){i=Math.max(i,t(this).height("").height())}).height(i))},_eventHandler:function(e){var i=this.options,s=this.active,n=t(e.currentTarget),a=n.closest("li"),o=a[0]===s[0],r=o&&i.collapsible,h=r?t():this._getPanelForTab(a),l=s.length?this._getPanelForTab(s):t(),u={oldTab:s,oldPanel:l,newTab:r?t():a,newPanel:h};e.preventDefault(),a.hasClass("ui-state-disabled")||a.hasClass("ui-tabs-loading")||this.running||o&&!i.collapsible||this._trigger("beforeActivate",e,u)===!1||(i.active=r?!1:this.tabs.index(a),this.active=o?t():a,this.xhr&&this.xhr.abort(),l.length||h.length||t.error("jQuery UI Tabs: Mismatching fragment identifier."),h.length&&this.load(this.tabs.index(a),e),this._toggle(e,u))},_toggle:function(e,i){function s(){a.running=!1,a._trigger("activate",e,i)}function n(){i.newTab.closest("li").addClass("ui-tabs-active ui-state-active"),o.length&&a.options.show?a._show(o,a.options.show,s):(o.show(),s())}var a=this,o=i.newPanel,r=i.oldPanel;this.running=!0,r.length&&this.options.hide?this._hide(r,this.options.hide,function(){i.oldTab.closest("li").removeClass("ui-tabs-active ui-state-active"),n()}):(i.oldTab.closest("li").removeClass("ui-tabs-active ui-state-active"),r.hide(),n()),r.attr({"aria-expanded":"false","aria-hidden":"true"}),i.oldTab.attr("aria-selected","false"),o.length&&r.length?i.oldTab.attr("tabIndex",-1):o.length&&this.tabs.filter(function(){return 0===t(this).attr("tabIndex")}).attr("tabIndex",-1),o.attr({"aria-expanded":"true","aria-hidden":"false"}),i.newTab.attr({"aria-selected":"true",tabIndex:0})},_activate:function(e){var i,s=this._findActive(e);s[0]!==this.active[0]&&(s.length||(s=this.active),i=s.find(".ui-tabs-anchor")[0],this._eventHandler({target:i,currentTarget:i,preventDefault:t.noop}))},_findActive:function(e){return e===!1?t():this.tabs.eq(e)},_getIndex:function(t){return"string"==typeof t&&(t=this.anchors.index(this.anchors.filter("[href$='"+t+"']"))),t},_destroy:function(){this.xhr&&this.xhr.abort(),this.element.removeClass("ui-tabs ui-widget ui-widget-content ui-corner-all ui-tabs-collapsible"),this.tablist.removeClass("ui-tabs-nav ui-helper-reset ui-helper-clearfix ui-widget-header ui-corner-all").removeAttr("role"),this.anchors.removeClass("ui-tabs-anchor").removeAttr("role").removeAttr("tabIndex").removeUniqueId(),this.tabs.add(this.panels).each(function(){t.data(this,"ui-tabs-destroy")?t(this).remove():t(this).removeClass("ui-state-default ui-state-active ui-state-disabled ui-corner-top ui-corner-bottom ui-widget-content ui-tabs-active ui-tabs-panel").removeAttr("tabIndex").removeAttr("aria-live").removeAttr("aria-busy").removeAttr("aria-selected").removeAttr("aria-labelledby").removeAttr("aria-hidden").removeAttr("aria-expanded").removeAttr("role")}),this.tabs.each(function(){var e=t(this),i=e.data("ui-tabs-aria-controls");i?e.attr("aria-controls",i).removeData("ui-tabs-aria-controls"):e.removeAttr("aria-controls")}),this.panels.show(),"content"!==this.options.heightStyle&&this.panels.css("height","")},enable:function(i){var s=this.options.disabled;s!==!1&&(i===e?s=!1:(i=this._getIndex(i),s=t.isArray(s)?t.map(s,function(t){return t!==i?t:null}):t.map(this.tabs,function(t,e){return e!==i?e:null})),this._setupDisabled(s))},disable:function(i){var s=this.options.disabled;if(s!==!0){if(i===e)s=!0;else{if(i=this._getIndex(i),-1!==t.inArray(i,s))return;s=t.isArray(s)?t.merge([i],s).sort():[i]}this._setupDisabled(s)}},load:function(e,i){e=this._getIndex(e);var n=this,a=this.tabs.eq(e),o=a.find(".ui-tabs-anchor"),r=this._getPanelForTab(a),h={tab:a,panel:r};s(o[0])||(this.xhr=t.ajax(this._ajaxSettings(o,i,h)),this.xhr&&"canceled"!==this.xhr.statusText&&(a.addClass("ui-tabs-loading"),r.attr("aria-busy","true"),this.xhr.success(function(t){setTimeout(function(){r.html(t),n._trigger("load",i,h)},1)}).complete(function(t,e){setTimeout(function(){"abort"===e&&n.panels.stop(!1,!0),a.removeClass("ui-tabs-loading"),r.removeAttr("aria-busy"),t===n.xhr&&delete n.xhr},1)})))},_ajaxSettings:function(e,i,s){var n=this;return{url:e.attr("href"),beforeSend:function(e,a){return n._trigger("beforeLoad",i,t.extend({jqXHR:e,ajaxSettings:a},s))}}},_getPanelForTab:function(e){var i=t(e).attr("aria-controls");return this.element.find(this._sanitizeSelector("#"+i))}})})(jQuery);
+
+
+/*! jQuery UI - v1.10.0 - 2013-01-17
+* http://jqueryui.com
+* Includes: jquery.ui.slider.js
+* Copyright 2013 jQuery Foundation and other contributors; Licensed MIT */
+(function(e,t){var n=5;e.widget("ui.slider",e.ui.mouse,{version:"1.10.0",widgetEventPrefix:"slide",options:{animate:!1,distance:0,max:100,min:0,orientation:"horizontal",range:!1,step:1,value:0,values:null,change:null,slide:null,start:null,stop:null},_create:function(){var t,n,r=this.options,i=this.element.find(".ui-slider-handle").addClass("ui-state-default ui-corner-all"),s="<a class='ui-slider-handle ui-state-default ui-corner-all' href='#'></a>",o=[];this._keySliding=!1,this._mouseSliding=!1,this._animateOff=!0,this._handleIndex=null,this._detectOrientation(),this._mouseInit(),this.element.addClass("ui-slider ui-slider-"+this.orientation+" ui-widget"+" ui-widget-content"+" ui-corner-all"),this.range=e([]),r.range&&(r.range===!0&&(r.values?r.values.length&&r.values.length!==2?r.values=[r.values[0],r.values[0]]:e.isArray(r.values)&&(r.values=r.values.slice(0)):r.values=[this._valueMin(),this._valueMin()]),this.range=e("<div></div>").appendTo(this.element).addClass("ui-slider-range ui-widget-header"+(r.range==="min"||r.range==="max"?" ui-slider-range-"+r.range:""))),n=r.values&&r.values.length||1;for(t=i.length;t<n;t++)o.push(s);this.handles=i.add(e(o.join("")).appendTo(this.element)),this.handle=this.handles.eq(0),this.handles.add(this.range).filter("a").click(function(e){e.preventDefault()}).mouseenter(function(){r.disabled||e(this).addClass("ui-state-hover")}).mouseleave(function(){e(this).removeClass("ui-state-hover")}).focus(function(){r.disabled?e(this).blur():(e(".ui-slider .ui-state-focus").removeClass("ui-state-focus"),e(this).addClass("ui-state-focus"))}).blur(function(){e(this).removeClass("ui-state-focus")}),this.handles.each(function(t){e(this).data("ui-slider-handle-index",t)}),this._setOption("disabled",r.disabled),this._on(this.handles,this._handleEvents),this._refreshValue(),this._animateOff=!1},_destroy:function(){this.handles.remove(),this.range.remove(),this.element.removeClass("ui-slider ui-slider-horizontal ui-slider-vertical ui-widget ui-widget-content ui-corner-all"),this._mouseDestroy()},_mouseCapture:function(t){var n,r,i,s,o,u,a,f,l=this,c=this.options;return c.disabled?!1:(this.elementSize={width:this.element.outerWidth(),height:this.element.outerHeight()},this.elementOffset=this.element.offset(),n={x:t.pageX,y:t.pageY},r=this._normValueFromMouse(n),i=this._valueMax()-this._valueMin()+1,this.handles.each(function(t){var n=Math.abs(r-l.values(t));if(i>n||i===n&&(t===l._lastChangedValue||l.values(t)===c.min))i=n,s=e(this),o=t}),u=this._start(t,o),u===!1?!1:(this._mouseSliding=!0,this._handleIndex=o,s.addClass("ui-state-active").focus(),a=s.offset(),f=!e(t.target).parents().addBack().is(".ui-slider-handle"),this._clickOffset=f?{left:0,top:0}:{left:t.pageX-a.left-s.width()/2,top:t.pageY-a.top-s.height()/2-(parseInt(s.css("borderTopWidth"),10)||0)-(parseInt(s.css("borderBottomWidth"),10)||0)+(parseInt(s.css("marginTop"),10)||0)},this.handles.hasClass("ui-state-hover")||this._slide(t,o,r),this._animateOff=!0,!0))},_mouseStart:function(){return!0},_mouseDrag:function(e){var t={x:e.pageX,y:e.pageY},n=this._normValueFromMouse(t);return this._slide(e,this._handleIndex,n),!1},_mouseStop:function(e){return this.handles.removeClass("ui-state-active"),this._mouseSliding=!1,this._stop(e,this._handleIndex),this._change(e,this._handleIndex),this._handleIndex=null,this._clickOffset=null,this._animateOff=!1,!1},_detectOrientation:function(){this.orientation=this.options.orientation==="vertical"?"vertical":"horizontal"},_normValueFromMouse:function(e){var t,n,r,i,s;return this.orientation==="horizontal"?(t=this.elementSize.width,n=e.x-this.elementOffset.left-(this._clickOffset?this._clickOffset.left:0)):(t=this.elementSize.height,n=e.y-this.elementOffset.top-(this._clickOffset?this._clickOffset.top:0)),r=n/t,r>1&&(r=1),r<0&&(r=0),this.orientation==="vertical"&&(r=1-r),i=this._valueMax()-this._valueMin(),s=this._valueMin()+r*i,this._trimAlignValue(s)},_start:function(e,t){var n={handle:this.handles[t],value:this.value()};return this.options.values&&this.options.values.length&&(n.value=this.values(t),n.values=this.values()),this._trigger("start",e,n)},_slide:function(e,t,n){var r,i,s;this.options.values&&this.options.values.length?(r=this.values(t?0:1),this.options.values.length===2&&this.options.range===!0&&(t===0&&n>r||t===1&&n<r)&&(n=r),n!==this.values(t)&&(i=this.values(),i[t]=n,s=this._trigger("slide",e,{handle:this.handles[t],value:n,values:i}),r=this.values(t?0:1),s!==!1&&this.values(t,n,!0))):n!==this.value()&&(s=this._trigger("slide",e,{handle:this.handles[t],value:n}),s!==!1&&this.value(n))},_stop:function(e,t){var n={handle:this.handles[t],value:this.value()};this.options.values&&this.options.values.length&&(n.value=this.values(t),n.values=this.values()),this._trigger("stop",e,n)},_change:function(e,t){if(!this._keySliding&&!this._mouseSliding){var n={handle:this.handles[t],value:this.value()};this.options.values&&this.options.values.length&&(n.value=this.values(t),n.values=this.values()),this._lastChangedValue=t,this._trigger("change",e,n)}},value:function(e){if(arguments.length){this.options.value=this._trimAlignValue(e),this._refreshValue(),this._change(null,0);return}return this._value()},values:function(t,n){var r,i,s;if(arguments.length>1){this.options.values[t]=this._trimAlignValue(n),this._refreshValue(),this._change(null,t);return}if(!arguments.length)return this._values();if(!e.isArray(arguments[0]))return this.options.values&&this.options.values.length?this._values(t):this.value();r=this.options.values,i=arguments[0];for(s=0;s<r.length;s+=1)r[s]=this._trimAlignValue(i[s]),this._change(null,s);this._refreshValue()},_setOption:function(t,n){var r,i=0;e.isArray(this.options.values)&&(i=this.options.values.length),e.Widget.prototype._setOption.apply(this,arguments);switch(t){case"disabled":n?(this.handles.filter(".ui-state-focus").blur(),this.handles.removeClass("ui-state-hover"),this.handles.prop("disabled",!0)):this.handles.prop("disabled",!1);break;case"orientation":this._detectOrientation(),this.element.removeClass("ui-slider-horizontal ui-slider-vertical").addClass("ui-slider-"+this.orientation),this._refreshValue();break;case"value":this._animateOff=!0,this._refreshValue(),this._change(null,0),this._animateOff=!1;break;case"values":this._animateOff=!0,this._refreshValue();for(r=0;r<i;r+=1)this._change(null,r);this._animateOff=!1;break;case"min":case"max":this._animateOff=!0,this._refreshValue(),this._animateOff=!1}},_value:function(){var e=this.options.value;return e=this._trimAlignValue(e),e},_values:function(e){var t,n,r;if(arguments.length)return t=this.options.values[e],t=this._trimAlignValue(t),t;n=this.options.values.slice();for(r=0;r<n.length;r+=1)n[r]=this._trimAlignValue(n[r]);return n},_trimAlignValue:function(e){if(e<=this._valueMin())return this._valueMin();if(e>=this._valueMax())return this._valueMax();var t=this.options.step>0?this.options.step:1,n=(e-this._valueMin())%t,r=e-n;return Math.abs(n)*2>=t&&(r+=n>0?t:-t),parseFloat(r.toFixed(5))},_valueMin:function(){return this.options.min},_valueMax:function(){return this.options.max},_refreshValue:function(){var t,n,r,i,s,o=this.options.range,u=this.options,a=this,f=this._animateOff?!1:u.animate,l={};this.options.values&&this.options.values.length?this.handles.each(function(r){n=(a.values(r)-a._valueMin())/(a._valueMax()-a._valueMin())*100,l[a.orientation==="horizontal"?"left":"bottom"]=n+"%",e(this).stop(1,1)[f?"animate":"css"](l,u.animate),a.options.range===!0&&(a.orientation==="horizontal"?(r===0&&a.range.stop(1,1)[f?"animate":"css"]({left:n+"%"},u.animate),r===1&&a.range[f?"animate":"css"]({width:n-t+"%"},{queue:!1,duration:u.animate})):(r===0&&a.range.stop(1,1)[f?"animate":"css"]({bottom:n+"%"},u.animate),r===1&&a.range[f?"animate":"css"]({height:n-t+"%"},{queue:!1,duration:u.animate}))),t=n}):(r=this.value(),i=this._valueMin(),s=this._valueMax(),n=s!==i?(r-i)/(s-i)*100:0,l[this.orientation==="horizontal"?"left":"bottom"]=n+"%",this.handle.stop(1,1)[f?"animate":"css"](l,u.animate),o==="min"&&this.orientation==="horizontal"&&this.range.stop(1,1)[f?"animate":"css"]({width:n+"%"},u.animate),o==="max"&&this.orientation==="horizontal"&&this.range[f?"animate":"css"]({width:100-n+"%"},{queue:!1,duration:u.animate}),o==="min"&&this.orientation==="vertical"&&this.range.stop(1,1)[f?"animate":"css"]({height:n+"%"},u.animate),o==="max"&&this.orientation==="vertical"&&this.range[f?"animate":"css"]({height:100-n+"%"},{queue:!1,duration:u.animate}))},_handleEvents:{keydown:function(t){var r,i,s,o,u=e(t.target).data("ui-slider-handle-index");switch(t.keyCode){case e.ui.keyCode.HOME:case e.ui.keyCode.END:case e.ui.keyCode.PAGE_UP:case e.ui.keyCode.PAGE_DOWN:case e.ui.keyCode.UP:case e.ui.keyCode.RIGHT:case e.ui.keyCode.DOWN:case e.ui.keyCode.LEFT:t.preventDefault();if(!this._keySliding){this._keySliding=!0,e(t.target).addClass("ui-state-active"),r=this._start(t,u);if(r===!1)return}}o=this.options.step,this.options.values&&this.options.values.length?i=s=this.values(u):i=s=this.value();switch(t.keyCode){case e.ui.keyCode.HOME:s=this._valueMin();break;case e.ui.keyCode.END:s=this._valueMax();break;case e.ui.keyCode.PAGE_UP:s=this._trimAlignValue(i+(this._valueMax()-this._valueMin())/n);break;case e.ui.keyCode.PAGE_DOWN:s=this._trimAlignValue(i-(this._valueMax()-this._valueMin())/n);break;case e.ui.keyCode.UP:case e.ui.keyCode.RIGHT:if(i===this._valueMax())return;s=this._trimAlignValue(i+o);break;case e.ui.keyCode.DOWN:case e.ui.keyCode.LEFT:if(i===this._valueMin())return;s=this._trimAlignValue(i-o)}this._slide(t,u,s)},keyup:function(t){var n=e(t.target).data("ui-slider-handle-index");this._keySliding&&(this._keySliding=!1,this._stop(t,n),this._change(t,n),e(t.target).removeClass("ui-state-active"))}}})})(jQuery);
\ No newline at end of file
--- /dev/null
+/*!
+ * jQuery UI Touch Punch 0.2.2 + patches
+ *
+ * Copyright 2011, Dave Furfero
+ * Dual licensed under the MIT or GPL Version 2 licenses.
+ *
+ * Depends:
+ * jquery.ui.widget.js
+ * jquery.ui.mouse.js
+ */
+(function (factory) {
+ if (typeof define === 'function' && define.amd) {
+ // AMD. Register as an anonymous module.
+ define(['jquery'], factory);
+ } else {
+ // Browser globals
+ factory(jQuery);
+ }
+}(function ($) {
+
+ var pointerEnabled = window.navigator.pointerEnabled
+ || window.navigator.msPointerEnabled;
+
+ // Detect touch support
+ $.support.touch = $.support.touch || ((typeof Modernizr !== 'undefined') ? Modernizr.touch : ('ontouchend' in document || 'createTouch' in document || pointerEnabled));
+
+ // Ignore browsers without touch support
+ if (!$.support.touch && !navigator.msPointerEnabled) {
+ return;
+ }
+
+ var mouseProto = $.ui.mouse.prototype,
+ _mouseInit = mouseProto._mouseInit,
+ touchHandled;
+
+ // see http://stackoverflow.com/a/12714084/220825
+ function fixTouch(touch) {
+ var winPageX = window.pageXOffset,
+ winPageY = window.pageYOffset,
+ x = touch.clientX,
+ y = touch.clientY;
+
+ if (touch.pageY === 0 && Math.floor(y) > Math.floor(touch.pageY) || touch.pageX === 0 && Math.floor(x) > Math.floor(touch.pageX)) {
+ // iOS4 clientX/clientY have the value that should have been
+ // in pageX/pageY. While pageX/page/ have the value 0
+ x = x - winPageX;
+ y = y - winPageY;
+ } else if (y < (touch.pageY - winPageY) || x < (touch.pageX - winPageX)) {
+ // Some Android browsers have totally bogus values for clientX/Y
+ // when scrolling/zooming a page. Detectable since clientX/clientY
+ // should never be smaller than pageX/pageY minus page scroll
+ x = touch.pageX - winPageX;
+ y = touch.pageY - winPageY;
+ }
+
+ return {
+ clientX: x,
+ clientY: y
+ };
+ }
+
+ /**
+ * Simulate a mouse event based on a corresponding touch event
+ * @param {Object} event A touch event
+ * @param {String} simulatedType The corresponding mouse event
+ */
+ function simulateMouseEvent (event, simulatedType) {
+
+ // Ignore multi-touch events
+ if ((!pointerEnabled && event.originalEvent.touches && event.originalEvent.touches.length > 1) || (pointerEnabled && !event.isPrimary)) {
+ return;
+ }
+
+ event.preventDefault();
+
+ var evt;
+ if (pointerEnabled) {
+ evt = event.originalEvent;
+ } else if (event.originalEvent.changedTouches) {
+ evt = event.originalEvent.changedTouches[0];
+ } else {
+ evt = event;
+ }
+ simulatedEvent = document.createEvent('MouseEvents');
+ coord = fixTouch(evt);
+
+ // Initialize the simulated mouse event using the touch event's coordinates
+ simulatedEvent.initMouseEvent(
+ simulatedType, // type
+ true, // bubbles
+ true, // cancelable
+ window, // view
+ 1, // detail
+ evt.screenX, // screenX
+ evt.screenY, // screenY
+ coord.clientX, // clientX
+ coord.clientY, // clientY
+ false, // ctrlKey
+ false, // altKey
+ false, // shiftKey
+ false, // metaKey
+ 0, // button
+ null // relatedTarget
+ );
+
+ // Dispatch the simulated event to the target element
+ event.target.dispatchEvent(simulatedEvent);
+ }
+
+ /**
+ * Handle the jQuery UI widget's touchstart events
+ * @param {Object} event The widget element's touchstart event
+ */
+ mouseProto._touchStart = function (event) {
+
+ var self = this;
+
+ // Ignore the event if another widget is already being handled
+ if (touchHandled || (!pointerEnabled && !self._mouseCapture(event.originalEvent.changedTouches[0]))) {
+ return;
+ }
+
+ // Set the flag to prevent other widgets from inheriting the touch event
+ touchHandled = true;
+
+ // Track movement to determine if interaction was a click
+ self._touchMoved = false;
+
+ // Simulate the mouseover event
+ simulateMouseEvent(event, 'mouseover');
+
+ // Simulate the mousemove event
+ simulateMouseEvent(event, 'mousemove');
+
+ // Simulate the mousedown event
+ simulateMouseEvent(event, 'mousedown');
+ };
+
+ /**
+ * Handle the jQuery UI widget's touchmove events
+ * @param {Object} event The document's touchmove event
+ */
+ mouseProto._touchMove = function (event) {
+
+ // Ignore event if not handled
+ if (!touchHandled) {
+ return;
+ }
+
+ // Interaction was not a click
+ this._touchMoved = true;
+
+ // Simulate the mousemove event
+ simulateMouseEvent(event, 'mousemove');
+ };
+
+ /**
+ * Handle the jQuery UI widget's touchend events
+ * @param {Object} event The document's touchend event
+ */
+ mouseProto._touchEnd = function (event) {
+
+ // Ignore event if not handled
+ if (!touchHandled) {
+ return;
+ }
+
+ // Simulate the mouseup event
+ simulateMouseEvent(event, 'mouseup');
+
+ // Simulate the mouseout event
+ simulateMouseEvent(event, 'mouseout');
+
+ // If the touch interaction did not move, it should trigger a click
+ if (!this._touchMoved) {
+
+ // Simulate the click event
+ simulateMouseEvent(event, 'click');
+ }
+
+ // Unset the flag to allow other widgets to inherit the touch event
+ touchHandled = false;
+ };
+
+ /**
+ * A duck punch of the $.ui.mouse _mouseInit method to support touch events.
+ * This method extends the widget with bound touch event handlers that
+ * translate touch events to mouse events and pass them to the widget's
+ * original mouse event handling methods.
+ */
+ mouseProto._mouseInit = function () {
+
+ var self = this;
+
+ // Undelegate the global touch events in
+ self.element
+ .off( 'touchstart' )
+ .off( 'touchmove' )
+ .off( 'touchend' );
+
+ // Delegate the touch handlers to the widget's element
+ if (pointerEnabled) {
+ self.element
+ .on('pointerDown', $.proxy(self, '_touchStart'))
+ .on('pointerMove', $.proxy(self, '_touchMove'))
+ .on('pointerUp', $.proxy(self, '_touchEnd'))
+ .on('MSPointerDown', $.proxy(self, '_touchStart'))
+ .on('MSPointerMove', $.proxy(self, '_touchMove'))
+ .on('MSPointerUp', $.proxy(self, '_touchEnd'));
+ } else {
+ self.element
+ .on(navigator.msPointerEnabled ? 'MSPointerDown' : 'touchstart', $.proxy(self, '_touchStart'))
+ .on(navigator.msPointerEnabled ? 'MSPointerMove' : 'touchmove', $.proxy(self, '_touchMove'))
+ .on(navigator.msPointerEnabled ? 'MSPointerUp' : 'touchend', $.proxy(self, '_touchEnd'));
+ // Add -ms-touch-action: none for touch devices on IE10
+ self.element.css({msTouchAction: 'none'});
+ }
+
+ // Call the original $.ui.mouse init method
+ _mouseInit.call(self);
+ };
+
+}));
\ No newline at end of file
--- /dev/null
+// Knockout JavaScript library v3.1.0
+// (c) Steven Sanderson - http://knockoutjs.com/
+// License: MIT (http://www.opensource.org/licenses/mit-license.php)
+
+(function(){
+var DEBUG=true;
+(function(undefined){
+ // (0, eval)('this') is a robust way of getting a reference to the global object
+ // For details, see http://stackoverflow.com/questions/14119988/return-this-0-evalthis/14120023#14120023
+ var window = this || (0, eval)('this'),
+ document = window['document'],
+ navigator = window['navigator'],
+ jQuery = window["jQuery"],
+ JSON = window["JSON"];
+(function(factory) {
+ // Support three module loading scenarios
+ if (typeof require === 'function' && typeof exports === 'object' && typeof module === 'object') {
+ // [1] CommonJS/Node.js
+ var target = module['exports'] || exports; // module.exports is for Node.js
+ factory(target);
+ } else if (typeof define === 'function' && define['amd']) {
+ // [2] AMD anonymous module
+ define(['exports'], factory);
+ } else {
+ // [3] No module loader (plain <script> tag) - put directly in global namespace
+ factory(window['ko'] = {});
+ }
+}(function(koExports){
+// Internally, all KO objects are attached to koExports (even the non-exported ones whose names will be minified by the closure compiler).
+// In the future, the following "ko" variable may be made distinct from "koExports" so that private objects are not externally reachable.
+var ko = typeof koExports !== 'undefined' ? koExports : {};
+// Google Closure Compiler helpers (used only to make the minified file smaller)
+ko.exportSymbol = function(koPath, object) {
+ var tokens = koPath.split(".");
+
+ // In the future, "ko" may become distinct from "koExports" (so that non-exported objects are not reachable)
+ // At that point, "target" would be set to: (typeof koExports !== "undefined" ? koExports : ko)
+ var target = ko;
+
+ for (var i = 0; i < tokens.length - 1; i++)
+ target = target[tokens[i]];
+ target[tokens[tokens.length - 1]] = object;
+};
+ko.exportProperty = function(owner, publicName, object) {
+ owner[publicName] = object;
+};
+ko.version = "3.1.0";
+
+ko.exportSymbol('version', ko.version);
+ko.utils = (function () {
+ function objectForEach(obj, action) {
+ for (var prop in obj) {
+ if (obj.hasOwnProperty(prop)) {
+ action(prop, obj[prop]);
+ }
+ }
+ }
+
+ function extend(target, source) {
+ if (source) {
+ for(var prop in source) {
+ if(source.hasOwnProperty(prop)) {
+ target[prop] = source[prop];
+ }
+ }
+ }
+ return target;
+ }
+
+ function setPrototypeOf(obj, proto) {
+ obj.__proto__ = proto;
+ return obj;
+ }
+
+ var canSetPrototype = ({ __proto__: [] } instanceof Array);
+
+ // Represent the known event types in a compact way, then at runtime transform it into a hash with event name as key (for fast lookup)
+ var knownEvents = {}, knownEventTypesByEventName = {};
+ var keyEventTypeName = (navigator && /Firefox\/2/i.test(navigator.userAgent)) ? 'KeyboardEvent' : 'UIEvents';
+ knownEvents[keyEventTypeName] = ['keyup', 'keydown', 'keypress'];
+ knownEvents['MouseEvents'] = ['click', 'dblclick', 'mousedown', 'mouseup', 'mousemove', 'mouseover', 'mouseout', 'mouseenter', 'mouseleave'];
+ objectForEach(knownEvents, function(eventType, knownEventsForType) {
+ if (knownEventsForType.length) {
+ for (var i = 0, j = knownEventsForType.length; i < j; i++)
+ knownEventTypesByEventName[knownEventsForType[i]] = eventType;
+ }
+ });
+ var eventsThatMustBeRegisteredUsingAttachEvent = { 'propertychange': true }; // Workaround for an IE9 issue - https://github.com/SteveSanderson/knockout/issues/406
+
+ // Detect IE versions for bug workarounds (uses IE conditionals, not UA string, for robustness)
+ // Note that, since IE 10 does not support conditional comments, the following logic only detects IE < 10.
+ // Currently this is by design, since IE 10+ behaves correctly when treated as a standard browser.
+ // If there is a future need to detect specific versions of IE10+, we will amend this.
+ var ieVersion = document && (function() {
+ var version = 3, div = document.createElement('div'), iElems = div.getElementsByTagName('i');
+
+ // Keep constructing conditional HTML blocks until we hit one that resolves to an empty fragment
+ while (
+ div.innerHTML = '<!--[if gt IE ' + (++version) + ']><i></i><![endif]-->',
+ iElems[0]
+ ) {}
+ return version > 4 ? version : undefined;
+ }());
+ var isIe6 = ieVersion === 6,
+ isIe7 = ieVersion === 7;
+
+ function isClickOnCheckableElement(element, eventType) {
+ if ((ko.utils.tagNameLower(element) !== "input") || !element.type) return false;
+ if (eventType.toLowerCase() != "click") return false;
+ var inputType = element.type;
+ return (inputType == "checkbox") || (inputType == "radio");
+ }
+
+ return {
+ fieldsIncludedWithJsonPost: ['authenticity_token', /^__RequestVerificationToken(_.*)?$/],
+
+ arrayForEach: function (array, action) {
+ for (var i = 0, j = array.length; i < j; i++)
+ action(array[i], i);
+ },
+
+ arrayIndexOf: function (array, item) {
+ if (typeof Array.prototype.indexOf == "function")
+ return Array.prototype.indexOf.call(array, item);
+ for (var i = 0, j = array.length; i < j; i++)
+ if (array[i] === item)
+ return i;
+ return -1;
+ },
+
+ arrayFirst: function (array, predicate, predicateOwner) {
+ for (var i = 0, j = array.length; i < j; i++)
+ if (predicate.call(predicateOwner, array[i], i))
+ return array[i];
+ return null;
+ },
+
+ arrayRemoveItem: function (array, itemToRemove) {
+ var index = ko.utils.arrayIndexOf(array, itemToRemove);
+ if (index > 0) {
+ array.splice(index, 1);
+ }
+ else if (index === 0) {
+ array.shift();
+ }
+ },
+
+ arrayGetDistinctValues: function (array) {
+ array = array || [];
+ var result = [];
+ for (var i = 0, j = array.length; i < j; i++) {
+ if (ko.utils.arrayIndexOf(result, array[i]) < 0)
+ result.push(array[i]);
+ }
+ return result;
+ },
+
+ arrayMap: function (array, mapping) {
+ array = array || [];
+ var result = [];
+ for (var i = 0, j = array.length; i < j; i++)
+ result.push(mapping(array[i], i));
+ return result;
+ },
+
+ arrayFilter: function (array, predicate) {
+ array = array || [];
+ var result = [];
+ for (var i = 0, j = array.length; i < j; i++)
+ if (predicate(array[i], i))
+ result.push(array[i]);
+ return result;
+ },
+
+ arrayPushAll: function (array, valuesToPush) {
+ if (valuesToPush instanceof Array)
+ array.push.apply(array, valuesToPush);
+ else
+ for (var i = 0, j = valuesToPush.length; i < j; i++)
+ array.push(valuesToPush[i]);
+ return array;
+ },
+
+ addOrRemoveItem: function(array, value, included) {
+ var existingEntryIndex = ko.utils.arrayIndexOf(ko.utils.peekObservable(array), value);
+ if (existingEntryIndex < 0) {
+ if (included)
+ array.push(value);
+ } else {
+ if (!included)
+ array.splice(existingEntryIndex, 1);
+ }
+ },
+
+ canSetPrototype: canSetPrototype,
+
+ extend: extend,
+
+ setPrototypeOf: setPrototypeOf,
+
+ setPrototypeOfOrExtend: canSetPrototype ? setPrototypeOf : extend,
+
+ objectForEach: objectForEach,
+
+ objectMap: function(source, mapping) {
+ if (!source)
+ return source;
+ var target = {};
+ for (var prop in source) {
+ if (source.hasOwnProperty(prop)) {
+ target[prop] = mapping(source[prop], prop, source);
+ }
+ }
+ return target;
+ },
+
+ emptyDomNode: function (domNode) {
+ while (domNode.firstChild) {
+ ko.removeNode(domNode.firstChild);
+ }
+ },
+
+ moveCleanedNodesToContainerElement: function(nodes) {
+ // Ensure it's a real array, as we're about to reparent the nodes and
+ // we don't want the underlying collection to change while we're doing that.
+ var nodesArray = ko.utils.makeArray(nodes);
+
+ var container = document.createElement('div');
+ for (var i = 0, j = nodesArray.length; i < j; i++) {
+ container.appendChild(ko.cleanNode(nodesArray[i]));
+ }
+ return container;
+ },
+
+ cloneNodes: function (nodesArray, shouldCleanNodes) {
+ for (var i = 0, j = nodesArray.length, newNodesArray = []; i < j; i++) {
+ var clonedNode = nodesArray[i].cloneNode(true);
+ newNodesArray.push(shouldCleanNodes ? ko.cleanNode(clonedNode) : clonedNode);
+ }
+ return newNodesArray;
+ },
+
+ setDomNodeChildren: function (domNode, childNodes) {
+ ko.utils.emptyDomNode(domNode);
+ if (childNodes) {
+ for (var i = 0, j = childNodes.length; i < j; i++)
+ domNode.appendChild(childNodes[i]);
+ }
+ },
+
+ replaceDomNodes: function (nodeToReplaceOrNodeArray, newNodesArray) {
+ var nodesToReplaceArray = nodeToReplaceOrNodeArray.nodeType ? [nodeToReplaceOrNodeArray] : nodeToReplaceOrNodeArray;
+ if (nodesToReplaceArray.length > 0) {
+ var insertionPoint = nodesToReplaceArray[0];
+ var parent = insertionPoint.parentNode;
+ for (var i = 0, j = newNodesArray.length; i < j; i++)
+ parent.insertBefore(newNodesArray[i], insertionPoint);
+ for (var i = 0, j = nodesToReplaceArray.length; i < j; i++) {
+ ko.removeNode(nodesToReplaceArray[i]);
+ }
+ }
+ },
+
+ fixUpContinuousNodeArray: function(continuousNodeArray, parentNode) {
+ // Before acting on a set of nodes that were previously outputted by a template function, we have to reconcile
+ // them against what is in the DOM right now. It may be that some of the nodes have already been removed, or that
+ // new nodes might have been inserted in the middle, for example by a binding. Also, there may previously have been
+ // leading comment nodes (created by rewritten string-based templates) that have since been removed during binding.
+ // So, this function translates the old "map" output array into its best guess of the set of current DOM nodes.
+ //
+ // Rules:
+ // [A] Any leading nodes that have been removed should be ignored
+ // These most likely correspond to memoization nodes that were already removed during binding
+ // See https://github.com/SteveSanderson/knockout/pull/440
+ // [B] We want to output a continuous series of nodes. So, ignore any nodes that have already been removed,
+ // and include any nodes that have been inserted among the previous collection
+
+ if (continuousNodeArray.length) {
+ // The parent node can be a virtual element; so get the real parent node
+ parentNode = (parentNode.nodeType === 8 && parentNode.parentNode) || parentNode;
+
+ // Rule [A]
+ while (continuousNodeArray.length && continuousNodeArray[0].parentNode !== parentNode)
+ continuousNodeArray.shift();
+
+ // Rule [B]
+ if (continuousNodeArray.length > 1) {
+ var current = continuousNodeArray[0], last = continuousNodeArray[continuousNodeArray.length - 1];
+ // Replace with the actual new continuous node set
+ continuousNodeArray.length = 0;
+ while (current !== last) {
+ continuousNodeArray.push(current);
+ current = current.nextSibling;
+ if (!current) // Won't happen, except if the developer has manually removed some DOM elements (then we're in an undefined scenario)
+ return;
+ }
+ continuousNodeArray.push(last);
+ }
+ }
+ return continuousNodeArray;
+ },
+
+ setOptionNodeSelectionState: function (optionNode, isSelected) {
+ // IE6 sometimes throws "unknown error" if you try to write to .selected directly, whereas Firefox struggles with setAttribute. Pick one based on browser.
+ if (ieVersion < 7)
+ optionNode.setAttribute("selected", isSelected);
+ else
+ optionNode.selected = isSelected;
+ },
+
+ stringTrim: function (string) {
+ return string === null || string === undefined ? '' :
+ string.trim ?
+ string.trim() :
+ string.toString().replace(/^[\s\xa0]+|[\s\xa0]+$/g, '');
+ },
+
+ stringTokenize: function (string, delimiter) {
+ var result = [];
+ var tokens = (string || "").split(delimiter);
+ for (var i = 0, j = tokens.length; i < j; i++) {
+ var trimmed = ko.utils.stringTrim(tokens[i]);
+ if (trimmed !== "")
+ result.push(trimmed);
+ }
+ return result;
+ },
+
+ stringStartsWith: function (string, startsWith) {
+ string = string || "";
+ if (startsWith.length > string.length)
+ return false;
+ return string.substring(0, startsWith.length) === startsWith;
+ },
+
+ domNodeIsContainedBy: function (node, containedByNode) {
+ if (node === containedByNode)
+ return true;
+ if (node.nodeType === 11)
+ return false; // Fixes issue #1162 - can't use node.contains for document fragments on IE8
+ if (containedByNode.contains)
+ return containedByNode.contains(node.nodeType === 3 ? node.parentNode : node);
+ if (containedByNode.compareDocumentPosition)
+ return (containedByNode.compareDocumentPosition(node) & 16) == 16;
+ while (node && node != containedByNode) {
+ node = node.parentNode;
+ }
+ return !!node;
+ },
+
+ domNodeIsAttachedToDocument: function (node) {
+ return ko.utils.domNodeIsContainedBy(node, node.ownerDocument.documentElement);
+ },
+
+ anyDomNodeIsAttachedToDocument: function(nodes) {
+ return !!ko.utils.arrayFirst(nodes, ko.utils.domNodeIsAttachedToDocument);
+ },
+
+ tagNameLower: function(element) {
+ // For HTML elements, tagName will always be upper case; for XHTML elements, it'll be lower case.
+ // Possible future optimization: If we know it's an element from an XHTML document (not HTML),
+ // we don't need to do the .toLowerCase() as it will always be lower case anyway.
+ return element && element.tagName && element.tagName.toLowerCase();
+ },
+
+ registerEventHandler: function (element, eventType, handler) {
+ var mustUseAttachEvent = ieVersion && eventsThatMustBeRegisteredUsingAttachEvent[eventType];
+ if (!mustUseAttachEvent && jQuery) {
+ jQuery(element)['bind'](eventType, handler);
+ } else if (!mustUseAttachEvent && typeof element.addEventListener == "function")
+ element.addEventListener(eventType, handler, false);
+ else if (typeof element.attachEvent != "undefined") {
+ var attachEventHandler = function (event) { handler.call(element, event); },
+ attachEventName = "on" + eventType;
+ element.attachEvent(attachEventName, attachEventHandler);
+
+ // IE does not dispose attachEvent handlers automatically (unlike with addEventListener)
+ // so to avoid leaks, we have to remove them manually. See bug #856
+ ko.utils.domNodeDisposal.addDisposeCallback(element, function() {
+ element.detachEvent(attachEventName, attachEventHandler);
+ });
+ } else
+ throw new Error("Browser doesn't support addEventListener or attachEvent");
+ },
+
+ triggerEvent: function (element, eventType) {
+ if (!(element && element.nodeType))
+ throw new Error("element must be a DOM node when calling triggerEvent");
+
+ // For click events on checkboxes and radio buttons, jQuery toggles the element checked state *after* the
+ // event handler runs instead of *before*. (This was fixed in 1.9 for checkboxes but not for radio buttons.)
+ // IE doesn't change the checked state when you trigger the click event using "fireEvent".
+ // In both cases, we'll use the click method instead.
+ var useClickWorkaround = isClickOnCheckableElement(element, eventType);
+
+ if (jQuery && !useClickWorkaround) {
+ jQuery(element)['trigger'](eventType);
+ } else if (typeof document.createEvent == "function") {
+ if (typeof element.dispatchEvent == "function") {
+ var eventCategory = knownEventTypesByEventName[eventType] || "HTMLEvents";
+ var event = document.createEvent(eventCategory);
+ event.initEvent(eventType, true, true, window, 0, 0, 0, 0, 0, false, false, false, false, 0, element);
+ element.dispatchEvent(event);
+ }
+ else
+ throw new Error("The supplied element doesn't support dispatchEvent");
+ } else if (useClickWorkaround && element.click) {
+ element.click();
+ } else if (typeof element.fireEvent != "undefined") {
+ element.fireEvent("on" + eventType);
+ } else {
+ throw new Error("Browser doesn't support triggering events");
+ }
+ },
+
+ unwrapObservable: function (value) {
+ return ko.isObservable(value) ? value() : value;
+ },
+
+ peekObservable: function (value) {
+ return ko.isObservable(value) ? value.peek() : value;
+ },
+
+ toggleDomNodeCssClass: function (node, classNames, shouldHaveClass) {
+ if (classNames) {
+ var cssClassNameRegex = /\S+/g,
+ currentClassNames = node.className.match(cssClassNameRegex) || [];
+ ko.utils.arrayForEach(classNames.match(cssClassNameRegex), function(className) {
+ ko.utils.addOrRemoveItem(currentClassNames, className, shouldHaveClass);
+ });
+ node.className = currentClassNames.join(" ");
+ }
+ },
+
+ setTextContent: function(element, textContent) {
+ var value = ko.utils.unwrapObservable(textContent);
+ if ((value === null) || (value === undefined))
+ value = "";
+
+ // We need there to be exactly one child: a text node.
+ // If there are no children, more than one, or if it's not a text node,
+ // we'll clear everything and create a single text node.
+ var innerTextNode = ko.virtualElements.firstChild(element);
+ if (!innerTextNode || innerTextNode.nodeType != 3 || ko.virtualElements.nextSibling(innerTextNode)) {
+ ko.virtualElements.setDomNodeChildren(element, [element.ownerDocument.createTextNode(value)]);
+ } else {
+ innerTextNode.data = value;
+ }
+
+ ko.utils.forceRefresh(element);
+ },
+
+ setElementName: function(element, name) {
+ element.name = name;
+
+ // Workaround IE 6/7 issue
+ // - https://github.com/SteveSanderson/knockout/issues/197
+ // - http://www.matts411.com/post/setting_the_name_attribute_in_ie_dom/
+ if (ieVersion <= 7) {
+ try {
+ element.mergeAttributes(document.createElement("<input name='" + element.name + "'/>"), false);
+ }
+ catch(e) {} // For IE9 with doc mode "IE9 Standards" and browser mode "IE9 Compatibility View"
+ }
+ },
+
+ forceRefresh: function(node) {
+ // Workaround for an IE9 rendering bug - https://github.com/SteveSanderson/knockout/issues/209
+ if (ieVersion >= 9) {
+ // For text nodes and comment nodes (most likely virtual elements), we will have to refresh the container
+ var elem = node.nodeType == 1 ? node : node.parentNode;
+ if (elem.style)
+ elem.style.zoom = elem.style.zoom;
+ }
+ },
+
+ ensureSelectElementIsRenderedCorrectly: function(selectElement) {
+ // Workaround for IE9 rendering bug - it doesn't reliably display all the text in dynamically-added select boxes unless you force it to re-render by updating the width.
+ // (See https://github.com/SteveSanderson/knockout/issues/312, http://stackoverflow.com/questions/5908494/select-only-shows-first-char-of-selected-option)
+ // Also fixes IE7 and IE8 bug that causes selects to be zero width if enclosed by 'if' or 'with'. (See issue #839)
+ if (ieVersion) {
+ var originalWidth = selectElement.style.width;
+ selectElement.style.width = 0;
+ selectElement.style.width = originalWidth;
+ }
+ },
+
+ range: function (min, max) {
+ min = ko.utils.unwrapObservable(min);
+ max = ko.utils.unwrapObservable(max);
+ var result = [];
+ for (var i = min; i <= max; i++)
+ result.push(i);
+ return result;
+ },
+
+ makeArray: function(arrayLikeObject) {
+ var result = [];
+ for (var i = 0, j = arrayLikeObject.length; i < j; i++) {
+ result.push(arrayLikeObject[i]);
+ };
+ return result;
+ },
+
+ isIe6 : isIe6,
+ isIe7 : isIe7,
+ ieVersion : ieVersion,
+
+ getFormFields: function(form, fieldName) {
+ var fields = ko.utils.makeArray(form.getElementsByTagName("input")).concat(ko.utils.makeArray(form.getElementsByTagName("textarea")));
+ var isMatchingField = (typeof fieldName == 'string')
+ ? function(field) { return field.name === fieldName }
+ : function(field) { return fieldName.test(field.name) }; // Treat fieldName as regex or object containing predicate
+ var matches = [];
+ for (var i = fields.length - 1; i >= 0; i--) {
+ if (isMatchingField(fields[i]))
+ matches.push(fields[i]);
+ };
+ return matches;
+ },
+
+ parseJson: function (jsonString) {
+ if (typeof jsonString == "string") {
+ jsonString = ko.utils.stringTrim(jsonString);
+ if (jsonString) {
+ if (JSON && JSON.parse) // Use native parsing where available
+ return JSON.parse(jsonString);
+ return (new Function("return " + jsonString))(); // Fallback on less safe parsing for older browsers
+ }
+ }
+ return null;
+ },
+
+ stringifyJson: function (data, replacer, space) { // replacer and space are optional
+ if (!JSON || !JSON.stringify)
+ throw new Error("Cannot find JSON.stringify(). Some browsers (e.g., IE < 8) don't support it natively, but you can overcome this by adding a script reference to json2.js, downloadable from http://www.json.org/json2.js");
+ return JSON.stringify(ko.utils.unwrapObservable(data), replacer, space);
+ },
+
+ postJson: function (urlOrForm, data, options) {
+ options = options || {};
+ var params = options['params'] || {};
+ var includeFields = options['includeFields'] || this.fieldsIncludedWithJsonPost;
+ var url = urlOrForm;
+
+ // If we were given a form, use its 'action' URL and pick out any requested field values
+ if((typeof urlOrForm == 'object') && (ko.utils.tagNameLower(urlOrForm) === "form")) {
+ var originalForm = urlOrForm;
+ url = originalForm.action;
+ for (var i = includeFields.length - 1; i >= 0; i--) {
+ var fields = ko.utils.getFormFields(originalForm, includeFields[i]);
+ for (var j = fields.length - 1; j >= 0; j--)
+ params[fields[j].name] = fields[j].value;
+ }
+ }
+
+ data = ko.utils.unwrapObservable(data);
+ var form = document.createElement("form");
+ form.style.display = "none";
+ form.action = url;
+ form.method = "post";
+ for (var key in data) {
+ // Since 'data' this is a model object, we include all properties including those inherited from its prototype
+ var input = document.createElement("input");
+ input.name = key;
+ input.value = ko.utils.stringifyJson(ko.utils.unwrapObservable(data[key]));
+ form.appendChild(input);
+ }
+ objectForEach(params, function(key, value) {
+ var input = document.createElement("input");
+ input.name = key;
+ input.value = value;
+ form.appendChild(input);
+ });
+ document.body.appendChild(form);
+ options['submitter'] ? options['submitter'](form) : form.submit();
+ setTimeout(function () { form.parentNode.removeChild(form); }, 0);
+ }
+ }
+}());
+
+ko.exportSymbol('utils', ko.utils);
+ko.exportSymbol('utils.arrayForEach', ko.utils.arrayForEach);
+ko.exportSymbol('utils.arrayFirst', ko.utils.arrayFirst);
+ko.exportSymbol('utils.arrayFilter', ko.utils.arrayFilter);
+ko.exportSymbol('utils.arrayGetDistinctValues', ko.utils.arrayGetDistinctValues);
+ko.exportSymbol('utils.arrayIndexOf', ko.utils.arrayIndexOf);
+ko.exportSymbol('utils.arrayMap', ko.utils.arrayMap);
+ko.exportSymbol('utils.arrayPushAll', ko.utils.arrayPushAll);
+ko.exportSymbol('utils.arrayRemoveItem', ko.utils.arrayRemoveItem);
+ko.exportSymbol('utils.extend', ko.utils.extend);
+ko.exportSymbol('utils.fieldsIncludedWithJsonPost', ko.utils.fieldsIncludedWithJsonPost);
+ko.exportSymbol('utils.getFormFields', ko.utils.getFormFields);
+ko.exportSymbol('utils.peekObservable', ko.utils.peekObservable);
+ko.exportSymbol('utils.postJson', ko.utils.postJson);
+ko.exportSymbol('utils.parseJson', ko.utils.parseJson);
+ko.exportSymbol('utils.registerEventHandler', ko.utils.registerEventHandler);
+ko.exportSymbol('utils.stringifyJson', ko.utils.stringifyJson);
+ko.exportSymbol('utils.range', ko.utils.range);
+ko.exportSymbol('utils.toggleDomNodeCssClass', ko.utils.toggleDomNodeCssClass);
+ko.exportSymbol('utils.triggerEvent', ko.utils.triggerEvent);
+ko.exportSymbol('utils.unwrapObservable', ko.utils.unwrapObservable);
+ko.exportSymbol('utils.objectForEach', ko.utils.objectForEach);
+ko.exportSymbol('utils.addOrRemoveItem', ko.utils.addOrRemoveItem);
+ko.exportSymbol('unwrap', ko.utils.unwrapObservable); // Convenient shorthand, because this is used so commonly
+
+if (!Function.prototype['bind']) {
+ // Function.prototype.bind is a standard part of ECMAScript 5th Edition (December 2009, http://www.ecma-international.org/publications/files/ECMA-ST/ECMA-262.pdf)
+ // In case the browser doesn't implement it natively, provide a JavaScript implementation. This implementation is based on the one in prototype.js
+ Function.prototype['bind'] = function (object) {
+ var originalFunction = this, args = Array.prototype.slice.call(arguments), object = args.shift();
+ return function () {
+ return originalFunction.apply(object, args.concat(Array.prototype.slice.call(arguments)));
+ };
+ };
+}
+
+ko.utils.domData = new (function () {
+ var uniqueId = 0;
+ var dataStoreKeyExpandoPropertyName = "__ko__" + (new Date).getTime();
+ var dataStore = {};
+
+ function getAll(node, createIfNotFound) {
+ var dataStoreKey = node[dataStoreKeyExpandoPropertyName];
+ var hasExistingDataStore = dataStoreKey && (dataStoreKey !== "null") && dataStore[dataStoreKey];
+ if (!hasExistingDataStore) {
+ if (!createIfNotFound)
+ return undefined;
+ dataStoreKey = node[dataStoreKeyExpandoPropertyName] = "ko" + uniqueId++;
+ dataStore[dataStoreKey] = {};
+ }
+ return dataStore[dataStoreKey];
+ }
+
+ return {
+ get: function (node, key) {
+ var allDataForNode = getAll(node, false);
+ return allDataForNode === undefined ? undefined : allDataForNode[key];
+ },
+ set: function (node, key, value) {
+ if (value === undefined) {
+ // Make sure we don't actually create a new domData key if we are actually deleting a value
+ if (getAll(node, false) === undefined)
+ return;
+ }
+ var allDataForNode = getAll(node, true);
+ allDataForNode[key] = value;
+ },
+ clear: function (node) {
+ var dataStoreKey = node[dataStoreKeyExpandoPropertyName];
+ if (dataStoreKey) {
+ delete dataStore[dataStoreKey];
+ node[dataStoreKeyExpandoPropertyName] = null;
+ return true; // Exposing "did clean" flag purely so specs can infer whether things have been cleaned up as intended
+ }
+ return false;
+ },
+
+ nextKey: function () {
+ return (uniqueId++) + dataStoreKeyExpandoPropertyName;
+ }
+ };
+})();
+
+ko.exportSymbol('utils.domData', ko.utils.domData);
+ko.exportSymbol('utils.domData.clear', ko.utils.domData.clear); // Exporting only so specs can clear up after themselves fully
+
+ko.utils.domNodeDisposal = new (function () {
+ var domDataKey = ko.utils.domData.nextKey();
+ var cleanableNodeTypes = { 1: true, 8: true, 9: true }; // Element, Comment, Document
+ var cleanableNodeTypesWithDescendants = { 1: true, 9: true }; // Element, Document
+
+ function getDisposeCallbacksCollection(node, createIfNotFound) {
+ var allDisposeCallbacks = ko.utils.domData.get(node, domDataKey);
+ if ((allDisposeCallbacks === undefined) && createIfNotFound) {
+ allDisposeCallbacks = [];
+ ko.utils.domData.set(node, domDataKey, allDisposeCallbacks);
+ }
+ return allDisposeCallbacks;
+ }
+ function destroyCallbacksCollection(node) {
+ ko.utils.domData.set(node, domDataKey, undefined);
+ }
+
+ function cleanSingleNode(node) {
+ // Run all the dispose callbacks
+ var callbacks = getDisposeCallbacksCollection(node, false);
+ if (callbacks) {
+ callbacks = callbacks.slice(0); // Clone, as the array may be modified during iteration (typically, callbacks will remove themselves)
+ for (var i = 0; i < callbacks.length; i++)
+ callbacks[i](node);
+ }
+
+ // Erase the DOM data
+ ko.utils.domData.clear(node);
+
+ // Perform cleanup needed by external libraries (currently only jQuery, but can be extended)
+ ko.utils.domNodeDisposal["cleanExternalData"](node);
+
+ // Clear any immediate-child comment nodes, as these wouldn't have been found by
+ // node.getElementsByTagName("*") in cleanNode() (comment nodes aren't elements)
+ if (cleanableNodeTypesWithDescendants[node.nodeType])
+ cleanImmediateCommentTypeChildren(node);
+ }
+
+ function cleanImmediateCommentTypeChildren(nodeWithChildren) {
+ var child, nextChild = nodeWithChildren.firstChild;
+ while (child = nextChild) {
+ nextChild = child.nextSibling;
+ if (child.nodeType === 8)
+ cleanSingleNode(child);
+ }
+ }
+
+ return {
+ addDisposeCallback : function(node, callback) {
+ if (typeof callback != "function")
+ throw new Error("Callback must be a function");
+ getDisposeCallbacksCollection(node, true).push(callback);
+ },
+
+ removeDisposeCallback : function(node, callback) {
+ var callbacksCollection = getDisposeCallbacksCollection(node, false);
+ if (callbacksCollection) {
+ ko.utils.arrayRemoveItem(callbacksCollection, callback);
+ if (callbacksCollection.length == 0)
+ destroyCallbacksCollection(node);
+ }
+ },
+
+ cleanNode : function(node) {
+ // First clean this node, where applicable
+ if (cleanableNodeTypes[node.nodeType]) {
+ cleanSingleNode(node);
+
+ // ... then its descendants, where applicable
+ if (cleanableNodeTypesWithDescendants[node.nodeType]) {
+ // Clone the descendants list in case it changes during iteration
+ var descendants = [];
+ ko.utils.arrayPushAll(descendants, node.getElementsByTagName("*"));
+ for (var i = 0, j = descendants.length; i < j; i++)
+ cleanSingleNode(descendants[i]);
+ }
+ }
+ return node;
+ },
+
+ removeNode : function(node) {
+ ko.cleanNode(node);
+ if (node.parentNode)
+ node.parentNode.removeChild(node);
+ },
+
+ "cleanExternalData" : function (node) {
+ // Special support for jQuery here because it's so commonly used.
+ // Many jQuery plugins (including jquery.tmpl) store data using jQuery's equivalent of domData
+ // so notify it to tear down any resources associated with the node & descendants here.
+ if (jQuery && (typeof jQuery['cleanData'] == "function"))
+ jQuery['cleanData']([node]);
+ }
+ }
+})();
+ko.cleanNode = ko.utils.domNodeDisposal.cleanNode; // Shorthand name for convenience
+ko.removeNode = ko.utils.domNodeDisposal.removeNode; // Shorthand name for convenience
+ko.exportSymbol('cleanNode', ko.cleanNode);
+ko.exportSymbol('removeNode', ko.removeNode);
+ko.exportSymbol('utils.domNodeDisposal', ko.utils.domNodeDisposal);
+ko.exportSymbol('utils.domNodeDisposal.addDisposeCallback', ko.utils.domNodeDisposal.addDisposeCallback);
+ko.exportSymbol('utils.domNodeDisposal.removeDisposeCallback', ko.utils.domNodeDisposal.removeDisposeCallback);
+(function () {
+ var leadingCommentRegex = /^(\s*)<!--(.*?)-->/;
+
+ function simpleHtmlParse(html) {
+ // Based on jQuery's "clean" function, but only accounting for table-related elements.
+ // If you have referenced jQuery, this won't be used anyway - KO will use jQuery's "clean" function directly
+
+ // Note that there's still an issue in IE < 9 whereby it will discard comment nodes that are the first child of
+ // a descendant node. For example: "<div><!-- mycomment -->abc</div>" will get parsed as "<div>abc</div>"
+ // This won't affect anyone who has referenced jQuery, and there's always the workaround of inserting a dummy node
+ // (possibly a text node) in front of the comment. So, KO does not attempt to workaround this IE issue automatically at present.
+
+ // Trim whitespace, otherwise indexOf won't work as expected
+ var tags = ko.utils.stringTrim(html).toLowerCase(), div = document.createElement("div");
+
+ // Finds the first match from the left column, and returns the corresponding "wrap" data from the right column
+ var wrap = tags.match(/^<(thead|tbody|tfoot)/) && [1, "<table>", "</table>"] ||
+ !tags.indexOf("<tr") && [2, "<table><tbody>", "</tbody></table>"] ||
+ (!tags.indexOf("<td") || !tags.indexOf("<th")) && [3, "<table><tbody><tr>", "</tr></tbody></table>"] ||
+ /* anything else */ [0, "", ""];
+
+ // Go to html and back, then peel off extra wrappers
+ // Note that we always prefix with some dummy text, because otherwise, IE<9 will strip out leading comment nodes in descendants. Total madness.
+ var markup = "ignored<div>" + wrap[1] + html + wrap[2] + "</div>";
+ if (typeof window['innerShiv'] == "function") {
+ div.appendChild(window['innerShiv'](markup));
+ } else {
+ div.innerHTML = markup;
+ }
+
+ // Move to the right depth
+ while (wrap[0]--)
+ div = div.lastChild;
+
+ return ko.utils.makeArray(div.lastChild.childNodes);
+ }
+
+ function jQueryHtmlParse(html) {
+ // jQuery's "parseHTML" function was introduced in jQuery 1.8.0 and is a documented public API.
+ if (jQuery['parseHTML']) {
+ return jQuery['parseHTML'](html) || []; // Ensure we always return an array and never null
+ } else {
+ // For jQuery < 1.8.0, we fall back on the undocumented internal "clean" function.
+ var elems = jQuery['clean']([html]);
+
+ // As of jQuery 1.7.1, jQuery parses the HTML by appending it to some dummy parent nodes held in an in-memory document fragment.
+ // Unfortunately, it never clears the dummy parent nodes from the document fragment, so it leaks memory over time.
+ // Fix this by finding the top-most dummy parent element, and detaching it from its owner fragment.
+ if (elems && elems[0]) {
+ // Find the top-most parent element that's a direct child of a document fragment
+ var elem = elems[0];
+ while (elem.parentNode && elem.parentNode.nodeType !== 11 /* i.e., DocumentFragment */)
+ elem = elem.parentNode;
+ // ... then detach it
+ if (elem.parentNode)
+ elem.parentNode.removeChild(elem);
+ }
+
+ return elems;
+ }
+ }
+
+ ko.utils.parseHtmlFragment = function(html) {
+ return jQuery ? jQueryHtmlParse(html) // As below, benefit from jQuery's optimisations where possible
+ : simpleHtmlParse(html); // ... otherwise, this simple logic will do in most common cases.
+ };
+
+ ko.utils.setHtml = function(node, html) {
+ ko.utils.emptyDomNode(node);
+
+ // There's no legitimate reason to display a stringified observable without unwrapping it, so we'll unwrap it
+ html = ko.utils.unwrapObservable(html);
+
+ if ((html !== null) && (html !== undefined)) {
+ if (typeof html != 'string')
+ html = html.toString();
+
+ // jQuery contains a lot of sophisticated code to parse arbitrary HTML fragments,
+ // for example <tr> elements which are not normally allowed to exist on their own.
+ // If you've referenced jQuery we'll use that rather than duplicating its code.
+ if (jQuery) {
+ jQuery(node)['html'](html);
+ } else {
+ // ... otherwise, use KO's own parsing logic.
+ var parsedNodes = ko.utils.parseHtmlFragment(html);
+ for (var i = 0; i < parsedNodes.length; i++)
+ node.appendChild(parsedNodes[i]);
+ }
+ }
+ };
+})();
+
+ko.exportSymbol('utils.parseHtmlFragment', ko.utils.parseHtmlFragment);
+ko.exportSymbol('utils.setHtml', ko.utils.setHtml);
+
+ko.memoization = (function () {
+ var memos = {};
+
+ function randomMax8HexChars() {
+ return (((1 + Math.random()) * 0x100000000) | 0).toString(16).substring(1);
+ }
+ function generateRandomId() {
+ return randomMax8HexChars() + randomMax8HexChars();
+ }
+ function findMemoNodes(rootNode, appendToArray) {
+ if (!rootNode)
+ return;
+ if (rootNode.nodeType == 8) {
+ var memoId = ko.memoization.parseMemoText(rootNode.nodeValue);
+ if (memoId != null)
+ appendToArray.push({ domNode: rootNode, memoId: memoId });
+ } else if (rootNode.nodeType == 1) {
+ for (var i = 0, childNodes = rootNode.childNodes, j = childNodes.length; i < j; i++)
+ findMemoNodes(childNodes[i], appendToArray);
+ }
+ }
+
+ return {
+ memoize: function (callback) {
+ if (typeof callback != "function")
+ throw new Error("You can only pass a function to ko.memoization.memoize()");
+ var memoId = generateRandomId();
+ memos[memoId] = callback;
+ return "<!--[ko_memo:" + memoId + "]-->";
+ },
+
+ unmemoize: function (memoId, callbackParams) {
+ var callback = memos[memoId];
+ if (callback === undefined)
+ throw new Error("Couldn't find any memo with ID " + memoId + ". Perhaps it's already been unmemoized.");
+ try {
+ callback.apply(null, callbackParams || []);
+ return true;
+ }
+ finally { delete memos[memoId]; }
+ },
+
+ unmemoizeDomNodeAndDescendants: function (domNode, extraCallbackParamsArray) {
+ var memos = [];
+ findMemoNodes(domNode, memos);
+ for (var i = 0, j = memos.length; i < j; i++) {
+ var node = memos[i].domNode;
+ var combinedParams = [node];
+ if (extraCallbackParamsArray)
+ ko.utils.arrayPushAll(combinedParams, extraCallbackParamsArray);
+ ko.memoization.unmemoize(memos[i].memoId, combinedParams);
+ node.nodeValue = ""; // Neuter this node so we don't try to unmemoize it again
+ if (node.parentNode)
+ node.parentNode.removeChild(node); // If possible, erase it totally (not always possible - someone else might just hold a reference to it then call unmemoizeDomNodeAndDescendants again)
+ }
+ },
+
+ parseMemoText: function (memoText) {
+ var match = memoText.match(/^\[ko_memo\:(.*?)\]$/);
+ return match ? match[1] : null;
+ }
+ };
+})();
+
+ko.exportSymbol('memoization', ko.memoization);
+ko.exportSymbol('memoization.memoize', ko.memoization.memoize);
+ko.exportSymbol('memoization.unmemoize', ko.memoization.unmemoize);
+ko.exportSymbol('memoization.parseMemoText', ko.memoization.parseMemoText);
+ko.exportSymbol('memoization.unmemoizeDomNodeAndDescendants', ko.memoization.unmemoizeDomNodeAndDescendants);
+ko.extenders = {
+ 'throttle': function(target, timeout) {
+ // Throttling means two things:
+
+ // (1) For dependent observables, we throttle *evaluations* so that, no matter how fast its dependencies
+ // notify updates, the target doesn't re-evaluate (and hence doesn't notify) faster than a certain rate
+ target['throttleEvaluation'] = timeout;
+
+ // (2) For writable targets (observables, or writable dependent observables), we throttle *writes*
+ // so the target cannot change value synchronously or faster than a certain rate
+ var writeTimeoutInstance = null;
+ return ko.dependentObservable({
+ 'read': target,
+ 'write': function(value) {
+ clearTimeout(writeTimeoutInstance);
+ writeTimeoutInstance = setTimeout(function() {
+ target(value);
+ }, timeout);
+ }
+ });
+ },
+
+ 'rateLimit': function(target, options) {
+ var timeout, method, limitFunction;
+
+ if (typeof options == 'number') {
+ timeout = options;
+ } else {
+ timeout = options['timeout'];
+ method = options['method'];
+ }
+
+ limitFunction = method == 'notifyWhenChangesStop' ? debounce : throttle;
+ target.limit(function(callback) {
+ return limitFunction(callback, timeout);
+ });
+ },
+
+ 'notify': function(target, notifyWhen) {
+ target["equalityComparer"] = notifyWhen == "always" ?
+ null : // null equalityComparer means to always notify
+ valuesArePrimitiveAndEqual;
+ }
+};
+
+var primitiveTypes = { 'undefined':1, 'boolean':1, 'number':1, 'string':1 };
+function valuesArePrimitiveAndEqual(a, b) {
+ var oldValueIsPrimitive = (a === null) || (typeof(a) in primitiveTypes);
+ return oldValueIsPrimitive ? (a === b) : false;
+}
+
+function throttle(callback, timeout) {
+ var timeoutInstance;
+ return function () {
+ if (!timeoutInstance) {
+ timeoutInstance = setTimeout(function() {
+ timeoutInstance = undefined;
+ callback();
+ }, timeout);
+ }
+ };
+}
+
+function debounce(callback, timeout) {
+ var timeoutInstance;
+ return function () {
+ clearTimeout(timeoutInstance);
+ timeoutInstance = setTimeout(callback, timeout);
+ };
+}
+
+function applyExtenders(requestedExtenders) {
+ var target = this;
+ if (requestedExtenders) {
+ ko.utils.objectForEach(requestedExtenders, function(key, value) {
+ var extenderHandler = ko.extenders[key];
+ if (typeof extenderHandler == 'function') {
+ target = extenderHandler(target, value) || target;
+ }
+ });
+ }
+ return target;
+}
+
+ko.exportSymbol('extenders', ko.extenders);
+
+ko.subscription = function (target, callback, disposeCallback) {
+ this.target = target;
+ this.callback = callback;
+ this.disposeCallback = disposeCallback;
+ this.isDisposed = false;
+ ko.exportProperty(this, 'dispose', this.dispose);
+};
+ko.subscription.prototype.dispose = function () {
+ this.isDisposed = true;
+ this.disposeCallback();
+};
+
+ko.subscribable = function () {
+ ko.utils.setPrototypeOfOrExtend(this, ko.subscribable['fn']);
+ this._subscriptions = {};
+}
+
+var defaultEvent = "change";
+
+var ko_subscribable_fn = {
+ subscribe: function (callback, callbackTarget, event) {
+ var self = this;
+
+ event = event || defaultEvent;
+ var boundCallback = callbackTarget ? callback.bind(callbackTarget) : callback;
+
+ var subscription = new ko.subscription(self, boundCallback, function () {
+ ko.utils.arrayRemoveItem(self._subscriptions[event], subscription);
+ });
+
+ // This will force a computed with deferEvaluation to evaluate before any subscriptions
+ // are registered.
+ if (self.peek) {
+ self.peek();
+ }
+
+ if (!self._subscriptions[event])
+ self._subscriptions[event] = [];
+ self._subscriptions[event].push(subscription);
+ return subscription;
+ },
+
+ "notifySubscribers": function (valueToNotify, event) {
+ event = event || defaultEvent;
+ if (this.hasSubscriptionsForEvent(event)) {
+ try {
+ ko.dependencyDetection.begin(); // Begin suppressing dependency detection (by setting the top frame to undefined)
+ for (var a = this._subscriptions[event].slice(0), i = 0, subscription; subscription = a[i]; ++i) {
+ // In case a subscription was disposed during the arrayForEach cycle, check
+ // for isDisposed on each subscription before invoking its callback
+ if (!subscription.isDisposed)
+ subscription.callback(valueToNotify);
+ }
+ } finally {
+ ko.dependencyDetection.end(); // End suppressing dependency detection
+ }
+ }
+ },
+
+ limit: function(limitFunction) {
+ var self = this, selfIsObservable = ko.isObservable(self),
+ isPending, previousValue, pendingValue, beforeChange = 'beforeChange';
+
+ if (!self._origNotifySubscribers) {
+ self._origNotifySubscribers = self["notifySubscribers"];
+ self["notifySubscribers"] = function(value, event) {
+ if (!event || event === defaultEvent) {
+ self._rateLimitedChange(value);
+ } else if (event === beforeChange) {
+ self._rateLimitedBeforeChange(value);
+ } else {
+ self._origNotifySubscribers(value, event);
+ }
+ };
+ }
+
+ var finish = limitFunction(function() {
+ // If an observable provided a reference to itself, access it to get the latest value.
+ // This allows computed observables to delay calculating their value until needed.
+ if (selfIsObservable && pendingValue === self) {
+ pendingValue = self();
+ }
+ isPending = false;
+ if (self.isDifferent(previousValue, pendingValue)) {
+ self._origNotifySubscribers(previousValue = pendingValue);
+ }
+ });
+
+ self._rateLimitedChange = function(value) {
+ isPending = true;
+ pendingValue = value;
+ finish();
+ };
+ self._rateLimitedBeforeChange = function(value) {
+ if (!isPending) {
+ previousValue = value;
+ self._origNotifySubscribers(value, beforeChange);
+ }
+ };
+ },
+
+ hasSubscriptionsForEvent: function(event) {
+ return this._subscriptions[event] && this._subscriptions[event].length;
+ },
+
+ getSubscriptionsCount: function () {
+ var total = 0;
+ ko.utils.objectForEach(this._subscriptions, function(eventName, subscriptions) {
+ total += subscriptions.length;
+ });
+ return total;
+ },
+
+ isDifferent: function(oldValue, newValue) {
+ return !this['equalityComparer'] || !this['equalityComparer'](oldValue, newValue);
+ },
+
+ extend: applyExtenders
+};
+
+ko.exportProperty(ko_subscribable_fn, 'subscribe', ko_subscribable_fn.subscribe);
+ko.exportProperty(ko_subscribable_fn, 'extend', ko_subscribable_fn.extend);
+ko.exportProperty(ko_subscribable_fn, 'getSubscriptionsCount', ko_subscribable_fn.getSubscriptionsCount);
+
+// For browsers that support proto assignment, we overwrite the prototype of each
+// observable instance. Since observables are functions, we need Function.prototype
+// to still be in the prototype chain.
+if (ko.utils.canSetPrototype) {
+ ko.utils.setPrototypeOf(ko_subscribable_fn, Function.prototype);
+}
+
+ko.subscribable['fn'] = ko_subscribable_fn;
+
+
+ko.isSubscribable = function (instance) {
+ return instance != null && typeof instance.subscribe == "function" && typeof instance["notifySubscribers"] == "function";
+};
+
+ko.exportSymbol('subscribable', ko.subscribable);
+ko.exportSymbol('isSubscribable', ko.isSubscribable);
+
+ko.computedContext = ko.dependencyDetection = (function () {
+ var outerFrames = [],
+ currentFrame,
+ lastId = 0;
+
+ // Return a unique ID that can be assigned to an observable for dependency tracking.
+ // Theoretically, you could eventually overflow the number storage size, resulting
+ // in duplicate IDs. But in JavaScript, the largest exact integral value is 2^53
+ // or 9,007,199,254,740,992. If you created 1,000,000 IDs per second, it would
+ // take over 285 years to reach that number.
+ // Reference http://blog.vjeux.com/2010/javascript/javascript-max_int-number-limits.html
+ function getId() {
+ return ++lastId;
+ }
+
+ function begin(options) {
+ outerFrames.push(currentFrame);
+ currentFrame = options;
+ }
+
+ function end() {
+ currentFrame = outerFrames.pop();
+ }
+
+ return {
+ begin: begin,
+
+ end: end,
+
+ registerDependency: function (subscribable) {
+ if (currentFrame) {
+ if (!ko.isSubscribable(subscribable))
+ throw new Error("Only subscribable things can act as dependencies");
+ currentFrame.callback(subscribable, subscribable._id || (subscribable._id = getId()));
+ }
+ },
+
+ ignore: function (callback, callbackTarget, callbackArgs) {
+ try {
+ begin();
+ return callback.apply(callbackTarget, callbackArgs || []);
+ } finally {
+ end();
+ }
+ },
+
+ getDependenciesCount: function () {
+ if (currentFrame)
+ return currentFrame.computed.getDependenciesCount();
+ },
+
+ isInitial: function() {
+ if (currentFrame)
+ return currentFrame.isInitial;
+ }
+ };
+})();
+
+ko.exportSymbol('computedContext', ko.computedContext);
+ko.exportSymbol('computedContext.getDependenciesCount', ko.computedContext.getDependenciesCount);
+ko.exportSymbol('computedContext.isInitial', ko.computedContext.isInitial);
+ko.observable = function (initialValue) {
+ var _latestValue = initialValue;
+
+ function observable() {
+ if (arguments.length > 0) {
+ // Write
+
+ // Ignore writes if the value hasn't changed
+ if (observable.isDifferent(_latestValue, arguments[0])) {
+ observable.valueWillMutate();
+ _latestValue = arguments[0];
+ if (DEBUG) observable._latestValue = _latestValue;
+ observable.valueHasMutated();
+ }
+ return this; // Permits chained assignments
+ }
+ else {
+ // Read
+ ko.dependencyDetection.registerDependency(observable); // The caller only needs to be notified of changes if they did a "read" operation
+ return _latestValue;
+ }
+ }
+ ko.subscribable.call(observable);
+ ko.utils.setPrototypeOfOrExtend(observable, ko.observable['fn']);
+
+ if (DEBUG) observable._latestValue = _latestValue;
+ observable.peek = function() { return _latestValue };
+ observable.valueHasMutated = function () { observable["notifySubscribers"](_latestValue); }
+ observable.valueWillMutate = function () { observable["notifySubscribers"](_latestValue, "beforeChange"); }
+
+ ko.exportProperty(observable, 'peek', observable.peek);
+ ko.exportProperty(observable, "valueHasMutated", observable.valueHasMutated);
+ ko.exportProperty(observable, "valueWillMutate", observable.valueWillMutate);
+
+ return observable;
+}
+
+ko.observable['fn'] = {
+ "equalityComparer": valuesArePrimitiveAndEqual
+};
+
+var protoProperty = ko.observable.protoProperty = "__ko_proto__";
+ko.observable['fn'][protoProperty] = ko.observable;
+
+// Note that for browsers that don't support proto assignment, the
+// inheritance chain is created manually in the ko.observable constructor
+if (ko.utils.canSetPrototype) {
+ ko.utils.setPrototypeOf(ko.observable['fn'], ko.subscribable['fn']);
+}
+
+ko.hasPrototype = function(instance, prototype) {
+ if ((instance === null) || (instance === undefined) || (instance[protoProperty] === undefined)) return false;
+ if (instance[protoProperty] === prototype) return true;
+ return ko.hasPrototype(instance[protoProperty], prototype); // Walk the prototype chain
+};
+
+ko.isObservable = function (instance) {
+ return ko.hasPrototype(instance, ko.observable);
+}
+ko.isWriteableObservable = function (instance) {
+ // Observable
+ if ((typeof instance == "function") && instance[protoProperty] === ko.observable)
+ return true;
+ // Writeable dependent observable
+ if ((typeof instance == "function") && (instance[protoProperty] === ko.dependentObservable) && (instance.hasWriteFunction))
+ return true;
+ // Anything else
+ return false;
+}
+
+
+ko.exportSymbol('observable', ko.observable);
+ko.exportSymbol('isObservable', ko.isObservable);
+ko.exportSymbol('isWriteableObservable', ko.isWriteableObservable);
+ko.observableArray = function (initialValues) {
+ initialValues = initialValues || [];
+
+ if (typeof initialValues != 'object' || !('length' in initialValues))
+ throw new Error("The argument passed when initializing an observable array must be an array, or null, or undefined.");
+
+ var result = ko.observable(initialValues);
+ ko.utils.setPrototypeOfOrExtend(result, ko.observableArray['fn']);
+ return result.extend({'trackArrayChanges':true});
+};
+
+ko.observableArray['fn'] = {
+ 'remove': function (valueOrPredicate) {
+ var underlyingArray = this.peek();
+ var removedValues = [];
+ var predicate = typeof valueOrPredicate == "function" && !ko.isObservable(valueOrPredicate) ? valueOrPredicate : function (value) { return value === valueOrPredicate; };
+ for (var i = 0; i < underlyingArray.length; i++) {
+ var value = underlyingArray[i];
+ if (predicate(value)) {
+ if (removedValues.length === 0) {
+ this.valueWillMutate();
+ }
+ removedValues.push(value);
+ underlyingArray.splice(i, 1);
+ i--;
+ }
+ }
+ if (removedValues.length) {
+ this.valueHasMutated();
+ }
+ return removedValues;
+ },
+
+ 'removeAll': function (arrayOfValues) {
+ // If you passed zero args, we remove everything
+ if (arrayOfValues === undefined) {
+ var underlyingArray = this.peek();
+ var allValues = underlyingArray.slice(0);
+ this.valueWillMutate();
+ underlyingArray.splice(0, underlyingArray.length);
+ this.valueHasMutated();
+ return allValues;
+ }
+ // If you passed an arg, we interpret it as an array of entries to remove
+ if (!arrayOfValues)
+ return [];
+ return this['remove'](function (value) {
+ return ko.utils.arrayIndexOf(arrayOfValues, value) >= 0;
+ });
+ },
+
+ 'destroy': function (valueOrPredicate) {
+ var underlyingArray = this.peek();
+ var predicate = typeof valueOrPredicate == "function" && !ko.isObservable(valueOrPredicate) ? valueOrPredicate : function (value) { return value === valueOrPredicate; };
+ this.valueWillMutate();
+ for (var i = underlyingArray.length - 1; i >= 0; i--) {
+ var value = underlyingArray[i];
+ if (predicate(value))
+ underlyingArray[i]["_destroy"] = true;
+ }
+ this.valueHasMutated();
+ },
+
+ 'destroyAll': function (arrayOfValues) {
+ // If you passed zero args, we destroy everything
+ if (arrayOfValues === undefined)
+ return this['destroy'](function() { return true });
+
+ // If you passed an arg, we interpret it as an array of entries to destroy
+ if (!arrayOfValues)
+ return [];
+ return this['destroy'](function (value) {
+ return ko.utils.arrayIndexOf(arrayOfValues, value) >= 0;
+ });
+ },
+
+ 'indexOf': function (item) {
+ var underlyingArray = this();
+ return ko.utils.arrayIndexOf(underlyingArray, item);
+ },
+
+ 'replace': function(oldItem, newItem) {
+ var index = this['indexOf'](oldItem);
+ if (index >= 0) {
+ this.valueWillMutate();
+ this.peek()[index] = newItem;
+ this.valueHasMutated();
+ }
+ }
+};
+
+// Populate ko.observableArray.fn with read/write functions from native arrays
+// Important: Do not add any additional functions here that may reasonably be used to *read* data from the array
+// because we'll eval them without causing subscriptions, so ko.computed output could end up getting stale
+ko.utils.arrayForEach(["pop", "push", "reverse", "shift", "sort", "splice", "unshift"], function (methodName) {
+ ko.observableArray['fn'][methodName] = function () {
+ // Use "peek" to avoid creating a subscription in any computed that we're executing in the context of
+ // (for consistency with mutating regular observables)
+ var underlyingArray = this.peek();
+ this.valueWillMutate();
+ this.cacheDiffForKnownOperation(underlyingArray, methodName, arguments);
+ var methodCallResult = underlyingArray[methodName].apply(underlyingArray, arguments);
+ this.valueHasMutated();
+ return methodCallResult;
+ };
+});
+
+// Populate ko.observableArray.fn with read-only functions from native arrays
+ko.utils.arrayForEach(["slice"], function (methodName) {
+ ko.observableArray['fn'][methodName] = function () {
+ var underlyingArray = this();
+ return underlyingArray[methodName].apply(underlyingArray, arguments);
+ };
+});
+
+// Note that for browsers that don't support proto assignment, the
+// inheritance chain is created manually in the ko.observableArray constructor
+if (ko.utils.canSetPrototype) {
+ ko.utils.setPrototypeOf(ko.observableArray['fn'], ko.observable['fn']);
+}
+
+ko.exportSymbol('observableArray', ko.observableArray);
+var arrayChangeEventName = 'arrayChange';
+ko.extenders['trackArrayChanges'] = function(target) {
+ // Only modify the target observable once
+ if (target.cacheDiffForKnownOperation) {
+ return;
+ }
+ var trackingChanges = false,
+ cachedDiff = null,
+ pendingNotifications = 0,
+ underlyingSubscribeFunction = target.subscribe;
+
+ // Intercept "subscribe" calls, and for array change events, ensure change tracking is enabled
+ target.subscribe = target['subscribe'] = function(callback, callbackTarget, event) {
+ if (event === arrayChangeEventName) {
+ trackChanges();
+ }
+ return underlyingSubscribeFunction.apply(this, arguments);
+ };
+
+ function trackChanges() {
+ // Calling 'trackChanges' multiple times is the same as calling it once
+ if (trackingChanges) {
+ return;
+ }
+
+ trackingChanges = true;
+
+ // Intercept "notifySubscribers" to track how many times it was called.
+ var underlyingNotifySubscribersFunction = target['notifySubscribers'];
+ target['notifySubscribers'] = function(valueToNotify, event) {
+ if (!event || event === defaultEvent) {
+ ++pendingNotifications;
+ }
+ return underlyingNotifySubscribersFunction.apply(this, arguments);
+ };
+
+ // Each time the array changes value, capture a clone so that on the next
+ // change it's possible to produce a diff
+ var previousContents = [].concat(target.peek() || []);
+ cachedDiff = null;
+ target.subscribe(function(currentContents) {
+ // Make a copy of the current contents and ensure it's an array
+ currentContents = [].concat(currentContents || []);
+
+ // Compute the diff and issue notifications, but only if someone is listening
+ if (target.hasSubscriptionsForEvent(arrayChangeEventName)) {
+ var changes = getChanges(previousContents, currentContents);
+ if (changes.length) {
+ target['notifySubscribers'](changes, arrayChangeEventName);
+ }
+ }
+
+ // Eliminate references to the old, removed items, so they can be GCed
+ previousContents = currentContents;
+ cachedDiff = null;
+ pendingNotifications = 0;
+ });
+ }
+
+ function getChanges(previousContents, currentContents) {
+ // We try to re-use cached diffs.
+ // The scenarios where pendingNotifications > 1 are when using rate-limiting or the Deferred Updates
+ // plugin, which without this check would not be compatible with arrayChange notifications. Normally,
+ // notifications are issued immediately so we wouldn't be queueing up more than one.
+ if (!cachedDiff || pendingNotifications > 1) {
+ cachedDiff = ko.utils.compareArrays(previousContents, currentContents, { 'sparse': true });
+ }
+
+ return cachedDiff;
+ }
+
+ target.cacheDiffForKnownOperation = function(rawArray, operationName, args) {
+ // Only run if we're currently tracking changes for this observable array
+ // and there aren't any pending deferred notifications.
+ if (!trackingChanges || pendingNotifications) {
+ return;
+ }
+ var diff = [],
+ arrayLength = rawArray.length,
+ argsLength = args.length,
+ offset = 0;
+
+ function pushDiff(status, value, index) {
+ return diff[diff.length] = { 'status': status, 'value': value, 'index': index };
+ }
+ switch (operationName) {
+ case 'push':
+ offset = arrayLength;
+ case 'unshift':
+ for (var index = 0; index < argsLength; index++) {
+ pushDiff('added', args[index], offset + index);
+ }
+ break;
+
+ case 'pop':
+ offset = arrayLength - 1;
+ case 'shift':
+ if (arrayLength) {
+ pushDiff('deleted', rawArray[offset], offset);
+ }
+ break;
+
+ case 'splice':
+ // Negative start index means 'from end of array'. After that we clamp to [0...arrayLength].
+ // See https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/splice
+ var startIndex = Math.min(Math.max(0, args[0] < 0 ? arrayLength + args[0] : args[0]), arrayLength),
+ endDeleteIndex = argsLength === 1 ? arrayLength : Math.min(startIndex + (args[1] || 0), arrayLength),
+ endAddIndex = startIndex + argsLength - 2,
+ endIndex = Math.max(endDeleteIndex, endAddIndex),
+ additions = [], deletions = [];
+ for (var index = startIndex, argsIndex = 2; index < endIndex; ++index, ++argsIndex) {
+ if (index < endDeleteIndex)
+ deletions.push(pushDiff('deleted', rawArray[index], index));
+ if (index < endAddIndex)
+ additions.push(pushDiff('added', args[argsIndex], index));
+ }
+ ko.utils.findMovesInArrayComparison(deletions, additions);
+ break;
+
+ default:
+ return;
+ }
+ cachedDiff = diff;
+ };
+};
+ko.computed = ko.dependentObservable = function (evaluatorFunctionOrOptions, evaluatorFunctionTarget, options) {
+ var _latestValue,
+ _needsEvaluation = true,
+ _isBeingEvaluated = false,
+ _suppressDisposalUntilDisposeWhenReturnsFalse = false,
+ _isDisposed = false,
+ readFunction = evaluatorFunctionOrOptions;
+
+ if (readFunction && typeof readFunction == "object") {
+ // Single-parameter syntax - everything is on this "options" param
+ options = readFunction;
+ readFunction = options["read"];
+ } else {
+ // Multi-parameter syntax - construct the options according to the params passed
+ options = options || {};
+ if (!readFunction)
+ readFunction = options["read"];
+ }
+ if (typeof readFunction != "function")
+ throw new Error("Pass a function that returns the value of the ko.computed");
+
+ function addSubscriptionToDependency(subscribable, id) {
+ if (!_subscriptionsToDependencies[id]) {
+ _subscriptionsToDependencies[id] = subscribable.subscribe(evaluatePossiblyAsync);
+ ++_dependenciesCount;
+ }
+ }
+
+ function disposeAllSubscriptionsToDependencies() {
+ _isDisposed = true;
+ ko.utils.objectForEach(_subscriptionsToDependencies, function (id, subscription) {
+ subscription.dispose();
+ });
+ _subscriptionsToDependencies = {};
+ _dependenciesCount = 0;
+ _needsEvaluation = false;
+ }
+
+ function evaluatePossiblyAsync() {
+ var throttleEvaluationTimeout = dependentObservable['throttleEvaluation'];
+ if (throttleEvaluationTimeout && throttleEvaluationTimeout >= 0) {
+ clearTimeout(evaluationTimeoutInstance);
+ evaluationTimeoutInstance = setTimeout(evaluateImmediate, throttleEvaluationTimeout);
+ } else if (dependentObservable._evalRateLimited) {
+ dependentObservable._evalRateLimited();
+ } else {
+ evaluateImmediate();
+ }
+ }
+
+ function evaluateImmediate() {
+ if (_isBeingEvaluated) {
+ // If the evaluation of a ko.computed causes side effects, it's possible that it will trigger its own re-evaluation.
+ // This is not desirable (it's hard for a developer to realise a chain of dependencies might cause this, and they almost
+ // certainly didn't intend infinite re-evaluations). So, for predictability, we simply prevent ko.computeds from causing
+ // their own re-evaluation. Further discussion at https://github.com/SteveSanderson/knockout/pull/387
+ return;
+ }
+
+ // Do not evaluate (and possibly capture new dependencies) if disposed
+ if (_isDisposed) {
+ return;
+ }
+
+ if (disposeWhen && disposeWhen()) {
+ // See comment below about _suppressDisposalUntilDisposeWhenReturnsFalse
+ if (!_suppressDisposalUntilDisposeWhenReturnsFalse) {
+ dispose();
+ return;
+ }
+ } else {
+ // It just did return false, so we can stop suppressing now
+ _suppressDisposalUntilDisposeWhenReturnsFalse = false;
+ }
+
+ _isBeingEvaluated = true;
+ try {
+ // Initially, we assume that none of the subscriptions are still being used (i.e., all are candidates for disposal).
+ // Then, during evaluation, we cross off any that are in fact still being used.
+ var disposalCandidates = _subscriptionsToDependencies, disposalCount = _dependenciesCount;
+ ko.dependencyDetection.begin({
+ callback: function(subscribable, id) {
+ if (!_isDisposed) {
+ if (disposalCount && disposalCandidates[id]) {
+ // Don't want to dispose this subscription, as it's still being used
+ _subscriptionsToDependencies[id] = disposalCandidates[id];
+ ++_dependenciesCount;
+ delete disposalCandidates[id];
+ --disposalCount;
+ } else {
+ // Brand new subscription - add it
+ addSubscriptionToDependency(subscribable, id);
+ }
+ }
+ },
+ computed: dependentObservable,
+ isInitial: !_dependenciesCount // If we're evaluating when there are no previous dependencies, it must be the first time
+ });
+
+ _subscriptionsToDependencies = {};
+ _dependenciesCount = 0;
+
+ try {
+ var newValue = evaluatorFunctionTarget ? readFunction.call(evaluatorFunctionTarget) : readFunction();
+
+ } finally {
+ ko.dependencyDetection.end();
+
+ // For each subscription no longer being used, remove it from the active subscriptions list and dispose it
+ if (disposalCount) {
+ ko.utils.objectForEach(disposalCandidates, function(id, toDispose) {
+ toDispose.dispose();
+ });
+ }
+
+ _needsEvaluation = false;
+ }
+
+ if (dependentObservable.isDifferent(_latestValue, newValue)) {
+ dependentObservable["notifySubscribers"](_latestValue, "beforeChange");
+
+ _latestValue = newValue;
+ if (DEBUG) dependentObservable._latestValue = _latestValue;
+
+ // If rate-limited, the notification will happen within the limit function. Otherwise,
+ // notify as soon as the value changes. Check specifically for the throttle setting since
+ // it overrides rateLimit.
+ if (!dependentObservable._evalRateLimited || dependentObservable['throttleEvaluation']) {
+ dependentObservable["notifySubscribers"](_latestValue);
+ }
+ }
+ } finally {
+ _isBeingEvaluated = false;
+ }
+
+ if (!_dependenciesCount)
+ dispose();
+ }
+
+ function dependentObservable() {
+ if (arguments.length > 0) {
+ if (typeof writeFunction === "function") {
+ // Writing a value
+ writeFunction.apply(evaluatorFunctionTarget, arguments);
+ } else {
+ throw new Error("Cannot write a value to a ko.computed unless you specify a 'write' option. If you wish to read the current value, don't pass any parameters.");
+ }
+ return this; // Permits chained assignments
+ } else {
+ // Reading the value
+ if (_needsEvaluation)
+ evaluateImmediate();
+ ko.dependencyDetection.registerDependency(dependentObservable);
+ return _latestValue;
+ }
+ }
+
+ function peek() {
+ // Peek won't re-evaluate, except to get the initial value when "deferEvaluation" is set.
+ // That's the only time that both of these conditions will be satisfied.
+ if (_needsEvaluation && !_dependenciesCount)
+ evaluateImmediate();
+ return _latestValue;
+ }
+
+ function isActive() {
+ return _needsEvaluation || _dependenciesCount > 0;
+ }
+
+ // By here, "options" is always non-null
+ var writeFunction = options["write"],
+ disposeWhenNodeIsRemoved = options["disposeWhenNodeIsRemoved"] || options.disposeWhenNodeIsRemoved || null,
+ disposeWhenOption = options["disposeWhen"] || options.disposeWhen,
+ disposeWhen = disposeWhenOption,
+ dispose = disposeAllSubscriptionsToDependencies,
+ _subscriptionsToDependencies = {},
+ _dependenciesCount = 0,
+ evaluationTimeoutInstance = null;
+
+ if (!evaluatorFunctionTarget)
+ evaluatorFunctionTarget = options["owner"];
+
+ ko.subscribable.call(dependentObservable);
+ ko.utils.setPrototypeOfOrExtend(dependentObservable, ko.dependentObservable['fn']);
+
+ dependentObservable.peek = peek;
+ dependentObservable.getDependenciesCount = function () { return _dependenciesCount; };
+ dependentObservable.hasWriteFunction = typeof options["write"] === "function";
+ dependentObservable.dispose = function () { dispose(); };
+ dependentObservable.isActive = isActive;
+
+ // Replace the limit function with one that delays evaluation as well.
+ var originalLimit = dependentObservable.limit;
+ dependentObservable.limit = function(limitFunction) {
+ originalLimit.call(dependentObservable, limitFunction);
+ dependentObservable._evalRateLimited = function() {
+ dependentObservable._rateLimitedBeforeChange(_latestValue);
+
+ _needsEvaluation = true; // Mark as dirty
+
+ // Pass the observable to the rate-limit code, which will access it when
+ // it's time to do the notification.
+ dependentObservable._rateLimitedChange(dependentObservable);
+ }
+ };
+
+ ko.exportProperty(dependentObservable, 'peek', dependentObservable.peek);
+ ko.exportProperty(dependentObservable, 'dispose', dependentObservable.dispose);
+ ko.exportProperty(dependentObservable, 'isActive', dependentObservable.isActive);
+ ko.exportProperty(dependentObservable, 'getDependenciesCount', dependentObservable.getDependenciesCount);
+
+ // Add a "disposeWhen" callback that, on each evaluation, disposes if the node was removed without using ko.removeNode.
+ if (disposeWhenNodeIsRemoved) {
+ // Since this computed is associated with a DOM node, and we don't want to dispose the computed
+ // until the DOM node is *removed* from the document (as opposed to never having been in the document),
+ // we'll prevent disposal until "disposeWhen" first returns false.
+ _suppressDisposalUntilDisposeWhenReturnsFalse = true;
+
+ // Only watch for the node's disposal if the value really is a node. It might not be,
+ // e.g., { disposeWhenNodeIsRemoved: true } can be used to opt into the "only dispose
+ // after first false result" behaviour even if there's no specific node to watch. This
+ // technique is intended for KO's internal use only and shouldn't be documented or used
+ // by application code, as it's likely to change in a future version of KO.
+ if (disposeWhenNodeIsRemoved.nodeType) {
+ disposeWhen = function () {
+ return !ko.utils.domNodeIsAttachedToDocument(disposeWhenNodeIsRemoved) || (disposeWhenOption && disposeWhenOption());
+ };
+ }
+ }
+
+ // Evaluate, unless deferEvaluation is true
+ if (options['deferEvaluation'] !== true)
+ evaluateImmediate();
+
+ // Attach a DOM node disposal callback so that the computed will be proactively disposed as soon as the node is
+ // removed using ko.removeNode. But skip if isActive is false (there will never be any dependencies to dispose).
+ if (disposeWhenNodeIsRemoved && isActive() && disposeWhenNodeIsRemoved.nodeType) {
+ dispose = function() {
+ ko.utils.domNodeDisposal.removeDisposeCallback(disposeWhenNodeIsRemoved, dispose);
+ disposeAllSubscriptionsToDependencies();
+ };
+ ko.utils.domNodeDisposal.addDisposeCallback(disposeWhenNodeIsRemoved, dispose);
+ }
+
+ return dependentObservable;
+};
+
+ko.isComputed = function(instance) {
+ return ko.hasPrototype(instance, ko.dependentObservable);
+};
+
+var protoProp = ko.observable.protoProperty; // == "__ko_proto__"
+ko.dependentObservable[protoProp] = ko.observable;
+
+ko.dependentObservable['fn'] = {
+ "equalityComparer": valuesArePrimitiveAndEqual
+};
+ko.dependentObservable['fn'][protoProp] = ko.dependentObservable;
+
+// Note that for browsers that don't support proto assignment, the
+// inheritance chain is created manually in the ko.dependentObservable constructor
+if (ko.utils.canSetPrototype) {
+ ko.utils.setPrototypeOf(ko.dependentObservable['fn'], ko.subscribable['fn']);
+}
+
+ko.exportSymbol('dependentObservable', ko.dependentObservable);
+ko.exportSymbol('computed', ko.dependentObservable); // Make "ko.computed" an alias for "ko.dependentObservable"
+ko.exportSymbol('isComputed', ko.isComputed);
+
+(function() {
+ var maxNestedObservableDepth = 10; // Escape the (unlikely) pathalogical case where an observable's current value is itself (or similar reference cycle)
+
+ ko.toJS = function(rootObject) {
+ if (arguments.length == 0)
+ throw new Error("When calling ko.toJS, pass the object you want to convert.");
+
+ // We just unwrap everything at every level in the object graph
+ return mapJsObjectGraph(rootObject, function(valueToMap) {
+ // Loop because an observable's value might in turn be another observable wrapper
+ for (var i = 0; ko.isObservable(valueToMap) && (i < maxNestedObservableDepth); i++)
+ valueToMap = valueToMap();
+ return valueToMap;
+ });
+ };
+
+ ko.toJSON = function(rootObject, replacer, space) { // replacer and space are optional
+ var plainJavaScriptObject = ko.toJS(rootObject);
+ return ko.utils.stringifyJson(plainJavaScriptObject, replacer, space);
+ };
+
+ function mapJsObjectGraph(rootObject, mapInputCallback, visitedObjects) {
+ visitedObjects = visitedObjects || new objectLookup();
+
+ rootObject = mapInputCallback(rootObject);
+ var canHaveProperties = (typeof rootObject == "object") && (rootObject !== null) && (rootObject !== undefined) && (!(rootObject instanceof Date)) && (!(rootObject instanceof String)) && (!(rootObject instanceof Number)) && (!(rootObject instanceof Boolean));
+ if (!canHaveProperties)
+ return rootObject;
+
+ var outputProperties = rootObject instanceof Array ? [] : {};
+ visitedObjects.save(rootObject, outputProperties);
+
+ visitPropertiesOrArrayEntries(rootObject, function(indexer) {
+ var propertyValue = mapInputCallback(rootObject[indexer]);
+
+ switch (typeof propertyValue) {
+ case "boolean":
+ case "number":
+ case "string":
+ case "function":
+ outputProperties[indexer] = propertyValue;
+ break;
+ case "object":
+ case "undefined":
+ var previouslyMappedValue = visitedObjects.get(propertyValue);
+ outputProperties[indexer] = (previouslyMappedValue !== undefined)
+ ? previouslyMappedValue
+ : mapJsObjectGraph(propertyValue, mapInputCallback, visitedObjects);
+ break;
+ }
+ });
+
+ return outputProperties;
+ }
+
+ function visitPropertiesOrArrayEntries(rootObject, visitorCallback) {
+ if (rootObject instanceof Array) {
+ for (var i = 0; i < rootObject.length; i++)
+ visitorCallback(i);
+
+ // For arrays, also respect toJSON property for custom mappings (fixes #278)
+ if (typeof rootObject['toJSON'] == 'function')
+ visitorCallback('toJSON');
+ } else {
+ for (var propertyName in rootObject) {
+ visitorCallback(propertyName);
+ }
+ }
+ };
+
+ function objectLookup() {
+ this.keys = [];
+ this.values = [];
+ };
+
+ objectLookup.prototype = {
+ constructor: objectLookup,
+ save: function(key, value) {
+ var existingIndex = ko.utils.arrayIndexOf(this.keys, key);
+ if (existingIndex >= 0)
+ this.values[existingIndex] = value;
+ else {
+ this.keys.push(key);
+ this.values.push(value);
+ }
+ },
+ get: function(key) {
+ var existingIndex = ko.utils.arrayIndexOf(this.keys, key);
+ return (existingIndex >= 0) ? this.values[existingIndex] : undefined;
+ }
+ };
+})();
+
+ko.exportSymbol('toJS', ko.toJS);
+ko.exportSymbol('toJSON', ko.toJSON);
+(function () {
+ var hasDomDataExpandoProperty = '__ko__hasDomDataOptionValue__';
+
+ // Normally, SELECT elements and their OPTIONs can only take value of type 'string' (because the values
+ // are stored on DOM attributes). ko.selectExtensions provides a way for SELECTs/OPTIONs to have values
+ // that are arbitrary objects. This is very convenient when implementing things like cascading dropdowns.
+ ko.selectExtensions = {
+ readValue : function(element) {
+ switch (ko.utils.tagNameLower(element)) {
+ case 'option':
+ if (element[hasDomDataExpandoProperty] === true)
+ return ko.utils.domData.get(element, ko.bindingHandlers.options.optionValueDomDataKey);
+ return ko.utils.ieVersion <= 7
+ ? (element.getAttributeNode('value') && element.getAttributeNode('value').specified ? element.value : element.text)
+ : element.value;
+ case 'select':
+ return element.selectedIndex >= 0 ? ko.selectExtensions.readValue(element.options[element.selectedIndex]) : undefined;
+ default:
+ return element.value;
+ }
+ },
+
+ writeValue: function(element, value, allowUnset) {
+ switch (ko.utils.tagNameLower(element)) {
+ case 'option':
+ switch(typeof value) {
+ case "string":
+ ko.utils.domData.set(element, ko.bindingHandlers.options.optionValueDomDataKey, undefined);
+ if (hasDomDataExpandoProperty in element) { // IE <= 8 throws errors if you delete non-existent properties from a DOM node
+ delete element[hasDomDataExpandoProperty];
+ }
+ element.value = value;
+ break;
+ default:
+ // Store arbitrary object using DomData
+ ko.utils.domData.set(element, ko.bindingHandlers.options.optionValueDomDataKey, value);
+ element[hasDomDataExpandoProperty] = true;
+
+ // Special treatment of numbers is just for backward compatibility. KO 1.2.1 wrote numerical values to element.value.
+ element.value = typeof value === "number" ? value : "";
+ break;
+ }
+ break;
+ case 'select':
+ if (value === "" || value === null) // A blank string or null value will select the caption
+ value = undefined;
+ var selection = -1;
+ for (var i = 0, n = element.options.length, optionValue; i < n; ++i) {
+ optionValue = ko.selectExtensions.readValue(element.options[i]);
+ // Include special check to handle selecting a caption with a blank string value
+ if (optionValue == value || (optionValue == "" && value === undefined)) {
+ selection = i;
+ break;
+ }
+ }
+ if (allowUnset || selection >= 0 || (value === undefined && element.size > 1)) {
+ element.selectedIndex = selection;
+ }
+ break;
+ default:
+ if ((value === null) || (value === undefined))
+ value = "";
+ element.value = value;
+ break;
+ }
+ }
+ };
+})();
+
+ko.exportSymbol('selectExtensions', ko.selectExtensions);
+ko.exportSymbol('selectExtensions.readValue', ko.selectExtensions.readValue);
+ko.exportSymbol('selectExtensions.writeValue', ko.selectExtensions.writeValue);
+ko.expressionRewriting = (function () {
+ var javaScriptReservedWords = ["true", "false", "null", "undefined"];
+
+ // Matches something that can be assigned to--either an isolated identifier or something ending with a property accessor
+ // This is designed to be simple and avoid false negatives, but could produce false positives (e.g., a+b.c).
+ // This also will not properly handle nested brackets (e.g., obj1[obj2['prop']]; see #911).
+ var javaScriptAssignmentTarget = /^(?:[$_a-z][$\w]*|(.+)(\.\s*[$_a-z][$\w]*|\[.+\]))$/i;
+
+ function getWriteableValue(expression) {
+ if (ko.utils.arrayIndexOf(javaScriptReservedWords, expression) >= 0)
+ return false;
+ var match = expression.match(javaScriptAssignmentTarget);
+ return match === null ? false : match[1] ? ('Object(' + match[1] + ')' + match[2]) : expression;
+ }
+
+ // The following regular expressions will be used to split an object-literal string into tokens
+
+ // These two match strings, either with double quotes or single quotes
+ var stringDouble = '"(?:[^"\\\\]|\\\\.)*"',
+ stringSingle = "'(?:[^'\\\\]|\\\\.)*'",
+ // Matches a regular expression (text enclosed by slashes), but will also match sets of divisions
+ // as a regular expression (this is handled by the parsing loop below).
+ stringRegexp = '/(?:[^/\\\\]|\\\\.)*/\w*',
+ // These characters have special meaning to the parser and must not appear in the middle of a
+ // token, except as part of a string.
+ specials = ',"\'{}()/:[\\]',
+ // Match text (at least two characters) that does not contain any of the above special characters,
+ // although some of the special characters are allowed to start it (all but the colon and comma).
+ // The text can contain spaces, but leading or trailing spaces are skipped.
+ everyThingElse = '[^\\s:,/][^' + specials + ']*[^\\s' + specials + ']',
+ // Match any non-space character not matched already. This will match colons and commas, since they're
+ // not matched by "everyThingElse", but will also match any other single character that wasn't already
+ // matched (for example: in "a: 1, b: 2", each of the non-space characters will be matched by oneNotSpace).
+ oneNotSpace = '[^\\s]',
+
+ // Create the actual regular expression by or-ing the above strings. The order is important.
+ bindingToken = RegExp(stringDouble + '|' + stringSingle + '|' + stringRegexp + '|' + everyThingElse + '|' + oneNotSpace, 'g'),
+
+ // Match end of previous token to determine whether a slash is a division or regex.
+ divisionLookBehind = /[\])"'A-Za-z0-9_$]+$/,
+ keywordRegexLookBehind = {'in':1,'return':1,'typeof':1};
+
+ function parseObjectLiteral(objectLiteralString) {
+ // Trim leading and trailing spaces from the string
+ var str = ko.utils.stringTrim(objectLiteralString);
+
+ // Trim braces '{' surrounding the whole object literal
+ if (str.charCodeAt(0) === 123) str = str.slice(1, -1);
+
+ // Split into tokens
+ var result = [], toks = str.match(bindingToken), key, values, depth = 0;
+
+ if (toks) {
+ // Append a comma so that we don't need a separate code block to deal with the last item
+ toks.push(',');
+
+ for (var i = 0, tok; tok = toks[i]; ++i) {
+ var c = tok.charCodeAt(0);
+ // A comma signals the end of a key/value pair if depth is zero
+ if (c === 44) { // ","
+ if (depth <= 0) {
+ if (key)
+ result.push(values ? {key: key, value: values.join('')} : {'unknown': key});
+ key = values = depth = 0;
+ continue;
+ }
+ // Simply skip the colon that separates the name and value
+ } else if (c === 58) { // ":"
+ if (!values)
+ continue;
+ // A set of slashes is initially matched as a regular expression, but could be division
+ } else if (c === 47 && i && tok.length > 1) { // "/"
+ // Look at the end of the previous token to determine if the slash is actually division
+ var match = toks[i-1].match(divisionLookBehind);
+ if (match && !keywordRegexLookBehind[match[0]]) {
+ // The slash is actually a division punctuator; re-parse the remainder of the string (not including the slash)
+ str = str.substr(str.indexOf(tok) + 1);
+ toks = str.match(bindingToken);
+ toks.push(',');
+ i = -1;
+ // Continue with just the slash
+ tok = '/';
+ }
+ // Increment depth for parentheses, braces, and brackets so that interior commas are ignored
+ } else if (c === 40 || c === 123 || c === 91) { // '(', '{', '['
+ ++depth;
+ } else if (c === 41 || c === 125 || c === 93) { // ')', '}', ']'
+ --depth;
+ // The key must be a single token; if it's a string, trim the quotes
+ } else if (!key && !values) {
+ key = (c === 34 || c === 39) /* '"', "'" */ ? tok.slice(1, -1) : tok;
+ continue;
+ }
+ if (values)
+ values.push(tok);
+ else
+ values = [tok];
+ }
+ }
+ return result;
+ }
+
+ // Two-way bindings include a write function that allow the handler to update the value even if it's not an observable.
+ var twoWayBindings = {};
+
+ function preProcessBindings(bindingsStringOrKeyValueArray, bindingOptions) {
+ bindingOptions = bindingOptions || {};
+
+ function processKeyValue(key, val) {
+ var writableVal;
+ function callPreprocessHook(obj) {
+ return (obj && obj['preprocess']) ? (val = obj['preprocess'](val, key, processKeyValue)) : true;
+ }
+ if (!callPreprocessHook(ko['getBindingHandler'](key)))
+ return;
+
+ if (twoWayBindings[key] && (writableVal = getWriteableValue(val))) {
+ // For two-way bindings, provide a write method in case the value
+ // isn't a writable observable.
+ propertyAccessorResultStrings.push("'" + key + "':function(_z){" + writableVal + "=_z}");
+ }
+
+ // Values are wrapped in a function so that each value can be accessed independently
+ if (makeValueAccessors) {
+ val = 'function(){return ' + val + ' }';
+ }
+ resultStrings.push("'" + key + "':" + val);
+ }
+
+ var resultStrings = [],
+ propertyAccessorResultStrings = [],
+ makeValueAccessors = bindingOptions['valueAccessors'],
+ keyValueArray = typeof bindingsStringOrKeyValueArray === "string" ?
+ parseObjectLiteral(bindingsStringOrKeyValueArray) : bindingsStringOrKeyValueArray;
+
+ ko.utils.arrayForEach(keyValueArray, function(keyValue) {
+ processKeyValue(keyValue.key || keyValue['unknown'], keyValue.value);
+ });
+
+ if (propertyAccessorResultStrings.length)
+ processKeyValue('_ko_property_writers', "{" + propertyAccessorResultStrings.join(",") + " }");
+
+ return resultStrings.join(",");
+ }
+
+ return {
+ bindingRewriteValidators: [],
+
+ twoWayBindings: twoWayBindings,
+
+ parseObjectLiteral: parseObjectLiteral,
+
+ preProcessBindings: preProcessBindings,
+
+ keyValueArrayContainsKey: function(keyValueArray, key) {
+ for (var i = 0; i < keyValueArray.length; i++)
+ if (keyValueArray[i]['key'] == key)
+ return true;
+ return false;
+ },
+
+ // Internal, private KO utility for updating model properties from within bindings
+ // property: If the property being updated is (or might be) an observable, pass it here
+ // If it turns out to be a writable observable, it will be written to directly
+ // allBindings: An object with a get method to retrieve bindings in the current execution context.
+ // This will be searched for a '_ko_property_writers' property in case you're writing to a non-observable
+ // key: The key identifying the property to be written. Example: for { hasFocus: myValue }, write to 'myValue' by specifying the key 'hasFocus'
+ // value: The value to be written
+ // checkIfDifferent: If true, and if the property being written is a writable observable, the value will only be written if
+ // it is !== existing value on that writable observable
+ writeValueToProperty: function(property, allBindings, key, value, checkIfDifferent) {
+ if (!property || !ko.isObservable(property)) {
+ var propWriters = allBindings.get('_ko_property_writers');
+ if (propWriters && propWriters[key])
+ propWriters[key](value);
+ } else if (ko.isWriteableObservable(property) && (!checkIfDifferent || property.peek() !== value)) {
+ property(value);
+ }
+ }
+ };
+})();
+
+ko.exportSymbol('expressionRewriting', ko.expressionRewriting);
+ko.exportSymbol('expressionRewriting.bindingRewriteValidators', ko.expressionRewriting.bindingRewriteValidators);
+ko.exportSymbol('expressionRewriting.parseObjectLiteral', ko.expressionRewriting.parseObjectLiteral);
+ko.exportSymbol('expressionRewriting.preProcessBindings', ko.expressionRewriting.preProcessBindings);
+
+// Making bindings explicitly declare themselves as "two way" isn't ideal in the long term (it would be better if
+// all bindings could use an official 'property writer' API without needing to declare that they might). However,
+// since this is not, and has never been, a public API (_ko_property_writers was never documented), it's acceptable
+// as an internal implementation detail in the short term.
+// For those developers who rely on _ko_property_writers in their custom bindings, we expose _twoWayBindings as an
+// undocumented feature that makes it relatively easy to upgrade to KO 3.0. However, this is still not an official
+// public API, and we reserve the right to remove it at any time if we create a real public property writers API.
+ko.exportSymbol('expressionRewriting._twoWayBindings', ko.expressionRewriting.twoWayBindings);
+
+// For backward compatibility, define the following aliases. (Previously, these function names were misleading because
+// they referred to JSON specifically, even though they actually work with arbitrary JavaScript object literal expressions.)
+ko.exportSymbol('jsonExpressionRewriting', ko.expressionRewriting);
+ko.exportSymbol('jsonExpressionRewriting.insertPropertyAccessorsIntoJson', ko.expressionRewriting.preProcessBindings);
+(function() {
+ // "Virtual elements" is an abstraction on top of the usual DOM API which understands the notion that comment nodes
+ // may be used to represent hierarchy (in addition to the DOM's natural hierarchy).
+ // If you call the DOM-manipulating functions on ko.virtualElements, you will be able to read and write the state
+ // of that virtual hierarchy
+ //
+ // The point of all this is to support containerless templates (e.g., <!-- ko foreach:someCollection -->blah<!-- /ko -->)
+ // without having to scatter special cases all over the binding and templating code.
+
+ // IE 9 cannot reliably read the "nodeValue" property of a comment node (see https://github.com/SteveSanderson/knockout/issues/186)
+ // but it does give them a nonstandard alternative property called "text" that it can read reliably. Other browsers don't have that property.
+ // So, use node.text where available, and node.nodeValue elsewhere
+ var commentNodesHaveTextProperty = document && document.createComment("test").text === "<!--test-->";
+
+ var startCommentRegex = commentNodesHaveTextProperty ? /^<!--\s*ko(?:\s+([\s\S]+))?\s*-->$/ : /^\s*ko(?:\s+([\s\S]+))?\s*$/;
+ var endCommentRegex = commentNodesHaveTextProperty ? /^<!--\s*\/ko\s*-->$/ : /^\s*\/ko\s*$/;
+ var htmlTagsWithOptionallyClosingChildren = { 'ul': true, 'ol': true };
+
+ function isStartComment(node) {
+ return (node.nodeType == 8) && startCommentRegex.test(commentNodesHaveTextProperty ? node.text : node.nodeValue);
+ }
+
+ function isEndComment(node) {
+ return (node.nodeType == 8) && endCommentRegex.test(commentNodesHaveTextProperty ? node.text : node.nodeValue);
+ }
+
+ function getVirtualChildren(startComment, allowUnbalanced) {
+ var currentNode = startComment;
+ var depth = 1;
+ var children = [];
+ while (currentNode = currentNode.nextSibling) {
+ if (isEndComment(currentNode)) {
+ depth--;
+ if (depth === 0)
+ return children;
+ }
+
+ children.push(currentNode);
+
+ if (isStartComment(currentNode))
+ depth++;
+ }
+ if (!allowUnbalanced)
+ throw new Error("Cannot find closing comment tag to match: " + startComment.nodeValue);
+ return null;
+ }
+
+ function getMatchingEndComment(startComment, allowUnbalanced) {
+ var allVirtualChildren = getVirtualChildren(startComment, allowUnbalanced);
+ if (allVirtualChildren) {
+ if (allVirtualChildren.length > 0)
+ return allVirtualChildren[allVirtualChildren.length - 1].nextSibling;
+ return startComment.nextSibling;
+ } else
+ return null; // Must have no matching end comment, and allowUnbalanced is true
+ }
+
+ function getUnbalancedChildTags(node) {
+ // e.g., from <div>OK</div><!-- ko blah --><span>Another</span>, returns: <!-- ko blah --><span>Another</span>
+ // from <div>OK</div><!-- /ko --><!-- /ko -->, returns: <!-- /ko --><!-- /ko -->
+ var childNode = node.firstChild, captureRemaining = null;
+ if (childNode) {
+ do {
+ if (captureRemaining) // We already hit an unbalanced node and are now just scooping up all subsequent nodes
+ captureRemaining.push(childNode);
+ else if (isStartComment(childNode)) {
+ var matchingEndComment = getMatchingEndComment(childNode, /* allowUnbalanced: */ true);
+ if (matchingEndComment) // It's a balanced tag, so skip immediately to the end of this virtual set
+ childNode = matchingEndComment;
+ else
+ captureRemaining = [childNode]; // It's unbalanced, so start capturing from this point
+ } else if (isEndComment(childNode)) {
+ captureRemaining = [childNode]; // It's unbalanced (if it wasn't, we'd have skipped over it already), so start capturing
+ }
+ } while (childNode = childNode.nextSibling);
+ }
+ return captureRemaining;
+ }
+
+ ko.virtualElements = {
+ allowedBindings: {},
+
+ childNodes: function(node) {
+ return isStartComment(node) ? getVirtualChildren(node) : node.childNodes;
+ },
+
+ emptyNode: function(node) {
+ if (!isStartComment(node))
+ ko.utils.emptyDomNode(node);
+ else {
+ var virtualChildren = ko.virtualElements.childNodes(node);
+ for (var i = 0, j = virtualChildren.length; i < j; i++)
+ ko.removeNode(virtualChildren[i]);
+ }
+ },
+
+ setDomNodeChildren: function(node, childNodes) {
+ if (!isStartComment(node))
+ ko.utils.setDomNodeChildren(node, childNodes);
+ else {
+ ko.virtualElements.emptyNode(node);
+ var endCommentNode = node.nextSibling; // Must be the next sibling, as we just emptied the children
+ for (var i = 0, j = childNodes.length; i < j; i++)
+ endCommentNode.parentNode.insertBefore(childNodes[i], endCommentNode);
+ }
+ },
+
+ prepend: function(containerNode, nodeToPrepend) {
+ if (!isStartComment(containerNode)) {
+ if (containerNode.firstChild)
+ containerNode.insertBefore(nodeToPrepend, containerNode.firstChild);
+ else
+ containerNode.appendChild(nodeToPrepend);
+ } else {
+ // Start comments must always have a parent and at least one following sibling (the end comment)
+ containerNode.parentNode.insertBefore(nodeToPrepend, containerNode.nextSibling);
+ }
+ },
+
+ insertAfter: function(containerNode, nodeToInsert, insertAfterNode) {
+ if (!insertAfterNode) {
+ ko.virtualElements.prepend(containerNode, nodeToInsert);
+ } else if (!isStartComment(containerNode)) {
+ // Insert after insertion point
+ if (insertAfterNode.nextSibling)
+ containerNode.insertBefore(nodeToInsert, insertAfterNode.nextSibling);
+ else
+ containerNode.appendChild(nodeToInsert);
+ } else {
+ // Children of start comments must always have a parent and at least one following sibling (the end comment)
+ containerNode.parentNode.insertBefore(nodeToInsert, insertAfterNode.nextSibling);
+ }
+ },
+
+ firstChild: function(node) {
+ if (!isStartComment(node))
+ return node.firstChild;
+ if (!node.nextSibling || isEndComment(node.nextSibling))
+ return null;
+ return node.nextSibling;
+ },
+
+ nextSibling: function(node) {
+ if (isStartComment(node))
+ node = getMatchingEndComment(node);
+ if (node.nextSibling && isEndComment(node.nextSibling))
+ return null;
+ return node.nextSibling;
+ },
+
+ hasBindingValue: isStartComment,
+
+ virtualNodeBindingValue: function(node) {
+ var regexMatch = (commentNodesHaveTextProperty ? node.text : node.nodeValue).match(startCommentRegex);
+ return regexMatch ? regexMatch[1] : null;
+ },
+
+ normaliseVirtualElementDomStructure: function(elementVerified) {
+ // Workaround for https://github.com/SteveSanderson/knockout/issues/155
+ // (IE <= 8 or IE 9 quirks mode parses your HTML weirdly, treating closing </li> tags as if they don't exist, thereby moving comment nodes
+ // that are direct descendants of <ul> into the preceding <li>)
+ if (!htmlTagsWithOptionallyClosingChildren[ko.utils.tagNameLower(elementVerified)])
+ return;
+
+ // Scan immediate children to see if they contain unbalanced comment tags. If they do, those comment tags
+ // must be intended to appear *after* that child, so move them there.
+ var childNode = elementVerified.firstChild;
+ if (childNode) {
+ do {
+ if (childNode.nodeType === 1) {
+ var unbalancedTags = getUnbalancedChildTags(childNode);
+ if (unbalancedTags) {
+ // Fix up the DOM by moving the unbalanced tags to where they most likely were intended to be placed - *after* the child
+ var nodeToInsertBefore = childNode.nextSibling;
+ for (var i = 0; i < unbalancedTags.length; i++) {
+ if (nodeToInsertBefore)
+ elementVerified.insertBefore(unbalancedTags[i], nodeToInsertBefore);
+ else
+ elementVerified.appendChild(unbalancedTags[i]);
+ }
+ }
+ }
+ } while (childNode = childNode.nextSibling);
+ }
+ }
+ };
+})();
+ko.exportSymbol('virtualElements', ko.virtualElements);
+ko.exportSymbol('virtualElements.allowedBindings', ko.virtualElements.allowedBindings);
+ko.exportSymbol('virtualElements.emptyNode', ko.virtualElements.emptyNode);
+//ko.exportSymbol('virtualElements.firstChild', ko.virtualElements.firstChild); // firstChild is not minified
+ko.exportSymbol('virtualElements.insertAfter', ko.virtualElements.insertAfter);
+//ko.exportSymbol('virtualElements.nextSibling', ko.virtualElements.nextSibling); // nextSibling is not minified
+ko.exportSymbol('virtualElements.prepend', ko.virtualElements.prepend);
+ko.exportSymbol('virtualElements.setDomNodeChildren', ko.virtualElements.setDomNodeChildren);
+(function() {
+ var defaultBindingAttributeName = "data-bind";
+
+ ko.bindingProvider = function() {
+ this.bindingCache = {};
+ };
+
+ ko.utils.extend(ko.bindingProvider.prototype, {
+ 'nodeHasBindings': function(node) {
+ switch (node.nodeType) {
+ case 1: return node.getAttribute(defaultBindingAttributeName) != null; // Element
+ case 8: return ko.virtualElements.hasBindingValue(node); // Comment node
+ default: return false;
+ }
+ },
+
+ 'getBindings': function(node, bindingContext) {
+ var bindingsString = this['getBindingsString'](node, bindingContext);
+ return bindingsString ? this['parseBindingsString'](bindingsString, bindingContext, node) : null;
+ },
+
+ 'getBindingAccessors': function(node, bindingContext) {
+ var bindingsString = this['getBindingsString'](node, bindingContext);
+ return bindingsString ? this['parseBindingsString'](bindingsString, bindingContext, node, {'valueAccessors':true}) : null;
+ },
+
+ // The following function is only used internally by this default provider.
+ // It's not part of the interface definition for a general binding provider.
+ 'getBindingsString': function(node, bindingContext) {
+ switch (node.nodeType) {
+ case 1: return node.getAttribute(defaultBindingAttributeName); // Element
+ case 8: return ko.virtualElements.virtualNodeBindingValue(node); // Comment node
+ default: return null;
+ }
+ },
+
+ // The following function is only used internally by this default provider.
+ // It's not part of the interface definition for a general binding provider.
+ 'parseBindingsString': function(bindingsString, bindingContext, node, options) {
+ try {
+ var bindingFunction = createBindingsStringEvaluatorViaCache(bindingsString, this.bindingCache, options);
+ return bindingFunction(bindingContext, node);
+ } catch (ex) {
+ ex.message = "Unable to parse bindings.\nBindings value: " + bindingsString + "\nMessage: " + ex.message;
+ throw ex;
+ }
+ }
+ });
+
+ ko.bindingProvider['instance'] = new ko.bindingProvider();
+
+ function createBindingsStringEvaluatorViaCache(bindingsString, cache, options) {
+ var cacheKey = bindingsString + (options && options['valueAccessors'] || '');
+ return cache[cacheKey]
+ || (cache[cacheKey] = createBindingsStringEvaluator(bindingsString, options));
+ }
+
+ function createBindingsStringEvaluator(bindingsString, options) {
+ // Build the source for a function that evaluates "expression"
+ // For each scope variable, add an extra level of "with" nesting
+ // Example result: with(sc1) { with(sc0) { return (expression) } }
+ var rewrittenBindings = ko.expressionRewriting.preProcessBindings(bindingsString, options),
+ functionBody = "with($context){with($data||{}){return{" + rewrittenBindings + "}}}";
+ return new Function("$context", "$element", functionBody);
+ }
+})();
+
+ko.exportSymbol('bindingProvider', ko.bindingProvider);
+(function () {
+ ko.bindingHandlers = {};
+
+ // The following element types will not be recursed into during binding. In the future, we
+ // may consider adding <template> to this list, because such elements' contents are always
+ // intended to be bound in a different context from where they appear in the document.
+ var bindingDoesNotRecurseIntoElementTypes = {
+ // Don't want bindings that operate on text nodes to mutate <script> contents,
+ // because it's unexpected and a potential XSS issue
+ 'script': true
+ };
+
+ // Use an overridable method for retrieving binding handlers so that a plugins may support dynamically created handlers
+ ko['getBindingHandler'] = function(bindingKey) {
+ return ko.bindingHandlers[bindingKey];
+ };
+
+ // The ko.bindingContext constructor is only called directly to create the root context. For child
+ // contexts, use bindingContext.createChildContext or bindingContext.extend.
+ ko.bindingContext = function(dataItemOrAccessor, parentContext, dataItemAlias, extendCallback) {
+
+ // The binding context object includes static properties for the current, parent, and root view models.
+ // If a view model is actually stored in an observable, the corresponding binding context object, and
+ // any child contexts, must be updated when the view model is changed.
+ function updateContext() {
+ // Most of the time, the context will directly get a view model object, but if a function is given,
+ // we call the function to retrieve the view model. If the function accesses any obsevables or returns
+ // an observable, the dependency is tracked, and those observables can later cause the binding
+ // context to be updated.
+ var dataItemOrObservable = isFunc ? dataItemOrAccessor() : dataItemOrAccessor,
+ dataItem = ko.utils.unwrapObservable(dataItemOrObservable);
+
+ if (parentContext) {
+ // When a "parent" context is given, register a dependency on the parent context. Thus whenever the
+ // parent context is updated, this context will also be updated.
+ if (parentContext._subscribable)
+ parentContext._subscribable();
+
+ // Copy $root and any custom properties from the parent context
+ ko.utils.extend(self, parentContext);
+
+ // Because the above copy overwrites our own properties, we need to reset them.
+ // During the first execution, "subscribable" isn't set, so don't bother doing the update then.
+ if (subscribable) {
+ self._subscribable = subscribable;
+ }
+ } else {
+ self['$parents'] = [];
+ self['$root'] = dataItem;
+
+ // Export 'ko' in the binding context so it will be available in bindings and templates
+ // even if 'ko' isn't exported as a global, such as when using an AMD loader.
+ // See https://github.com/SteveSanderson/knockout/issues/490
+ self['ko'] = ko;
+ }
+ self['$rawData'] = dataItemOrObservable;
+ self['$data'] = dataItem;
+ if (dataItemAlias)
+ self[dataItemAlias] = dataItem;
+
+ // The extendCallback function is provided when creating a child context or extending a context.
+ // It handles the specific actions needed to finish setting up the binding context. Actions in this
+ // function could also add dependencies to this binding context.
+ if (extendCallback)
+ extendCallback(self, parentContext, dataItem);
+
+ return self['$data'];
+ }
+ function disposeWhen() {
+ return nodes && !ko.utils.anyDomNodeIsAttachedToDocument(nodes);
+ }
+
+ var self = this,
+ isFunc = typeof(dataItemOrAccessor) == "function" && !ko.isObservable(dataItemOrAccessor),
+ nodes,
+ subscribable = ko.dependentObservable(updateContext, null, { disposeWhen: disposeWhen, disposeWhenNodeIsRemoved: true });
+
+ // At this point, the binding context has been initialized, and the "subscribable" computed observable is
+ // subscribed to any observables that were accessed in the process. If there is nothing to track, the
+ // computed will be inactive, and we can safely throw it away. If it's active, the computed is stored in
+ // the context object.
+ if (subscribable.isActive()) {
+ self._subscribable = subscribable;
+
+ // Always notify because even if the model ($data) hasn't changed, other context properties might have changed
+ subscribable['equalityComparer'] = null;
+
+ // We need to be able to dispose of this computed observable when it's no longer needed. This would be
+ // easy if we had a single node to watch, but binding contexts can be used by many different nodes, and
+ // we cannot assume that those nodes have any relation to each other. So instead we track any node that
+ // the context is attached to, and dispose the computed when all of those nodes have been cleaned.
+
+ // Add properties to *subscribable* instead of *self* because any properties added to *self* may be overwritten on updates
+ nodes = [];
+ subscribable._addNode = function(node) {
+ nodes.push(node);
+ ko.utils.domNodeDisposal.addDisposeCallback(node, function(node) {
+ ko.utils.arrayRemoveItem(nodes, node);
+ if (!nodes.length) {
+ subscribable.dispose();
+ self._subscribable = subscribable = undefined;
+ }
+ });
+ };
+ }
+ }
+
+ // Extend the binding context hierarchy with a new view model object. If the parent context is watching
+ // any obsevables, the new child context will automatically get a dependency on the parent context.
+ // But this does not mean that the $data value of the child context will also get updated. If the child
+ // view model also depends on the parent view model, you must provide a function that returns the correct
+ // view model on each update.
+ ko.bindingContext.prototype['createChildContext'] = function (dataItemOrAccessor, dataItemAlias, extendCallback) {
+ return new ko.bindingContext(dataItemOrAccessor, this, dataItemAlias, function(self, parentContext) {
+ // Extend the context hierarchy by setting the appropriate pointers
+ self['$parentContext'] = parentContext;
+ self['$parent'] = parentContext['$data'];
+ self['$parents'] = (parentContext['$parents'] || []).slice(0);
+ self['$parents'].unshift(self['$parent']);
+ if (extendCallback)
+ extendCallback(self);
+ });
+ };
+
+ // Extend the binding context with new custom properties. This doesn't change the context hierarchy.
+ // Similarly to "child" contexts, provide a function here to make sure that the correct values are set
+ // when an observable view model is updated.
+ ko.bindingContext.prototype['extend'] = function(properties) {
+ // If the parent context references an observable view model, "_subscribable" will always be the
+ // latest view model object. If not, "_subscribable" isn't set, and we can use the static "$data" value.
+ return new ko.bindingContext(this._subscribable || this['$data'], this, null, function(self, parentContext) {
+ // This "child" context doesn't directly track a parent observable view model,
+ // so we need to manually set the $rawData value to match the parent.
+ self['$rawData'] = parentContext['$rawData'];
+ ko.utils.extend(self, typeof(properties) == "function" ? properties() : properties);
+ });
+ };
+
+ // Returns the valueAccesor function for a binding value
+ function makeValueAccessor(value) {
+ return function() {
+ return value;
+ };
+ }
+
+ // Returns the value of a valueAccessor function
+ function evaluateValueAccessor(valueAccessor) {
+ return valueAccessor();
+ }
+
+ // Given a function that returns bindings, create and return a new object that contains
+ // binding value-accessors functions. Each accessor function calls the original function
+ // so that it always gets the latest value and all dependencies are captured. This is used
+ // by ko.applyBindingsToNode and getBindingsAndMakeAccessors.
+ function makeAccessorsFromFunction(callback) {
+ return ko.utils.objectMap(ko.dependencyDetection.ignore(callback), function(value, key) {
+ return function() {
+ return callback()[key];
+ };
+ });
+ }
+
+ // Given a bindings function or object, create and return a new object that contains
+ // binding value-accessors functions. This is used by ko.applyBindingsToNode.
+ function makeBindingAccessors(bindings, context, node) {
+ if (typeof bindings === 'function') {
+ return makeAccessorsFromFunction(bindings.bind(null, context, node));
+ } else {
+ return ko.utils.objectMap(bindings, makeValueAccessor);
+ }
+ }
+
+ // This function is used if the binding provider doesn't include a getBindingAccessors function.
+ // It must be called with 'this' set to the provider instance.
+ function getBindingsAndMakeAccessors(node, context) {
+ return makeAccessorsFromFunction(this['getBindings'].bind(this, node, context));
+ }
+
+ function validateThatBindingIsAllowedForVirtualElements(bindingName) {
+ var validator = ko.virtualElements.allowedBindings[bindingName];
+ if (!validator)
+ throw new Error("The binding '" + bindingName + "' cannot be used with virtual elements")
+ }
+
+ function applyBindingsToDescendantsInternal (bindingContext, elementOrVirtualElement, bindingContextsMayDifferFromDomParentElement) {
+ var currentChild,
+ nextInQueue = ko.virtualElements.firstChild(elementOrVirtualElement),
+ provider = ko.bindingProvider['instance'],
+ preprocessNode = provider['preprocessNode'];
+
+ // Preprocessing allows a binding provider to mutate a node before bindings are applied to it. For example it's
+ // possible to insert new siblings after it, and/or replace the node with a different one. This can be used to
+ // implement custom binding syntaxes, such as {{ value }} for string interpolation, or custom element types that
+ // trigger insertion of <template> contents at that point in the document.
+ if (preprocessNode) {
+ while (currentChild = nextInQueue) {
+ nextInQueue = ko.virtualElements.nextSibling(currentChild);
+ preprocessNode.call(provider, currentChild);
+ }
+ // Reset nextInQueue for the next loop
+ nextInQueue = ko.virtualElements.firstChild(elementOrVirtualElement);
+ }
+
+ while (currentChild = nextInQueue) {
+ // Keep a record of the next child *before* applying bindings, in case the binding removes the current child from its position
+ nextInQueue = ko.virtualElements.nextSibling(currentChild);
+ applyBindingsToNodeAndDescendantsInternal(bindingContext, currentChild, bindingContextsMayDifferFromDomParentElement);
+ }
+ }
+
+ function applyBindingsToNodeAndDescendantsInternal (bindingContext, nodeVerified, bindingContextMayDifferFromDomParentElement) {
+ var shouldBindDescendants = true;
+
+ // Perf optimisation: Apply bindings only if...
+ // (1) We need to store the binding context on this node (because it may differ from the DOM parent node's binding context)
+ // Note that we can't store binding contexts on non-elements (e.g., text nodes), as IE doesn't allow expando properties for those
+ // (2) It might have bindings (e.g., it has a data-bind attribute, or it's a marker for a containerless template)
+ var isElement = (nodeVerified.nodeType === 1);
+ if (isElement) // Workaround IE <= 8 HTML parsing weirdness
+ ko.virtualElements.normaliseVirtualElementDomStructure(nodeVerified);
+
+ var shouldApplyBindings = (isElement && bindingContextMayDifferFromDomParentElement) // Case (1)
+ || ko.bindingProvider['instance']['nodeHasBindings'](nodeVerified); // Case (2)
+ if (shouldApplyBindings)
+ shouldBindDescendants = applyBindingsToNodeInternal(nodeVerified, null, bindingContext, bindingContextMayDifferFromDomParentElement)['shouldBindDescendants'];
+
+ if (shouldBindDescendants && !bindingDoesNotRecurseIntoElementTypes[ko.utils.tagNameLower(nodeVerified)]) {
+ // We're recursing automatically into (real or virtual) child nodes without changing binding contexts. So,
+ // * For children of a *real* element, the binding context is certainly the same as on their DOM .parentNode,
+ // hence bindingContextsMayDifferFromDomParentElement is false
+ // * For children of a *virtual* element, we can't be sure. Evaluating .parentNode on those children may
+ // skip over any number of intermediate virtual elements, any of which might define a custom binding context,
+ // hence bindingContextsMayDifferFromDomParentElement is true
+ applyBindingsToDescendantsInternal(bindingContext, nodeVerified, /* bindingContextsMayDifferFromDomParentElement: */ !isElement);
+ }
+ }
+
+ var boundElementDomDataKey = ko.utils.domData.nextKey();
+
+
+ function topologicalSortBindings(bindings) {
+ // Depth-first sort
+ var result = [], // The list of key/handler pairs that we will return
+ bindingsConsidered = {}, // A temporary record of which bindings are already in 'result'
+ cyclicDependencyStack = []; // Keeps track of a depth-search so that, if there's a cycle, we know which bindings caused it
+ ko.utils.objectForEach(bindings, function pushBinding(bindingKey) {
+ if (!bindingsConsidered[bindingKey]) {
+ var binding = ko['getBindingHandler'](bindingKey);
+ if (binding) {
+ // First add dependencies (if any) of the current binding
+ if (binding['after']) {
+ cyclicDependencyStack.push(bindingKey);
+ ko.utils.arrayForEach(binding['after'], function(bindingDependencyKey) {
+ if (bindings[bindingDependencyKey]) {
+ if (ko.utils.arrayIndexOf(cyclicDependencyStack, bindingDependencyKey) !== -1) {
+ throw Error("Cannot combine the following bindings, because they have a cyclic dependency: " + cyclicDependencyStack.join(", "));
+ } else {
+ pushBinding(bindingDependencyKey);
+ }
+ }
+ });
+ cyclicDependencyStack.length--;
+ }
+ // Next add the current binding
+ result.push({ key: bindingKey, handler: binding });
+ }
+ bindingsConsidered[bindingKey] = true;
+ }
+ });
+
+ return result;
+ }
+
+ function applyBindingsToNodeInternal(node, sourceBindings, bindingContext, bindingContextMayDifferFromDomParentElement) {
+ // Prevent multiple applyBindings calls for the same node, except when a binding value is specified
+ var alreadyBound = ko.utils.domData.get(node, boundElementDomDataKey);
+ if (!sourceBindings) {
+ if (alreadyBound) {
+ throw Error("You cannot apply bindings multiple times to the same element.");
+ }
+ ko.utils.domData.set(node, boundElementDomDataKey, true);
+ }
+
+ // Optimization: Don't store the binding context on this node if it's definitely the same as on node.parentNode, because
+ // we can easily recover it just by scanning up the node's ancestors in the DOM
+ // (note: here, parent node means "real DOM parent" not "virtual parent", as there's no O(1) way to find the virtual parent)
+ if (!alreadyBound && bindingContextMayDifferFromDomParentElement)
+ ko.storedBindingContextForNode(node, bindingContext);
+
+ // Use bindings if given, otherwise fall back on asking the bindings provider to give us some bindings
+ var bindings;
+ if (sourceBindings && typeof sourceBindings !== 'function') {
+ bindings = sourceBindings;
+ } else {
+ var provider = ko.bindingProvider['instance'],
+ getBindings = provider['getBindingAccessors'] || getBindingsAndMakeAccessors;
+
+ // Get the binding from the provider within a computed observable so that we can update the bindings whenever
+ // the binding context is updated or if the binding provider accesses observables.
+ var bindingsUpdater = ko.dependentObservable(
+ function() {
+ bindings = sourceBindings ? sourceBindings(bindingContext, node) : getBindings.call(provider, node, bindingContext);
+ // Register a dependency on the binding context to support obsevable view models.
+ if (bindings && bindingContext._subscribable)
+ bindingContext._subscribable();
+ return bindings;
+ },
+ null, { disposeWhenNodeIsRemoved: node }
+ );
+
+ if (!bindings || !bindingsUpdater.isActive())
+ bindingsUpdater = null;
+ }
+
+ var bindingHandlerThatControlsDescendantBindings;
+ if (bindings) {
+ // Return the value accessor for a given binding. When bindings are static (won't be updated because of a binding
+ // context update), just return the value accessor from the binding. Otherwise, return a function that always gets
+ // the latest binding value and registers a dependency on the binding updater.
+ var getValueAccessor = bindingsUpdater
+ ? function(bindingKey) {
+ return function() {
+ return evaluateValueAccessor(bindingsUpdater()[bindingKey]);
+ };
+ } : function(bindingKey) {
+ return bindings[bindingKey];
+ };
+
+ // Use of allBindings as a function is maintained for backwards compatibility, but its use is deprecated
+ function allBindings() {
+ return ko.utils.objectMap(bindingsUpdater ? bindingsUpdater() : bindings, evaluateValueAccessor);
+ }
+ // The following is the 3.x allBindings API
+ allBindings['get'] = function(key) {
+ return bindings[key] && evaluateValueAccessor(getValueAccessor(key));
+ };
+ allBindings['has'] = function(key) {
+ return key in bindings;
+ };
+
+ // First put the bindings into the right order
+ var orderedBindings = topologicalSortBindings(bindings);
+
+ // Go through the sorted bindings, calling init and update for each
+ ko.utils.arrayForEach(orderedBindings, function(bindingKeyAndHandler) {
+ // Note that topologicalSortBindings has already filtered out any nonexistent binding handlers,
+ // so bindingKeyAndHandler.handler will always be nonnull.
+ var handlerInitFn = bindingKeyAndHandler.handler["init"],
+ handlerUpdateFn = bindingKeyAndHandler.handler["update"],
+ bindingKey = bindingKeyAndHandler.key;
+
+ if (node.nodeType === 8) {
+ validateThatBindingIsAllowedForVirtualElements(bindingKey);
+ }
+
+ try {
+ // Run init, ignoring any dependencies
+ if (typeof handlerInitFn == "function") {
+ ko.dependencyDetection.ignore(function() {
+ var initResult = handlerInitFn(node, getValueAccessor(bindingKey), allBindings, bindingContext['$data'], bindingContext);
+
+ // If this binding handler claims to control descendant bindings, make a note of this
+ if (initResult && initResult['controlsDescendantBindings']) {
+ if (bindingHandlerThatControlsDescendantBindings !== undefined)
+ throw new Error("Multiple bindings (" + bindingHandlerThatControlsDescendantBindings + " and " + bindingKey + ") are trying to control descendant bindings of the same element. You cannot use these bindings together on the same element.");
+ bindingHandlerThatControlsDescendantBindings = bindingKey;
+ }
+ });
+ }
+
+ // Run update in its own computed wrapper
+ if (typeof handlerUpdateFn == "function") {
+ ko.dependentObservable(
+ function() {
+ handlerUpdateFn(node, getValueAccessor(bindingKey), allBindings, bindingContext['$data'], bindingContext);
+ },
+ null,
+ { disposeWhenNodeIsRemoved: node }
+ );
+ }
+ } catch (ex) {
+ ex.message = "Unable to process binding \"" + bindingKey + ": " + bindings[bindingKey] + "\"\nMessage: " + ex.message;
+ throw ex;
+ }
+ });
+ }
+
+ return {
+ 'shouldBindDescendants': bindingHandlerThatControlsDescendantBindings === undefined
+ };
+ };
+
+ var storedBindingContextDomDataKey = ko.utils.domData.nextKey();
+ ko.storedBindingContextForNode = function (node, bindingContext) {
+ if (arguments.length == 2) {
+ ko.utils.domData.set(node, storedBindingContextDomDataKey, bindingContext);
+ if (bindingContext._subscribable)
+ bindingContext._subscribable._addNode(node);
+ } else {
+ return ko.utils.domData.get(node, storedBindingContextDomDataKey);
+ }
+ }
+
+ function getBindingContext(viewModelOrBindingContext) {
+ return viewModelOrBindingContext && (viewModelOrBindingContext instanceof ko.bindingContext)
+ ? viewModelOrBindingContext
+ : new ko.bindingContext(viewModelOrBindingContext);
+ }
+
+ ko.applyBindingAccessorsToNode = function (node, bindings, viewModelOrBindingContext) {
+ if (node.nodeType === 1) // If it's an element, workaround IE <= 8 HTML parsing weirdness
+ ko.virtualElements.normaliseVirtualElementDomStructure(node);
+ return applyBindingsToNodeInternal(node, bindings, getBindingContext(viewModelOrBindingContext), true);
+ };
+
+ ko.applyBindingsToNode = function (node, bindings, viewModelOrBindingContext) {
+ var context = getBindingContext(viewModelOrBindingContext);
+ return ko.applyBindingAccessorsToNode(node, makeBindingAccessors(bindings, context, node), context);
+ };
+
+ ko.applyBindingsToDescendants = function(viewModelOrBindingContext, rootNode) {
+ if (rootNode.nodeType === 1 || rootNode.nodeType === 8)
+ applyBindingsToDescendantsInternal(getBindingContext(viewModelOrBindingContext), rootNode, true);
+ };
+
+ ko.applyBindings = function (viewModelOrBindingContext, rootNode) {
+ // If jQuery is loaded after Knockout, we won't initially have access to it. So save it here.
+ if (!jQuery && window['jQuery']) {
+ jQuery = window['jQuery'];
+ }
+
+ if (rootNode && (rootNode.nodeType !== 1) && (rootNode.nodeType !== 8))
+ throw new Error("ko.applyBindings: first parameter should be your view model; second parameter should be a DOM node");
+ rootNode = rootNode || window.document.body; // Make "rootNode" parameter optional
+
+ applyBindingsToNodeAndDescendantsInternal(getBindingContext(viewModelOrBindingContext), rootNode, true);
+ };
+
+ // Retrieving binding context from arbitrary nodes
+ ko.contextFor = function(node) {
+ // We can only do something meaningful for elements and comment nodes (in particular, not text nodes, as IE can't store domdata for them)
+ switch (node.nodeType) {
+ case 1:
+ case 8:
+ var context = ko.storedBindingContextForNode(node);
+ if (context) return context;
+ if (node.parentNode) return ko.contextFor(node.parentNode);
+ break;
+ }
+ return undefined;
+ };
+ ko.dataFor = function(node) {
+ var context = ko.contextFor(node);
+ return context ? context['$data'] : undefined;
+ };
+
+ ko.exportSymbol('bindingHandlers', ko.bindingHandlers);
+ ko.exportSymbol('applyBindings', ko.applyBindings);
+ ko.exportSymbol('applyBindingsToDescendants', ko.applyBindingsToDescendants);
+ ko.exportSymbol('applyBindingAccessorsToNode', ko.applyBindingAccessorsToNode);
+ ko.exportSymbol('applyBindingsToNode', ko.applyBindingsToNode);
+ ko.exportSymbol('contextFor', ko.contextFor);
+ ko.exportSymbol('dataFor', ko.dataFor);
+})();
+var attrHtmlToJavascriptMap = { 'class': 'className', 'for': 'htmlFor' };
+ko.bindingHandlers['attr'] = {
+ 'update': function(element, valueAccessor, allBindings) {
+ var value = ko.utils.unwrapObservable(valueAccessor()) || {};
+ ko.utils.objectForEach(value, function(attrName, attrValue) {
+ attrValue = ko.utils.unwrapObservable(attrValue);
+
+ // To cover cases like "attr: { checked:someProp }", we want to remove the attribute entirely
+ // when someProp is a "no value"-like value (strictly null, false, or undefined)
+ // (because the absence of the "checked" attr is how to mark an element as not checked, etc.)
+ var toRemove = (attrValue === false) || (attrValue === null) || (attrValue === undefined);
+ if (toRemove)
+ element.removeAttribute(attrName);
+
+ // In IE <= 7 and IE8 Quirks Mode, you have to use the Javascript property name instead of the
+ // HTML attribute name for certain attributes. IE8 Standards Mode supports the correct behavior,
+ // but instead of figuring out the mode, we'll just set the attribute through the Javascript
+ // property for IE <= 8.
+ if (ko.utils.ieVersion <= 8 && attrName in attrHtmlToJavascriptMap) {
+ attrName = attrHtmlToJavascriptMap[attrName];
+ if (toRemove)
+ element.removeAttribute(attrName);
+ else
+ element[attrName] = attrValue;
+ } else if (!toRemove) {
+ element.setAttribute(attrName, attrValue.toString());
+ }
+
+ // Treat "name" specially - although you can think of it as an attribute, it also needs
+ // special handling on older versions of IE (https://github.com/SteveSanderson/knockout/pull/333)
+ // Deliberately being case-sensitive here because XHTML would regard "Name" as a different thing
+ // entirely, and there's no strong reason to allow for such casing in HTML.
+ if (attrName === "name") {
+ ko.utils.setElementName(element, toRemove ? "" : attrValue.toString());
+ }
+ });
+ }
+};
+(function() {
+
+ko.bindingHandlers['checked'] = {
+ 'after': ['value', 'attr'],
+ 'init': function (element, valueAccessor, allBindings) {
+ function checkedValue() {
+ return allBindings['has']('checkedValue')
+ ? ko.utils.unwrapObservable(allBindings.get('checkedValue'))
+ : element.value;
+ }
+
+ function updateModel() {
+ // This updates the model value from the view value.
+ // It runs in response to DOM events (click) and changes in checkedValue.
+ var isChecked = element.checked,
+ elemValue = useCheckedValue ? checkedValue() : isChecked;
+
+ // When we're first setting up this computed, don't change any model state.
+ if (ko.computedContext.isInitial()) {
+ return;
+ }
+
+ // We can ignore unchecked radio buttons, because some other radio
+ // button will be getting checked, and that one can take care of updating state.
+ if (isRadio && !isChecked) {
+ return;
+ }
+
+ var modelValue = ko.dependencyDetection.ignore(valueAccessor);
+ if (isValueArray) {
+ if (oldElemValue !== elemValue) {
+ // When we're responding to the checkedValue changing, and the element is
+ // currently checked, replace the old elem value with the new elem value
+ // in the model array.
+ if (isChecked) {
+ ko.utils.addOrRemoveItem(modelValue, elemValue, true);
+ ko.utils.addOrRemoveItem(modelValue, oldElemValue, false);
+ }
+
+ oldElemValue = elemValue;
+ } else {
+ // When we're responding to the user having checked/unchecked a checkbox,
+ // add/remove the element value to the model array.
+ ko.utils.addOrRemoveItem(modelValue, elemValue, isChecked);
+ }
+ } else {
+ ko.expressionRewriting.writeValueToProperty(modelValue, allBindings, 'checked', elemValue, true);
+ }
+ };
+
+ function updateView() {
+ // This updates the view value from the model value.
+ // It runs in response to changes in the bound (checked) value.
+ var modelValue = ko.utils.unwrapObservable(valueAccessor());
+
+ if (isValueArray) {
+ // When a checkbox is bound to an array, being checked represents its value being present in that array
+ element.checked = ko.utils.arrayIndexOf(modelValue, checkedValue()) >= 0;
+ } else if (isCheckbox) {
+ // When a checkbox is bound to any other value (not an array), being checked represents the value being trueish
+ element.checked = modelValue;
+ } else {
+ // For radio buttons, being checked means that the radio button's value corresponds to the model value
+ element.checked = (checkedValue() === modelValue);
+ }
+ };
+
+ var isCheckbox = element.type == "checkbox",
+ isRadio = element.type == "radio";
+
+ // Only bind to check boxes and radio buttons
+ if (!isCheckbox && !isRadio) {
+ return;
+ }
+
+ var isValueArray = isCheckbox && (ko.utils.unwrapObservable(valueAccessor()) instanceof Array),
+ oldElemValue = isValueArray ? checkedValue() : undefined,
+ useCheckedValue = isRadio || isValueArray;
+
+ // IE 6 won't allow radio buttons to be selected unless they have a name
+ if (isRadio && !element.name)
+ ko.bindingHandlers['uniqueName']['init'](element, function() { return true });
+
+ // Set up two computeds to update the binding:
+
+ // The first responds to changes in the checkedValue value and to element clicks
+ ko.computed(updateModel, null, { disposeWhenNodeIsRemoved: element });
+ ko.utils.registerEventHandler(element, "click", updateModel);
+
+ // The second responds to changes in the model value (the one associated with the checked binding)
+ ko.computed(updateView, null, { disposeWhenNodeIsRemoved: element });
+ }
+};
+ko.expressionRewriting.twoWayBindings['checked'] = true;
+
+ko.bindingHandlers['checkedValue'] = {
+ 'update': function (element, valueAccessor) {
+ element.value = ko.utils.unwrapObservable(valueAccessor());
+ }
+};
+
+})();var classesWrittenByBindingKey = '__ko__cssValue';
+ko.bindingHandlers['css'] = {
+ 'update': function (element, valueAccessor) {
+ var value = ko.utils.unwrapObservable(valueAccessor());
+ if (typeof value == "object") {
+ ko.utils.objectForEach(value, function(className, shouldHaveClass) {
+ shouldHaveClass = ko.utils.unwrapObservable(shouldHaveClass);
+ ko.utils.toggleDomNodeCssClass(element, className, shouldHaveClass);
+ });
+ } else {
+ value = String(value || ''); // Make sure we don't try to store or set a non-string value
+ ko.utils.toggleDomNodeCssClass(element, element[classesWrittenByBindingKey], false);
+ element[classesWrittenByBindingKey] = value;
+ ko.utils.toggleDomNodeCssClass(element, value, true);
+ }
+ }
+};
+ko.bindingHandlers['enable'] = {
+ 'update': function (element, valueAccessor) {
+ var value = ko.utils.unwrapObservable(valueAccessor());
+ if (value && element.disabled)
+ element.removeAttribute("disabled");
+ else if ((!value) && (!element.disabled))
+ element.disabled = true;
+ }
+};
+
+ko.bindingHandlers['disable'] = {
+ 'update': function (element, valueAccessor) {
+ ko.bindingHandlers['enable']['update'](element, function() { return !ko.utils.unwrapObservable(valueAccessor()) });
+ }
+};
+// For certain common events (currently just 'click'), allow a simplified data-binding syntax
+// e.g. click:handler instead of the usual full-length event:{click:handler}
+function makeEventHandlerShortcut(eventName) {
+ ko.bindingHandlers[eventName] = {
+ 'init': function(element, valueAccessor, allBindings, viewModel, bindingContext) {
+ var newValueAccessor = function () {
+ var result = {};
+ result[eventName] = valueAccessor();
+ return result;
+ };
+ return ko.bindingHandlers['event']['init'].call(this, element, newValueAccessor, allBindings, viewModel, bindingContext);
+ }
+ }
+}
+
+ko.bindingHandlers['event'] = {
+ 'init' : function (element, valueAccessor, allBindings, viewModel, bindingContext) {
+ var eventsToHandle = valueAccessor() || {};
+ ko.utils.objectForEach(eventsToHandle, function(eventName) {
+ if (typeof eventName == "string") {
+ ko.utils.registerEventHandler(element, eventName, function (event) {
+ var handlerReturnValue;
+ var handlerFunction = valueAccessor()[eventName];
+ if (!handlerFunction)
+ return;
+
+ try {
+ // Take all the event args, and prefix with the viewmodel
+ var argsForHandler = ko.utils.makeArray(arguments);
+ viewModel = bindingContext['$data'];
+ argsForHandler.unshift(viewModel);
+ handlerReturnValue = handlerFunction.apply(viewModel, argsForHandler);
+ } finally {
+ if (handlerReturnValue !== true) { // Normally we want to prevent default action. Developer can override this be explicitly returning true.
+ if (event.preventDefault)
+ event.preventDefault();
+ else
+ event.returnValue = false;
+ }
+ }
+
+ var bubble = allBindings.get(eventName + 'Bubble') !== false;
+ if (!bubble) {
+ event.cancelBubble = true;
+ if (event.stopPropagation)
+ event.stopPropagation();
+ }
+ });
+ }
+ });
+ }
+};
+// "foreach: someExpression" is equivalent to "template: { foreach: someExpression }"
+// "foreach: { data: someExpression, afterAdd: myfn }" is equivalent to "template: { foreach: someExpression, afterAdd: myfn }"
+ko.bindingHandlers['foreach'] = {
+ makeTemplateValueAccessor: function(valueAccessor) {
+ return function() {
+ var modelValue = valueAccessor(),
+ unwrappedValue = ko.utils.peekObservable(modelValue); // Unwrap without setting a dependency here
+
+ // If unwrappedValue is the array, pass in the wrapped value on its own
+ // The value will be unwrapped and tracked within the template binding
+ // (See https://github.com/SteveSanderson/knockout/issues/523)
+ if ((!unwrappedValue) || typeof unwrappedValue.length == "number")
+ return { 'foreach': modelValue, 'templateEngine': ko.nativeTemplateEngine.instance };
+
+ // If unwrappedValue.data is the array, preserve all relevant options and unwrap again value so we get updates
+ ko.utils.unwrapObservable(modelValue);
+ return {
+ 'foreach': unwrappedValue['data'],
+ 'as': unwrappedValue['as'],
+ 'includeDestroyed': unwrappedValue['includeDestroyed'],
+ 'afterAdd': unwrappedValue['afterAdd'],
+ 'beforeRemove': unwrappedValue['beforeRemove'],
+ 'afterRender': unwrappedValue['afterRender'],
+ 'beforeMove': unwrappedValue['beforeMove'],
+ 'afterMove': unwrappedValue['afterMove'],
+ 'templateEngine': ko.nativeTemplateEngine.instance
+ };
+ };
+ },
+ 'init': function(element, valueAccessor, allBindings, viewModel, bindingContext) {
+ return ko.bindingHandlers['template']['init'](element, ko.bindingHandlers['foreach'].makeTemplateValueAccessor(valueAccessor));
+ },
+ 'update': function(element, valueAccessor, allBindings, viewModel, bindingContext) {
+ return ko.bindingHandlers['template']['update'](element, ko.bindingHandlers['foreach'].makeTemplateValueAccessor(valueAccessor), allBindings, viewModel, bindingContext);
+ }
+};
+ko.expressionRewriting.bindingRewriteValidators['foreach'] = false; // Can't rewrite control flow bindings
+ko.virtualElements.allowedBindings['foreach'] = true;
+var hasfocusUpdatingProperty = '__ko_hasfocusUpdating';
+var hasfocusLastValue = '__ko_hasfocusLastValue';
+ko.bindingHandlers['hasfocus'] = {
+ 'init': function(element, valueAccessor, allBindings) {
+ var handleElementFocusChange = function(isFocused) {
+ // Where possible, ignore which event was raised and determine focus state using activeElement,
+ // as this avoids phantom focus/blur events raised when changing tabs in modern browsers.
+ // However, not all KO-targeted browsers (Firefox 2) support activeElement. For those browsers,
+ // prevent a loss of focus when changing tabs/windows by setting a flag that prevents hasfocus
+ // from calling 'blur()' on the element when it loses focus.
+ // Discussion at https://github.com/SteveSanderson/knockout/pull/352
+ element[hasfocusUpdatingProperty] = true;
+ var ownerDoc = element.ownerDocument;
+ if ("activeElement" in ownerDoc) {
+ var active;
+ try {
+ active = ownerDoc.activeElement;
+ } catch(e) {
+ // IE9 throws if you access activeElement during page load (see issue #703)
+ active = ownerDoc.body;
+ }
+ isFocused = (active === element);
+ }
+ var modelValue = valueAccessor();
+ ko.expressionRewriting.writeValueToProperty(modelValue, allBindings, 'hasfocus', isFocused, true);
+
+ //cache the latest value, so we can avoid unnecessarily calling focus/blur in the update function
+ element[hasfocusLastValue] = isFocused;
+ element[hasfocusUpdatingProperty] = false;
+ };
+ var handleElementFocusIn = handleElementFocusChange.bind(null, true);
+ var handleElementFocusOut = handleElementFocusChange.bind(null, false);
+
+ ko.utils.registerEventHandler(element, "focus", handleElementFocusIn);
+ ko.utils.registerEventHandler(element, "focusin", handleElementFocusIn); // For IE
+ ko.utils.registerEventHandler(element, "blur", handleElementFocusOut);
+ ko.utils.registerEventHandler(element, "focusout", handleElementFocusOut); // For IE
+ },
+ 'update': function(element, valueAccessor) {
+ var value = !!ko.utils.unwrapObservable(valueAccessor()); //force boolean to compare with last value
+ if (!element[hasfocusUpdatingProperty] && element[hasfocusLastValue] !== value) {
+ value ? element.focus() : element.blur();
+ ko.dependencyDetection.ignore(ko.utils.triggerEvent, null, [element, value ? "focusin" : "focusout"]); // For IE, which doesn't reliably fire "focus" or "blur" events synchronously
+ }
+ }
+};
+ko.expressionRewriting.twoWayBindings['hasfocus'] = true;
+
+ko.bindingHandlers['hasFocus'] = ko.bindingHandlers['hasfocus']; // Make "hasFocus" an alias
+ko.expressionRewriting.twoWayBindings['hasFocus'] = true;
+ko.bindingHandlers['html'] = {
+ 'init': function() {
+ // Prevent binding on the dynamically-injected HTML (as developers are unlikely to expect that, and it has security implications)
+ return { 'controlsDescendantBindings': true };
+ },
+ 'update': function (element, valueAccessor) {
+ // setHtml will unwrap the value if needed
+ ko.utils.setHtml(element, valueAccessor());
+ }
+};
+// Makes a binding like with or if
+function makeWithIfBinding(bindingKey, isWith, isNot, makeContextCallback) {
+ ko.bindingHandlers[bindingKey] = {
+ 'init': function(element, valueAccessor, allBindings, viewModel, bindingContext) {
+ var didDisplayOnLastUpdate,
+ savedNodes;
+ ko.computed(function() {
+ var dataValue = ko.utils.unwrapObservable(valueAccessor()),
+ shouldDisplay = !isNot !== !dataValue, // equivalent to isNot ? !dataValue : !!dataValue
+ isFirstRender = !savedNodes,
+ needsRefresh = isFirstRender || isWith || (shouldDisplay !== didDisplayOnLastUpdate);
+
+ if (needsRefresh) {
+ // Save a copy of the inner nodes on the initial update, but only if we have dependencies.
+ if (isFirstRender && ko.computedContext.getDependenciesCount()) {
+ savedNodes = ko.utils.cloneNodes(ko.virtualElements.childNodes(element), true /* shouldCleanNodes */);
+ }
+
+ if (shouldDisplay) {
+ if (!isFirstRender) {
+ ko.virtualElements.setDomNodeChildren(element, ko.utils.cloneNodes(savedNodes));
+ }
+ ko.applyBindingsToDescendants(makeContextCallback ? makeContextCallback(bindingContext, dataValue) : bindingContext, element);
+ } else {
+ ko.virtualElements.emptyNode(element);
+ }
+
+ didDisplayOnLastUpdate = shouldDisplay;
+ }
+ }, null, { disposeWhenNodeIsRemoved: element });
+ return { 'controlsDescendantBindings': true };
+ }
+ };
+ ko.expressionRewriting.bindingRewriteValidators[bindingKey] = false; // Can't rewrite control flow bindings
+ ko.virtualElements.allowedBindings[bindingKey] = true;
+}
+
+// Construct the actual binding handlers
+makeWithIfBinding('if');
+makeWithIfBinding('ifnot', false /* isWith */, true /* isNot */);
+makeWithIfBinding('with', true /* isWith */, false /* isNot */,
+ function(bindingContext, dataValue) {
+ return bindingContext['createChildContext'](dataValue);
+ }
+);
+var captionPlaceholder = {};
+ko.bindingHandlers['options'] = {
+ 'init': function(element) {
+ if (ko.utils.tagNameLower(element) !== "select")
+ throw new Error("options binding applies only to SELECT elements");
+
+ // Remove all existing <option>s.
+ while (element.length > 0) {
+ element.remove(0);
+ }
+
+ // Ensures that the binding processor doesn't try to bind the options
+ return { 'controlsDescendantBindings': true };
+ },
+ 'update': function (element, valueAccessor, allBindings) {
+ function selectedOptions() {
+ return ko.utils.arrayFilter(element.options, function (node) { return node.selected; });
+ }
+
+ var selectWasPreviouslyEmpty = element.length == 0;
+ var previousScrollTop = (!selectWasPreviouslyEmpty && element.multiple) ? element.scrollTop : null;
+ var unwrappedArray = ko.utils.unwrapObservable(valueAccessor());
+ var includeDestroyed = allBindings.get('optionsIncludeDestroyed');
+ var arrayToDomNodeChildrenOptions = {};
+ var captionValue;
+ var filteredArray;
+ var previousSelectedValues;
+
+ if (element.multiple) {
+ previousSelectedValues = ko.utils.arrayMap(selectedOptions(), ko.selectExtensions.readValue);
+ } else {
+ previousSelectedValues = element.selectedIndex >= 0 ? [ ko.selectExtensions.readValue(element.options[element.selectedIndex]) ] : [];
+ }
+
+ if (unwrappedArray) {
+ if (typeof unwrappedArray.length == "undefined") // Coerce single value into array
+ unwrappedArray = [unwrappedArray];
+
+ // Filter out any entries marked as destroyed
+ filteredArray = ko.utils.arrayFilter(unwrappedArray, function(item) {
+ return includeDestroyed || item === undefined || item === null || !ko.utils.unwrapObservable(item['_destroy']);
+ });
+
+ // If caption is included, add it to the array
+ if (allBindings['has']('optionsCaption')) {
+ captionValue = ko.utils.unwrapObservable(allBindings.get('optionsCaption'));
+ // If caption value is null or undefined, don't show a caption
+ if (captionValue !== null && captionValue !== undefined) {
+ filteredArray.unshift(captionPlaceholder);
+ }
+ }
+ } else {
+ // If a falsy value is provided (e.g. null), we'll simply empty the select element
+ }
+
+ function applyToObject(object, predicate, defaultValue) {
+ var predicateType = typeof predicate;
+ if (predicateType == "function") // Given a function; run it against the data value
+ return predicate(object);
+ else if (predicateType == "string") // Given a string; treat it as a property name on the data value
+ return object[predicate];
+ else // Given no optionsText arg; use the data value itself
+ return defaultValue;
+ }
+
+ // The following functions can run at two different times:
+ // The first is when the whole array is being updated directly from this binding handler.
+ // The second is when an observable value for a specific array entry is updated.
+ // oldOptions will be empty in the first case, but will be filled with the previously generated option in the second.
+ var itemUpdate = false;
+ function optionForArrayItem(arrayEntry, index, oldOptions) {
+ if (oldOptions.length) {
+ previousSelectedValues = oldOptions[0].selected ? [ ko.selectExtensions.readValue(oldOptions[0]) ] : [];
+ itemUpdate = true;
+ }
+ var option = element.ownerDocument.createElement("option");
+ if (arrayEntry === captionPlaceholder) {
+ ko.utils.setTextContent(option, allBindings.get('optionsCaption'));
+ ko.selectExtensions.writeValue(option, undefined);
+ } else {
+ // Apply a value to the option element
+ var optionValue = applyToObject(arrayEntry, allBindings.get('optionsValue'), arrayEntry);
+ ko.selectExtensions.writeValue(option, ko.utils.unwrapObservable(optionValue));
+
+ // Apply some text to the option element
+ var optionText = applyToObject(arrayEntry, allBindings.get('optionsText'), optionValue);
+ ko.utils.setTextContent(option, optionText);
+ }
+ return [option];
+ }
+
+ // By using a beforeRemove callback, we delay the removal until after new items are added. This fixes a selection
+ // problem in IE<=8 and Firefox. See https://github.com/knockout/knockout/issues/1208
+ arrayToDomNodeChildrenOptions['beforeRemove'] =
+ function (option) {
+ element.removeChild(option);
+ };
+
+ function setSelectionCallback(arrayEntry, newOptions) {
+ // IE6 doesn't like us to assign selection to OPTION nodes before they're added to the document.
+ // That's why we first added them without selection. Now it's time to set the selection.
+ if (previousSelectedValues.length) {
+ var isSelected = ko.utils.arrayIndexOf(previousSelectedValues, ko.selectExtensions.readValue(newOptions[0])) >= 0;
+ ko.utils.setOptionNodeSelectionState(newOptions[0], isSelected);
+
+ // If this option was changed from being selected during a single-item update, notify the change
+ if (itemUpdate && !isSelected)
+ ko.dependencyDetection.ignore(ko.utils.triggerEvent, null, [element, "change"]);
+ }
+ }
+
+ var callback = setSelectionCallback;
+ if (allBindings['has']('optionsAfterRender')) {
+ callback = function(arrayEntry, newOptions) {
+ setSelectionCallback(arrayEntry, newOptions);
+ ko.dependencyDetection.ignore(allBindings.get('optionsAfterRender'), null, [newOptions[0], arrayEntry !== captionPlaceholder ? arrayEntry : undefined]);
+ }
+ }
+
+ ko.utils.setDomNodeChildrenFromArrayMapping(element, filteredArray, optionForArrayItem, arrayToDomNodeChildrenOptions, callback);
+
+ ko.dependencyDetection.ignore(function () {
+ if (allBindings.get('valueAllowUnset') && allBindings['has']('value')) {
+ // The model value is authoritative, so make sure its value is the one selected
+ ko.selectExtensions.writeValue(element, ko.utils.unwrapObservable(allBindings.get('value')), true /* allowUnset */);
+ } else {
+ // Determine if the selection has changed as a result of updating the options list
+ var selectionChanged;
+ if (element.multiple) {
+ // For a multiple-select box, compare the new selection count to the previous one
+ // But if nothing was selected before, the selection can't have changed
+ selectionChanged = previousSelectedValues.length && selectedOptions().length < previousSelectedValues.length;
+ } else {
+ // For a single-select box, compare the current value to the previous value
+ // But if nothing was selected before or nothing is selected now, just look for a change in selection
+ selectionChanged = (previousSelectedValues.length && element.selectedIndex >= 0)
+ ? (ko.selectExtensions.readValue(element.options[element.selectedIndex]) !== previousSelectedValues[0])
+ : (previousSelectedValues.length || element.selectedIndex >= 0);
+ }
+
+ // Ensure consistency between model value and selected option.
+ // If the dropdown was changed so that selection is no longer the same,
+ // notify the value or selectedOptions binding.
+ if (selectionChanged) {
+ ko.utils.triggerEvent(element, "change");
+ }
+ }
+ });
+
+ // Workaround for IE bug
+ ko.utils.ensureSelectElementIsRenderedCorrectly(element);
+
+ if (previousScrollTop && Math.abs(previousScrollTop - element.scrollTop) > 20)
+ element.scrollTop = previousScrollTop;
+ }
+};
+ko.bindingHandlers['options'].optionValueDomDataKey = ko.utils.domData.nextKey();
+ko.bindingHandlers['selectedOptions'] = {
+ 'after': ['options', 'foreach'],
+ 'init': function (element, valueAccessor, allBindings) {
+ ko.utils.registerEventHandler(element, "change", function () {
+ var value = valueAccessor(), valueToWrite = [];
+ ko.utils.arrayForEach(element.getElementsByTagName("option"), function(node) {
+ if (node.selected)
+ valueToWrite.push(ko.selectExtensions.readValue(node));
+ });
+ ko.expressionRewriting.writeValueToProperty(value, allBindings, 'selectedOptions', valueToWrite);
+ });
+ },
+ 'update': function (element, valueAccessor) {
+ if (ko.utils.tagNameLower(element) != "select")
+ throw new Error("values binding applies only to SELECT elements");
+
+ var newValue = ko.utils.unwrapObservable(valueAccessor());
+ if (newValue && typeof newValue.length == "number") {
+ ko.utils.arrayForEach(element.getElementsByTagName("option"), function(node) {
+ var isSelected = ko.utils.arrayIndexOf(newValue, ko.selectExtensions.readValue(node)) >= 0;
+ ko.utils.setOptionNodeSelectionState(node, isSelected);
+ });
+ }
+ }
+};
+ko.expressionRewriting.twoWayBindings['selectedOptions'] = true;
+ko.bindingHandlers['style'] = {
+ 'update': function (element, valueAccessor) {
+ var value = ko.utils.unwrapObservable(valueAccessor() || {});
+ ko.utils.objectForEach(value, function(styleName, styleValue) {
+ styleValue = ko.utils.unwrapObservable(styleValue);
+ element.style[styleName] = styleValue || ""; // Empty string removes the value, whereas null/undefined have no effect
+ });
+ }
+};
+ko.bindingHandlers['submit'] = {
+ 'init': function (element, valueAccessor, allBindings, viewModel, bindingContext) {
+ if (typeof valueAccessor() != "function")
+ throw new Error("The value for a submit binding must be a function");
+ ko.utils.registerEventHandler(element, "submit", function (event) {
+ var handlerReturnValue;
+ var value = valueAccessor();
+ try { handlerReturnValue = value.call(bindingContext['$data'], element); }
+ finally {
+ if (handlerReturnValue !== true) { // Normally we want to prevent default action. Developer can override this be explicitly returning true.
+ if (event.preventDefault)
+ event.preventDefault();
+ else
+ event.returnValue = false;
+ }
+ }
+ });
+ }
+};
+ko.bindingHandlers['text'] = {
+ 'init': function() {
+ // Prevent binding on the dynamically-injected text node (as developers are unlikely to expect that, and it has security implications).
+ // It should also make things faster, as we no longer have to consider whether the text node might be bindable.
+ return { 'controlsDescendantBindings': true };
+ },
+ 'update': function (element, valueAccessor) {
+ ko.utils.setTextContent(element, valueAccessor());
+ }
+};
+ko.virtualElements.allowedBindings['text'] = true;
+ko.bindingHandlers['uniqueName'] = {
+ 'init': function (element, valueAccessor) {
+ if (valueAccessor()) {
+ var name = "ko_unique_" + (++ko.bindingHandlers['uniqueName'].currentIndex);
+ ko.utils.setElementName(element, name);
+ }
+ }
+};
+ko.bindingHandlers['uniqueName'].currentIndex = 0;
+ko.bindingHandlers['value'] = {
+ 'after': ['options', 'foreach'],
+ 'init': function (element, valueAccessor, allBindings) {
+ // Always catch "change" event; possibly other events too if asked
+ var eventsToCatch = ["change"];
+ var requestedEventsToCatch = allBindings.get("valueUpdate");
+ var propertyChangedFired = false;
+ if (requestedEventsToCatch) {
+ if (typeof requestedEventsToCatch == "string") // Allow both individual event names, and arrays of event names
+ requestedEventsToCatch = [requestedEventsToCatch];
+ ko.utils.arrayPushAll(eventsToCatch, requestedEventsToCatch);
+ eventsToCatch = ko.utils.arrayGetDistinctValues(eventsToCatch);
+ }
+
+ var valueUpdateHandler = function() {
+ propertyChangedFired = false;
+ var modelValue = valueAccessor();
+ var elementValue = ko.selectExtensions.readValue(element);
+ ko.expressionRewriting.writeValueToProperty(modelValue, allBindings, 'value', elementValue);
+ }
+
+ // Workaround for https://github.com/SteveSanderson/knockout/issues/122
+ // IE doesn't fire "change" events on textboxes if the user selects a value from its autocomplete list
+ var ieAutoCompleteHackNeeded = ko.utils.ieVersion && element.tagName.toLowerCase() == "input" && element.type == "text"
+ && element.autocomplete != "off" && (!element.form || element.form.autocomplete != "off");
+ if (ieAutoCompleteHackNeeded && ko.utils.arrayIndexOf(eventsToCatch, "propertychange") == -1) {
+ ko.utils.registerEventHandler(element, "propertychange", function () { propertyChangedFired = true });
+ ko.utils.registerEventHandler(element, "focus", function () { propertyChangedFired = false });
+ ko.utils.registerEventHandler(element, "blur", function() {
+ if (propertyChangedFired) {
+ valueUpdateHandler();
+ }
+ });
+ }
+
+ ko.utils.arrayForEach(eventsToCatch, function(eventName) {
+ // The syntax "after<eventname>" means "run the handler asynchronously after the event"
+ // This is useful, for example, to catch "keydown" events after the browser has updated the control
+ // (otherwise, ko.selectExtensions.readValue(this) will receive the control's value *before* the key event)
+ var handler = valueUpdateHandler;
+ if (ko.utils.stringStartsWith(eventName, "after")) {
+ handler = function() { setTimeout(valueUpdateHandler, 0) };
+ eventName = eventName.substring("after".length);
+ }
+ ko.utils.registerEventHandler(element, eventName, handler);
+ });
+ },
+ 'update': function (element, valueAccessor, allBindings) {
+ var newValue = ko.utils.unwrapObservable(valueAccessor());
+ var elementValue = ko.selectExtensions.readValue(element);
+ var valueHasChanged = (newValue !== elementValue);
+
+ if (valueHasChanged) {
+ if (ko.utils.tagNameLower(element) === "select") {
+ var allowUnset = allBindings.get('valueAllowUnset');
+ var applyValueAction = function () {
+ ko.selectExtensions.writeValue(element, newValue, allowUnset);
+ };
+ applyValueAction();
+
+ if (!allowUnset && newValue !== ko.selectExtensions.readValue(element)) {
+ // If you try to set a model value that can't be represented in an already-populated dropdown, reject that change,
+ // because you're not allowed to have a model value that disagrees with a visible UI selection.
+ ko.dependencyDetection.ignore(ko.utils.triggerEvent, null, [element, "change"]);
+ } else {
+ // Workaround for IE6 bug: It won't reliably apply values to SELECT nodes during the same execution thread
+ // right after you've changed the set of OPTION nodes on it. So for that node type, we'll schedule a second thread
+ // to apply the value as well.
+ setTimeout(applyValueAction, 0);
+ }
+ } else {
+ ko.selectExtensions.writeValue(element, newValue);
+ }
+ }
+ }
+};
+ko.expressionRewriting.twoWayBindings['value'] = true;
+ko.bindingHandlers['visible'] = {
+ 'update': function (element, valueAccessor) {
+ var value = ko.utils.unwrapObservable(valueAccessor());
+ var isCurrentlyVisible = !(element.style.display == "none");
+ if (value && !isCurrentlyVisible)
+ element.style.display = "";
+ else if ((!value) && isCurrentlyVisible)
+ element.style.display = "none";
+ }
+};
+// 'click' is just a shorthand for the usual full-length event:{click:handler}
+makeEventHandlerShortcut('click');
+// If you want to make a custom template engine,
+//
+// [1] Inherit from this class (like ko.nativeTemplateEngine does)
+// [2] Override 'renderTemplateSource', supplying a function with this signature:
+//
+// function (templateSource, bindingContext, options) {
+// // - templateSource.text() is the text of the template you should render
+// // - bindingContext.$data is the data you should pass into the template
+// // - you might also want to make bindingContext.$parent, bindingContext.$parents,
+// // and bindingContext.$root available in the template too
+// // - options gives you access to any other properties set on "data-bind: { template: options }"
+// //
+// // Return value: an array of DOM nodes
+// }
+//
+// [3] Override 'createJavaScriptEvaluatorBlock', supplying a function with this signature:
+//
+// function (script) {
+// // Return value: Whatever syntax means "Evaluate the JavaScript statement 'script' and output the result"
+// // For example, the jquery.tmpl template engine converts 'someScript' to '${ someScript }'
+// }
+//
+// This is only necessary if you want to allow data-bind attributes to reference arbitrary template variables.
+// If you don't want to allow that, you can set the property 'allowTemplateRewriting' to false (like ko.nativeTemplateEngine does)
+// and then you don't need to override 'createJavaScriptEvaluatorBlock'.
+
+ko.templateEngine = function () { };
+
+ko.templateEngine.prototype['renderTemplateSource'] = function (templateSource, bindingContext, options) {
+ throw new Error("Override renderTemplateSource");
+};
+
+ko.templateEngine.prototype['createJavaScriptEvaluatorBlock'] = function (script) {
+ throw new Error("Override createJavaScriptEvaluatorBlock");
+};
+
+ko.templateEngine.prototype['makeTemplateSource'] = function(template, templateDocument) {
+ // Named template
+ if (typeof template == "string") {
+ templateDocument = templateDocument || document;
+ var elem = templateDocument.getElementById(template);
+ if (!elem)
+ throw new Error("Cannot find template with ID " + template);
+ return new ko.templateSources.domElement(elem);
+ } else if ((template.nodeType == 1) || (template.nodeType == 8)) {
+ // Anonymous template
+ return new ko.templateSources.anonymousTemplate(template);
+ } else
+ throw new Error("Unknown template type: " + template);
+};
+
+ko.templateEngine.prototype['renderTemplate'] = function (template, bindingContext, options, templateDocument) {
+ var templateSource = this['makeTemplateSource'](template, templateDocument);
+ return this['renderTemplateSource'](templateSource, bindingContext, options);
+};
+
+ko.templateEngine.prototype['isTemplateRewritten'] = function (template, templateDocument) {
+ // Skip rewriting if requested
+ if (this['allowTemplateRewriting'] === false)
+ return true;
+ return this['makeTemplateSource'](template, templateDocument)['data']("isRewritten");
+};
+
+ko.templateEngine.prototype['rewriteTemplate'] = function (template, rewriterCallback, templateDocument) {
+ var templateSource = this['makeTemplateSource'](template, templateDocument);
+ var rewritten = rewriterCallback(templateSource['text']());
+ templateSource['text'](rewritten);
+ templateSource['data']("isRewritten", true);
+};
+
+ko.exportSymbol('templateEngine', ko.templateEngine);
+
+ko.templateRewriting = (function () {
+ var memoizeDataBindingAttributeSyntaxRegex = /(<([a-z]+\d*)(?:\s+(?!data-bind\s*=\s*)[a-z0-9\-]+(?:=(?:\"[^\"]*\"|\'[^\']*\'))?)*\s+)data-bind\s*=\s*(["'])([\s\S]*?)\3/gi;
+ var memoizeVirtualContainerBindingSyntaxRegex = /<!--\s*ko\b\s*([\s\S]*?)\s*-->/g;
+
+ function validateDataBindValuesForRewriting(keyValueArray) {
+ var allValidators = ko.expressionRewriting.bindingRewriteValidators;
+ for (var i = 0; i < keyValueArray.length; i++) {
+ var key = keyValueArray[i]['key'];
+ if (allValidators.hasOwnProperty(key)) {
+ var validator = allValidators[key];
+
+ if (typeof validator === "function") {
+ var possibleErrorMessage = validator(keyValueArray[i]['value']);
+ if (possibleErrorMessage)
+ throw new Error(possibleErrorMessage);
+ } else if (!validator) {
+ throw new Error("This template engine does not support the '" + key + "' binding within its templates");
+ }
+ }
+ }
+ }
+
+ function constructMemoizedTagReplacement(dataBindAttributeValue, tagToRetain, nodeName, templateEngine) {
+ var dataBindKeyValueArray = ko.expressionRewriting.parseObjectLiteral(dataBindAttributeValue);
+ validateDataBindValuesForRewriting(dataBindKeyValueArray);
+ var rewrittenDataBindAttributeValue = ko.expressionRewriting.preProcessBindings(dataBindKeyValueArray, {'valueAccessors':true});
+
+ // For no obvious reason, Opera fails to evaluate rewrittenDataBindAttributeValue unless it's wrapped in an additional
+ // anonymous function, even though Opera's built-in debugger can evaluate it anyway. No other browser requires this
+ // extra indirection.
+ var applyBindingsToNextSiblingScript =
+ "ko.__tr_ambtns(function($context,$element){return(function(){return{ " + rewrittenDataBindAttributeValue + " } })()},'" + nodeName.toLowerCase() + "')";
+ return templateEngine['createJavaScriptEvaluatorBlock'](applyBindingsToNextSiblingScript) + tagToRetain;
+ }
+
+ return {
+ ensureTemplateIsRewritten: function (template, templateEngine, templateDocument) {
+ if (!templateEngine['isTemplateRewritten'](template, templateDocument))
+ templateEngine['rewriteTemplate'](template, function (htmlString) {
+ return ko.templateRewriting.memoizeBindingAttributeSyntax(htmlString, templateEngine);
+ }, templateDocument);
+ },
+
+ memoizeBindingAttributeSyntax: function (htmlString, templateEngine) {
+ return htmlString.replace(memoizeDataBindingAttributeSyntaxRegex, function () {
+ return constructMemoizedTagReplacement(/* dataBindAttributeValue: */ arguments[4], /* tagToRetain: */ arguments[1], /* nodeName: */ arguments[2], templateEngine);
+ }).replace(memoizeVirtualContainerBindingSyntaxRegex, function() {
+ return constructMemoizedTagReplacement(/* dataBindAttributeValue: */ arguments[1], /* tagToRetain: */ "<!-- ko -->", /* nodeName: */ "#comment", templateEngine);
+ });
+ },
+
+ applyMemoizedBindingsToNextSibling: function (bindings, nodeName) {
+ return ko.memoization.memoize(function (domNode, bindingContext) {
+ var nodeToBind = domNode.nextSibling;
+ if (nodeToBind && nodeToBind.nodeName.toLowerCase() === nodeName) {
+ ko.applyBindingAccessorsToNode(nodeToBind, bindings, bindingContext);
+ }
+ });
+ }
+ }
+})();
+
+
+// Exported only because it has to be referenced by string lookup from within rewritten template
+ko.exportSymbol('__tr_ambtns', ko.templateRewriting.applyMemoizedBindingsToNextSibling);
+(function() {
+ // A template source represents a read/write way of accessing a template. This is to eliminate the need for template loading/saving
+ // logic to be duplicated in every template engine (and means they can all work with anonymous templates, etc.)
+ //
+ // Two are provided by default:
+ // 1. ko.templateSources.domElement - reads/writes the text content of an arbitrary DOM element
+ // 2. ko.templateSources.anonymousElement - uses ko.utils.domData to read/write text *associated* with the DOM element, but
+ // without reading/writing the actual element text content, since it will be overwritten
+ // with the rendered template output.
+ // You can implement your own template source if you want to fetch/store templates somewhere other than in DOM elements.
+ // Template sources need to have the following functions:
+ // text() - returns the template text from your storage location
+ // text(value) - writes the supplied template text to your storage location
+ // data(key) - reads values stored using data(key, value) - see below
+ // data(key, value) - associates "value" with this template and the key "key". Is used to store information like "isRewritten".
+ //
+ // Optionally, template sources can also have the following functions:
+ // nodes() - returns a DOM element containing the nodes of this template, where available
+ // nodes(value) - writes the given DOM element to your storage location
+ // If a DOM element is available for a given template source, template engines are encouraged to use it in preference over text()
+ // for improved speed. However, all templateSources must supply text() even if they don't supply nodes().
+ //
+ // Once you've implemented a templateSource, make your template engine use it by subclassing whatever template engine you were
+ // using and overriding "makeTemplateSource" to return an instance of your custom template source.
+
+ ko.templateSources = {};
+
+ // ---- ko.templateSources.domElement -----
+
+ ko.templateSources.domElement = function(element) {
+ this.domElement = element;
+ }
+
+ ko.templateSources.domElement.prototype['text'] = function(/* valueToWrite */) {
+ var tagNameLower = ko.utils.tagNameLower(this.domElement),
+ elemContentsProperty = tagNameLower === "script" ? "text"
+ : tagNameLower === "textarea" ? "value"
+ : "innerHTML";
+
+ if (arguments.length == 0) {
+ return this.domElement[elemContentsProperty];
+ } else {
+ var valueToWrite = arguments[0];
+ if (elemContentsProperty === "innerHTML")
+ ko.utils.setHtml(this.domElement, valueToWrite);
+ else
+ this.domElement[elemContentsProperty] = valueToWrite;
+ }
+ };
+
+ var dataDomDataPrefix = ko.utils.domData.nextKey() + "_";
+ ko.templateSources.domElement.prototype['data'] = function(key /*, valueToWrite */) {
+ if (arguments.length === 1) {
+ return ko.utils.domData.get(this.domElement, dataDomDataPrefix + key);
+ } else {
+ ko.utils.domData.set(this.domElement, dataDomDataPrefix + key, arguments[1]);
+ }
+ };
+
+ // ---- ko.templateSources.anonymousTemplate -----
+ // Anonymous templates are normally saved/retrieved as DOM nodes through "nodes".
+ // For compatibility, you can also read "text"; it will be serialized from the nodes on demand.
+ // Writing to "text" is still supported, but then the template data will not be available as DOM nodes.
+
+ var anonymousTemplatesDomDataKey = ko.utils.domData.nextKey();
+ ko.templateSources.anonymousTemplate = function(element) {
+ this.domElement = element;
+ }
+ ko.templateSources.anonymousTemplate.prototype = new ko.templateSources.domElement();
+ ko.templateSources.anonymousTemplate.prototype.constructor = ko.templateSources.anonymousTemplate;
+ ko.templateSources.anonymousTemplate.prototype['text'] = function(/* valueToWrite */) {
+ if (arguments.length == 0) {
+ var templateData = ko.utils.domData.get(this.domElement, anonymousTemplatesDomDataKey) || {};
+ if (templateData.textData === undefined && templateData.containerData)
+ templateData.textData = templateData.containerData.innerHTML;
+ return templateData.textData;
+ } else {
+ var valueToWrite = arguments[0];
+ ko.utils.domData.set(this.domElement, anonymousTemplatesDomDataKey, {textData: valueToWrite});
+ }
+ };
+ ko.templateSources.domElement.prototype['nodes'] = function(/* valueToWrite */) {
+ if (arguments.length == 0) {
+ var templateData = ko.utils.domData.get(this.domElement, anonymousTemplatesDomDataKey) || {};
+ return templateData.containerData;
+ } else {
+ var valueToWrite = arguments[0];
+ ko.utils.domData.set(this.domElement, anonymousTemplatesDomDataKey, {containerData: valueToWrite});
+ }
+ };
+
+ ko.exportSymbol('templateSources', ko.templateSources);
+ ko.exportSymbol('templateSources.domElement', ko.templateSources.domElement);
+ ko.exportSymbol('templateSources.anonymousTemplate', ko.templateSources.anonymousTemplate);
+})();
+(function () {
+ var _templateEngine;
+ ko.setTemplateEngine = function (templateEngine) {
+ if ((templateEngine != undefined) && !(templateEngine instanceof ko.templateEngine))
+ throw new Error("templateEngine must inherit from ko.templateEngine");
+ _templateEngine = templateEngine;
+ }
+
+ function invokeForEachNodeInContinuousRange(firstNode, lastNode, action) {
+ var node, nextInQueue = firstNode, firstOutOfRangeNode = ko.virtualElements.nextSibling(lastNode);
+ while (nextInQueue && ((node = nextInQueue) !== firstOutOfRangeNode)) {
+ nextInQueue = ko.virtualElements.nextSibling(node);
+ action(node, nextInQueue);
+ }
+ }
+
+ function activateBindingsOnContinuousNodeArray(continuousNodeArray, bindingContext) {
+ // To be used on any nodes that have been rendered by a template and have been inserted into some parent element
+ // Walks through continuousNodeArray (which *must* be continuous, i.e., an uninterrupted sequence of sibling nodes, because
+ // the algorithm for walking them relies on this), and for each top-level item in the virtual-element sense,
+ // (1) Does a regular "applyBindings" to associate bindingContext with this node and to activate any non-memoized bindings
+ // (2) Unmemoizes any memos in the DOM subtree (e.g., to activate bindings that had been memoized during template rewriting)
+
+ if (continuousNodeArray.length) {
+ var firstNode = continuousNodeArray[0],
+ lastNode = continuousNodeArray[continuousNodeArray.length - 1],
+ parentNode = firstNode.parentNode,
+ provider = ko.bindingProvider['instance'],
+ preprocessNode = provider['preprocessNode'];
+
+ if (preprocessNode) {
+ invokeForEachNodeInContinuousRange(firstNode, lastNode, function(node, nextNodeInRange) {
+ var nodePreviousSibling = node.previousSibling;
+ var newNodes = preprocessNode.call(provider, node);
+ if (newNodes) {
+ if (node === firstNode)
+ firstNode = newNodes[0] || nextNodeInRange;
+ if (node === lastNode)
+ lastNode = newNodes[newNodes.length - 1] || nodePreviousSibling;
+ }
+ });
+
+ // Because preprocessNode can change the nodes, including the first and last nodes, update continuousNodeArray to match.
+ // We need the full set, including inner nodes, because the unmemoize step might remove the first node (and so the real
+ // first node needs to be in the array).
+ continuousNodeArray.length = 0;
+ if (!firstNode) { // preprocessNode might have removed all the nodes, in which case there's nothing left to do
+ return;
+ }
+ if (firstNode === lastNode) {
+ continuousNodeArray.push(firstNode);
+ } else {
+ continuousNodeArray.push(firstNode, lastNode);
+ ko.utils.fixUpContinuousNodeArray(continuousNodeArray, parentNode);
+ }
+ }
+
+ // Need to applyBindings *before* unmemoziation, because unmemoization might introduce extra nodes (that we don't want to re-bind)
+ // whereas a regular applyBindings won't introduce new memoized nodes
+ invokeForEachNodeInContinuousRange(firstNode, lastNode, function(node) {
+ if (node.nodeType === 1 || node.nodeType === 8)
+ ko.applyBindings(bindingContext, node);
+ });
+ invokeForEachNodeInContinuousRange(firstNode, lastNode, function(node) {
+ if (node.nodeType === 1 || node.nodeType === 8)
+ ko.memoization.unmemoizeDomNodeAndDescendants(node, [bindingContext]);
+ });
+
+ // Make sure any changes done by applyBindings or unmemoize are reflected in the array
+ ko.utils.fixUpContinuousNodeArray(continuousNodeArray, parentNode);
+ }
+ }
+
+ function getFirstNodeFromPossibleArray(nodeOrNodeArray) {
+ return nodeOrNodeArray.nodeType ? nodeOrNodeArray
+ : nodeOrNodeArray.length > 0 ? nodeOrNodeArray[0]
+ : null;
+ }
+
+ function executeTemplate(targetNodeOrNodeArray, renderMode, template, bindingContext, options) {
+ options = options || {};
+ var firstTargetNode = targetNodeOrNodeArray && getFirstNodeFromPossibleArray(targetNodeOrNodeArray);
+ var templateDocument = firstTargetNode && firstTargetNode.ownerDocument;
+ var templateEngineToUse = (options['templateEngine'] || _templateEngine);
+ ko.templateRewriting.ensureTemplateIsRewritten(template, templateEngineToUse, templateDocument);
+ var renderedNodesArray = templateEngineToUse['renderTemplate'](template, bindingContext, options, templateDocument);
+
+ // Loosely check result is an array of DOM nodes
+ if ((typeof renderedNodesArray.length != "number") || (renderedNodesArray.length > 0 && typeof renderedNodesArray[0].nodeType != "number"))
+ throw new Error("Template engine must return an array of DOM nodes");
+
+ var haveAddedNodesToParent = false;
+ switch (renderMode) {
+ case "replaceChildren":
+ ko.virtualElements.setDomNodeChildren(targetNodeOrNodeArray, renderedNodesArray);
+ haveAddedNodesToParent = true;
+ break;
+ case "replaceNode":
+ ko.utils.replaceDomNodes(targetNodeOrNodeArray, renderedNodesArray);
+ haveAddedNodesToParent = true;
+ break;
+ case "ignoreTargetNode": break;
+ default:
+ throw new Error("Unknown renderMode: " + renderMode);
+ }
+
+ if (haveAddedNodesToParent) {
+ activateBindingsOnContinuousNodeArray(renderedNodesArray, bindingContext);
+ if (options['afterRender'])
+ ko.dependencyDetection.ignore(options['afterRender'], null, [renderedNodesArray, bindingContext['$data']]);
+ }
+
+ return renderedNodesArray;
+ }
+
+ ko.renderTemplate = function (template, dataOrBindingContext, options, targetNodeOrNodeArray, renderMode) {
+ options = options || {};
+ if ((options['templateEngine'] || _templateEngine) == undefined)
+ throw new Error("Set a template engine before calling renderTemplate");
+ renderMode = renderMode || "replaceChildren";
+
+ if (targetNodeOrNodeArray) {
+ var firstTargetNode = getFirstNodeFromPossibleArray(targetNodeOrNodeArray);
+
+ var whenToDispose = function () { return (!firstTargetNode) || !ko.utils.domNodeIsAttachedToDocument(firstTargetNode); }; // Passive disposal (on next evaluation)
+ var activelyDisposeWhenNodeIsRemoved = (firstTargetNode && renderMode == "replaceNode") ? firstTargetNode.parentNode : firstTargetNode;
+
+ return ko.dependentObservable( // So the DOM is automatically updated when any dependency changes
+ function () {
+ // Ensure we've got a proper binding context to work with
+ var bindingContext = (dataOrBindingContext && (dataOrBindingContext instanceof ko.bindingContext))
+ ? dataOrBindingContext
+ : new ko.bindingContext(ko.utils.unwrapObservable(dataOrBindingContext));
+
+ // Support selecting template as a function of the data being rendered
+ var templateName = ko.isObservable(template) ? template()
+ : typeof(template) == 'function' ? template(bindingContext['$data'], bindingContext) : template;
+
+ var renderedNodesArray = executeTemplate(targetNodeOrNodeArray, renderMode, templateName, bindingContext, options);
+ if (renderMode == "replaceNode") {
+ targetNodeOrNodeArray = renderedNodesArray;
+ firstTargetNode = getFirstNodeFromPossibleArray(targetNodeOrNodeArray);
+ }
+ },
+ null,
+ { disposeWhen: whenToDispose, disposeWhenNodeIsRemoved: activelyDisposeWhenNodeIsRemoved }
+ );
+ } else {
+ // We don't yet have a DOM node to evaluate, so use a memo and render the template later when there is a DOM node
+ return ko.memoization.memoize(function (domNode) {
+ ko.renderTemplate(template, dataOrBindingContext, options, domNode, "replaceNode");
+ });
+ }
+ };
+
+ ko.renderTemplateForEach = function (template, arrayOrObservableArray, options, targetNode, parentBindingContext) {
+ // Since setDomNodeChildrenFromArrayMapping always calls executeTemplateForArrayItem and then
+ // activateBindingsCallback for added items, we can store the binding context in the former to use in the latter.
+ var arrayItemContext;
+
+ // This will be called by setDomNodeChildrenFromArrayMapping to get the nodes to add to targetNode
+ var executeTemplateForArrayItem = function (arrayValue, index) {
+ // Support selecting template as a function of the data being rendered
+ arrayItemContext = parentBindingContext['createChildContext'](arrayValue, options['as'], function(context) {
+ context['$index'] = index;
+ });
+ var templateName = typeof(template) == 'function' ? template(arrayValue, arrayItemContext) : template;
+ return executeTemplate(null, "ignoreTargetNode", templateName, arrayItemContext, options);
+ }
+
+ // This will be called whenever setDomNodeChildrenFromArrayMapping has added nodes to targetNode
+ var activateBindingsCallback = function(arrayValue, addedNodesArray, index) {
+ activateBindingsOnContinuousNodeArray(addedNodesArray, arrayItemContext);
+ if (options['afterRender'])
+ options['afterRender'](addedNodesArray, arrayValue);
+ };
+
+ return ko.dependentObservable(function () {
+ var unwrappedArray = ko.utils.unwrapObservable(arrayOrObservableArray) || [];
+ if (typeof unwrappedArray.length == "undefined") // Coerce single value into array
+ unwrappedArray = [unwrappedArray];
+
+ // Filter out any entries marked as destroyed
+ var filteredArray = ko.utils.arrayFilter(unwrappedArray, function(item) {
+ return options['includeDestroyed'] || item === undefined || item === null || !ko.utils.unwrapObservable(item['_destroy']);
+ });
+
+ // Call setDomNodeChildrenFromArrayMapping, ignoring any observables unwrapped within (most likely from a callback function).
+ // If the array items are observables, though, they will be unwrapped in executeTemplateForArrayItem and managed within setDomNodeChildrenFromArrayMapping.
+ ko.dependencyDetection.ignore(ko.utils.setDomNodeChildrenFromArrayMapping, null, [targetNode, filteredArray, executeTemplateForArrayItem, options, activateBindingsCallback]);
+
+ }, null, { disposeWhenNodeIsRemoved: targetNode });
+ };
+
+ var templateComputedDomDataKey = ko.utils.domData.nextKey();
+ function disposeOldComputedAndStoreNewOne(element, newComputed) {
+ var oldComputed = ko.utils.domData.get(element, templateComputedDomDataKey);
+ if (oldComputed && (typeof(oldComputed.dispose) == 'function'))
+ oldComputed.dispose();
+ ko.utils.domData.set(element, templateComputedDomDataKey, (newComputed && newComputed.isActive()) ? newComputed : undefined);
+ }
+
+ ko.bindingHandlers['template'] = {
+ 'init': function(element, valueAccessor) {
+ // Support anonymous templates
+ var bindingValue = ko.utils.unwrapObservable(valueAccessor());
+ if (typeof bindingValue == "string" || bindingValue['name']) {
+ // It's a named template - clear the element
+ ko.virtualElements.emptyNode(element);
+ } else {
+ // It's an anonymous template - store the element contents, then clear the element
+ var templateNodes = ko.virtualElements.childNodes(element),
+ container = ko.utils.moveCleanedNodesToContainerElement(templateNodes); // This also removes the nodes from their current parent
+ new ko.templateSources.anonymousTemplate(element)['nodes'](container);
+ }
+ return { 'controlsDescendantBindings': true };
+ },
+ 'update': function (element, valueAccessor, allBindings, viewModel, bindingContext) {
+ var value = valueAccessor(),
+ dataValue,
+ options = ko.utils.unwrapObservable(value),
+ shouldDisplay = true,
+ templateComputed = null,
+ templateName;
+
+ if (typeof options == "string") {
+ templateName = value;
+ options = {};
+ } else {
+ templateName = options['name'];
+
+ // Support "if"/"ifnot" conditions
+ if ('if' in options)
+ shouldDisplay = ko.utils.unwrapObservable(options['if']);
+ if (shouldDisplay && 'ifnot' in options)
+ shouldDisplay = !ko.utils.unwrapObservable(options['ifnot']);
+
+ dataValue = ko.utils.unwrapObservable(options['data']);
+ }
+
+ if ('foreach' in options) {
+ // Render once for each data point (treating data set as empty if shouldDisplay==false)
+ var dataArray = (shouldDisplay && options['foreach']) || [];
+ templateComputed = ko.renderTemplateForEach(templateName || element, dataArray, options, element, bindingContext);
+ } else if (!shouldDisplay) {
+ ko.virtualElements.emptyNode(element);
+ } else {
+ // Render once for this single data point (or use the viewModel if no data was provided)
+ var innerBindingContext = ('data' in options) ?
+ bindingContext['createChildContext'](dataValue, options['as']) : // Given an explitit 'data' value, we create a child binding context for it
+ bindingContext; // Given no explicit 'data' value, we retain the same binding context
+ templateComputed = ko.renderTemplate(templateName || element, innerBindingContext, options, element);
+ }
+
+ // It only makes sense to have a single template computed per element (otherwise which one should have its output displayed?)
+ disposeOldComputedAndStoreNewOne(element, templateComputed);
+ }
+ };
+
+ // Anonymous templates can't be rewritten. Give a nice error message if you try to do it.
+ ko.expressionRewriting.bindingRewriteValidators['template'] = function(bindingValue) {
+ var parsedBindingValue = ko.expressionRewriting.parseObjectLiteral(bindingValue);
+
+ if ((parsedBindingValue.length == 1) && parsedBindingValue[0]['unknown'])
+ return null; // It looks like a string literal, not an object literal, so treat it as a named template (which is allowed for rewriting)
+
+ if (ko.expressionRewriting.keyValueArrayContainsKey(parsedBindingValue, "name"))
+ return null; // Named templates can be rewritten, so return "no error"
+ return "This template engine does not support anonymous templates nested within its templates";
+ };
+
+ ko.virtualElements.allowedBindings['template'] = true;
+})();
+
+ko.exportSymbol('setTemplateEngine', ko.setTemplateEngine);
+ko.exportSymbol('renderTemplate', ko.renderTemplate);
+// Go through the items that have been added and deleted and try to find matches between them.
+ko.utils.findMovesInArrayComparison = function (left, right, limitFailedCompares) {
+ if (left.length && right.length) {
+ var failedCompares, l, r, leftItem, rightItem;
+ for (failedCompares = l = 0; (!limitFailedCompares || failedCompares < limitFailedCompares) && (leftItem = left[l]); ++l) {
+ for (r = 0; rightItem = right[r]; ++r) {
+ if (leftItem['value'] === rightItem['value']) {
+ leftItem['moved'] = rightItem['index'];
+ rightItem['moved'] = leftItem['index'];
+ right.splice(r, 1); // This item is marked as moved; so remove it from right list
+ failedCompares = r = 0; // Reset failed compares count because we're checking for consecutive failures
+ break;
+ }
+ }
+ failedCompares += r;
+ }
+ }
+};
+
+ko.utils.compareArrays = (function () {
+ var statusNotInOld = 'added', statusNotInNew = 'deleted';
+
+ // Simple calculation based on Levenshtein distance.
+ function compareArrays(oldArray, newArray, options) {
+ // For backward compatibility, if the third arg is actually a bool, interpret
+ // it as the old parameter 'dontLimitMoves'. Newer code should use { dontLimitMoves: true }.
+ options = (typeof options === 'boolean') ? { 'dontLimitMoves': options } : (options || {});
+ oldArray = oldArray || [];
+ newArray = newArray || [];
+
+ if (oldArray.length <= newArray.length)
+ return compareSmallArrayToBigArray(oldArray, newArray, statusNotInOld, statusNotInNew, options);
+ else
+ return compareSmallArrayToBigArray(newArray, oldArray, statusNotInNew, statusNotInOld, options);
+ }
+
+ function compareSmallArrayToBigArray(smlArray, bigArray, statusNotInSml, statusNotInBig, options) {
+ var myMin = Math.min,
+ myMax = Math.max,
+ editDistanceMatrix = [],
+ smlIndex, smlIndexMax = smlArray.length,
+ bigIndex, bigIndexMax = bigArray.length,
+ compareRange = (bigIndexMax - smlIndexMax) || 1,
+ maxDistance = smlIndexMax + bigIndexMax + 1,
+ thisRow, lastRow,
+ bigIndexMaxForRow, bigIndexMinForRow;
+
+ for (smlIndex = 0; smlIndex <= smlIndexMax; smlIndex++) {
+ lastRow = thisRow;
+ editDistanceMatrix.push(thisRow = []);
+ bigIndexMaxForRow = myMin(bigIndexMax, smlIndex + compareRange);
+ bigIndexMinForRow = myMax(0, smlIndex - 1);
+ for (bigIndex = bigIndexMinForRow; bigIndex <= bigIndexMaxForRow; bigIndex++) {
+ if (!bigIndex)
+ thisRow[bigIndex] = smlIndex + 1;
+ else if (!smlIndex) // Top row - transform empty array into new array via additions
+ thisRow[bigIndex] = bigIndex + 1;
+ else if (smlArray[smlIndex - 1] === bigArray[bigIndex - 1])
+ thisRow[bigIndex] = lastRow[bigIndex - 1]; // copy value (no edit)
+ else {
+ var northDistance = lastRow[bigIndex] || maxDistance; // not in big (deletion)
+ var westDistance = thisRow[bigIndex - 1] || maxDistance; // not in small (addition)
+ thisRow[bigIndex] = myMin(northDistance, westDistance) + 1;
+ }
+ }
+ }
+
+ var editScript = [], meMinusOne, notInSml = [], notInBig = [];
+ for (smlIndex = smlIndexMax, bigIndex = bigIndexMax; smlIndex || bigIndex;) {
+ meMinusOne = editDistanceMatrix[smlIndex][bigIndex] - 1;
+ if (bigIndex && meMinusOne === editDistanceMatrix[smlIndex][bigIndex-1]) {
+ notInSml.push(editScript[editScript.length] = { // added
+ 'status': statusNotInSml,
+ 'value': bigArray[--bigIndex],
+ 'index': bigIndex });
+ } else if (smlIndex && meMinusOne === editDistanceMatrix[smlIndex - 1][bigIndex]) {
+ notInBig.push(editScript[editScript.length] = { // deleted
+ 'status': statusNotInBig,
+ 'value': smlArray[--smlIndex],
+ 'index': smlIndex });
+ } else {
+ --bigIndex;
+ --smlIndex;
+ if (!options['sparse']) {
+ editScript.push({
+ 'status': "retained",
+ 'value': bigArray[bigIndex] });
+ }
+ }
+ }
+
+ // Set a limit on the number of consecutive non-matching comparisons; having it a multiple of
+ // smlIndexMax keeps the time complexity of this algorithm linear.
+ ko.utils.findMovesInArrayComparison(notInSml, notInBig, smlIndexMax * 10);
+
+ return editScript.reverse();
+ }
+
+ return compareArrays;
+})();
+
+ko.exportSymbol('utils.compareArrays', ko.utils.compareArrays);
+(function () {
+ // Objective:
+ // * Given an input array, a container DOM node, and a function from array elements to arrays of DOM nodes,
+ // map the array elements to arrays of DOM nodes, concatenate together all these arrays, and use them to populate the container DOM node
+ // * Next time we're given the same combination of things (with the array possibly having mutated), update the container DOM node
+ // so that its children is again the concatenation of the mappings of the array elements, but don't re-map any array elements that we
+ // previously mapped - retain those nodes, and just insert/delete other ones
+
+ // "callbackAfterAddingNodes" will be invoked after any "mapping"-generated nodes are inserted into the container node
+ // You can use this, for example, to activate bindings on those nodes.
+
+ function mapNodeAndRefreshWhenChanged(containerNode, mapping, valueToMap, callbackAfterAddingNodes, index) {
+ // Map this array value inside a dependentObservable so we re-map when any dependency changes
+ var mappedNodes = [];
+ var dependentObservable = ko.dependentObservable(function() {
+ var newMappedNodes = mapping(valueToMap, index, ko.utils.fixUpContinuousNodeArray(mappedNodes, containerNode)) || [];
+
+ // On subsequent evaluations, just replace the previously-inserted DOM nodes
+ if (mappedNodes.length > 0) {
+ ko.utils.replaceDomNodes(mappedNodes, newMappedNodes);
+ if (callbackAfterAddingNodes)
+ ko.dependencyDetection.ignore(callbackAfterAddingNodes, null, [valueToMap, newMappedNodes, index]);
+ }
+
+ // Replace the contents of the mappedNodes array, thereby updating the record
+ // of which nodes would be deleted if valueToMap was itself later removed
+ mappedNodes.length = 0;
+ ko.utils.arrayPushAll(mappedNodes, newMappedNodes);
+ }, null, { disposeWhenNodeIsRemoved: containerNode, disposeWhen: function() { return !ko.utils.anyDomNodeIsAttachedToDocument(mappedNodes); } });
+ return { mappedNodes : mappedNodes, dependentObservable : (dependentObservable.isActive() ? dependentObservable : undefined) };
+ }
+
+ var lastMappingResultDomDataKey = ko.utils.domData.nextKey();
+
+ ko.utils.setDomNodeChildrenFromArrayMapping = function (domNode, array, mapping, options, callbackAfterAddingNodes) {
+ // Compare the provided array against the previous one
+ array = array || [];
+ options = options || {};
+ var isFirstExecution = ko.utils.domData.get(domNode, lastMappingResultDomDataKey) === undefined;
+ var lastMappingResult = ko.utils.domData.get(domNode, lastMappingResultDomDataKey) || [];
+ var lastArray = ko.utils.arrayMap(lastMappingResult, function (x) { return x.arrayEntry; });
+ var editScript = ko.utils.compareArrays(lastArray, array, options['dontLimitMoves']);
+
+ // Build the new mapping result
+ var newMappingResult = [];
+ var lastMappingResultIndex = 0;
+ var newMappingResultIndex = 0;
+
+ var nodesToDelete = [];
+ var itemsToProcess = [];
+ var itemsForBeforeRemoveCallbacks = [];
+ var itemsForMoveCallbacks = [];
+ var itemsForAfterAddCallbacks = [];
+ var mapData;
+
+ function itemMovedOrRetained(editScriptIndex, oldPosition) {
+ mapData = lastMappingResult[oldPosition];
+ if (newMappingResultIndex !== oldPosition)
+ itemsForMoveCallbacks[editScriptIndex] = mapData;
+ // Since updating the index might change the nodes, do so before calling fixUpContinuousNodeArray
+ mapData.indexObservable(newMappingResultIndex++);
+ ko.utils.fixUpContinuousNodeArray(mapData.mappedNodes, domNode);
+ newMappingResult.push(mapData);
+ itemsToProcess.push(mapData);
+ }
+
+ function callCallback(callback, items) {
+ if (callback) {
+ for (var i = 0, n = items.length; i < n; i++) {
+ if (items[i]) {
+ ko.utils.arrayForEach(items[i].mappedNodes, function(node) {
+ callback(node, i, items[i].arrayEntry);
+ });
+ }
+ }
+ }
+ }
+
+ for (var i = 0, editScriptItem, movedIndex; editScriptItem = editScript[i]; i++) {
+ movedIndex = editScriptItem['moved'];
+ switch (editScriptItem['status']) {
+ case "deleted":
+ if (movedIndex === undefined) {
+ mapData = lastMappingResult[lastMappingResultIndex];
+
+ // Stop tracking changes to the mapping for these nodes
+ if (mapData.dependentObservable)
+ mapData.dependentObservable.dispose();
+
+ // Queue these nodes for later removal
+ nodesToDelete.push.apply(nodesToDelete, ko.utils.fixUpContinuousNodeArray(mapData.mappedNodes, domNode));
+ if (options['beforeRemove']) {
+ itemsForBeforeRemoveCallbacks[i] = mapData;
+ itemsToProcess.push(mapData);
+ }
+ }
+ lastMappingResultIndex++;
+ break;
+
+ case "retained":
+ itemMovedOrRetained(i, lastMappingResultIndex++);
+ break;
+
+ case "added":
+ if (movedIndex !== undefined) {
+ itemMovedOrRetained(i, movedIndex);
+ } else {
+ mapData = { arrayEntry: editScriptItem['value'], indexObservable: ko.observable(newMappingResultIndex++) };
+ newMappingResult.push(mapData);
+ itemsToProcess.push(mapData);
+ if (!isFirstExecution)
+ itemsForAfterAddCallbacks[i] = mapData;
+ }
+ break;
+ }
+ }
+
+ // Call beforeMove first before any changes have been made to the DOM
+ callCallback(options['beforeMove'], itemsForMoveCallbacks);
+
+ // Next remove nodes for deleted items (or just clean if there's a beforeRemove callback)
+ ko.utils.arrayForEach(nodesToDelete, options['beforeRemove'] ? ko.cleanNode : ko.removeNode);
+
+ // Next add/reorder the remaining items (will include deleted items if there's a beforeRemove callback)
+ for (var i = 0, nextNode = ko.virtualElements.firstChild(domNode), lastNode, node; mapData = itemsToProcess[i]; i++) {
+ // Get nodes for newly added items
+ if (!mapData.mappedNodes)
+ ko.utils.extend(mapData, mapNodeAndRefreshWhenChanged(domNode, mapping, mapData.arrayEntry, callbackAfterAddingNodes, mapData.indexObservable));
+
+ // Put nodes in the right place if they aren't there already
+ for (var j = 0; node = mapData.mappedNodes[j]; nextNode = node.nextSibling, lastNode = node, j++) {
+ if (node !== nextNode)
+ ko.virtualElements.insertAfter(domNode, node, lastNode);
+ }
+
+ // Run the callbacks for newly added nodes (for example, to apply bindings, etc.)
+ if (!mapData.initialized && callbackAfterAddingNodes) {
+ callbackAfterAddingNodes(mapData.arrayEntry, mapData.mappedNodes, mapData.indexObservable);
+ mapData.initialized = true;
+ }
+ }
+
+ // If there's a beforeRemove callback, call it after reordering.
+ // Note that we assume that the beforeRemove callback will usually be used to remove the nodes using
+ // some sort of animation, which is why we first reorder the nodes that will be removed. If the
+ // callback instead removes the nodes right away, it would be more efficient to skip reordering them.
+ // Perhaps we'll make that change in the future if this scenario becomes more common.
+ callCallback(options['beforeRemove'], itemsForBeforeRemoveCallbacks);
+
+ // Finally call afterMove and afterAdd callbacks
+ callCallback(options['afterMove'], itemsForMoveCallbacks);
+ callCallback(options['afterAdd'], itemsForAfterAddCallbacks);
+
+ // Store a copy of the array items we just considered so we can difference it next time
+ ko.utils.domData.set(domNode, lastMappingResultDomDataKey, newMappingResult);
+ }
+})();
+
+ko.exportSymbol('utils.setDomNodeChildrenFromArrayMapping', ko.utils.setDomNodeChildrenFromArrayMapping);
+ko.nativeTemplateEngine = function () {
+ this['allowTemplateRewriting'] = false;
+}
+
+ko.nativeTemplateEngine.prototype = new ko.templateEngine();
+ko.nativeTemplateEngine.prototype.constructor = ko.nativeTemplateEngine;
+ko.nativeTemplateEngine.prototype['renderTemplateSource'] = function (templateSource, bindingContext, options) {
+ var useNodesIfAvailable = !(ko.utils.ieVersion < 9), // IE<9 cloneNode doesn't work properly
+ templateNodesFunc = useNodesIfAvailable ? templateSource['nodes'] : null,
+ templateNodes = templateNodesFunc ? templateSource['nodes']() : null;
+
+ if (templateNodes) {
+ return ko.utils.makeArray(templateNodes.cloneNode(true).childNodes);
+ } else {
+ var templateText = templateSource['text']();
+ return ko.utils.parseHtmlFragment(templateText);
+ }
+};
+
+ko.nativeTemplateEngine.instance = new ko.nativeTemplateEngine();
+ko.setTemplateEngine(ko.nativeTemplateEngine.instance);
+
+ko.exportSymbol('nativeTemplateEngine', ko.nativeTemplateEngine);
+(function() {
+ ko.jqueryTmplTemplateEngine = function () {
+ // Detect which version of jquery-tmpl you're using. Unfortunately jquery-tmpl
+ // doesn't expose a version number, so we have to infer it.
+ // Note that as of Knockout 1.3, we only support jQuery.tmpl 1.0.0pre and later,
+ // which KO internally refers to as version "2", so older versions are no longer detected.
+ var jQueryTmplVersion = this.jQueryTmplVersion = (function() {
+ if (!jQuery || !(jQuery['tmpl']))
+ return 0;
+ // Since it exposes no official version number, we use our own numbering system. To be updated as jquery-tmpl evolves.
+ try {
+ if (jQuery['tmpl']['tag']['tmpl']['open'].toString().indexOf('__') >= 0) {
+ // Since 1.0.0pre, custom tags should append markup to an array called "__"
+ return 2; // Final version of jquery.tmpl
+ }
+ } catch(ex) { /* Apparently not the version we were looking for */ }
+
+ return 1; // Any older version that we don't support
+ })();
+
+ function ensureHasReferencedJQueryTemplates() {
+ if (jQueryTmplVersion < 2)
+ throw new Error("Your version of jQuery.tmpl is too old. Please upgrade to jQuery.tmpl 1.0.0pre or later.");
+ }
+
+ function executeTemplate(compiledTemplate, data, jQueryTemplateOptions) {
+ return jQuery['tmpl'](compiledTemplate, data, jQueryTemplateOptions);
+ }
+
+ this['renderTemplateSource'] = function(templateSource, bindingContext, options) {
+ options = options || {};
+ ensureHasReferencedJQueryTemplates();
+
+ // Ensure we have stored a precompiled version of this template (don't want to reparse on every render)
+ var precompiled = templateSource['data']('precompiled');
+ if (!precompiled) {
+ var templateText = templateSource['text']() || "";
+ // Wrap in "with($whatever.koBindingContext) { ... }"
+ templateText = "{{ko_with $item.koBindingContext}}" + templateText + "{{/ko_with}}";
+
+ precompiled = jQuery['template'](null, templateText);
+ templateSource['data']('precompiled', precompiled);
+ }
+
+ var data = [bindingContext['$data']]; // Prewrap the data in an array to stop jquery.tmpl from trying to unwrap any arrays
+ var jQueryTemplateOptions = jQuery['extend']({ 'koBindingContext': bindingContext }, options['templateOptions']);
+
+ var resultNodes = executeTemplate(precompiled, data, jQueryTemplateOptions);
+ resultNodes['appendTo'](document.createElement("div")); // Using "appendTo" forces jQuery/jQuery.tmpl to perform necessary cleanup work
+
+ jQuery['fragments'] = {}; // Clear jQuery's fragment cache to avoid a memory leak after a large number of template renders
+ return resultNodes;
+ };
+
+ this['createJavaScriptEvaluatorBlock'] = function(script) {
+ return "{{ko_code ((function() { return " + script + " })()) }}";
+ };
+
+ this['addTemplate'] = function(templateName, templateMarkup) {
+ document.write("<script type='text/html' id='" + templateName + "'>" + templateMarkup + "<" + "/script>");
+ };
+
+ if (jQueryTmplVersion > 0) {
+ jQuery['tmpl']['tag']['ko_code'] = {
+ open: "__.push($1 || '');"
+ };
+ jQuery['tmpl']['tag']['ko_with'] = {
+ open: "with($1) {",
+ close: "} "
+ };
+ }
+ };
+
+ ko.jqueryTmplTemplateEngine.prototype = new ko.templateEngine();
+ ko.jqueryTmplTemplateEngine.prototype.constructor = ko.jqueryTmplTemplateEngine;
+
+ // Use this one by default *only if jquery.tmpl is referenced*
+ var jqueryTmplTemplateEngineInstance = new ko.jqueryTmplTemplateEngine();
+ if (jqueryTmplTemplateEngineInstance.jQueryTmplVersion > 0)
+ ko.setTemplateEngine(jqueryTmplTemplateEngineInstance);
+
+ ko.exportSymbol('jqueryTmplTemplateEngine', ko.jqueryTmplTemplateEngine);
+})();
+}));
+}());
+})();
\ No newline at end of file
--- /dev/null
+/*global define:false */
+/**
+ * Copyright 2013 Craig Campbell
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ * Mousetrap is a simple keyboard shortcut library for Javascript with
+ * no external dependencies
+ *
+ * @version 1.4.6
+ * @url craig.is/killing/mice
+ */
+(function(window, document, undefined) {
+
+ /**
+ * mapping of special keycodes to their corresponding keys
+ *
+ * everything in this dictionary cannot use keypress events
+ * so it has to be here to map to the correct keycodes for
+ * keyup/keydown events
+ *
+ * @type {Object}
+ */
+ var _MAP = {
+ 8: 'backspace',
+ 9: 'tab',
+ 13: 'enter',
+ 16: 'shift',
+ 17: 'ctrl',
+ 18: 'alt',
+ 20: 'capslock',
+ 27: 'esc',
+ 32: 'space',
+ 33: 'pageup',
+ 34: 'pagedown',
+ 35: 'end',
+ 36: 'home',
+ 37: 'left',
+ 38: 'up',
+ 39: 'right',
+ 40: 'down',
+ 45: 'ins',
+ 46: 'del',
+ 91: 'meta',
+ 93: 'meta',
+ 224: 'meta'
+ },
+
+ /**
+ * mapping for special characters so they can support
+ *
+ * this dictionary is only used incase you want to bind a
+ * keyup or keydown event to one of these keys
+ *
+ * @type {Object}
+ */
+ _KEYCODE_MAP = {
+ 106: '*',
+ 107: '+',
+ 109: '-',
+ 110: '.',
+ 111 : '/',
+ 186: ';',
+ 187: '=',
+ 188: ',',
+ 189: '-',
+ 190: '.',
+ 191: '/',
+ 192: '`',
+ 219: '[',
+ 220: '\\',
+ 221: ']',
+ 222: '\''
+ },
+
+ /**
+ * this is a mapping of keys that require shift on a US keypad
+ * back to the non shift equivelents
+ *
+ * this is so you can use keyup events with these keys
+ *
+ * note that this will only work reliably on US keyboards
+ *
+ * @type {Object}
+ */
+ _SHIFT_MAP = {
+ '~': '`',
+ '!': '1',
+ '@': '2',
+ '#': '3',
+ '$': '4',
+ '%': '5',
+ '^': '6',
+ '&': '7',
+ '*': '8',
+ '(': '9',
+ ')': '0',
+ '_': '-',
+ '+': '=',
+ ':': ';',
+ '\"': '\'',
+ '<': ',',
+ '>': '.',
+ '?': '/',
+ '|': '\\'
+ },
+
+ /**
+ * this is a list of special strings you can use to map
+ * to modifier keys when you specify your keyboard shortcuts
+ *
+ * @type {Object}
+ */
+ _SPECIAL_ALIASES = {
+ 'option': 'alt',
+ 'command': 'meta',
+ 'return': 'enter',
+ 'escape': 'esc',
+ 'mod': /Mac|iPod|iPhone|iPad/.test(navigator.platform) ? 'meta' : 'ctrl'
+ },
+
+ /**
+ * variable to store the flipped version of _MAP from above
+ * needed to check if we should use keypress or not when no action
+ * is specified
+ *
+ * @type {Object|undefined}
+ */
+ _REVERSE_MAP,
+
+ /**
+ * a list of all the callbacks setup via Mousetrap.bind()
+ *
+ * @type {Object}
+ */
+ _callbacks = {},
+
+ /**
+ * direct map of string combinations to callbacks used for trigger()
+ *
+ * @type {Object}
+ */
+ _directMap = {},
+
+ /**
+ * keeps track of what level each sequence is at since multiple
+ * sequences can start out with the same sequence
+ *
+ * @type {Object}
+ */
+ _sequenceLevels = {},
+
+ /**
+ * variable to store the setTimeout call
+ *
+ * @type {null|number}
+ */
+ _resetTimer,
+
+ /**
+ * temporary state where we will ignore the next keyup
+ *
+ * @type {boolean|string}
+ */
+ _ignoreNextKeyup = false,
+
+ /**
+ * temporary state where we will ignore the next keypress
+ *
+ * @type {boolean}
+ */
+ _ignoreNextKeypress = false,
+
+ /**
+ * are we currently inside of a sequence?
+ * type of action ("keyup" or "keydown" or "keypress") or false
+ *
+ * @type {boolean|string}
+ */
+ _nextExpectedAction = false;
+
+ /**
+ * loop through the f keys, f1 to f19 and add them to the map
+ * programatically
+ */
+ for (var i = 1; i < 20; ++i) {
+ _MAP[111 + i] = 'f' + i;
+ }
+
+ /**
+ * loop through to map numbers on the numeric keypad
+ */
+ for (i = 0; i <= 9; ++i) {
+ _MAP[i + 96] = i;
+ }
+
+ /**
+ * cross browser add event method
+ *
+ * @param {Element|HTMLDocument} object
+ * @param {string} type
+ * @param {Function} callback
+ * @returns void
+ */
+ function _addEvent(object, type, callback) {
+ if (object.addEventListener) {
+ object.addEventListener(type, callback, false);
+ return;
+ }
+
+ object.attachEvent('on' + type, callback);
+ }
+
+ /**
+ * takes the event and returns the key character
+ *
+ * @param {Event} e
+ * @return {string}
+ */
+ function _characterFromEvent(e) {
+
+ // for keypress events we should return the character as is
+ if (e.type == 'keypress') {
+ var character = String.fromCharCode(e.which);
+
+ // if the shift key is not pressed then it is safe to assume
+ // that we want the character to be lowercase. this means if
+ // you accidentally have caps lock on then your key bindings
+ // will continue to work
+ //
+ // the only side effect that might not be desired is if you
+ // bind something like 'A' cause you want to trigger an
+ // event when capital A is pressed caps lock will no longer
+ // trigger the event. shift+a will though.
+ if (!e.shiftKey) {
+ character = character.toLowerCase();
+ }
+
+ return character;
+ }
+
+ // for non keypress events the special maps are needed
+ if (_MAP[e.which]) {
+ return _MAP[e.which];
+ }
+
+ if (_KEYCODE_MAP[e.which]) {
+ return _KEYCODE_MAP[e.which];
+ }
+
+ // if it is not in the special map
+
+ // with keydown and keyup events the character seems to always
+ // come in as an uppercase character whether you are pressing shift
+ // or not. we should make sure it is always lowercase for comparisons
+ return String.fromCharCode(e.which).toLowerCase();
+ }
+
+ /**
+ * checks if two arrays are equal
+ *
+ * @param {Array} modifiers1
+ * @param {Array} modifiers2
+ * @returns {boolean}
+ */
+ function _modifiersMatch(modifiers1, modifiers2) {
+ return modifiers1.sort().join(',') === modifiers2.sort().join(',');
+ }
+
+ /**
+ * resets all sequence counters except for the ones passed in
+ *
+ * @param {Object} doNotReset
+ * @returns void
+ */
+ function _resetSequences(doNotReset) {
+ doNotReset = doNotReset || {};
+
+ var activeSequences = false,
+ key;
+
+ for (key in _sequenceLevels) {
+ if (doNotReset[key]) {
+ activeSequences = true;
+ continue;
+ }
+ _sequenceLevels[key] = 0;
+ }
+
+ if (!activeSequences) {
+ _nextExpectedAction = false;
+ }
+ }
+
+ /**
+ * finds all callbacks that match based on the keycode, modifiers,
+ * and action
+ *
+ * @param {string} character
+ * @param {Array} modifiers
+ * @param {Event|Object} e
+ * @param {string=} sequenceName - name of the sequence we are looking for
+ * @param {string=} combination
+ * @param {number=} level
+ * @returns {Array}
+ */
+ function _getMatches(character, modifiers, e, sequenceName, combination, level) {
+ var i,
+ callback,
+ matches = [],
+ action = e.type;
+
+ // if there are no events related to this keycode
+ if (!_callbacks[character]) {
+ return [];
+ }
+
+ // if a modifier key is coming up on its own we should allow it
+ if (action == 'keyup' && _isModifier(character)) {
+ modifiers = [character];
+ }
+
+ // loop through all callbacks for the key that was pressed
+ // and see if any of them match
+ for (i = 0; i < _callbacks[character].length; ++i) {
+ callback = _callbacks[character][i];
+
+ // if a sequence name is not specified, but this is a sequence at
+ // the wrong level then move onto the next match
+ if (!sequenceName && callback.seq && _sequenceLevels[callback.seq] != callback.level) {
+ continue;
+ }
+
+ // if the action we are looking for doesn't match the action we got
+ // then we should keep going
+ if (action != callback.action) {
+ continue;
+ }
+
+ // if this is a keypress event and the meta key and control key
+ // are not pressed that means that we need to only look at the
+ // character, otherwise check the modifiers as well
+ //
+ // chrome will not fire a keypress if meta or control is down
+ // safari will fire a keypress if meta or meta+shift is down
+ // firefox will fire a keypress if meta or control is down
+ if ((action == 'keypress' && !e.metaKey && !e.ctrlKey) || _modifiersMatch(modifiers, callback.modifiers)) {
+
+ // when you bind a combination or sequence a second time it
+ // should overwrite the first one. if a sequenceName or
+ // combination is specified in this call it does just that
+ //
+ // @todo make deleting its own method?
+ var deleteCombo = !sequenceName && callback.combo == combination;
+ var deleteSequence = sequenceName && callback.seq == sequenceName && callback.level == level;
+ if (deleteCombo || deleteSequence) {
+ _callbacks[character].splice(i, 1);
+ }
+
+ matches.push(callback);
+ }
+ }
+
+ return matches;
+ }
+
+ /**
+ * takes a key event and figures out what the modifiers are
+ *
+ * @param {Event} e
+ * @returns {Array}
+ */
+ function _eventModifiers(e) {
+ var modifiers = [];
+
+ if (e.shiftKey) {
+ modifiers.push('shift');
+ }
+
+ if (e.altKey) {
+ modifiers.push('alt');
+ }
+
+ if (e.ctrlKey) {
+ modifiers.push('ctrl');
+ }
+
+ if (e.metaKey) {
+ modifiers.push('meta');
+ }
+
+ return modifiers;
+ }
+
+ /**
+ * prevents default for this event
+ *
+ * @param {Event} e
+ * @returns void
+ */
+ function _preventDefault(e) {
+ if (e.preventDefault) {
+ e.preventDefault();
+ return;
+ }
+
+ e.returnValue = false;
+ }
+
+ /**
+ * stops propogation for this event
+ *
+ * @param {Event} e
+ * @returns void
+ */
+ function _stopPropagation(e) {
+ if (e.stopPropagation) {
+ e.stopPropagation();
+ return;
+ }
+
+ e.cancelBubble = true;
+ }
+
+ /**
+ * actually calls the callback function
+ *
+ * if your callback function returns false this will use the jquery
+ * convention - prevent default and stop propogation on the event
+ *
+ * @param {Function} callback
+ * @param {Event} e
+ * @returns void
+ */
+ function _fireCallback(callback, e, combo, sequence) {
+
+ // if this event should not happen stop here
+ if (Mousetrap.stopCallback(e, e.target || e.srcElement, combo, sequence)) {
+ return;
+ }
+
+ if (callback(e, combo) === false) {
+ _preventDefault(e);
+ _stopPropagation(e);
+ }
+ }
+
+ /**
+ * handles a character key event
+ *
+ * @param {string} character
+ * @param {Array} modifiers
+ * @param {Event} e
+ * @returns void
+ */
+ function _handleKey(character, modifiers, e) {
+ var callbacks = _getMatches(character, modifiers, e),
+ i,
+ doNotReset = {},
+ maxLevel = 0,
+ processedSequenceCallback = false;
+
+ // Calculate the maxLevel for sequences so we can only execute the longest callback sequence
+ for (i = 0; i < callbacks.length; ++i) {
+ if (callbacks[i].seq) {
+ maxLevel = Math.max(maxLevel, callbacks[i].level);
+ }
+ }
+
+ // loop through matching callbacks for this key event
+ for (i = 0; i < callbacks.length; ++i) {
+
+ // fire for all sequence callbacks
+ // this is because if for example you have multiple sequences
+ // bound such as "g i" and "g t" they both need to fire the
+ // callback for matching g cause otherwise you can only ever
+ // match the first one
+ if (callbacks[i].seq) {
+
+ // only fire callbacks for the maxLevel to prevent
+ // subsequences from also firing
+ //
+ // for example 'a option b' should not cause 'option b' to fire
+ // even though 'option b' is part of the other sequence
+ //
+ // any sequences that do not match here will be discarded
+ // below by the _resetSequences call
+ if (callbacks[i].level != maxLevel) {
+ continue;
+ }
+
+ processedSequenceCallback = true;
+
+ // keep a list of which sequences were matches for later
+ doNotReset[callbacks[i].seq] = 1;
+ _fireCallback(callbacks[i].callback, e, callbacks[i].combo, callbacks[i].seq);
+ continue;
+ }
+
+ // if there were no sequence matches but we are still here
+ // that means this is a regular match so we should fire that
+ if (!processedSequenceCallback) {
+ _fireCallback(callbacks[i].callback, e, callbacks[i].combo);
+ }
+ }
+
+ // if the key you pressed matches the type of sequence without
+ // being a modifier (ie "keyup" or "keypress") then we should
+ // reset all sequences that were not matched by this event
+ //
+ // this is so, for example, if you have the sequence "h a t" and you
+ // type "h e a r t" it does not match. in this case the "e" will
+ // cause the sequence to reset
+ //
+ // modifier keys are ignored because you can have a sequence
+ // that contains modifiers such as "enter ctrl+space" and in most
+ // cases the modifier key will be pressed before the next key
+ //
+ // also if you have a sequence such as "ctrl+b a" then pressing the
+ // "b" key will trigger a "keypress" and a "keydown"
+ //
+ // the "keydown" is expected when there is a modifier, but the
+ // "keypress" ends up matching the _nextExpectedAction since it occurs
+ // after and that causes the sequence to reset
+ //
+ // we ignore keypresses in a sequence that directly follow a keydown
+ // for the same character
+ var ignoreThisKeypress = e.type == 'keypress' && _ignoreNextKeypress;
+ if (e.type == _nextExpectedAction && !_isModifier(character) && !ignoreThisKeypress) {
+ _resetSequences(doNotReset);
+ }
+
+ _ignoreNextKeypress = processedSequenceCallback && e.type == 'keydown';
+ }
+
+ /**
+ * handles a keydown event
+ *
+ * @param {Event} e
+ * @returns void
+ */
+ function _handleKeyEvent(e) {
+
+ // normalize e.which for key events
+ // @see http://stackoverflow.com/questions/4285627/javascript-keycode-vs-charcode-utter-confusion
+ if (typeof e.which !== 'number') {
+ e.which = e.keyCode;
+ }
+
+ var character = _characterFromEvent(e);
+
+ // no character found then stop
+ if (!character) {
+ return;
+ }
+
+ // need to use === for the character check because the character can be 0
+ if (e.type == 'keyup' && _ignoreNextKeyup === character) {
+ _ignoreNextKeyup = false;
+ return;
+ }
+
+ Mousetrap.handleKey(character, _eventModifiers(e), e);
+ }
+
+ /**
+ * determines if the keycode specified is a modifier key or not
+ *
+ * @param {string} key
+ * @returns {boolean}
+ */
+ function _isModifier(key) {
+ return key == 'shift' || key == 'ctrl' || key == 'alt' || key == 'meta';
+ }
+
+ /**
+ * called to set a 1 second timeout on the specified sequence
+ *
+ * this is so after each key press in the sequence you have 1 second
+ * to press the next key before you have to start over
+ *
+ * @returns void
+ */
+ function _resetSequenceTimer() {
+ clearTimeout(_resetTimer);
+ _resetTimer = setTimeout(_resetSequences, 1000);
+ }
+
+ /**
+ * reverses the map lookup so that we can look for specific keys
+ * to see what can and can't use keypress
+ *
+ * @return {Object}
+ */
+ function _getReverseMap() {
+ if (!_REVERSE_MAP) {
+ _REVERSE_MAP = {};
+ for (var key in _MAP) {
+
+ // pull out the numeric keypad from here cause keypress should
+ // be able to detect the keys from the character
+ if (key > 95 && key < 112) {
+ continue;
+ }
+
+ if (_MAP.hasOwnProperty(key)) {
+ _REVERSE_MAP[_MAP[key]] = key;
+ }
+ }
+ }
+ return _REVERSE_MAP;
+ }
+
+ /**
+ * picks the best action based on the key combination
+ *
+ * @param {string} key - character for key
+ * @param {Array} modifiers
+ * @param {string=} action passed in
+ */
+ function _pickBestAction(key, modifiers, action) {
+
+ // if no action was picked in we should try to pick the one
+ // that we think would work best for this key
+ if (!action) {
+ action = _getReverseMap()[key] ? 'keydown' : 'keypress';
+ }
+
+ // modifier keys don't work as expected with keypress,
+ // switch to keydown
+ if (action == 'keypress' && modifiers.length) {
+ action = 'keydown';
+ }
+
+ return action;
+ }
+
+ /**
+ * binds a key sequence to an event
+ *
+ * @param {string} combo - combo specified in bind call
+ * @param {Array} keys
+ * @param {Function} callback
+ * @param {string=} action
+ * @returns void
+ */
+ function _bindSequence(combo, keys, callback, action) {
+
+ // start off by adding a sequence level record for this combination
+ // and setting the level to 0
+ _sequenceLevels[combo] = 0;
+
+ /**
+ * callback to increase the sequence level for this sequence and reset
+ * all other sequences that were active
+ *
+ * @param {string} nextAction
+ * @returns {Function}
+ */
+ function _increaseSequence(nextAction) {
+ return function() {
+ _nextExpectedAction = nextAction;
+ ++_sequenceLevels[combo];
+ _resetSequenceTimer();
+ };
+ }
+
+ /**
+ * wraps the specified callback inside of another function in order
+ * to reset all sequence counters as soon as this sequence is done
+ *
+ * @param {Event} e
+ * @returns void
+ */
+ function _callbackAndReset(e) {
+ _fireCallback(callback, e, combo);
+
+ // we should ignore the next key up if the action is key down
+ // or keypress. this is so if you finish a sequence and
+ // release the key the final key will not trigger a keyup
+ if (action !== 'keyup') {
+ _ignoreNextKeyup = _characterFromEvent(e);
+ }
+
+ // weird race condition if a sequence ends with the key
+ // another sequence begins with
+ setTimeout(_resetSequences, 10);
+ }
+
+ // loop through keys one at a time and bind the appropriate callback
+ // function. for any key leading up to the final one it should
+ // increase the sequence. after the final, it should reset all sequences
+ //
+ // if an action is specified in the original bind call then that will
+ // be used throughout. otherwise we will pass the action that the
+ // next key in the sequence should match. this allows a sequence
+ // to mix and match keypress and keydown events depending on which
+ // ones are better suited to the key provided
+ for (var i = 0; i < keys.length; ++i) {
+ var isFinal = i + 1 === keys.length;
+ var wrappedCallback = isFinal ? _callbackAndReset : _increaseSequence(action || _getKeyInfo(keys[i + 1]).action);
+ _bindSingle(keys[i], wrappedCallback, action, combo, i);
+ }
+ }
+
+ /**
+ * Converts from a string key combination to an array
+ *
+ * @param {string} combination like "command+shift+l"
+ * @return {Array}
+ */
+ function _keysFromString(combination) {
+ if (combination === '+') {
+ return ['+'];
+ }
+
+ return combination.split('+');
+ }
+
+ /**
+ * Gets info for a specific key combination
+ *
+ * @param {string} combination key combination ("command+s" or "a" or "*")
+ * @param {string=} action
+ * @returns {Object}
+ */
+ function _getKeyInfo(combination, action) {
+ var keys,
+ key,
+ i,
+ modifiers = [];
+
+ // take the keys from this pattern and figure out what the actual
+ // pattern is all about
+ keys = _keysFromString(combination);
+
+ for (i = 0; i < keys.length; ++i) {
+ key = keys[i];
+
+ // normalize key names
+ if (_SPECIAL_ALIASES[key]) {
+ key = _SPECIAL_ALIASES[key];
+ }
+
+ // if this is not a keypress event then we should
+ // be smart about using shift keys
+ // this will only work for US keyboards however
+ if (action && action != 'keypress' && _SHIFT_MAP[key]) {
+ key = _SHIFT_MAP[key];
+ modifiers.push('shift');
+ }
+
+ // if this key is a modifier then add it to the list of modifiers
+ if (_isModifier(key)) {
+ modifiers.push(key);
+ }
+ }
+
+ // depending on what the key combination is
+ // we will try to pick the best event for it
+ action = _pickBestAction(key, modifiers, action);
+
+ return {
+ key: key,
+ modifiers: modifiers,
+ action: action
+ };
+ }
+
+ /**
+ * binds a single keyboard combination
+ *
+ * @param {string} combination
+ * @param {Function} callback
+ * @param {string=} action
+ * @param {string=} sequenceName - name of sequence if part of sequence
+ * @param {number=} level - what part of the sequence the command is
+ * @returns void
+ */
+ function _bindSingle(combination, callback, action, sequenceName, level) {
+
+ // store a direct mapped reference for use with Mousetrap.trigger
+ _directMap[combination + ':' + action] = callback;
+
+ // make sure multiple spaces in a row become a single space
+ combination = combination.replace(/\s+/g, ' ');
+
+ var sequence = combination.split(' '),
+ info;
+
+ // if this pattern is a sequence of keys then run through this method
+ // to reprocess each pattern one key at a time
+ if (sequence.length > 1) {
+ _bindSequence(combination, sequence, callback, action);
+ return;
+ }
+
+ info = _getKeyInfo(combination, action);
+
+ // make sure to initialize array if this is the first time
+ // a callback is added for this key
+ _callbacks[info.key] = _callbacks[info.key] || [];
+
+ // remove an existing match if there is one
+ _getMatches(info.key, info.modifiers, {type: info.action}, sequenceName, combination, level);
+
+ // add this call back to the array
+ // if it is a sequence put it at the beginning
+ // if not put it at the end
+ //
+ // this is important because the way these are processed expects
+ // the sequence ones to come first
+ _callbacks[info.key][sequenceName ? 'unshift' : 'push']({
+ callback: callback,
+ modifiers: info.modifiers,
+ action: info.action,
+ seq: sequenceName,
+ level: level,
+ combo: combination
+ });
+ }
+
+ /**
+ * binds multiple combinations to the same callback
+ *
+ * @param {Array} combinations
+ * @param {Function} callback
+ * @param {string|undefined} action
+ * @returns void
+ */
+ function _bindMultiple(combinations, callback, action) {
+ for (var i = 0; i < combinations.length; ++i) {
+ _bindSingle(combinations[i], callback, action);
+ }
+ }
+
+ // start!
+ _addEvent(document, 'keypress', _handleKeyEvent);
+ _addEvent(document, 'keydown', _handleKeyEvent);
+ _addEvent(document, 'keyup', _handleKeyEvent);
+
+ var Mousetrap = {
+
+ /**
+ * binds an event to mousetrap
+ *
+ * can be a single key, a combination of keys separated with +,
+ * an array of keys, or a sequence of keys separated by spaces
+ *
+ * be sure to list the modifier keys first to make sure that the
+ * correct key ends up getting bound (the last key in the pattern)
+ *
+ * @param {string|Array} keys
+ * @param {Function} callback
+ * @param {string=} action - 'keypress', 'keydown', or 'keyup'
+ * @returns void
+ */
+ bind: function(keys, callback, action) {
+ keys = keys instanceof Array ? keys : [keys];
+ _bindMultiple(keys, callback, action);
+ return this;
+ },
+
+ /**
+ * unbinds an event to mousetrap
+ *
+ * the unbinding sets the callback function of the specified key combo
+ * to an empty function and deletes the corresponding key in the
+ * _directMap dict.
+ *
+ * TODO: actually remove this from the _callbacks dictionary instead
+ * of binding an empty function
+ *
+ * the keycombo+action has to be exactly the same as
+ * it was defined in the bind method
+ *
+ * @param {string|Array} keys
+ * @param {string} action
+ * @returns void
+ */
+ unbind: function(keys, action) {
+ return Mousetrap.bind(keys, function() {}, action);
+ },
+
+ /**
+ * triggers an event that has already been bound
+ *
+ * @param {string} keys
+ * @param {string=} action
+ * @returns void
+ */
+ trigger: function(keys, action) {
+ if (_directMap[keys + ':' + action]) {
+ _directMap[keys + ':' + action]({}, keys);
+ }
+ return this;
+ },
+
+ /**
+ * resets the library back to its initial state. this is useful
+ * if you want to clear out the current keyboard shortcuts and bind
+ * new ones - for example if you switch to another page
+ *
+ * @returns void
+ */
+ reset: function() {
+ _callbacks = {};
+ _directMap = {};
+ return this;
+ },
+
+ /**
+ * should we stop this event before firing off callbacks
+ *
+ * @param {Event} e
+ * @param {Element} element
+ * @return {boolean}
+ */
+ stopCallback: function(e, element) {
+
+ // if the element has the class "mousetrap" then no need to stop
+ if ((' ' + element.className + ' ').indexOf(' mousetrap ') > -1) {
+ return false;
+ }
+
+ // stop for input, select, and textarea
+ return element.tagName == 'INPUT' || element.tagName == 'SELECT' || element.tagName == 'TEXTAREA' || element.isContentEditable;
+ },
+
+ bindEventsTo: function(el){
+ if (el == undefined) {
+ el = document;
+ }
+
+ _addEvent(el, 'keypress', _handleKeyEvent);
+ _addEvent(el, 'keydown', _handleKeyEvent);
+ _addEvent(el, 'keyup', _handleKeyEvent);
+ },
+
+ /**
+ * exposes _handleKey publicly so it can be overwritten by extensions
+ */
+ handleKey: _handleKey
+ };
+
+ // expose mousetrap to the global object
+ window.Mousetrap = Mousetrap;
+
+ // expose mousetrap as an AMD module
+ if (typeof define === 'function' && define.amd) {
+ define(Mousetrap);
+ }
+}) (window, document);
\ No newline at end of file
--- /dev/null
+/** vim: et:ts=4:sw=4:sts=4
+ * @license RequireJS 2.1.11 Copyright (c) 2010-2014, The Dojo Foundation All Rights Reserved.
+ * Available via the MIT or new BSD license.
+ * see: http://github.com/jrburke/requirejs for details
+ */
+//Not using strict: uneven strict support in browsers, #392, and causes
+//problems with requirejs.exec()/transpiler plugins that may not be strict.
+/*jslint regexp: true, nomen: true, sloppy: true */
+/*global window, navigator, document, importScripts, setTimeout, opera */
+
+var requirejs, require, define;
+(function (global) {
+ var req, s, head, baseElement, dataMain, src,
+ interactiveScript, currentlyAddingScript, mainScript, subPath,
+ version = '2.1.11',
+ commentRegExp = /(\/\*([\s\S]*?)\*\/|([^:]|^)\/\/(.*)$)/mg,
+ cjsRequireRegExp = /[^.]\s*require\s*\(\s*["']([^'"\s]+)["']\s*\)/g,
+ jsSuffixRegExp = /\.js$/,
+ currDirRegExp = /^\.\//,
+ op = Object.prototype,
+ ostring = op.toString,
+ hasOwn = op.hasOwnProperty,
+ ap = Array.prototype,
+ apsp = ap.splice,
+ isBrowser = !!(typeof window !== 'undefined' && typeof navigator !== 'undefined' && window.document),
+ isWebWorker = !isBrowser && typeof importScripts !== 'undefined',
+ //PS3 indicates loaded and complete, but need to wait for complete
+ //specifically. Sequence is 'loading', 'loaded', execution,
+ // then 'complete'. The UA check is unfortunate, but not sure how
+ //to feature test w/o causing perf issues.
+ readyRegExp = isBrowser && navigator.platform === 'PLAYSTATION 3' ?
+ /^complete$/ : /^(complete|loaded)$/,
+ defContextName = '_',
+ //Oh the tragedy, detecting opera. See the usage of isOpera for reason.
+ isOpera = typeof opera !== 'undefined' && opera.toString() === '[object Opera]',
+ contexts = {},
+ cfg = {},
+ globalDefQueue = [],
+ useInteractive = false;
+
+ function isFunction(it) {
+ return ostring.call(it) === '[object Function]';
+ }
+
+ function isArray(it) {
+ return ostring.call(it) === '[object Array]';
+ }
+
+ /**
+ * Helper function for iterating over an array. If the func returns
+ * a true value, it will break out of the loop.
+ */
+ function each(ary, func) {
+ if (ary) {
+ var i;
+ for (i = 0; i < ary.length; i += 1) {
+ if (ary[i] && func(ary[i], i, ary)) {
+ break;
+ }
+ }
+ }
+ }
+
+ /**
+ * Helper function for iterating over an array backwards. If the func
+ * returns a true value, it will break out of the loop.
+ */
+ function eachReverse(ary, func) {
+ if (ary) {
+ var i;
+ for (i = ary.length - 1; i > -1; i -= 1) {
+ if (ary[i] && func(ary[i], i, ary)) {
+ break;
+ }
+ }
+ }
+ }
+
+ function hasProp(obj, prop) {
+ return hasOwn.call(obj, prop);
+ }
+
+ function getOwn(obj, prop) {
+ return hasProp(obj, prop) && obj[prop];
+ }
+
+ /**
+ * Cycles over properties in an object and calls a function for each
+ * property value. If the function returns a truthy value, then the
+ * iteration is stopped.
+ */
+ function eachProp(obj, func) {
+ var prop;
+ for (prop in obj) {
+ if (hasProp(obj, prop)) {
+ if (func(obj[prop], prop)) {
+ break;
+ }
+ }
+ }
+ }
+
+ /**
+ * Simple function to mix in properties from source into target,
+ * but only if target does not already have a property of the same name.
+ */
+ function mixin(target, source, force, deepStringMixin) {
+ if (source) {
+ eachProp(source, function (value, prop) {
+ if (force || !hasProp(target, prop)) {
+ if (deepStringMixin && typeof value === 'object' && value &&
+ !isArray(value) && !isFunction(value) &&
+ !(value instanceof RegExp)) {
+
+ if (!target[prop]) {
+ target[prop] = {};
+ }
+ mixin(target[prop], value, force, deepStringMixin);
+ } else {
+ target[prop] = value;
+ }
+ }
+ });
+ }
+ return target;
+ }
+
+ //Similar to Function.prototype.bind, but the 'this' object is specified
+ //first, since it is easier to read/figure out what 'this' will be.
+ function bind(obj, fn) {
+ return function () {
+ return fn.apply(obj, arguments);
+ };
+ }
+
+ function scripts() {
+ return document.getElementsByTagName('script');
+ }
+
+ function defaultOnError(err) {
+ throw err;
+ }
+
+ //Allow getting a global that is expressed in
+ //dot notation, like 'a.b.c'.
+ function getGlobal(value) {
+ if (!value) {
+ return value;
+ }
+ var g = global;
+ each(value.split('.'), function (part) {
+ g = g[part];
+ });
+ return g;
+ }
+
+ /**
+ * Constructs an error with a pointer to an URL with more information.
+ * @param {String} id the error ID that maps to an ID on a web page.
+ * @param {String} message human readable error.
+ * @param {Error} [err] the original error, if there is one.
+ *
+ * @returns {Error}
+ */
+ function makeError(id, msg, err, requireModules) {
+ var e = new Error(msg + '\nhttp://requirejs.org/docs/errors.html#' + id);
+ e.requireType = id;
+ e.requireModules = requireModules;
+ if (err) {
+ e.originalError = err;
+ }
+ return e;
+ }
+
+ if (typeof define !== 'undefined') {
+ //If a define is already in play via another AMD loader,
+ //do not overwrite.
+ return;
+ }
+
+ if (typeof requirejs !== 'undefined') {
+ if (isFunction(requirejs)) {
+ //Do not overwrite and existing requirejs instance.
+ return;
+ }
+ cfg = requirejs;
+ requirejs = undefined;
+ }
+
+ //Allow for a require config object
+ if (typeof require !== 'undefined' && !isFunction(require)) {
+ //assume it is a config object.
+ cfg = require;
+ require = undefined;
+ }
+
+ function newContext(contextName) {
+ var inCheckLoaded, Module, context, handlers,
+ checkLoadedTimeoutId,
+ config = {
+ //Defaults. Do not set a default for map
+ //config to speed up normalize(), which
+ //will run faster if there is no default.
+ waitSeconds: 7,
+ baseUrl: './',
+ paths: {},
+ bundles: {},
+ pkgs: {},
+ shim: {},
+ config: {}
+ },
+ registry = {},
+ //registry of just enabled modules, to speed
+ //cycle breaking code when lots of modules
+ //are registered, but not activated.
+ enabledRegistry = {},
+ undefEvents = {},
+ defQueue = [],
+ defined = {},
+ urlFetched = {},
+ bundlesMap = {},
+ requireCounter = 1,
+ unnormalizedCounter = 1;
+
+ /**
+ * Trims the . and .. from an array of path segments.
+ * It will keep a leading path segment if a .. will become
+ * the first path segment, to help with module name lookups,
+ * which act like paths, but can be remapped. But the end result,
+ * all paths that use this function should look normalized.
+ * NOTE: this method MODIFIES the input array.
+ * @param {Array} ary the array of path segments.
+ */
+ function trimDots(ary) {
+ var i, part, length = ary.length;
+ for (i = 0; i < length; i++) {
+ part = ary[i];
+ if (part === '.') {
+ ary.splice(i, 1);
+ i -= 1;
+ } else if (part === '..') {
+ if (i === 1 && (ary[2] === '..' || ary[0] === '..')) {
+ //End of the line. Keep at least one non-dot
+ //path segment at the front so it can be mapped
+ //correctly to disk. Otherwise, there is likely
+ //no path mapping for a path starting with '..'.
+ //This can still fail, but catches the most reasonable
+ //uses of ..
+ break;
+ } else if (i > 0) {
+ ary.splice(i - 1, 2);
+ i -= 2;
+ }
+ }
+ }
+ }
+
+ /**
+ * Given a relative module name, like ./something, normalize it to
+ * a real name that can be mapped to a path.
+ * @param {String} name the relative name
+ * @param {String} baseName a real name that the name arg is relative
+ * to.
+ * @param {Boolean} applyMap apply the map config to the value. Should
+ * only be done if this normalization is for a dependency ID.
+ * @returns {String} normalized name
+ */
+ function normalize(name, baseName, applyMap) {
+ var pkgMain, mapValue, nameParts, i, j, nameSegment, lastIndex,
+ foundMap, foundI, foundStarMap, starI,
+ baseParts = baseName && baseName.split('/'),
+ normalizedBaseParts = baseParts,
+ map = config.map,
+ starMap = map && map['*'];
+
+ //Adjust any relative paths.
+ if (name && name.charAt(0) === '.') {
+ //If have a base name, try to normalize against it,
+ //otherwise, assume it is a top-level require that will
+ //be relative to baseUrl in the end.
+ if (baseName) {
+ //Convert baseName to array, and lop off the last part,
+ //so that . matches that 'directory' and not name of the baseName's
+ //module. For instance, baseName of 'one/two/three', maps to
+ //'one/two/three.js', but we want the directory, 'one/two' for
+ //this normalization.
+ normalizedBaseParts = baseParts.slice(0, baseParts.length - 1);
+ name = name.split('/');
+ lastIndex = name.length - 1;
+
+ // If wanting node ID compatibility, strip .js from end
+ // of IDs. Have to do this here, and not in nameToUrl
+ // because node allows either .js or non .js to map
+ // to same file.
+ if (config.nodeIdCompat && jsSuffixRegExp.test(name[lastIndex])) {
+ name[lastIndex] = name[lastIndex].replace(jsSuffixRegExp, '');
+ }
+
+ name = normalizedBaseParts.concat(name);
+ trimDots(name);
+ name = name.join('/');
+ } else if (name.indexOf('./') === 0) {
+ // No baseName, so this is ID is resolved relative
+ // to baseUrl, pull off the leading dot.
+ name = name.substring(2);
+ }
+ }
+
+ //Apply map config if available.
+ if (applyMap && map && (baseParts || starMap)) {
+ nameParts = name.split('/');
+
+ outerLoop: for (i = nameParts.length; i > 0; i -= 1) {
+ nameSegment = nameParts.slice(0, i).join('/');
+
+ if (baseParts) {
+ //Find the longest baseName segment match in the config.
+ //So, do joins on the biggest to smallest lengths of baseParts.
+ for (j = baseParts.length; j > 0; j -= 1) {
+ mapValue = getOwn(map, baseParts.slice(0, j).join('/'));
+
+ //baseName segment has config, find if it has one for
+ //this name.
+ if (mapValue) {
+ mapValue = getOwn(mapValue, nameSegment);
+ if (mapValue) {
+ //Match, update name to the new value.
+ foundMap = mapValue;
+ foundI = i;
+ break outerLoop;
+ }
+ }
+ }
+ }
+
+ //Check for a star map match, but just hold on to it,
+ //if there is a shorter segment match later in a matching
+ //config, then favor over this star map.
+ if (!foundStarMap && starMap && getOwn(starMap, nameSegment)) {
+ foundStarMap = getOwn(starMap, nameSegment);
+ starI = i;
+ }
+ }
+
+ if (!foundMap && foundStarMap) {
+ foundMap = foundStarMap;
+ foundI = starI;
+ }
+
+ if (foundMap) {
+ nameParts.splice(0, foundI, foundMap);
+ name = nameParts.join('/');
+ }
+ }
+
+ // If the name points to a package's name, use
+ // the package main instead.
+ pkgMain = getOwn(config.pkgs, name);
+
+ return pkgMain ? pkgMain : name;
+ }
+
+ function removeScript(name) {
+ if (isBrowser) {
+ each(scripts(), function (scriptNode) {
+ if (scriptNode.getAttribute('data-requiremodule') === name &&
+ scriptNode.getAttribute('data-requirecontext') === context.contextName) {
+ scriptNode.parentNode.removeChild(scriptNode);
+ return true;
+ }
+ });
+ }
+ }
+
+ function hasPathFallback(id) {
+ var pathConfig = getOwn(config.paths, id);
+ if (pathConfig && isArray(pathConfig) && pathConfig.length > 1) {
+ //Pop off the first array value, since it failed, and
+ //retry
+ pathConfig.shift();
+ context.require.undef(id);
+ context.require([id]);
+ return true;
+ }
+ }
+
+ //Turns a plugin!resource to [plugin, resource]
+ //with the plugin being undefined if the name
+ //did not have a plugin prefix.
+ function splitPrefix(name) {
+ var prefix,
+ index = name ? name.indexOf('!') : -1;
+ if (index > -1) {
+ prefix = name.substring(0, index);
+ name = name.substring(index + 1, name.length);
+ }
+ return [prefix, name];
+ }
+
+ /**
+ * Creates a module mapping that includes plugin prefix, module
+ * name, and path. If parentModuleMap is provided it will
+ * also normalize the name via require.normalize()
+ *
+ * @param {String} name the module name
+ * @param {String} [parentModuleMap] parent module map
+ * for the module name, used to resolve relative names.
+ * @param {Boolean} isNormalized: is the ID already normalized.
+ * This is true if this call is done for a define() module ID.
+ * @param {Boolean} applyMap: apply the map config to the ID.
+ * Should only be true if this map is for a dependency.
+ *
+ * @returns {Object}
+ */
+ function makeModuleMap(name, parentModuleMap, isNormalized, applyMap) {
+ var url, pluginModule, suffix, nameParts,
+ prefix = null,
+ parentName = parentModuleMap ? parentModuleMap.name : null,
+ originalName = name,
+ isDefine = true,
+ normalizedName = '';
+
+ //If no name, then it means it is a require call, generate an
+ //internal name.
+ if (!name) {
+ isDefine = false;
+ name = '_@r' + (requireCounter += 1);
+ }
+
+ nameParts = splitPrefix(name);
+ prefix = nameParts[0];
+ name = nameParts[1];
+
+ if (prefix) {
+ prefix = normalize(prefix, parentName, applyMap);
+ pluginModule = getOwn(defined, prefix);
+ }
+
+ //Account for relative paths if there is a base name.
+ if (name) {
+ if (prefix) {
+ if (pluginModule && pluginModule.normalize) {
+ //Plugin is loaded, use its normalize method.
+ normalizedName = pluginModule.normalize(name, function (name) {
+ return normalize(name, parentName, applyMap);
+ });
+ } else {
+ normalizedName = normalize(name, parentName, applyMap);
+ }
+ } else {
+ //A regular module.
+ normalizedName = normalize(name, parentName, applyMap);
+
+ //Normalized name may be a plugin ID due to map config
+ //application in normalize. The map config values must
+ //already be normalized, so do not need to redo that part.
+ nameParts = splitPrefix(normalizedName);
+ prefix = nameParts[0];
+ normalizedName = nameParts[1];
+ isNormalized = true;
+
+ url = context.nameToUrl(normalizedName);
+ }
+ }
+
+ //If the id is a plugin id that cannot be determined if it needs
+ //normalization, stamp it with a unique ID so two matching relative
+ //ids that may conflict can be separate.
+ suffix = prefix && !pluginModule && !isNormalized ?
+ '_unnormalized' + (unnormalizedCounter += 1) :
+ '';
+
+ return {
+ prefix: prefix,
+ name: normalizedName,
+ parentMap: parentModuleMap,
+ unnormalized: !!suffix,
+ url: url,
+ originalName: originalName,
+ isDefine: isDefine,
+ id: (prefix ?
+ prefix + '!' + normalizedName :
+ normalizedName) + suffix
+ };
+ }
+
+ function getModule(depMap) {
+ var id = depMap.id,
+ mod = getOwn(registry, id);
+
+ if (!mod) {
+ mod = registry[id] = new context.Module(depMap);
+ }
+
+ return mod;
+ }
+
+ function on(depMap, name, fn) {
+ var id = depMap.id,
+ mod = getOwn(registry, id);
+
+ if (hasProp(defined, id) &&
+ (!mod || mod.defineEmitComplete)) {
+ if (name === 'defined') {
+ fn(defined[id]);
+ }
+ } else {
+ mod = getModule(depMap);
+ if (mod.error && name === 'error') {
+ fn(mod.error);
+ } else {
+ mod.on(name, fn);
+ }
+ }
+ }
+
+ function onError(err, errback) {
+ var ids = err.requireModules,
+ notified = false;
+
+ if (errback) {
+ errback(err);
+ } else {
+ each(ids, function (id) {
+ var mod = getOwn(registry, id);
+ if (mod) {
+ //Set error on module, so it skips timeout checks.
+ mod.error = err;
+ if (mod.events.error) {
+ notified = true;
+ mod.emit('error', err);
+ }
+ }
+ });
+
+ if (!notified) {
+ req.onError(err);
+ }
+ }
+ }
+
+ /**
+ * Internal method to transfer globalQueue items to this context's
+ * defQueue.
+ */
+ function takeGlobalQueue() {
+ //Push all the globalDefQueue items into the context's defQueue
+ if (globalDefQueue.length) {
+ //Array splice in the values since the context code has a
+ //local var ref to defQueue, so cannot just reassign the one
+ //on context.
+ apsp.apply(defQueue,
+ [defQueue.length, 0].concat(globalDefQueue));
+ globalDefQueue = [];
+ }
+ }
+
+ handlers = {
+ 'require': function (mod) {
+ if (mod.require) {
+ return mod.require;
+ } else {
+ return (mod.require = context.makeRequire(mod.map));
+ }
+ },
+ 'exports': function (mod) {
+ mod.usingExports = true;
+ if (mod.map.isDefine) {
+ if (mod.exports) {
+ return (defined[mod.map.id] = mod.exports);
+ } else {
+ return (mod.exports = defined[mod.map.id] = {});
+ }
+ }
+ },
+ 'module': function (mod) {
+ if (mod.module) {
+ return mod.module;
+ } else {
+ return (mod.module = {
+ id: mod.map.id,
+ uri: mod.map.url,
+ config: function () {
+ return getOwn(config.config, mod.map.id) || {};
+ },
+ exports: mod.exports || (mod.exports = {})
+ });
+ }
+ }
+ };
+
+ function cleanRegistry(id) {
+ //Clean up machinery used for waiting modules.
+ delete registry[id];
+ delete enabledRegistry[id];
+ }
+
+ function breakCycle(mod, traced, processed) {
+ var id = mod.map.id;
+
+ if (mod.error) {
+ mod.emit('error', mod.error);
+ } else {
+ traced[id] = true;
+ each(mod.depMaps, function (depMap, i) {
+ var depId = depMap.id,
+ dep = getOwn(registry, depId);
+
+ //Only force things that have not completed
+ //being defined, so still in the registry,
+ //and only if it has not been matched up
+ //in the module already.
+ if (dep && !mod.depMatched[i] && !processed[depId]) {
+ if (getOwn(traced, depId)) {
+ mod.defineDep(i, defined[depId]);
+ mod.check(); //pass false?
+ } else {
+ breakCycle(dep, traced, processed);
+ }
+ }
+ });
+ processed[id] = true;
+ }
+ }
+
+ function checkLoaded() {
+ var err, usingPathFallback,
+ waitInterval = config.waitSeconds * 1000,
+ //It is possible to disable the wait interval by using waitSeconds of 0.
+ expired = waitInterval && (context.startTime + waitInterval) < new Date().getTime(),
+ noLoads = [],
+ reqCalls = [],
+ stillLoading = false,
+ needCycleCheck = true;
+
+ //Do not bother if this call was a result of a cycle break.
+ if (inCheckLoaded) {
+ return;
+ }
+
+ inCheckLoaded = true;
+
+ //Figure out the state of all the modules.
+ eachProp(enabledRegistry, function (mod) {
+ var map = mod.map,
+ modId = map.id;
+
+ //Skip things that are not enabled or in error state.
+ if (!mod.enabled) {
+ return;
+ }
+
+ if (!map.isDefine) {
+ reqCalls.push(mod);
+ }
+
+ if (!mod.error) {
+ //If the module should be executed, and it has not
+ //been inited and time is up, remember it.
+ if (!mod.inited && expired) {
+ if (hasPathFallback(modId)) {
+ usingPathFallback = true;
+ stillLoading = true;
+ } else {
+ noLoads.push(modId);
+ removeScript(modId);
+ }
+ } else if (!mod.inited && mod.fetched && map.isDefine) {
+ stillLoading = true;
+ if (!map.prefix) {
+ //No reason to keep looking for unfinished
+ //loading. If the only stillLoading is a
+ //plugin resource though, keep going,
+ //because it may be that a plugin resource
+ //is waiting on a non-plugin cycle.
+ return (needCycleCheck = false);
+ }
+ }
+ }
+ });
+
+ if (expired && noLoads.length) {
+ //If wait time expired, throw error of unloaded modules.
+ err = makeError('timeout', 'Load timeout for modules: ' + noLoads, null, noLoads);
+ err.contextName = context.contextName;
+ return onError(err);
+ }
+
+ //Not expired, check for a cycle.
+ if (needCycleCheck) {
+ each(reqCalls, function (mod) {
+ breakCycle(mod, {}, {});
+ });
+ }
+
+ //If still waiting on loads, and the waiting load is something
+ //other than a plugin resource, or there are still outstanding
+ //scripts, then just try back later.
+ if ((!expired || usingPathFallback) && stillLoading) {
+ //Something is still waiting to load. Wait for it, but only
+ //if a timeout is not already in effect.
+ if ((isBrowser || isWebWorker) && !checkLoadedTimeoutId) {
+ checkLoadedTimeoutId = setTimeout(function () {
+ checkLoadedTimeoutId = 0;
+ checkLoaded();
+ }, 50);
+ }
+ }
+
+ inCheckLoaded = false;
+ }
+
+ Module = function (map) {
+ this.events = getOwn(undefEvents, map.id) || {};
+ this.map = map;
+ this.shim = getOwn(config.shim, map.id);
+ this.depExports = [];
+ this.depMaps = [];
+ this.depMatched = [];
+ this.pluginMaps = {};
+ this.depCount = 0;
+
+ /* this.exports this.factory
+ this.depMaps = [],
+ this.enabled, this.fetched
+ */
+ };
+
+ Module.prototype = {
+ init: function (depMaps, factory, errback, options) {
+ options = options || {};
+
+ //Do not do more inits if already done. Can happen if there
+ //are multiple define calls for the same module. That is not
+ //a normal, common case, but it is also not unexpected.
+ if (this.inited) {
+ return;
+ }
+
+ this.factory = factory;
+
+ if (errback) {
+ //Register for errors on this module.
+ this.on('error', errback);
+ } else if (this.events.error) {
+ //If no errback already, but there are error listeners
+ //on this module, set up an errback to pass to the deps.
+ errback = bind(this, function (err) {
+ this.emit('error', err);
+ });
+ }
+
+ //Do a copy of the dependency array, so that
+ //source inputs are not modified. For example
+ //"shim" deps are passed in here directly, and
+ //doing a direct modification of the depMaps array
+ //would affect that config.
+ this.depMaps = depMaps && depMaps.slice(0);
+
+ this.errback = errback;
+
+ //Indicate this module has be initialized
+ this.inited = true;
+
+ this.ignore = options.ignore;
+
+ //Could have option to init this module in enabled mode,
+ //or could have been previously marked as enabled. However,
+ //the dependencies are not known until init is called. So
+ //if enabled previously, now trigger dependencies as enabled.
+ if (options.enabled || this.enabled) {
+ //Enable this module and dependencies.
+ //Will call this.check()
+ this.enable();
+ } else {
+ this.check();
+ }
+ },
+
+ defineDep: function (i, depExports) {
+ //Because of cycles, defined callback for a given
+ //export can be called more than once.
+ if (!this.depMatched[i]) {
+ this.depMatched[i] = true;
+ this.depCount -= 1;
+ this.depExports[i] = depExports;
+ }
+ },
+
+ fetch: function () {
+ if (this.fetched) {
+ return;
+ }
+ this.fetched = true;
+
+ context.startTime = (new Date()).getTime();
+
+ var map = this.map;
+
+ //If the manager is for a plugin managed resource,
+ //ask the plugin to load it now.
+ if (this.shim) {
+ context.makeRequire(this.map, {
+ enableBuildCallback: true
+ })(this.shim.deps || [], bind(this, function () {
+ return map.prefix ? this.callPlugin() : this.load();
+ }));
+ } else {
+ //Regular dependency.
+ return map.prefix ? this.callPlugin() : this.load();
+ }
+ },
+
+ load: function () {
+ var url = this.map.url;
+
+ //Regular dependency.
+ if (!urlFetched[url]) {
+ urlFetched[url] = true;
+ context.load(this.map.id, url);
+ }
+ },
+
+ /**
+ * Checks if the module is ready to define itself, and if so,
+ * define it.
+ */
+ check: function () {
+ if (!this.enabled || this.enabling) {
+ return;
+ }
+
+ var err, cjsModule,
+ id = this.map.id,
+ depExports = this.depExports,
+ exports = this.exports,
+ factory = this.factory;
+
+ if (!this.inited) {
+ this.fetch();
+ } else if (this.error) {
+ this.emit('error', this.error);
+ } else if (!this.defining) {
+ //The factory could trigger another require call
+ //that would result in checking this module to
+ //define itself again. If already in the process
+ //of doing that, skip this work.
+ this.defining = true;
+
+ if (this.depCount < 1 && !this.defined) {
+ if (isFunction(factory)) {
+ //If there is an error listener, favor passing
+ //to that instead of throwing an error. However,
+ //only do it for define()'d modules. require
+ //errbacks should not be called for failures in
+ //their callbacks (#699). However if a global
+ //onError is set, use that.
+ if ((this.events.error && this.map.isDefine) ||
+ req.onError !== defaultOnError) {
+ try {
+ exports = context.execCb(id, factory, depExports, exports);
+ } catch (e) {
+ err = e;
+ }
+ } else {
+ exports = context.execCb(id, factory, depExports, exports);
+ }
+
+ // Favor return value over exports. If node/cjs in play,
+ // then will not have a return value anyway. Favor
+ // module.exports assignment over exports object.
+ if (this.map.isDefine && exports === undefined) {
+ cjsModule = this.module;
+ if (cjsModule) {
+ exports = cjsModule.exports;
+ } else if (this.usingExports) {
+ //exports already set the defined value.
+ exports = this.exports;
+ }
+ }
+
+ if (err) {
+ err.requireMap = this.map;
+ err.requireModules = this.map.isDefine ? [this.map.id] : null;
+ err.requireType = this.map.isDefine ? 'define' : 'require';
+ return onError((this.error = err));
+ }
+
+ } else {
+ //Just a literal value
+ exports = factory;
+ }
+
+ this.exports = exports;
+
+ if (this.map.isDefine && !this.ignore) {
+ defined[id] = exports;
+
+ if (req.onResourceLoad) {
+ req.onResourceLoad(context, this.map, this.depMaps);
+ }
+ }
+
+ //Clean up
+ cleanRegistry(id);
+
+ this.defined = true;
+ }
+
+ //Finished the define stage. Allow calling check again
+ //to allow define notifications below in the case of a
+ //cycle.
+ this.defining = false;
+
+ if (this.defined && !this.defineEmitted) {
+ this.defineEmitted = true;
+ this.emit('defined', this.exports);
+ this.defineEmitComplete = true;
+ }
+
+ }
+ },
+
+ callPlugin: function () {
+ var map = this.map,
+ id = map.id,
+ //Map already normalized the prefix.
+ pluginMap = makeModuleMap(map.prefix);
+
+ //Mark this as a dependency for this plugin, so it
+ //can be traced for cycles.
+ this.depMaps.push(pluginMap);
+
+ on(pluginMap, 'defined', bind(this, function (plugin) {
+ var load, normalizedMap, normalizedMod,
+ bundleId = getOwn(bundlesMap, this.map.id),
+ name = this.map.name,
+ parentName = this.map.parentMap ? this.map.parentMap.name : null,
+ localRequire = context.makeRequire(map.parentMap, {
+ enableBuildCallback: true
+ });
+
+ //If current map is not normalized, wait for that
+ //normalized name to load instead of continuing.
+ if (this.map.unnormalized) {
+ //Normalize the ID if the plugin allows it.
+ if (plugin.normalize) {
+ name = plugin.normalize(name, function (name) {
+ return normalize(name, parentName, true);
+ }) || '';
+ }
+
+ //prefix and name should already be normalized, no need
+ //for applying map config again either.
+ normalizedMap = makeModuleMap(map.prefix + '!' + name,
+ this.map.parentMap);
+ on(normalizedMap,
+ 'defined', bind(this, function (value) {
+ this.init([], function () { return value; }, null, {
+ enabled: true,
+ ignore: true
+ });
+ }));
+
+ normalizedMod = getOwn(registry, normalizedMap.id);
+ if (normalizedMod) {
+ //Mark this as a dependency for this plugin, so it
+ //can be traced for cycles.
+ this.depMaps.push(normalizedMap);
+
+ if (this.events.error) {
+ normalizedMod.on('error', bind(this, function (err) {
+ this.emit('error', err);
+ }));
+ }
+ normalizedMod.enable();
+ }
+
+ return;
+ }
+
+ //If a paths config, then just load that file instead to
+ //resolve the plugin, as it is built into that paths layer.
+ if (bundleId) {
+ this.map.url = context.nameToUrl(bundleId);
+ this.load();
+ return;
+ }
+
+ load = bind(this, function (value) {
+ this.init([], function () { return value; }, null, {
+ enabled: true
+ });
+ });
+
+ load.error = bind(this, function (err) {
+ this.inited = true;
+ this.error = err;
+ err.requireModules = [id];
+
+ //Remove temp unnormalized modules for this module,
+ //since they will never be resolved otherwise now.
+ eachProp(registry, function (mod) {
+ if (mod.map.id.indexOf(id + '_unnormalized') === 0) {
+ cleanRegistry(mod.map.id);
+ }
+ });
+
+ onError(err);
+ });
+
+ //Allow plugins to load other code without having to know the
+ //context or how to 'complete' the load.
+ load.fromText = bind(this, function (text, textAlt) {
+ /*jslint evil: true */
+ var moduleName = map.name,
+ moduleMap = makeModuleMap(moduleName),
+ hasInteractive = useInteractive;
+
+ //As of 2.1.0, support just passing the text, to reinforce
+ //fromText only being called once per resource. Still
+ //support old style of passing moduleName but discard
+ //that moduleName in favor of the internal ref.
+ if (textAlt) {
+ text = textAlt;
+ }
+
+ //Turn off interactive script matching for IE for any define
+ //calls in the text, then turn it back on at the end.
+ if (hasInteractive) {
+ useInteractive = false;
+ }
+
+ //Prime the system by creating a module instance for
+ //it.
+ getModule(moduleMap);
+
+ //Transfer any config to this other module.
+ if (hasProp(config.config, id)) {
+ config.config[moduleName] = config.config[id];
+ }
+
+ try {
+ req.exec(text);
+ } catch (e) {
+ return onError(makeError('fromtexteval',
+ 'fromText eval for ' + id +
+ ' failed: ' + e,
+ e,
+ [id]));
+ }
+
+ if (hasInteractive) {
+ useInteractive = true;
+ }
+
+ //Mark this as a dependency for the plugin
+ //resource
+ this.depMaps.push(moduleMap);
+
+ //Support anonymous modules.
+ context.completeLoad(moduleName);
+
+ //Bind the value of that module to the value for this
+ //resource ID.
+ localRequire([moduleName], load);
+ });
+
+ //Use parentName here since the plugin's name is not reliable,
+ //could be some weird string with no path that actually wants to
+ //reference the parentName's path.
+ plugin.load(map.name, localRequire, load, config);
+ }));
+
+ context.enable(pluginMap, this);
+ this.pluginMaps[pluginMap.id] = pluginMap;
+ },
+
+ enable: function () {
+ enabledRegistry[this.map.id] = this;
+ this.enabled = true;
+
+ //Set flag mentioning that the module is enabling,
+ //so that immediate calls to the defined callbacks
+ //for dependencies do not trigger inadvertent load
+ //with the depCount still being zero.
+ this.enabling = true;
+
+ //Enable each dependency
+ each(this.depMaps, bind(this, function (depMap, i) {
+ var id, mod, handler;
+
+ if (typeof depMap === 'string') {
+ //Dependency needs to be converted to a depMap
+ //and wired up to this module.
+ depMap = makeModuleMap(depMap,
+ (this.map.isDefine ? this.map : this.map.parentMap),
+ false,
+ !this.skipMap);
+ this.depMaps[i] = depMap;
+
+ handler = getOwn(handlers, depMap.id);
+
+ if (handler) {
+ this.depExports[i] = handler(this);
+ return;
+ }
+
+ this.depCount += 1;
+
+ on(depMap, 'defined', bind(this, function (depExports) {
+ this.defineDep(i, depExports);
+ this.check();
+ }));
+
+ if (this.errback) {
+ on(depMap, 'error', bind(this, this.errback));
+ }
+ }
+
+ id = depMap.id;
+ mod = registry[id];
+
+ //Skip special modules like 'require', 'exports', 'module'
+ //Also, don't call enable if it is already enabled,
+ //important in circular dependency cases.
+ if (!hasProp(handlers, id) && mod && !mod.enabled) {
+ context.enable(depMap, this);
+ }
+ }));
+
+ //Enable each plugin that is used in
+ //a dependency
+ eachProp(this.pluginMaps, bind(this, function (pluginMap) {
+ var mod = getOwn(registry, pluginMap.id);
+ if (mod && !mod.enabled) {
+ context.enable(pluginMap, this);
+ }
+ }));
+
+ this.enabling = false;
+
+ this.check();
+ },
+
+ on: function (name, cb) {
+ var cbs = this.events[name];
+ if (!cbs) {
+ cbs = this.events[name] = [];
+ }
+ cbs.push(cb);
+ },
+
+ emit: function (name, evt) {
+ each(this.events[name], function (cb) {
+ cb(evt);
+ });
+ if (name === 'error') {
+ //Now that the error handler was triggered, remove
+ //the listeners, since this broken Module instance
+ //can stay around for a while in the registry.
+ delete this.events[name];
+ }
+ }
+ };
+
+ function callGetModule(args) {
+ //Skip modules already defined.
+ if (!hasProp(defined, args[0])) {
+ getModule(makeModuleMap(args[0], null, true)).init(args[1], args[2]);
+ }
+ }
+
+ function removeListener(node, func, name, ieName) {
+ //Favor detachEvent because of IE9
+ //issue, see attachEvent/addEventListener comment elsewhere
+ //in this file.
+ if (node.detachEvent && !isOpera) {
+ //Probably IE. If not it will throw an error, which will be
+ //useful to know.
+ if (ieName) {
+ node.detachEvent(ieName, func);
+ }
+ } else {
+ node.removeEventListener(name, func, false);
+ }
+ }
+
+ /**
+ * Given an event from a script node, get the requirejs info from it,
+ * and then removes the event listeners on the node.
+ * @param {Event} evt
+ * @returns {Object}
+ */
+ function getScriptData(evt) {
+ //Using currentTarget instead of target for Firefox 2.0's sake. Not
+ //all old browsers will be supported, but this one was easy enough
+ //to support and still makes sense.
+ var node = evt.currentTarget || evt.srcElement;
+
+ //Remove the listeners once here.
+ removeListener(node, context.onScriptLoad, 'load', 'onreadystatechange');
+ removeListener(node, context.onScriptError, 'error');
+
+ return {
+ node: node,
+ id: node && node.getAttribute('data-requiremodule')
+ };
+ }
+
+ function intakeDefines() {
+ var args;
+
+ //Any defined modules in the global queue, intake them now.
+ takeGlobalQueue();
+
+ //Make sure any remaining defQueue items get properly processed.
+ while (defQueue.length) {
+ args = defQueue.shift();
+ if (args[0] === null) {
+ return onError(makeError('mismatch', 'Mismatched anonymous define() module: ' + args[args.length - 1]));
+ } else {
+ //args are id, deps, factory. Should be normalized by the
+ //define() function.
+ callGetModule(args);
+ }
+ }
+ }
+
+ context = {
+ config: config,
+ contextName: contextName,
+ registry: registry,
+ defined: defined,
+ urlFetched: urlFetched,
+ defQueue: defQueue,
+ Module: Module,
+ makeModuleMap: makeModuleMap,
+ nextTick: req.nextTick,
+ onError: onError,
+
+ /**
+ * Set a configuration for the context.
+ * @param {Object} cfg config object to integrate.
+ */
+ configure: function (cfg) {
+ //Make sure the baseUrl ends in a slash.
+ if (cfg.baseUrl) {
+ if (cfg.baseUrl.charAt(cfg.baseUrl.length - 1) !== '/') {
+ cfg.baseUrl += '/';
+ }
+ }
+
+ //Save off the paths since they require special processing,
+ //they are additive.
+ var shim = config.shim,
+ objs = {
+ paths: true,
+ bundles: true,
+ config: true,
+ map: true
+ };
+
+ eachProp(cfg, function (value, prop) {
+ if (objs[prop]) {
+ if (!config[prop]) {
+ config[prop] = {};
+ }
+ mixin(config[prop], value, true, true);
+ } else {
+ config[prop] = value;
+ }
+ });
+
+ //Reverse map the bundles
+ if (cfg.bundles) {
+ eachProp(cfg.bundles, function (value, prop) {
+ each(value, function (v) {
+ if (v !== prop) {
+ bundlesMap[v] = prop;
+ }
+ });
+ });
+ }
+
+ //Merge shim
+ if (cfg.shim) {
+ eachProp(cfg.shim, function (value, id) {
+ //Normalize the structure
+ if (isArray(value)) {
+ value = {
+ deps: value
+ };
+ }
+ if ((value.exports || value.init) && !value.exportsFn) {
+ value.exportsFn = context.makeShimExports(value);
+ }
+ shim[id] = value;
+ });
+ config.shim = shim;
+ }
+
+ //Adjust packages if necessary.
+ if (cfg.packages) {
+ each(cfg.packages, function (pkgObj) {
+ var location, name;
+
+ pkgObj = typeof pkgObj === 'string' ? { name: pkgObj } : pkgObj;
+
+ name = pkgObj.name;
+ location = pkgObj.location;
+ if (location) {
+ config.paths[name] = pkgObj.location;
+ }
+
+ //Save pointer to main module ID for pkg name.
+ //Remove leading dot in main, so main paths are normalized,
+ //and remove any trailing .js, since different package
+ //envs have different conventions: some use a module name,
+ //some use a file name.
+ config.pkgs[name] = pkgObj.name + '/' + (pkgObj.main || 'main')
+ .replace(currDirRegExp, '')
+ .replace(jsSuffixRegExp, '');
+ });
+ }
+
+ //If there are any "waiting to execute" modules in the registry,
+ //update the maps for them, since their info, like URLs to load,
+ //may have changed.
+ eachProp(registry, function (mod, id) {
+ //If module already has init called, since it is too
+ //late to modify them, and ignore unnormalized ones
+ //since they are transient.
+ if (!mod.inited && !mod.map.unnormalized) {
+ mod.map = makeModuleMap(id);
+ }
+ });
+
+ //If a deps array or a config callback is specified, then call
+ //require with those args. This is useful when require is defined as a
+ //config object before require-and-jquery.js is loaded.
+ if (cfg.deps || cfg.callback) {
+ context.require(cfg.deps || [], cfg.callback);
+ }
+ },
+
+ makeShimExports: function (value) {
+ function fn() {
+ var ret;
+ if (value.init) {
+ ret = value.init.apply(global, arguments);
+ }
+ return ret || (value.exports && getGlobal(value.exports));
+ }
+ return fn;
+ },
+
+ makeRequire: function (relMap, options) {
+ options = options || {};
+
+ function localRequire(deps, callback, errback) {
+ var id, map, requireMod;
+
+ if (options.enableBuildCallback && callback && isFunction(callback)) {
+ callback.__requireJsBuild = true;
+ }
+
+ if (typeof deps === 'string') {
+ if (isFunction(callback)) {
+ //Invalid call
+ return onError(makeError('requireargs', 'Invalid require call'), errback);
+ }
+
+ //If require|exports|module are requested, get the
+ //value for them from the special handlers. Caveat:
+ //this only works while module is being defined.
+ if (relMap && hasProp(handlers, deps)) {
+ return handlers[deps](registry[relMap.id]);
+ }
+
+ //Synchronous access to one module. If require.get is
+ //available (as in the Node adapter), prefer that.
+ if (req.get) {
+ return req.get(context, deps, relMap, localRequire);
+ }
+
+ //Normalize module name, if it contains . or ..
+ map = makeModuleMap(deps, relMap, false, true);
+ id = map.id;
+
+ if (!hasProp(defined, id)) {
+ return onError(makeError('notloaded', 'Module name "' +
+ id +
+ '" has not been loaded yet for context: ' +
+ contextName +
+ (relMap ? '' : '. Use require([])')));
+ }
+ return defined[id];
+ }
+
+ //Grab defines waiting in the global queue.
+ intakeDefines();
+
+ //Mark all the dependencies as needing to be loaded.
+ context.nextTick(function () {
+ //Some defines could have been added since the
+ //require call, collect them.
+ intakeDefines();
+
+ requireMod = getModule(makeModuleMap(null, relMap));
+
+ //Store if map config should be applied to this require
+ //call for dependencies.
+ requireMod.skipMap = options.skipMap;
+
+ requireMod.init(deps, callback, errback, {
+ enabled: true
+ });
+
+ checkLoaded();
+ });
+
+ return localRequire;
+ }
+
+ mixin(localRequire, {
+ isBrowser: isBrowser,
+
+ /**
+ * Converts a module name + .extension into an URL path.
+ * *Requires* the use of a module name. It does not support using
+ * plain URLs like nameToUrl.
+ */
+ toUrl: function (moduleNamePlusExt) {
+ var ext,
+ index = moduleNamePlusExt.lastIndexOf('.'),
+ segment = moduleNamePlusExt.split('/')[0],
+ isRelative = segment === '.' || segment === '..';
+
+ //Have a file extension alias, and it is not the
+ //dots from a relative path.
+ if (index !== -1 && (!isRelative || index > 1)) {
+ ext = moduleNamePlusExt.substring(index, moduleNamePlusExt.length);
+ moduleNamePlusExt = moduleNamePlusExt.substring(0, index);
+ }
+
+ return context.nameToUrl(normalize(moduleNamePlusExt,
+ relMap && relMap.id, true), ext, true);
+ },
+
+ defined: function (id) {
+ return hasProp(defined, makeModuleMap(id, relMap, false, true).id);
+ },
+
+ specified: function (id) {
+ id = makeModuleMap(id, relMap, false, true).id;
+ return hasProp(defined, id) || hasProp(registry, id);
+ }
+ });
+
+ //Only allow undef on top level require calls
+ if (!relMap) {
+ localRequire.undef = function (id) {
+ //Bind any waiting define() calls to this context,
+ //fix for #408
+ takeGlobalQueue();
+
+ var map = makeModuleMap(id, relMap, true),
+ mod = getOwn(registry, id);
+
+ removeScript(id);
+
+ delete defined[id];
+ delete urlFetched[map.url];
+ delete undefEvents[id];
+
+ //Clean queued defines too. Go backwards
+ //in array so that the splices do not
+ //mess up the iteration.
+ eachReverse(defQueue, function(args, i) {
+ if(args[0] === id) {
+ defQueue.splice(i, 1);
+ }
+ });
+
+ if (mod) {
+ //Hold on to listeners in case the
+ //module will be attempted to be reloaded
+ //using a different config.
+ if (mod.events.defined) {
+ undefEvents[id] = mod.events;
+ }
+
+ cleanRegistry(id);
+ }
+ };
+ }
+
+ return localRequire;
+ },
+
+ /**
+ * Called to enable a module if it is still in the registry
+ * awaiting enablement. A second arg, parent, the parent module,
+ * is passed in for context, when this method is overridden by
+ * the optimizer. Not shown here to keep code compact.
+ */
+ enable: function (depMap) {
+ var mod = getOwn(registry, depMap.id);
+ if (mod) {
+ getModule(depMap).enable();
+ }
+ },
+
+ /**
+ * Internal method used by environment adapters to complete a load event.
+ * A load event could be a script load or just a load pass from a synchronous
+ * load call.
+ * @param {String} moduleName the name of the module to potentially complete.
+ */
+ completeLoad: function (moduleName) {
+ var found, args, mod,
+ shim = getOwn(config.shim, moduleName) || {},
+ shExports = shim.exports;
+
+ takeGlobalQueue();
+
+ while (defQueue.length) {
+ args = defQueue.shift();
+ if (args[0] === null) {
+ args[0] = moduleName;
+ //If already found an anonymous module and bound it
+ //to this name, then this is some other anon module
+ //waiting for its completeLoad to fire.
+ if (found) {
+ break;
+ }
+ found = true;
+ } else if (args[0] === moduleName) {
+ //Found matching define call for this script!
+ found = true;
+ }
+
+ callGetModule(args);
+ }
+
+ //Do this after the cycle of callGetModule in case the result
+ //of those calls/init calls changes the registry.
+ mod = getOwn(registry, moduleName);
+
+ if (!found && !hasProp(defined, moduleName) && mod && !mod.inited) {
+ if (config.enforceDefine && (!shExports || !getGlobal(shExports))) {
+ if (hasPathFallback(moduleName)) {
+ return;
+ } else {
+ return onError(makeError('nodefine',
+ 'No define call for ' + moduleName,
+ null,
+ [moduleName]));
+ }
+ } else {
+ //A script that does not call define(), so just simulate
+ //the call for it.
+ callGetModule([moduleName, (shim.deps || []), shim.exportsFn]);
+ }
+ }
+
+ checkLoaded();
+ },
+
+ /**
+ * Converts a module name to a file path. Supports cases where
+ * moduleName may actually be just an URL.
+ * Note that it **does not** call normalize on the moduleName,
+ * it is assumed to have already been normalized. This is an
+ * internal API, not a public one. Use toUrl for the public API.
+ */
+ nameToUrl: function (moduleName, ext, skipExt) {
+ var paths, syms, i, parentModule, url,
+ parentPath, bundleId,
+ pkgMain = getOwn(config.pkgs, moduleName);
+
+ if (pkgMain) {
+ moduleName = pkgMain;
+ }
+
+ bundleId = getOwn(bundlesMap, moduleName);
+
+ if (bundleId) {
+ return context.nameToUrl(bundleId, ext, skipExt);
+ }
+
+ //If a colon is in the URL, it indicates a protocol is used and it is just
+ //an URL to a file, or if it starts with a slash, contains a query arg (i.e. ?)
+ //or ends with .js, then assume the user meant to use an url and not a module id.
+ //The slash is important for protocol-less URLs as well as full paths.
+ if (req.jsExtRegExp.test(moduleName)) {
+ //Just a plain path, not module name lookup, so just return it.
+ //Add extension if it is included. This is a bit wonky, only non-.js things pass
+ //an extension, this method probably needs to be reworked.
+ url = moduleName + (ext || '');
+ } else {
+ //A module that needs to be converted to a path.
+ paths = config.paths;
+
+ syms = moduleName.split('/');
+ //For each module name segment, see if there is a path
+ //registered for it. Start with most specific name
+ //and work up from it.
+ for (i = syms.length; i > 0; i -= 1) {
+ parentModule = syms.slice(0, i).join('/');
+
+ parentPath = getOwn(paths, parentModule);
+ if (parentPath) {
+ //If an array, it means there are a few choices,
+ //Choose the one that is desired
+ if (isArray(parentPath)) {
+ parentPath = parentPath[0];
+ }
+ syms.splice(0, i, parentPath);
+ break;
+ }
+ }
+
+ //Join the path parts together, then figure out if baseUrl is needed.
+ url = syms.join('/');
+ url += (ext || (/^data\:|\?/.test(url) || skipExt ? '' : '.js'));
+ url = (url.charAt(0) === '/' || url.match(/^[\w\+\.\-]+:/) ? '' : config.baseUrl) + url;
+ }
+
+ return config.urlArgs ? url +
+ ((url.indexOf('?') === -1 ? '?' : '&') +
+ config.urlArgs) : url;
+ },
+
+ //Delegates to req.load. Broken out as a separate function to
+ //allow overriding in the optimizer.
+ load: function (id, url) {
+ req.load(context, id, url);
+ },
+
+ /**
+ * Executes a module callback function. Broken out as a separate function
+ * solely to allow the build system to sequence the files in the built
+ * layer in the right sequence.
+ *
+ * @private
+ */
+ execCb: function (name, callback, args, exports) {
+ return callback.apply(exports, args);
+ },
+
+ /**
+ * callback for script loads, used to check status of loading.
+ *
+ * @param {Event} evt the event from the browser for the script
+ * that was loaded.
+ */
+ onScriptLoad: function (evt) {
+ //Using currentTarget instead of target for Firefox 2.0's sake. Not
+ //all old browsers will be supported, but this one was easy enough
+ //to support and still makes sense.
+ if (evt.type === 'load' ||
+ (readyRegExp.test((evt.currentTarget || evt.srcElement).readyState))) {
+ //Reset interactive script so a script node is not held onto for
+ //to long.
+ interactiveScript = null;
+
+ //Pull out the name of the module and the context.
+ var data = getScriptData(evt);
+ context.completeLoad(data.id);
+ }
+ },
+
+ /**
+ * Callback for script errors.
+ */
+ onScriptError: function (evt) {
+ var data = getScriptData(evt);
+ if (!hasPathFallback(data.id)) {
+ return onError(makeError('scripterror', 'Script error for: ' + data.id, evt, [data.id]));
+ }
+ }
+ };
+
+ context.require = context.makeRequire();
+ return context;
+ }
+
+ /**
+ * Main entry point.
+ *
+ * If the only argument to require is a string, then the module that
+ * is represented by that string is fetched for the appropriate context.
+ *
+ * If the first argument is an array, then it will be treated as an array
+ * of dependency string names to fetch. An optional function callback can
+ * be specified to execute when all of those dependencies are available.
+ *
+ * Make a local req variable to help Caja compliance (it assumes things
+ * on a require that are not standardized), and to give a short
+ * name for minification/local scope use.
+ */
+ req = requirejs = function (deps, callback, errback, optional) {
+
+ //Find the right context, use default
+ var context, config,
+ contextName = defContextName;
+
+ // Determine if have config object in the call.
+ if (!isArray(deps) && typeof deps !== 'string') {
+ // deps is a config object
+ config = deps;
+ if (isArray(callback)) {
+ // Adjust args if there are dependencies
+ deps = callback;
+ callback = errback;
+ errback = optional;
+ } else {
+ deps = [];
+ }
+ }
+
+ if (config && config.context) {
+ contextName = config.context;
+ }
+
+ context = getOwn(contexts, contextName);
+ if (!context) {
+ context = contexts[contextName] = req.s.newContext(contextName);
+ }
+
+ if (config) {
+ context.configure(config);
+ }
+
+ return context.require(deps, callback, errback);
+ };
+
+ /**
+ * Support require.config() to make it easier to cooperate with other
+ * AMD loaders on globally agreed names.
+ */
+ req.config = function (config) {
+ return req(config);
+ };
+
+ /**
+ * Execute something after the current tick
+ * of the event loop. Override for other envs
+ * that have a better solution than setTimeout.
+ * @param {Function} fn function to execute later.
+ */
+ req.nextTick = typeof setTimeout !== 'undefined' ? function (fn) {
+ setTimeout(fn, 4);
+ } : function (fn) { fn(); };
+
+ /**
+ * Export require as a global, but only if it does not already exist.
+ */
+ if (!require) {
+ require = req;
+ }
+
+ req.version = version;
+
+ //Used to filter out dependencies that are already paths.
+ req.jsExtRegExp = /^\/|:|\?|\.js$/;
+ req.isBrowser = isBrowser;
+ s = req.s = {
+ contexts: contexts,
+ newContext: newContext
+ };
+
+ //Create default context.
+ req({});
+
+ //Exports some context-sensitive methods on global require.
+ each([
+ 'toUrl',
+ 'undef',
+ 'defined',
+ 'specified'
+ ], function (prop) {
+ //Reference from contexts instead of early binding to default context,
+ //so that during builds, the latest instance of the default context
+ //with its config gets used.
+ req[prop] = function () {
+ var ctx = contexts[defContextName];
+ return ctx.require[prop].apply(ctx, arguments);
+ };
+ });
+
+ if (isBrowser) {
+ head = s.head = document.getElementsByTagName('head')[0];
+ //If BASE tag is in play, using appendChild is a problem for IE6.
+ //When that browser dies, this can be removed. Details in this jQuery bug:
+ //http://dev.jquery.com/ticket/2709
+ baseElement = document.getElementsByTagName('base')[0];
+ if (baseElement) {
+ head = s.head = baseElement.parentNode;
+ }
+ }
+
+ /**
+ * Any errors that require explicitly generates will be passed to this
+ * function. Intercept/override it if you want custom error handling.
+ * @param {Error} err the error object.
+ */
+ req.onError = defaultOnError;
+
+ /**
+ * Creates the node for the load command. Only used in browser envs.
+ */
+ req.createNode = function (config, moduleName, url) {
+ var node = config.xhtml ?
+ document.createElementNS('http://www.w3.org/1999/xhtml', 'html:script') :
+ document.createElement('script');
+ node.type = config.scriptType || 'text/javascript';
+ node.charset = 'utf-8';
+ node.async = true;
+ return node;
+ };
+
+ /**
+ * Does the request to load a module for the browser case.
+ * Make this a separate function to allow other environments
+ * to override it.
+ *
+ * @param {Object} context the require context to find state.
+ * @param {String} moduleName the name of the module.
+ * @param {Object} url the URL to the module.
+ */
+ req.load = function (context, moduleName, url) {
+ var config = (context && context.config) || {},
+ node;
+ if (isBrowser) {
+ //In the browser so use a script tag
+ node = req.createNode(config, moduleName, url);
+
+ node.setAttribute('data-requirecontext', context.contextName);
+ node.setAttribute('data-requiremodule', moduleName);
+
+ //Set up load listener. Test attachEvent first because IE9 has
+ //a subtle issue in its addEventListener and script onload firings
+ //that do not match the behavior of all other browsers with
+ //addEventListener support, which fire the onload event for a
+ //script right after the script execution. See:
+ //https://connect.microsoft.com/IE/feedback/details/648057/script-onload-event-is-not-fired-immediately-after-script-execution
+ //UNFORTUNATELY Opera implements attachEvent but does not follow the script
+ //script execution mode.
+ if (node.attachEvent &&
+ //Check if node.attachEvent is artificially added by custom script or
+ //natively supported by browser
+ //read https://github.com/jrburke/requirejs/issues/187
+ //if we can NOT find [native code] then it must NOT natively supported.
+ //in IE8, node.attachEvent does not have toString()
+ //Note the test for "[native code" with no closing brace, see:
+ //https://github.com/jrburke/requirejs/issues/273
+ !(node.attachEvent.toString && node.attachEvent.toString().indexOf('[native code') < 0) &&
+ !isOpera) {
+ //Probably IE. IE (at least 6-8) do not fire
+ //script onload right after executing the script, so
+ //we cannot tie the anonymous define call to a name.
+ //However, IE reports the script as being in 'interactive'
+ //readyState at the time of the define call.
+ useInteractive = true;
+
+ node.attachEvent('onreadystatechange', context.onScriptLoad);
+ //It would be great to add an error handler here to catch
+ //404s in IE9+. However, onreadystatechange will fire before
+ //the error handler, so that does not help. If addEventListener
+ //is used, then IE will fire error before load, but we cannot
+ //use that pathway given the connect.microsoft.com issue
+ //mentioned above about not doing the 'script execute,
+ //then fire the script load event listener before execute
+ //next script' that other browsers do.
+ //Best hope: IE10 fixes the issues,
+ //and then destroys all installs of IE 6-9.
+ //node.attachEvent('onerror', context.onScriptError);
+ } else {
+ node.addEventListener('load', context.onScriptLoad, false);
+ node.addEventListener('error', context.onScriptError, false);
+ }
+ node.src = url;
+
+ //For some cache cases in IE 6-8, the script executes before the end
+ //of the appendChild execution, so to tie an anonymous define
+ //call to the module name (which is stored on the node), hold on
+ //to a reference to this node, but clear after the DOM insertion.
+ currentlyAddingScript = node;
+ if (baseElement) {
+ head.insertBefore(node, baseElement);
+ } else {
+ head.appendChild(node);
+ }
+ currentlyAddingScript = null;
+
+ return node;
+ } else if (isWebWorker) {
+ try {
+ //In a web worker, use importScripts. This is not a very
+ //efficient use of importScripts, importScripts will block until
+ //its script is downloaded and evaluated. However, if web workers
+ //are in play, the expectation that a build has been done so that
+ //only one script needs to be loaded anyway. This may need to be
+ //reevaluated if other use cases become common.
+ importScripts(url);
+
+ //Account for anonymous modules
+ context.completeLoad(moduleName);
+ } catch (e) {
+ context.onError(makeError('importscripts',
+ 'importScripts failed for ' +
+ moduleName + ' at ' + url,
+ e,
+ [moduleName]));
+ }
+ }
+ };
+
+ function getInteractiveScript() {
+ if (interactiveScript && interactiveScript.readyState === 'interactive') {
+ return interactiveScript;
+ }
+
+ eachReverse(scripts(), function (script) {
+ if (script.readyState === 'interactive') {
+ return (interactiveScript = script);
+ }
+ });
+ return interactiveScript;
+ }
+
+ //Look for a data-main script attribute, which could also adjust the baseUrl.
+ if (isBrowser && !cfg.skipDataMain) {
+ //Figure out baseUrl. Get it from the script tag with require-and-jquery.js in it.
+ eachReverse(scripts(), function (script) {
+ //Set the 'head' where we can append children by
+ //using the script's parent.
+ if (!head) {
+ head = script.parentNode;
+ }
+
+ //Look for a data-main attribute to set main script for the page
+ //to load. If it is there, the path to data main becomes the
+ //baseUrl, if it is not already set.
+ dataMain = script.getAttribute('data-main');
+ if (dataMain) {
+ //Preserve dataMain in case it is a path (i.e. contains '?')
+ mainScript = dataMain;
+
+ //Set final baseUrl if there is not already an explicit one.
+ if (!cfg.baseUrl) {
+ //Pull off the directory of data-main for use as the
+ //baseUrl.
+ src = mainScript.split('/');
+ mainScript = src.pop();
+ subPath = src.length ? src.join('/') + '/' : './';
+
+ cfg.baseUrl = subPath;
+ }
+
+ //Strip off any trailing .js since mainScript is now
+ //like a module name.
+ mainScript = mainScript.replace(jsSuffixRegExp, '');
+
+ //If mainScript is still a path, fall back to dataMain
+ if (req.jsExtRegExp.test(mainScript)) {
+ mainScript = dataMain;
+ }
+
+ //Put the data-main script in the files to load.
+ cfg.deps = cfg.deps ? cfg.deps.concat(mainScript) : [mainScript];
+
+ return true;
+ }
+ });
+ }
+
+ /**
+ * The function that handles definitions of modules. Differs from
+ * require() in that a string for the module should be the first argument,
+ * and the function to execute after dependencies are loaded should
+ * return a value to define the module corresponding to the first argument's
+ * name.
+ */
+ define = function (name, deps, callback) {
+ var node, context;
+
+ //Allow for anonymous modules
+ if (typeof name !== 'string') {
+ //Adjust args appropriately
+ callback = deps;
+ deps = name;
+ name = null;
+ }
+
+ //This module may not have dependencies
+ if (!isArray(deps)) {
+ callback = deps;
+ deps = null;
+ }
+
+ //If no name, and callback is a function, then figure out if it a
+ //CommonJS thing with dependencies.
+ if (!deps && isFunction(callback)) {
+ deps = [];
+ //Remove comments from the callback string,
+ //look for require calls, and pull them into the dependencies,
+ //but only if there are function args.
+ if (callback.length) {
+ callback
+ .toString()
+ .replace(commentRegExp, '')
+ .replace(cjsRequireRegExp, function (match, dep) {
+ deps.push(dep);
+ });
+
+ //May be a CommonJS thing even without require calls, but still
+ //could use exports, and module. Avoid doing exports and module
+ //work though if it just needs require.
+ //REQUIRES the function to expect the CommonJS variables in the
+ //order listed below.
+ deps = (callback.length === 1 ? ['require'] : ['require', 'exports', 'module']).concat(deps);
+ }
+ }
+
+ //If in IE 6-8 and hit an anonymous define() call, do the interactive
+ //work.
+ if (useInteractive) {
+ node = currentlyAddingScript || getInteractiveScript();
+ if (node) {
+ if (!name) {
+ name = node.getAttribute('data-requiremodule');
+ }
+ context = contexts[node.getAttribute('data-requirecontext')];
+ }
+ }
+
+ //Always save off evaluating the def call until the script onload handler.
+ //This allows multiple modules to be in a file without prematurely
+ //tracing dependencies, and allows for anonymous module support,
+ //where the module name is not known until the script onload event
+ //occurs. If no context, use the global queue, and get it processed
+ //in the onscript load callback.
+ (context ? context.defQueue : globalDefQueue).push([name, deps, callback]);
+ };
+
+ define.amd = {
+ jQuery: true
+ };
+
+
+ /**
+ * Executes the text. Normally just uses eval, but can be modified
+ * to use a better, environment-specific call. Only used for transpiling
+ * loader plugins, not for plain JS modules.
+ * @param {String} text the text to execute/evaluate.
+ */
+ req.exec = function (text) {
+ /*jslint evil: true */
+ return eval(text);
+ };
+
+ //Set up with config info.
+ req(cfg);
+}(this));
+
+/*!
+ * jQuery JavaScript Library v2.1.0
+ * http://jquery.com/
+ *
+ * Includes Sizzle.js
+ * http://sizzlejs.com/
+ *
+ * Copyright 2005, 2014 jQuery Foundation, Inc. and other contributors
+ * Released under the MIT license
+ * http://jquery.org/license
+ *
+ * Date: 2014-01-23T21:10Z
+ */
+
+(function (global, factory) {
+
+ if ( typeof module === "object" && typeof module.exports === "object" ) {
+ // For CommonJS and CommonJS-like environments where a proper window is present,
+ // execute the factory and get jQuery
+ // For environments that do not inherently posses a window with a document
+ // (such as Node.js), expose a jQuery-making factory as module.exports
+ // This accentuates the need for the creation of a real window
+ // e.g. var jQuery = require("jquery")(window);
+ // See ticket #14549 for more info
+ module.exports = global.document ?
+ factory(global, true) :
+ function (w) {
+ if ( !w.document ) {
+ throw new Error("jQuery requires a window with a document");
+ }
+ return factory(w);
+ };
+ } else {
+ factory(global);
+ }
+
+// Pass this if window is not defined yet
+}(typeof window !== "undefined" ? window : this, function (window, noGlobal) {
+
+// Can't do this because several apps including ASP.NET trace
+// the stack via arguments.caller.callee and Firefox dies if
+// you try to trace through "use strict" call chains. (#13335)
+// Support: Firefox 18+
+//
+
+ var arr = [];
+
+ var slice = arr.slice;
+
+ var concat = arr.concat;
+
+ var push = arr.push;
+
+ var indexOf = arr.indexOf;
+
+ var class2type = {};
+
+ var toString = class2type.toString;
+
+ var hasOwn = class2type.hasOwnProperty;
+
+ var trim = "".trim;
+
+ var support = {};
+
+
+ var
+ // Use the correct document accordingly with window argument (sandbox)
+ document = window.document,
+
+ version = "2.1.0",
+
+ // Define a local copy of jQuery
+ jQuery = function (selector, context) {
+ // The jQuery object is actually just the init constructor 'enhanced'
+ // Need init if jQuery is called (just allow error to be thrown if not included)
+ return new jQuery.fn.init(selector, context);
+ },
+
+ // 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();
+ };
+
+ jQuery.fn = jQuery.prototype = {
+ // The current version of jQuery being used
+ jquery: version,
+
+ constructor: jQuery,
+
+ // Start with an empty selector
+ selector: "",
+
+ // The default length of a jQuery object is 0
+ length: 0,
+
+ toArray: function () {
+ return 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
+ ( num < 0 ? this[ num + this.length ] : this[ num ] ) :
+
+ // Return just the object
+ slice.call(this);
+ },
+
+ // Take an array of elements and push it onto the stack
+ // (returning the new matched element set)
+ pushStack: function (elems) {
+
+ // Build a new jQuery matched element set
+ var ret = jQuery.merge(this.constructor(), elems);
+
+ // Add the old object onto the stack (as a reference)
+ ret.prevObject = this;
+ ret.context = this.context;
+
+ // Return the newly-formed element set
+ return ret;
+ },
+
+ // Execute a callback for every element in the matched set.
+ // (You can seed the arguments with an array of args, but this is
+ // only used internally.)
+ each: function (callback, args) {
+ return jQuery.each(this, callback, args);
+ },
+
+ map: function (callback) {
+ return this.pushStack(jQuery.map(this, function (elem, i) {
+ return callback.call(elem, i, elem);
+ }));
+ },
+
+ slice: function () {
+ return this.pushStack(slice.apply(this, arguments));
+ },
+
+ first: function () {
+ return this.eq(0);
+ },
+
+ last: function () {
+ return this.eq(-1);
+ },
+
+ eq: function (i) {
+ var len = this.length,
+ j = +i + ( i < 0 ? len : 0 );
+ return this.pushStack(j >= 0 && j < len ? [ this[j] ] : []);
+ },
+
+ end: function () {
+ return this.prevObject || this.constructor(null);
+ },
+
+ // For internal use only.
+ // Behaves like an Array's method, not like a jQuery method.
+ push: push,
+ sort: arr.sort,
+ splice: arr.splice
+ };
+
+ 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;
+
+ // skip the boolean and the target
+ target = arguments[ i ] || {};
+ i++;
+ }
+
+ // 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 ( i === length ) {
+ 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({
+ // Unique for each copy of jQuery on the page
+ expando: "jQuery" + ( version + Math.random() ).replace(/\D/g, ""),
+
+ // Assume jQuery is ready without the ready module
+ isReady: true,
+
+ error: function (msg) {
+ throw new Error(msg);
+ },
+
+ noop: function () {
+ },
+
+ // 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,
+
+ isWindow: function (obj) {
+ return obj != null && obj === obj.window;
+ },
+
+ isNumeric: function (obj) {
+ // parseFloat NaNs numeric-cast false positives (null|true|false|"")
+ // ...but misinterprets leading-number strings, particularly hex literals ("0x...")
+ // subtraction forces infinities to NaN
+ return obj - parseFloat(obj) >= 0;
+ },
+
+ isPlainObject: function (obj) {
+ // Not plain objects:
+ // - Any object or value whose internal [[Class]] property is not "[object Object]"
+ // - DOM nodes
+ // - window
+ if ( jQuery.type(obj) !== "object" || obj.nodeType || jQuery.isWindow(obj) ) {
+ return false;
+ }
+
+ // Support: Firefox <20
+ // The try/catch suppresses exceptions thrown when attempting to access
+ // the "constructor" property of certain host objects, ie. |window.location|
+ // https://bugzilla.mozilla.org/show_bug.cgi?id=814622
+ try {
+ if ( obj.constructor && !hasOwn.call(obj.constructor.prototype, "isPrototypeOf") ) {
+ return false;
+ }
+ } catch (e) {
+ return false;
+ }
+
+ // If the function hasn't returned already, we're confident that
+ // |obj| is a plain object, created by {} or constructed with new Object
+ return true;
+ },
+
+ isEmptyObject: function (obj) {
+ var name;
+ for ( name in obj ) {
+ return false;
+ }
+ return true;
+ },
+
+ type: function (obj) {
+ if ( obj == null ) {
+ return obj + "";
+ }
+ // Support: Android < 4.0, iOS < 6 (functionish RegExp)
+ return typeof obj === "object" || typeof obj === "function" ?
+ class2type[ toString.call(obj) ] || "object" :
+ typeof obj;
+ },
+
+ // Evaluates a script in a global context
+ globalEval: function (code) {
+ var script,
+ indirect = eval;
+
+ code = jQuery.trim(code);
+
+ if ( code ) {
+ // If the code includes a valid, prologue position
+ // strict mode pragma, execute code by injecting a
+ // script tag into the document.
+ if ( code.indexOf("use strict") === 1 ) {
+ script = document.createElement("script");
+ script.text = code;
+ document.head.appendChild(script).parentNode.removeChild(script);
+ } else {
+ // Otherwise, avoid the DOM node creation, insertion
+ // and removal by using an indirect global eval
+ indirect(code);
+ }
+ }
+ },
+
+ // Convert dashed to camelCase; used by the css and data modules
+ // Microsoft forgot to hump their vendor prefix (#9572)
+ camelCase: function (string) {
+ return string.replace(rmsPrefix, "ms-").replace(rdashAlpha, fcamelCase);
+ },
+
+ nodeName: function (elem, name) {
+ return elem.nodeName && elem.nodeName.toLowerCase() === name.toLowerCase();
+ },
+
+ // args is for internal usage only
+ each: function (obj, callback, args) {
+ var value,
+ i = 0,
+ length = obj.length,
+ isArray = isArraylike(obj);
+
+ if ( args ) {
+ if ( isArray ) {
+ for ( ; i < length; i++ ) {
+ value = callback.apply(obj[ i ], args);
+
+ if ( value === false ) {
+ break;
+ }
+ }
+ } else {
+ for ( i in obj ) {
+ value = callback.apply(obj[ i ], args);
+
+ if ( value === false ) {
+ break;
+ }
+ }
+ }
+
+ // A special, fast, case for the most common use of each
+ } else {
+ if ( isArray ) {
+ for ( ; i < length; i++ ) {
+ value = callback.call(obj[ i ], i, obj[ i ]);
+
+ if ( value === false ) {
+ break;
+ }
+ }
+ } else {
+ for ( i in obj ) {
+ value = callback.call(obj[ i ], i, obj[ i ]);
+
+ if ( value === false ) {
+ break;
+ }
+ }
+ }
+ }
+
+ return obj;
+ },
+
+ trim: function (text) {
+ return text == null ? "" : trim.call(text);
+ },
+
+ // results is for internal usage only
+ makeArray: function (arr, results) {
+ var ret = results || [];
+
+ if ( arr != null ) {
+ if ( isArraylike(Object(arr)) ) {
+ jQuery.merge(ret,
+ typeof arr === "string" ?
+ [ arr ] : arr
+ );
+ } else {
+ push.call(ret, arr);
+ }
+ }
+
+ return ret;
+ },
+
+ inArray: function (elem, arr, i) {
+ return arr == null ? -1 : indexOf.call(arr, elem, i);
+ },
+
+ merge: function (first, second) {
+ var len = +second.length,
+ j = 0,
+ i = first.length;
+
+ for ( ; j < len; j++ ) {
+ first[ i++ ] = second[ j ];
+ }
+
+ first.length = i;
+
+ return first;
+ },
+
+ grep: function (elems, callback, invert) {
+ var callbackInverse,
+ matches = [],
+ i = 0,
+ length = elems.length,
+ callbackExpect = !invert;
+
+ // Go through the array, only saving the items
+ // that pass the validator function
+ for ( ; i < length; i++ ) {
+ callbackInverse = !callback(elems[ i ], i);
+ if ( callbackInverse !== callbackExpect ) {
+ matches.push(elems[ i ]);
+ }
+ }
+
+ return matches;
+ },
+
+ // arg is for internal usage only
+ map: function (elems, callback, arg) {
+ var value,
+ i = 0,
+ length = elems.length,
+ isArray = isArraylike(elems),
+ ret = [];
+
+ // Go through the array, translating each of the items to their new values
+ if ( isArray ) {
+ for ( ; i < length; i++ ) {
+ value = callback(elems[ i ], i, arg);
+
+ if ( value != null ) {
+ ret.push(value);
+ }
+ }
+
+ // Go through every key on the object,
+ } else {
+ for ( i in elems ) {
+ value = callback(elems[ i ], i, arg);
+
+ if ( value != null ) {
+ ret.push(value);
+ }
+ }
+ }
+
+ // Flatten any nested arrays
+ return 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 = slice.call(arguments, 2);
+ proxy = function () {
+ return fn.apply(context || this, args.concat(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;
+ },
+
+ now: Date.now,
+
+ // jQuery.support is not used in Core but other projects attach their
+ // properties to it so it needs to exist.
+ support: support
+ });
+
+// Populate the class2type map
+ jQuery.each("Boolean Number String Function Array Date RegExp Object Error".split(" "), function (i, name) {
+ class2type[ "[object " + name + "]" ] = name.toLowerCase();
+ });
+
+ function isArraylike(obj) {
+ var length = obj.length,
+ type = jQuery.type(obj);
+
+ if ( type === "function" || jQuery.isWindow(obj) ) {
+ return false;
+ }
+
+ if ( obj.nodeType === 1 && length ) {
+ return true;
+ }
+
+ return type === "array" || length === 0 ||
+ typeof length === "number" && length > 0 && ( length - 1 ) in obj;
+ }
+
+ var Sizzle =
+ /*!
+ * Sizzle CSS Selector Engine v1.10.16
+ * http://sizzlejs.com/
+ *
+ * Copyright 2013 jQuery Foundation, Inc. and other contributors
+ * Released under the MIT license
+ * http://jquery.org/license
+ *
+ * Date: 2014-01-13
+ */
+ (function (window) {
+
+ var i,
+ support,
+ Expr,
+ getText,
+ isXML,
+ compile,
+ outermostContext,
+ sortInput,
+ hasDuplicate,
+
+ // Local document vars
+ setDocument,
+ document,
+ docElem,
+ documentIsHTML,
+ rbuggyQSA,
+ rbuggyMatches,
+ matches,
+ contains,
+
+ // Instance-specific data
+ expando = "sizzle" + -(new Date()),
+ preferredDoc = window.document,
+ dirruns = 0,
+ done = 0,
+ classCache = createCache(),
+ tokenCache = createCache(),
+ compilerCache = createCache(),
+ sortOrder = function (a, b) {
+ if ( a === b ) {
+ hasDuplicate = true;
+ }
+ return 0;
+ },
+
+ // General-purpose constants
+ strundefined = typeof undefined,
+ MAX_NEGATIVE = 1 << 31,
+
+ // Instance methods
+ hasOwn = ({}).hasOwnProperty,
+ arr = [],
+ pop = arr.pop,
+ push_native = arr.push,
+ push = arr.push,
+ slice = arr.slice,
+ // Use a stripped-down indexOf if we can't use a native one
+ indexOf = arr.indexOf || function (elem) {
+ var i = 0,
+ len = this.length;
+ for ( ; i < len; i++ ) {
+ if ( this[i] === elem ) {
+ return i;
+ }
+ }
+ return -1;
+ },
+
+ booleans = "checked|selected|async|autofocus|autoplay|controls|defer|disabled|hidden|ismap|loop|multiple|open|readonly|required|scoped",
+
+ // Regular expressions
+
+ // Whitespace characters http://www.w3.org/TR/css3-selectors/#whitespace
+ whitespace = "[\\x20\\t\\r\\n\\f]",
+ // http://www.w3.org/TR/css3-syntax/#characters
+ characterEncoding = "(?:\\\\.|[\\w-]|[^\\x00-\\xa0])+",
+
+ // Loosely modeled on CSS identifier characters
+ // An unquoted value should be a CSS identifier http://www.w3.org/TR/css3-selectors/#attribute-selectors
+ // Proper syntax: http://www.w3.org/TR/CSS21/syndata.html#value-def-identifier
+ identifier = characterEncoding.replace("w", "w#"),
+
+ // Acceptable operators http://www.w3.org/TR/selectors/#attribute-selectors
+ attributes = "\\[" + whitespace + "*(" + characterEncoding + ")" + whitespace +
+ "*(?:([*^$|!~]?=)" + whitespace + "*(?:(['\"])((?:\\\\.|[^\\\\])*?)\\3|(" + identifier + ")|)|)" + whitespace + "*\\]",
+
+ // Prefer arguments quoted,
+ // then not containing pseudos/brackets,
+ // then attribute selectors/non-parenthetical expressions,
+ // then anything else
+ // These preferences are here to reduce the number of selectors
+ // needing tokenize in the PSEUDO preFilter
+ pseudos = ":(" + characterEncoding + ")(?:\\(((['\"])((?:\\\\.|[^\\\\])*?)\\3|((?:\\\\.|[^\\\\()[\\]]|" + attributes.replace(3, 8) + ")*)|.*)\\)|)",
+
+ // Leading and non-escaped trailing whitespace, capturing some non-whitespace characters preceding the latter
+ rtrim = new RegExp("^" + whitespace + "+|((?:^|[^\\\\])(?:\\\\.)*)" + whitespace + "+$", "g"),
+
+ rcomma = new RegExp("^" + whitespace + "*," + whitespace + "*"),
+ rcombinators = new RegExp("^" + whitespace + "*([>+~]|" + whitespace + ")" + whitespace + "*"),
+
+ rattributeQuotes = new RegExp("=" + whitespace + "*([^\\]'\"]*?)" + whitespace + "*\\]", "g"),
+
+ rpseudo = new RegExp(pseudos),
+ ridentifier = new RegExp("^" + identifier + "$"),
+
+ matchExpr = {
+ "ID": new RegExp("^#(" + characterEncoding + ")"),
+ "CLASS": new RegExp("^\\.(" + characterEncoding + ")"),
+ "TAG": new RegExp("^(" + characterEncoding.replace("w", "w*") + ")"),
+ "ATTR": new RegExp("^" + attributes),
+ "PSEUDO": new RegExp("^" + pseudos),
+ "CHILD": new RegExp("^:(only|first|last|nth|nth-last)-(child|of-type)(?:\\(" + whitespace +
+ "*(even|odd|(([+-]|)(\\d*)n|)" + whitespace + "*(?:([+-]|)" + whitespace +
+ "*(\\d+)|))" + whitespace + "*\\)|)", "i"),
+ "bool": new RegExp("^(?:" + booleans + ")$", "i"),
+ // For use in libraries implementing .is()
+ // We use this for POS matching in `select`
+ "needsContext": new RegExp("^" + whitespace + "*[>+~]|:(even|odd|eq|gt|lt|nth|first|last)(?:\\(" +
+ whitespace + "*((?:-\\d)?\\d*)" + whitespace + "*\\)|)(?=[^-]|$)", "i")
+ },
+
+ rinputs = /^(?:input|select|textarea|button)$/i,
+ rheader = /^h\d$/i,
+
+ rnative = /^[^{]+\{\s*\[native \w/,
+
+ // Easily-parseable/retrievable ID or TAG or CLASS selectors
+ rquickExpr = /^(?:#([\w-]+)|(\w+)|\.([\w-]+))$/,
+
+ rsibling = /[+~]/,
+ rescape = /'|\\/g,
+
+ // CSS escapes http://www.w3.org/TR/CSS21/syndata.html#escaped-characters
+ runescape = new RegExp("\\\\([\\da-f]{1,6}" + whitespace + "?|(" + whitespace + ")|.)", "ig"),
+ funescape = function (_, escaped, escapedWhitespace) {
+ var high = "0x" + escaped - 0x10000;
+ // NaN means non-codepoint
+ // Support: Firefox
+ // Workaround erroneous numeric interpretation of +"0x"
+ return high !== high || escapedWhitespace ?
+ escaped :
+ high < 0 ?
+ // BMP codepoint
+ String.fromCharCode(high + 0x10000) :
+ // Supplemental Plane codepoint (surrogate pair)
+ String.fromCharCode(high >> 10 | 0xD800, high & 0x3FF | 0xDC00);
+ };
+
+// Optimize for push.apply( _, NodeList )
+ try {
+ push.apply(
+ (arr = slice.call(preferredDoc.childNodes)),
+ preferredDoc.childNodes
+ );
+ // Support: Android<4.0
+ // Detect silently failing push.apply
+ arr[ preferredDoc.childNodes.length ].nodeType;
+ } catch (e) {
+ push = { apply: arr.length ?
+
+ // Leverage slice if possible
+ function (target, els) {
+ push_native.apply(target, slice.call(els));
+ } :
+
+ // Support: IE<9
+ // Otherwise append directly
+ function (target, els) {
+ var j = target.length,
+ i = 0;
+ // Can't trust NodeList.length
+ while ( (target[j++] = els[i++]) ) {
+ }
+ target.length = j - 1;
+ }
+ };
+ }
+
+ function Sizzle(selector, context, results, seed) {
+ var match, elem, m, nodeType,
+ // QSA vars
+ i, groups, old, nid, newContext, newSelector;
+
+ if ( ( context ? context.ownerDocument || context : preferredDoc ) !== document ) {
+ setDocument(context);
+ }
+
+ context = context || document;
+ results = results || [];
+
+ if ( !selector || typeof selector !== "string" ) {
+ return results;
+ }
+
+ if ( (nodeType = context.nodeType) !== 1 && nodeType !== 9 ) {
+ return [];
+ }
+
+ if ( documentIsHTML && !seed ) {
+
+ // Shortcuts
+ if ( (match = rquickExpr.exec(selector)) ) {
+ // Speed-up: Sizzle("#ID")
+ if ( (m = match[1]) ) {
+ if ( nodeType === 9 ) {
+ elem = context.getElementById(m);
+ // Check parentNode to catch when Blackberry 4.6 returns
+ // nodes that are no longer in the document (jQuery #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, context.getElementsByTagName(selector));
+ return results;
+
+ // Speed-up: Sizzle(".CLASS")
+ } else if ( (m = match[3]) && support.getElementsByClassName && context.getElementsByClassName ) {
+ push.apply(results, context.getElementsByClassName(m));
+ return results;
+ }
+ }
+
+ // QSA path
+ if ( support.qsa && (!rbuggyQSA || !rbuggyQSA.test(selector)) ) {
+ nid = old = expando;
+ newContext = context;
+ newSelector = nodeType === 9 && selector;
+
+ // qSA works strangely on Element-rooted queries
+ // We can work around this by specifying an extra ID on the root
+ // and working up from there (Thanks to Andrew Dupont for the technique)
+ // IE 8 doesn't work on object elements
+ if ( nodeType === 1 && context.nodeName.toLowerCase() !== "object" ) {
+ groups = tokenize(selector);
+
+ if ( (old = context.getAttribute("id")) ) {
+ nid = old.replace(rescape, "\\$&");
+ } else {
+ context.setAttribute("id", nid);
+ }
+ nid = "[id='" + nid + "'] ";
+
+ i = groups.length;
+ while ( i-- ) {
+ groups[i] = nid + toSelector(groups[i]);
+ }
+ newContext = rsibling.test(selector) && testContext(context.parentNode) || context;
+ newSelector = groups.join(",");
+ }
+
+ if ( newSelector ) {
+ try {
+ push.apply(results,
+ newContext.querySelectorAll(newSelector)
+ );
+ return results;
+ } catch (qsaError) {
+ } finally {
+ if ( !old ) {
+ context.removeAttribute("id");
+ }
+ }
+ }
+ }
+ }
+
+ // All others
+ return select(selector.replace(rtrim, "$1"), context, results, seed);
+ }
+
+ /**
+ * Create key-value caches of limited size
+ * @returns {Function(string, Object)} Returns the Object data after storing it on itself with
+ * property name the (space-suffixed) string and (if the cache is larger than Expr.cacheLength)
+ * deleting the oldest entry
+ */
+ function createCache() {
+ var keys = [];
+
+ function cache(key, value) {
+ // Use (key + " ") to avoid collision with native prototype properties (see Issue #157)
+ if ( keys.push(key + " ") > Expr.cacheLength ) {
+ // Only keep the most recent entries
+ delete cache[ keys.shift() ];
+ }
+ return (cache[ key + " " ] = value);
+ }
+
+ return cache;
+ }
+
+ /**
+ * Mark a function for special use by Sizzle
+ * @param {Function} fn The function to mark
+ */
+ function markFunction(fn) {
+ fn[ expando ] = true;
+ return fn;
+ }
+
+ /**
+ * Support testing using an element
+ * @param {Function} fn Passed the created div and expects a boolean result
+ */
+ function assert(fn) {
+ var div = document.createElement("div");
+
+ try {
+ return !!fn(div);
+ } catch (e) {
+ return false;
+ } finally {
+ // Remove from its parent by default
+ if ( div.parentNode ) {
+ div.parentNode.removeChild(div);
+ }
+ // release memory in IE
+ div = null;
+ }
+ }
+
+ /**
+ * Adds the same handler for all of the specified attrs
+ * @param {String} attrs Pipe-separated list of attributes
+ * @param {Function} handler The method that will be applied
+ */
+ function addHandle(attrs, handler) {
+ var arr = attrs.split("|"),
+ i = attrs.length;
+
+ while ( i-- ) {
+ Expr.attrHandle[ arr[i] ] = handler;
+ }
+ }
+
+ /**
+ * Checks document order of two siblings
+ * @param {Element} a
+ * @param {Element} b
+ * @returns {Number} Returns less than 0 if a precedes b, greater than 0 if a follows b
+ */
+ function siblingCheck(a, b) {
+ var cur = b && a,
+ diff = cur && a.nodeType === 1 && b.nodeType === 1 &&
+ ( ~b.sourceIndex || MAX_NEGATIVE ) -
+ ( ~a.sourceIndex || MAX_NEGATIVE );
+
+ // Use IE sourceIndex if available on both nodes
+ if ( diff ) {
+ return diff;
+ }
+
+ // Check if b follows a
+ if ( cur ) {
+ while ( (cur = cur.nextSibling) ) {
+ if ( cur === b ) {
+ return -1;
+ }
+ }
+ }
+
+ return a ? 1 : -1;
+ }
+
+ /**
+ * Returns a function to use in pseudos for input types
+ * @param {String} type
+ */
+ 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
+ * @param {String} type
+ */
+ 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
+ * @param {Function} fn
+ */
+ 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]);
+ }
+ }
+ });
+ });
+ }
+
+ /**
+ * Checks a node for validity as a Sizzle context
+ * @param {Element|Object=} context
+ * @returns {Element|Object|Boolean} The input node if acceptable, otherwise a falsy value
+ */
+ function testContext(context) {
+ return context && typeof context.getElementsByTagName !== strundefined && context;
+ }
+
+// Expose support vars for convenience
+ support = Sizzle.support = {};
+
+ /**
+ * Detects XML nodes
+ * @param {Element|Object} elem An element or a document
+ * @returns {Boolean} True iff elem is a non-HTML XML node
+ */
+ isXML = Sizzle.isXML = function (elem) {
+ // documentElement is verified for cases where it doesn't yet exist
+ // (such as loading iframes in IE - #4833)
+ var documentElement = elem && (elem.ownerDocument || elem).documentElement;
+ return documentElement ? documentElement.nodeName !== "HTML" : false;
+ };
+
+ /**
+ * Sets document-related variables once based on the current document
+ * @param {Element|Object} [doc] An element or document object to use to set the document
+ * @returns {Object} Returns the current document
+ */
+ setDocument = Sizzle.setDocument = function (node) {
+ var hasCompare,
+ doc = node ? node.ownerDocument || node : preferredDoc,
+ parent = doc.defaultView;
+
+ // If no document and documentElement is available, return
+ if ( doc === document || doc.nodeType !== 9 || !doc.documentElement ) {
+ return document;
+ }
+
+ // Set our document
+ document = doc;
+ docElem = doc.documentElement;
+
+ // Support tests
+ documentIsHTML = !isXML(doc);
+
+ // Support: IE>8
+ // If iframe document is assigned to "document" variable and if iframe has been reloaded,
+ // IE will throw "permission denied" error when accessing "document" variable, see jQuery #13936
+ // IE6-8 do not support the defaultView property so parent will be undefined
+ if ( parent && parent !== parent.top ) {
+ // IE11 does not have attachEvent, so all must suffer
+ if ( parent.addEventListener ) {
+ parent.addEventListener("unload", function () {
+ setDocument();
+ }, false);
+ } else if ( parent.attachEvent ) {
+ parent.attachEvent("onunload", function () {
+ setDocument();
+ });
+ }
+ }
+
+ /* Attributes
+ ---------------------------------------------------------------------- */
+
+ // Support: IE<8
+ // Verify that getAttribute really returns attributes and not properties (excepting IE8 booleans)
+ support.attributes = assert(function (div) {
+ div.className = "i";
+ return !div.getAttribute("className");
+ });
+
+ /* getElement(s)By*
+ ---------------------------------------------------------------------- */
+
+ // Check if getElementsByTagName("*") returns only elements
+ support.getElementsByTagName = assert(function (div) {
+ div.appendChild(doc.createComment(""));
+ return !div.getElementsByTagName("*").length;
+ });
+
+ // Check if getElementsByClassName can be trusted
+ support.getElementsByClassName = rnative.test(doc.getElementsByClassName) && assert(function (div) {
+ div.innerHTML = "<div class='a'></div><div class='a i'></div>";
+
+ // Support: Safari<4
+ // Catch class over-caching
+ div.firstChild.className = "i";
+ // Support: Opera<10
+ // Catch gEBCN failure to find non-leading classes
+ return div.getElementsByClassName("i").length === 2;
+ });
+
+ // Support: IE<10
+ // Check if getElementById returns elements by name
+ // The broken getElementById methods don't pick up programatically-set names,
+ // so use a roundabout getElementsByName test
+ support.getById = assert(function (div) {
+ docElem.appendChild(div).id = expando;
+ return !doc.getElementsByName || !doc.getElementsByName(expando).length;
+ });
+
+ // ID find and filter
+ if ( support.getById ) {
+ Expr.find["ID"] = function (id, context) {
+ if ( typeof context.getElementById !== strundefined && documentIsHTML ) {
+ var m = context.getElementById(id);
+ // Check parentNode to catch when Blackberry 4.6 returns
+ // nodes that are no longer in the document #6963
+ return m && m.parentNode ? [m] : [];
+ }
+ };
+ Expr.filter["ID"] = function (id) {
+ var attrId = id.replace(runescape, funescape);
+ return function (elem) {
+ return elem.getAttribute("id") === attrId;
+ };
+ };
+ } else {
+ // Support: IE6/7
+ // getElementById is not reliable as a find shortcut
+ delete Expr.find["ID"];
+
+ Expr.filter["ID"] = function (id) {
+ var attrId = id.replace(runescape, funescape);
+ return function (elem) {
+ var node = typeof elem.getAttributeNode !== strundefined && elem.getAttributeNode("id");
+ return node && node.value === attrId;
+ };
+ };
+ }
+
+ // Tag
+ Expr.find["TAG"] = support.getElementsByTagName ?
+ function (tag, context) {
+ if ( typeof context.getElementsByTagName !== strundefined ) {
+ return context.getElementsByTagName(tag);
+ }
+ } :
+ function (tag, context) {
+ var elem,
+ tmp = [],
+ i = 0,
+ results = context.getElementsByTagName(tag);
+
+ // Filter out possible comments
+ if ( tag === "*" ) {
+ while ( (elem = results[i++]) ) {
+ if ( elem.nodeType === 1 ) {
+ tmp.push(elem);
+ }
+ }
+
+ return tmp;
+ }
+ return results;
+ };
+
+ // Class
+ Expr.find["CLASS"] = support.getElementsByClassName && function (className, context) {
+ if ( typeof context.getElementsByClassName !== strundefined && documentIsHTML ) {
+ return context.getElementsByClassName(className);
+ }
+ };
+
+ /* QSA/matchesSelector
+ ---------------------------------------------------------------------- */
+
+ // QSA and matchesSelector support
+
+ // matchesSelector(:active) reports false when true (IE9/Opera 11.5)
+ rbuggyMatches = [];
+
+ // qSa(:focus) reports false when true (Chrome 21)
+ // We allow this because of a bug in IE8/9 that throws an error
+ // whenever `document.activeElement` is accessed on an iframe
+ // So, we allow :focus to pass through QSA all the time to avoid the IE error
+ // See http://bugs.jquery.com/ticket/13378
+ rbuggyQSA = [];
+
+ if ( (support.qsa = rnative.test(doc.querySelectorAll)) ) {
+ // Build QSA regex
+ // Regex strategy adopted from Diego Perini
+ assert(function (div) {
+ // Select is set to empty string on purpose
+ // This is to test IE's treatment of not explicitly
+ // setting a boolean content attribute,
+ // since its presence should be enough
+ // http://bugs.jquery.com/ticket/12359
+ div.innerHTML = "<select t=''><option selected=''></option></select>";
+
+ // Support: IE8, Opera 10-12
+ // Nothing should be selected when empty strings follow ^= or $= or *=
+ if ( div.querySelectorAll("[t^='']").length ) {
+ rbuggyQSA.push("[*^$]=" + whitespace + "*(?:''|\"\")");
+ }
+
+ // Support: IE8
+ // Boolean attributes and "value" are not treated correctly
+ if ( !div.querySelectorAll("[selected]").length ) {
+ rbuggyQSA.push("\\[" + whitespace + "*(?:value|" + booleans + ")");
+ }
+
+ // Webkit/Opera - :checked should return selected option elements
+ // http://www.w3.org/TR/2011/REC-css3-selectors-20110929/#checked
+ // IE8 throws error here and will not see later tests
+ if ( !div.querySelectorAll(":checked").length ) {
+ rbuggyQSA.push(":checked");
+ }
+ });
+
+ assert(function (div) {
+ // Support: Windows 8 Native Apps
+ // The type and name attributes are restricted during .innerHTML assignment
+ var input = doc.createElement("input");
+ input.setAttribute("type", "hidden");
+ div.appendChild(input).setAttribute("name", "D");
+
+ // Support: IE8
+ // Enforce case-sensitivity of name attribute
+ if ( div.querySelectorAll("[name=d]").length ) {
+ rbuggyQSA.push("name" + whitespace + "*[*^$|!~]?=");
+ }
+
+ // FF 3.5 - :enabled/:disabled and hidden elements (hidden elements are still enabled)
+ // IE8 throws error here and will not see later tests
+ if ( !div.querySelectorAll(":enabled").length ) {
+ rbuggyQSA.push(":enabled", ":disabled");
+ }
+
+ // Opera 10-11 does not throw on post-comma invalid pseudos
+ div.querySelectorAll("*,:x");
+ rbuggyQSA.push(",.*:");
+ });
+ }
+
+ if ( (support.matchesSelector = rnative.test((matches = docElem.webkitMatchesSelector ||
+ docElem.mozMatchesSelector ||
+ docElem.oMatchesSelector ||
+ docElem.msMatchesSelector))) ) {
+
+ assert(function (div) {
+ // Check to see if it's possible to do matchesSelector
+ // on a disconnected node (IE 9)
+ support.disconnectedMatch = matches.call(div, "div");
+
+ // This should fail with an exception
+ // Gecko does not error, returns false instead
+ matches.call(div, "[s!='']:x");
+ rbuggyMatches.push("!=", pseudos);
+ });
+ }
+
+ rbuggyQSA = rbuggyQSA.length && new RegExp(rbuggyQSA.join("|"));
+ rbuggyMatches = rbuggyMatches.length && new RegExp(rbuggyMatches.join("|"));
+
+ /* Contains
+ ---------------------------------------------------------------------- */
+ hasCompare = rnative.test(docElem.compareDocumentPosition);
+
+ // Element contains another
+ // Purposefully does not implement inclusive descendent
+ // As in, an element does not contain itself
+ contains = hasCompare || rnative.test(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) :
+ a.compareDocumentPosition && a.compareDocumentPosition(bup) & 16
+ ));
+ } :
+ function (a, b) {
+ if ( b ) {
+ while ( (b = b.parentNode) ) {
+ if ( b === a ) {
+ return true;
+ }
+ }
+ }
+ return false;
+ };
+
+ /* Sorting
+ ---------------------------------------------------------------------- */
+
+ // Document order sorting
+ sortOrder = hasCompare ?
+ function (a, b) {
+
+ // Flag for duplicate removal
+ if ( a === b ) {
+ hasDuplicate = true;
+ return 0;
+ }
+
+ // Sort on method existence if only one input has compareDocumentPosition
+ var compare = !a.compareDocumentPosition - !b.compareDocumentPosition;
+ if ( compare ) {
+ return compare;
+ }
+
+ // Calculate position if both inputs belong to the same document
+ compare = ( a.ownerDocument || a ) === ( b.ownerDocument || b ) ?
+ a.compareDocumentPosition(b) :
+
+ // Otherwise we know they are disconnected
+ 1;
+
+ // Disconnected nodes
+ if ( compare & 1 ||
+ (!support.sortDetached && b.compareDocumentPosition(a) === compare) ) {
+
+ // Choose the first element that is related to our preferred document
+ if ( a === doc || a.ownerDocument === preferredDoc && contains(preferredDoc, a) ) {
+ return -1;
+ }
+ if ( b === doc || b.ownerDocument === preferredDoc && contains(preferredDoc, b) ) {
+ return 1;
+ }
+
+ // Maintain original order
+ return sortInput ?
+ ( indexOf.call(sortInput, a) - indexOf.call(sortInput, b) ) :
+ 0;
+ }
+
+ return compare & 4 ? -1 : 1;
+ } :
+ function (a, b) {
+ // Exit early if the nodes are identical
+ if ( a === b ) {
+ hasDuplicate = true;
+ return 0;
+ }
+
+ var cur,
+ i = 0,
+ aup = a.parentNode,
+ bup = b.parentNode,
+ ap = [ a ],
+ bp = [ b ];
+
+ // Parentless nodes are either documents or disconnected
+ if ( !aup || !bup ) {
+ return a === doc ? -1 :
+ b === doc ? 1 :
+ aup ? -1 :
+ bup ? 1 :
+ sortInput ?
+ ( indexOf.call(sortInput, a) - indexOf.call(sortInput, b) ) :
+ 0;
+
+ // If the nodes are siblings, we can do a quick check
+ } else if ( aup === bup ) {
+ return siblingCheck(a, b);
+ }
+
+ // Otherwise we need full lists of their ancestors for comparison
+ cur = a;
+ while ( (cur = cur.parentNode) ) {
+ ap.unshift(cur);
+ }
+ cur = b;
+ while ( (cur = cur.parentNode) ) {
+ bp.unshift(cur);
+ }
+
+ // Walk down the tree looking for a discrepancy
+ while ( ap[i] === bp[i] ) {
+ i++;
+ }
+
+ return i ?
+ // Do a sibling check if the nodes have a common ancestor
+ siblingCheck(ap[i], bp[i]) :
+
+ // Otherwise nodes in our document sort first
+ ap[i] === preferredDoc ? -1 :
+ bp[i] === preferredDoc ? 1 :
+ 0;
+ };
+
+ return doc;
+ };
+
+ Sizzle.matches = function (expr, elements) {
+ return Sizzle(expr, null, null, elements);
+ };
+
+ Sizzle.matchesSelector = function (elem, expr) {
+ // Set document vars if needed
+ if ( ( elem.ownerDocument || elem ) !== document ) {
+ setDocument(elem);
+ }
+
+ // Make sure that attribute selectors are quoted
+ expr = expr.replace(rattributeQuotes, "='$1']");
+
+ if ( support.matchesSelector && documentIsHTML &&
+ ( !rbuggyMatches || !rbuggyMatches.test(expr) ) &&
+ ( !rbuggyQSA || !rbuggyQSA.test(expr) ) ) {
+
+ try {
+ var ret = matches.call(elem, expr);
+
+ // IE 9's matchesSelector returns false on disconnected nodes
+ if ( ret || support.disconnectedMatch ||
+ // As well, disconnected nodes are said to be in a document
+ // fragment in IE 9
+ elem.document && elem.document.nodeType !== 11 ) {
+ return ret;
+ }
+ } catch (e) {
+ }
+ }
+
+ return Sizzle(expr, document, null, [elem]).length > 0;
+ };
+
+ Sizzle.contains = function (context, elem) {
+ // Set document vars if needed
+ if ( ( context.ownerDocument || context ) !== document ) {
+ setDocument(context);
+ }
+ return contains(context, elem);
+ };
+
+ Sizzle.attr = function (elem, name) {
+ // Set document vars if needed
+ if ( ( elem.ownerDocument || elem ) !== document ) {
+ setDocument(elem);
+ }
+
+ var fn = Expr.attrHandle[ name.toLowerCase() ],
+ // Don't get fooled by Object.prototype properties (jQuery #13807)
+ val = fn && hasOwn.call(Expr.attrHandle, name.toLowerCase()) ?
+ fn(elem, name, !documentIsHTML) :
+ undefined;
+
+ return val !== undefined ?
+ val :
+ support.attributes || !documentIsHTML ?
+ elem.getAttribute(name) :
+ (val = elem.getAttributeNode(name)) && val.specified ?
+ val.value :
+ null;
+ };
+
+ Sizzle.error = function (msg) {
+ throw new Error("Syntax error, unrecognized expression: " + msg);
+ };
+
+ /**
+ * Document sorting and removing duplicates
+ * @param {ArrayLike} results
+ */
+ Sizzle.uniqueSort = function (results) {
+ var elem,
+ duplicates = [],
+ j = 0,
+ i = 0;
+
+ // Unless we *know* we can detect duplicates, assume their presence
+ hasDuplicate = !support.detectDuplicates;
+ sortInput = !support.sortStable && results.slice(0);
+ results.sort(sortOrder);
+
+ if ( hasDuplicate ) {
+ while ( (elem = results[i++]) ) {
+ if ( elem === results[ i ] ) {
+ j = duplicates.push(i);
+ }
+ }
+ while ( j-- ) {
+ results.splice(duplicates[ j ], 1);
+ }
+ }
+
+ // Clear input after sorting to release objects
+ // See https://github.com/jquery/sizzle/pull/225
+ sortInput = null;
+
+ return results;
+ };
+
+ /**
+ * Utility function for retrieving the text value of an array of DOM nodes
+ * @param {Array|Element} elem
+ */
+ getText = Sizzle.getText = function (elem) {
+ var node,
+ ret = "",
+ i = 0,
+ nodeType = elem.nodeType;
+
+ if ( !nodeType ) {
+ // If no nodeType, this is expected to be an array
+ while ( (node = elem[i++]) ) {
+ // Do not traverse comment nodes
+ ret += getText(node);
+ }
+ } else if ( nodeType === 1 || nodeType === 9 || nodeType === 11 ) {
+ // Use textContent for elements
+ // innerText usage removed for consistency of new lines (jQuery #11153)
+ if ( typeof elem.textContent === "string" ) {
+ return elem.textContent;
+ } else {
+ // Traverse its children
+ for ( elem = elem.firstChild; elem; elem = elem.nextSibling ) {
+ ret += getText(elem);
+ }
+ }
+ } else if ( nodeType === 3 || nodeType === 4 ) {
+ return elem.nodeValue;
+ }
+ // Do not include comment or processing instruction nodes
+
+ return ret;
+ };
+
+ Expr = Sizzle.selectors = {
+
+ // Can be adjusted by the user
+ cacheLength: 50,
+
+ createPseudo: markFunction,
+
+ match: matchExpr,
+
+ attrHandle: {},
+
+ find: {},
+
+ relative: {
+ ">": { dir: "parentNode", first: true },
+ " ": { dir: "parentNode" },
+ "+": { dir: "previousSibling", first: true },
+ "~": { dir: "previousSibling" }
+ },
+
+ preFilter: {
+ "ATTR": function (match) {
+ match[1] = match[1].replace(runescape, funescape);
+
+ // Move the given value to match[3] whether quoted or unquoted
+ match[3] = ( match[4] || match[5] || "" ).replace(runescape, funescape);
+
+ if ( match[2] === "~=" ) {
+ match[3] = " " + match[3] + " ";
+ }
+
+ return match.slice(0, 4);
+ },
+
+ "CHILD": function (match) {
+ /* matches from matchExpr["CHILD"]
+ 1 type (only|nth|...)
+ 2 what (child|of-type)
+ 3 argument (even|odd|\d*|\d*n([+-]\d+)?|...)
+ 4 xn-component of xn+y argument ([+-]?\d*n|)
+ 5 sign of xn-component
+ 6 x of xn-component
+ 7 sign of y-component
+ 8 y of y-component
+ */
+ match[1] = match[1].toLowerCase();
+
+ if ( match[1].slice(0, 3) === "nth" ) {
+ // nth-* requires argument
+ if ( !match[3] ) {
+ Sizzle.error(match[0]);
+ }
+
+ // numeric x and y parameters for Expr.filter.CHILD
+ // remember that false/true cast respectively to 0/1
+ match[4] = +( match[4] ? match[5] + (match[6] || 1) : 2 * ( match[3] === "even" || match[3] === "odd" ) );
+ match[5] = +( ( match[7] + match[8] ) || match[3] === "odd" );
+
+ // other types prohibit arguments
+ } else if ( match[3] ) {
+ Sizzle.error(match[0]);
+ }
+
+ return match;
+ },
+
+ "PSEUDO": function (match) {
+ var excess,
+ unquoted = !match[5] && match[2];
+
+ if ( matchExpr["CHILD"].test(match[0]) ) {
+ return null;
+ }
+
+ // Accept quoted arguments as-is
+ if ( match[3] && match[4] !== undefined ) {
+ match[2] = match[4];
+
+ // Strip excess characters from unquoted arguments
+ } else if ( unquoted && rpseudo.test(unquoted) &&
+ // Get excess from tokenize (recursively)
+ (excess = tokenize(unquoted, true)) &&
+ // advance to the next closing parenthesis
+ (excess = unquoted.indexOf(")", unquoted.length - excess) - unquoted.length) ) {
+
+ // excess is a negative index
+ match[0] = match[0].slice(0, excess);
+ match[2] = unquoted.slice(0, excess);
+ }
+
+ // Return only captures needed by the pseudo filter method (type and argument)
+ return match.slice(0, 3);
+ }
+ },
+
+ filter: {
+
+ "TAG": function (nodeNameSelector) {
+ var nodeName = nodeNameSelector.replace(runescape, funescape).toLowerCase();
+ return nodeNameSelector === "*" ?
+ function () {
+ return true;
+ } :
+ function (elem) {
+ return elem.nodeName && elem.nodeName.toLowerCase() === nodeName;
+ };
+ },
+
+ "CLASS": function (className) {
+ var pattern = classCache[ className + " " ];
+
+ return pattern ||
+ (pattern = new RegExp("(^|" + whitespace + ")" + className + "(" + whitespace + "|$)")) &&
+ classCache(className, function (elem) {
+ return pattern.test(typeof elem.className === "string" && elem.className || typeof elem.getAttribute !== strundefined && elem.getAttribute("class") || "");
+ });
+ },
+
+ "ATTR": function (name, operator, check) {
+ return function (elem) {
+ var result = Sizzle.attr(elem, name);
+
+ if ( result == null ) {
+ return operator === "!=";
+ }
+ if ( !operator ) {
+ return true;
+ }
+
+ result += "";
+
+ return operator === "=" ? result === check :
+ operator === "!=" ? result !== check :
+ operator === "^=" ? check && result.indexOf(check) === 0 :
+ operator === "*=" ? check && result.indexOf(check) > -1 :
+ operator === "$=" ? check && result.slice(-check.length) === check :
+ operator === "~=" ? ( " " + result + " " ).indexOf(check) > -1 :
+ operator === "|=" ? result === check || result.slice(0, check.length + 1) === check + "-" :
+ false;
+ };
+ },
+
+ "CHILD": function (type, what, argument, first, last) {
+ var simple = type.slice(0, 3) !== "nth",
+ forward = type.slice(-4) !== "last",
+ ofType = what === "of-type";
+
+ return first === 1 && last === 0 ?
+
+ // Shortcut for :nth-*(n)
+ function (elem) {
+ return !!elem.parentNode;
+ } :
+
+ function (elem, context, xml) {
+ var cache, outerCache, node, diff, nodeIndex, start,
+ dir = simple !== forward ? "nextSibling" : "previousSibling",
+ parent = elem.parentNode,
+ name = ofType && elem.nodeName.toLowerCase(),
+ useCache = !xml && !ofType;
+
+ if ( parent ) {
+
+ // :(first|last|only)-(child|of-type)
+ if ( simple ) {
+ while ( dir ) {
+ node = elem;
+ while ( (node = node[ dir ]) ) {
+ if ( ofType ? node.nodeName.toLowerCase() === name : node.nodeType === 1 ) {
+ return false;
+ }
+ }
+ // Reverse direction for :only-* (if we haven't yet done so)
+ start = dir = type === "only" && !start && "nextSibling";
+ }
+ return true;
+ }
+
+ start = [ forward ? parent.firstChild : parent.lastChild ];
+
+ // non-xml :nth-child(...) stores cache data on `parent`
+ if ( forward && useCache ) {
+ // Seek `elem` from a previously-cached index
+ outerCache = parent[ expando ] || (parent[ expando ] = {});
+ cache = outerCache[ type ] || [];
+ nodeIndex = cache[0] === dirruns && cache[1];
+ diff = cache[0] === dirruns && cache[2];
+ node = nodeIndex && parent.childNodes[ nodeIndex ];
+
+ while ( (node = ++nodeIndex && node && node[ dir ] ||
+
+ // Fallback to seeking `elem` from the start
+ (diff = nodeIndex = 0) || start.pop()) ) {
+
+ // When found, cache indexes on `parent` and break
+ if ( node.nodeType === 1 && ++diff && node === elem ) {
+ outerCache[ type ] = [ dirruns, nodeIndex, diff ];
+ break;
+ }
+ }
+
+ // Use previously-cached element index if available
+ } else if ( useCache && (cache = (elem[ expando ] || (elem[ expando ] = {}))[ type ]) && cache[0] === dirruns ) {
+ diff = cache[1];
+
+ // xml :nth-child(...) or :nth-last-child(...) or :nth(-last)?-of-type(...)
+ } else {
+ // Use the same loop as above to seek `elem` from the start
+ while ( (node = ++nodeIndex && node && node[ dir ] ||
+ (diff = nodeIndex = 0) || start.pop()) ) {
+
+ if ( ( ofType ? node.nodeName.toLowerCase() === name : node.nodeType === 1 ) && ++diff ) {
+ // Cache the index of each encountered element
+ if ( useCache ) {
+ (node[ expando ] || (node[ expando ] = {}))[ type ] = [ dirruns, diff ];
+ }
+
+ if ( node === elem ) {
+ break;
+ }
+ }
+ }
+ }
+
+ // Incorporate the offset, then check against cycle size
+ diff -= last;
+ return diff === first || ( diff % first === 0 && diff / first >= 0 );
+ }
+ };
+ },
+
+ "PSEUDO": function (pseudo, argument) {
+ // pseudo-class names are case-insensitive
+ // http://www.w3.org/TR/selectors/#pseudo-classes
+ // Prioritize by case sensitivity in case custom pseudos are added with uppercase letters
+ // Remember that setFilters inherits from pseudos
+ var args,
+ fn = Expr.pseudos[ pseudo ] || Expr.setFilters[ pseudo.toLowerCase() ] ||
+ Sizzle.error("unsupported pseudo: " + pseudo);
+
+ // The user may use createPseudo to indicate that
+ // arguments are needed to create the filter function
+ // just as Sizzle does
+ if ( fn[ expando ] ) {
+ return fn(argument);
+ }
+
+ // But maintain support for old signatures
+ if ( fn.length > 1 ) {
+ args = [ pseudo, pseudo, "", argument ];
+ return Expr.setFilters.hasOwnProperty(pseudo.toLowerCase()) ?
+ markFunction(function (seed, matches) {
+ var idx,
+ matched = fn(seed, argument),
+ i = matched.length;
+ while ( i-- ) {
+ idx = indexOf.call(seed, matched[i]);
+ seed[ idx ] = !( matches[ idx ] = matched[i] );
+ }
+ }) :
+ function (elem) {
+ return fn(elem, 0, args);
+ };
+ }
+
+ return fn;
+ }
+ },
+
+ pseudos: {
+ // Potentially complex pseudos
+ "not": markFunction(function (selector) {
+ // Trim the selector passed to compile
+ // to avoid treating leading and trailing
+ // spaces as combinators
+ var input = [],
+ results = [],
+ matcher = compile(selector.replace(rtrim, "$1"));
+
+ return matcher[ expando ] ?
+ markFunction(function (seed, matches, context, xml) {
+ var elem,
+ unmatched = matcher(seed, null, xml, []),
+ i = seed.length;
+
+ // Match elements unmatched by `matcher`
+ while ( i-- ) {
+ if ( (elem = unmatched[i]) ) {
+ seed[i] = !(matches[i] = elem);
+ }
+ }
+ }) :
+ function (elem, context, xml) {
+ input[0] = elem;
+ matcher(input, null, xml, results);
+ return !results.pop();
+ };
+ }),
+
+ "has": markFunction(function (selector) {
+ return function (elem) {
+ return Sizzle(selector, elem).length > 0;
+ };
+ }),
+
+ "contains": markFunction(function (text) {
+ return function (elem) {
+ return ( elem.textContent || elem.innerText || getText(elem) ).indexOf(text) > -1;
+ };
+ }),
+
+ // "Whether an element is represented by a :lang() selector
+ // is based solely on the element's language value
+ // being equal to the identifier C,
+ // or beginning with the identifier C immediately followed by "-".
+ // The matching of C against the element's language value is performed case-insensitively.
+ // The identifier C does not have to be a valid language name."
+ // http://www.w3.org/TR/selectors/#lang-pseudo
+ "lang": markFunction(function (lang) {
+ // lang value must be a valid identifier
+ if ( !ridentifier.test(lang || "") ) {
+ Sizzle.error("unsupported lang: " + lang);
+ }
+ lang = lang.replace(runescape, funescape).toLowerCase();
+ return function (elem) {
+ var elemLang;
+ do {
+ if ( (elemLang = documentIsHTML ?
+ elem.lang :
+ elem.getAttribute("xml:lang") || elem.getAttribute("lang")) ) {
+
+ elemLang = elemLang.toLowerCase();
+ return elemLang === lang || elemLang.indexOf(lang + "-") === 0;
+ }
+ } while ( (elem = elem.parentNode) && elem.nodeType === 1 );
+ return false;
+ };
+ }),
+
+ // Miscellaneous
+ "target": function (elem) {
+ var hash = window.location && window.location.hash;
+ return hash && hash.slice(1) === elem.id;
+ },
+
+ "root": function (elem) {
+ return elem === docElem;
+ },
+
+ "focus": function (elem) {
+ return elem === document.activeElement && (!document.hasFocus || document.hasFocus()) && !!(elem.type || elem.href || ~elem.tabIndex);
+ },
+
+ // Boolean properties
+ "enabled": function (elem) {
+ return elem.disabled === false;
+ },
+
+ "disabled": function (elem) {
+ return elem.disabled === true;
+ },
+
+ "checked": function (elem) {
+ // In CSS3, :checked should return both checked and selected elements
+ // http://www.w3.org/TR/2011/REC-css3-selectors-20110929/#checked
+ var nodeName = elem.nodeName.toLowerCase();
+ return (nodeName === "input" && !!elem.checked) || (nodeName === "option" && !!elem.selected);
+ },
+
+ "selected": function (elem) {
+ // Accessing this property makes selected-by-default
+ // options in Safari work properly
+ if ( elem.parentNode ) {
+ elem.parentNode.selectedIndex;
+ }
+
+ return elem.selected === true;
+ },
+
+ // Contents
+ "empty": function (elem) {
+ // http://www.w3.org/TR/selectors/#empty-pseudo
+ // :empty is negated by element (1) or content nodes (text: 3; cdata: 4; entity ref: 5),
+ // but not by others (comment: 8; processing instruction: 7; etc.)
+ // nodeType < 6 works because attributes (2) do not appear as children
+ for ( elem = elem.firstChild; elem; elem = elem.nextSibling ) {
+ if ( elem.nodeType < 6 ) {
+ return false;
+ }
+ }
+ return true;
+ },
+
+ "parent": function (elem) {
+ return !Expr.pseudos["empty"](elem);
+ },
+
+ // Element/input types
+ "header": function (elem) {
+ return rheader.test(elem.nodeName);
+ },
+
+ "input": function (elem) {
+ return rinputs.test(elem.nodeName);
+ },
+
+ "button": function (elem) {
+ var name = elem.nodeName.toLowerCase();
+ return name === "input" && elem.type === "button" || name === "button";
+ },
+
+ "text": function (elem) {
+ var attr;
+ return elem.nodeName.toLowerCase() === "input" &&
+ elem.type === "text" &&
+
+ // Support: IE<8
+ // New HTML5 attribute values (e.g., "search") appear with elem.type === "text"
+ ( (attr = elem.getAttribute("type")) == null || attr.toLowerCase() === "text" );
+ },
+
+ // Position-in-collection
+ "first": createPositionalPseudo(function () {
+ return [ 0 ];
+ }),
+
+ "last": createPositionalPseudo(function (matchIndexes, length) {
+ return [ length - 1 ];
+ }),
+
+ "eq": createPositionalPseudo(function (matchIndexes, length, argument) {
+ return [ argument < 0 ? argument + length : argument ];
+ }),
+
+ "even": createPositionalPseudo(function (matchIndexes, length) {
+ var i = 0;
+ for ( ; i < length; i += 2 ) {
+ matchIndexes.push(i);
+ }
+ return matchIndexes;
+ }),
+
+ "odd": createPositionalPseudo(function (matchIndexes, length) {
+ var i = 1;
+ for ( ; i < length; i += 2 ) {
+ matchIndexes.push(i);
+ }
+ return matchIndexes;
+ }),
+
+ "lt": createPositionalPseudo(function (matchIndexes, length, argument) {
+ var i = argument < 0 ? argument + length : argument;
+ for ( ; --i >= 0; ) {
+ matchIndexes.push(i);
+ }
+ return matchIndexes;
+ }),
+
+ "gt": createPositionalPseudo(function (matchIndexes, length, argument) {
+ var i = argument < 0 ? argument + length : argument;
+ for ( ; ++i < length; ) {
+ matchIndexes.push(i);
+ }
+ return matchIndexes;
+ })
+ }
+ };
+
+ Expr.pseudos["nth"] = Expr.pseudos["eq"];
+
+// Add button/input type pseudos
+ for ( i in { radio: true, checkbox: true, file: true, password: true, image: true } ) {
+ Expr.pseudos[ i ] = createInputPseudo(i);
+ }
+ for ( i in { submit: true, reset: true } ) {
+ Expr.pseudos[ i ] = createButtonPseudo(i);
+ }
+
+// Easy API for creating new setFilters
+ function setFilters() {
+ }
+
+ setFilters.prototype = Expr.filters = Expr.pseudos;
+ Expr.setFilters = new setFilters();
+
+ function tokenize(selector, parseOnly) {
+ var matched, match, tokens, type,
+ soFar, groups, preFilters,
+ cached = tokenCache[ selector + " " ];
+
+ if ( cached ) {
+ return parseOnly ? 0 : cached.slice(0);
+ }
+
+ soFar = selector;
+ groups = [];
+ preFilters = Expr.preFilter;
+
+ while ( soFar ) {
+
+ // Comma and first run
+ if ( !matched || (match = rcomma.exec(soFar)) ) {
+ if ( match ) {
+ // Don't consume trailing commas as valid
+ soFar = soFar.slice(match[0].length) || soFar;
+ }
+ groups.push((tokens = []));
+ }
+
+ matched = false;
+
+ // Combinators
+ if ( (match = rcombinators.exec(soFar)) ) {
+ matched = match.shift();
+ tokens.push({
+ value: matched,
+ // Cast descendant combinators to space
+ type: match[0].replace(rtrim, " ")
+ });
+ soFar = soFar.slice(matched.length);
+ }
+
+ // Filters
+ for ( type in Expr.filter ) {
+ if ( (match = matchExpr[ type ].exec(soFar)) && (!preFilters[ type ] ||
+ (match = preFilters[ type ](match))) ) {
+ matched = match.shift();
+ tokens.push({
+ value: matched,
+ type: type,
+ matches: match
+ });
+ soFar = soFar.slice(matched.length);
+ }
+ }
+
+ if ( !matched ) {
+ break;
+ }
+ }
+
+ // Return the length of the invalid excess
+ // if we're just parsing
+ // Otherwise, throw an error or return tokens
+ return parseOnly ?
+ soFar.length :
+ soFar ?
+ Sizzle.error(selector) :
+ // Cache the tokens
+ tokenCache(selector, groups).slice(0);
+ }
+
+ function toSelector(tokens) {
+ var i = 0,
+ len = tokens.length,
+ selector = "";
+ for ( ; i < len; i++ ) {
+ selector += tokens[i].value;
+ }
+ return selector;
+ }
+
+ function addCombinator(matcher, combinator, base) {
+ var dir = combinator.dir,
+ checkNonElements = base && dir === "parentNode",
+ doneName = done++;
+
+ return combinator.first ?
+ // Check against closest ancestor/preceding element
+ function (elem, context, xml) {
+ while ( (elem = elem[ dir ]) ) {
+ if ( elem.nodeType === 1 || checkNonElements ) {
+ return matcher(elem, context, xml);
+ }
+ }
+ } :
+
+ // Check against all ancestor/preceding elements
+ function (elem, context, xml) {
+ var oldCache, outerCache,
+ newCache = [ dirruns, doneName ];
+
+ // We can't set arbitrary data on XML nodes, so they don't benefit from dir caching
+ if ( xml ) {
+ while ( (elem = elem[ dir ]) ) {
+ if ( elem.nodeType === 1 || checkNonElements ) {
+ if ( matcher(elem, context, xml) ) {
+ return true;
+ }
+ }
+ }
+ } else {
+ while ( (elem = elem[ dir ]) ) {
+ if ( elem.nodeType === 1 || checkNonElements ) {
+ outerCache = elem[ expando ] || (elem[ expando ] = {});
+ if ( (oldCache = outerCache[ dir ]) &&
+ oldCache[ 0 ] === dirruns && oldCache[ 1 ] === doneName ) {
+
+ // Assign to newCache so results back-propagate to previous elements
+ return (newCache[ 2 ] = oldCache[ 2 ]);
+ } else {
+ // Reuse newcache so results back-propagate to previous elements
+ outerCache[ dir ] = newCache;
+
+ // A match means we're done; a fail means we have to keep checking
+ if ( (newCache[ 2 ] = matcher(elem, context, xml)) ) {
+ return true;
+ }
+ }
+ }
+ }
+ }
+ };
+ }
+
+ function elementMatcher(matchers) {
+ return matchers.length > 1 ?
+ function (elem, context, xml) {
+ var i = matchers.length;
+ while ( i-- ) {
+ if ( !matchers[i](elem, context, xml) ) {
+ return false;
+ }
+ }
+ return true;
+ } :
+ matchers[0];
+ }
+
+ function condense(unmatched, map, filter, context, xml) {
+ var elem,
+ newUnmatched = [],
+ i = 0,
+ len = unmatched.length,
+ mapped = map != null;
+
+ for ( ; i < len; i++ ) {
+ if ( (elem = unmatched[i]) ) {
+ if ( !filter || filter(elem, context, xml) ) {
+ newUnmatched.push(elem);
+ if ( mapped ) {
+ map.push(i);
+ }
+ }
+ }
+ }
+
+ return newUnmatched;
+ }
+
+ function setMatcher(preFilter, selector, matcher, postFilter, postFinder, postSelector) {
+ if ( postFilter && !postFilter[ expando ] ) {
+ postFilter = setMatcher(postFilter);
+ }
+ if ( postFinder && !postFinder[ expando ] ) {
+ postFinder = setMatcher(postFinder, postSelector);
+ }
+ return markFunction(function (seed, results, context, xml) {
+ var temp, i, elem,
+ preMap = [],
+ postMap = [],
+ preexisting = results.length,
+
+ // Get initial elements from seed or context
+ elems = seed || multipleContexts(selector || "*", context.nodeType ? [ context ] : context, []),
+
+ // Prefilter to get matcher input, preserving a map for seed-results synchronization
+ matcherIn = preFilter && ( seed || !selector ) ?
+ condense(elems, preMap, preFilter, context, xml) :
+ elems,
+
+ matcherOut = matcher ?
+ // If we have a postFinder, or filtered seed, or non-seed postFilter or preexisting results,
+ postFinder || ( seed ? preFilter : preexisting || postFilter ) ?
+
+ // ...intermediate processing is necessary
+ [] :
+
+ // ...otherwise use results directly
+ results :
+ matcherIn;
+
+ // Find primary matches
+ if ( matcher ) {
+ matcher(matcherIn, matcherOut, context, xml);
+ }
+
+ // Apply postFilter
+ if ( postFilter ) {
+ temp = condense(matcherOut, postMap);
+ postFilter(temp, [], context, xml);
+
+ // Un-match failing elements by moving them back to matcherIn
+ i = temp.length;
+ while ( i-- ) {
+ if ( (elem = temp[i]) ) {
+ matcherOut[ postMap[i] ] = !(matcherIn[ postMap[i] ] = elem);
+ }
+ }
+ }
+
+ if ( seed ) {
+ if ( postFinder || preFilter ) {
+ if ( postFinder ) {
+ // Get the final matcherOut by condensing this intermediate into postFinder contexts
+ temp = [];
+ i = matcherOut.length;
+ while ( i-- ) {
+ if ( (elem = matcherOut[i]) ) {
+ // Restore matcherIn since elem is not yet a final match
+ temp.push((matcherIn[i] = elem));
+ }
+ }
+ postFinder(null, (matcherOut = []), temp, xml);
+ }
+
+ // Move matched elements from seed to results to keep them synchronized
+ i = matcherOut.length;
+ while ( i-- ) {
+ if ( (elem = matcherOut[i]) &&
+ (temp = postFinder ? indexOf.call(seed, elem) : preMap[i]) > -1 ) {
+
+ seed[temp] = !(results[temp] = elem);
+ }
+ }
+ }
+
+ // Add elements to results, through postFinder if defined
+ } else {
+ matcherOut = condense(
+ matcherOut === results ?
+ matcherOut.splice(preexisting, matcherOut.length) :
+ matcherOut
+ );
+ if ( postFinder ) {
+ postFinder(null, results, matcherOut, xml);
+ } else {
+ push.apply(results, matcherOut);
+ }
+ }
+ });
+ }
+
+ function matcherFromTokens(tokens) {
+ var checkContext, matcher, j,
+ len = tokens.length,
+ leadingRelative = Expr.relative[ tokens[0].type ],
+ implicitRelative = leadingRelative || Expr.relative[" "],
+ i = leadingRelative ? 1 : 0,
+
+ // The foundational matcher ensures that elements are reachable from top-level context(s)
+ matchContext = addCombinator(function (elem) {
+ return elem === checkContext;
+ }, implicitRelative, true),
+ matchAnyContext = addCombinator(function (elem) {
+ return indexOf.call(checkContext, elem) > -1;
+ }, implicitRelative, true),
+ matchers = [ function (elem, context, xml) {
+ return ( !leadingRelative && ( xml || context !== outermostContext ) ) || (
+ (checkContext = context).nodeType ?
+ matchContext(elem, context, xml) :
+ matchAnyContext(elem, context, xml) );
+ } ];
+
+ for ( ; i < len; i++ ) {
+ if ( (matcher = Expr.relative[ tokens[i].type ]) ) {
+ matchers = [ addCombinator(elementMatcher(matchers), matcher) ];
+ } else {
+ matcher = Expr.filter[ tokens[i].type ].apply(null, tokens[i].matches);
+
+ // Return special upon seeing a positional matcher
+ if ( matcher[ expando ] ) {
+ // Find the next relative operator (if any) for proper handling
+ j = ++i;
+ for ( ; j < len; j++ ) {
+ if ( Expr.relative[ tokens[j].type ] ) {
+ break;
+ }
+ }
+ return setMatcher(
+ i > 1 && elementMatcher(matchers),
+ i > 1 && toSelector(
+ // If the preceding token was a descendant combinator, insert an implicit any-element `*`
+ tokens.slice(0, i - 1).concat({ value: tokens[ i - 2 ].type === " " ? "*" : "" })
+ ).replace(rtrim, "$1"),
+ matcher,
+ i < j && matcherFromTokens(tokens.slice(i, j)),
+ j < len && matcherFromTokens((tokens = tokens.slice(j))),
+ j < len && toSelector(tokens)
+ );
+ }
+ matchers.push(matcher);
+ }
+ }
+
+ return elementMatcher(matchers);
+ }
+
+ function matcherFromGroupMatchers(elementMatchers, setMatchers) {
+ var bySet = setMatchers.length > 0,
+ byElement = elementMatchers.length > 0,
+ superMatcher = function (seed, context, xml, results, outermost) {
+ var elem, j, matcher,
+ matchedCount = 0,
+ i = "0",
+ unmatched = seed && [],
+ setMatched = [],
+ contextBackup = outermostContext,
+ // We must always have either seed elements or outermost context
+ elems = seed || byElement && Expr.find["TAG"]("*", outermost),
+ // Use integer dirruns iff this is the outermost matcher
+ dirrunsUnique = (dirruns += contextBackup == null ? 1 : Math.random() || 0.1),
+ len = elems.length;
+
+ if ( outermost ) {
+ outermostContext = context !== document && context;
+ }
+
+ // Add elements passing elementMatchers directly to results
+ // Keep `i` a string if there are no elements so `matchedCount` will be "00" below
+ // Support: IE<9, Safari
+ // Tolerate NodeList properties (IE: "length"; Safari: <number>) matching elements by id
+ for ( ; i !== len && (elem = elems[i]) != null; i++ ) {
+ if ( byElement && elem ) {
+ j = 0;
+ while ( (matcher = elementMatchers[j++]) ) {
+ if ( matcher(elem, context, xml) ) {
+ results.push(elem);
+ break;
+ }
+ }
+ if ( outermost ) {
+ dirruns = dirrunsUnique;
+ }
+ }
+
+ // Track unmatched elements for set filters
+ if ( bySet ) {
+ // They will have gone through all possible matchers
+ if ( (elem = !matcher && elem) ) {
+ matchedCount--;
+ }
+
+ // Lengthen the array for every element, matched or not
+ if ( seed ) {
+ unmatched.push(elem);
+ }
+ }
+ }
+
+ // Apply set filters to unmatched elements
+ matchedCount += i;
+ if ( bySet && i !== matchedCount ) {
+ j = 0;
+ while ( (matcher = setMatchers[j++]) ) {
+ matcher(unmatched, setMatched, context, xml);
+ }
+
+ if ( seed ) {
+ // Reintegrate element matches to eliminate the need for sorting
+ if ( matchedCount > 0 ) {
+ while ( i-- ) {
+ if ( !(unmatched[i] || setMatched[i]) ) {
+ setMatched[i] = pop.call(results);
+ }
+ }
+ }
+
+ // Discard index placeholder values to get only actual matches
+ setMatched = condense(setMatched);
+ }
+
+ // Add matches to results
+ push.apply(results, setMatched);
+
+ // Seedless set matches succeeding multiple successful matchers stipulate sorting
+ if ( outermost && !seed && setMatched.length > 0 &&
+ ( matchedCount + setMatchers.length ) > 1 ) {
+
+ Sizzle.uniqueSort(results);
+ }
+ }
+
+ // Override manipulation of globals by nested matchers
+ if ( outermost ) {
+ dirruns = dirrunsUnique;
+ outermostContext = contextBackup;
+ }
+
+ return unmatched;
+ };
+
+ return bySet ?
+ markFunction(superMatcher) :
+ superMatcher;
+ }
+
+ compile = Sizzle.compile = function (selector, group /* Internal Use Only */) {
+ var i,
+ setMatchers = [],
+ elementMatchers = [],
+ cached = compilerCache[ selector + " " ];
+
+ if ( !cached ) {
+ // Generate a function of recursive functions that can be used to check each element
+ if ( !group ) {
+ group = tokenize(selector);
+ }
+ i = group.length;
+ while ( i-- ) {
+ cached = matcherFromTokens(group[i]);
+ if ( cached[ expando ] ) {
+ setMatchers.push(cached);
+ } else {
+ elementMatchers.push(cached);
+ }
+ }
+
+ // Cache the compiled function
+ cached = compilerCache(selector, matcherFromGroupMatchers(elementMatchers, setMatchers));
+ }
+ return cached;
+ };
+
+ function multipleContexts(selector, contexts, results) {
+ var i = 0,
+ len = contexts.length;
+ for ( ; i < len; i++ ) {
+ Sizzle(selector, contexts[i], results);
+ }
+ return results;
+ }
+
+ function select(selector, context, results, seed) {
+ var i, tokens, token, type, find,
+ match = tokenize(selector);
+
+ if ( !seed ) {
+ // Try to minimize operations if there is only one group
+ if ( match.length === 1 ) {
+
+ // Take a shortcut and set the context if the root selector is an ID
+ tokens = match[0] = match[0].slice(0);
+ if ( tokens.length > 2 && (token = tokens[0]).type === "ID" &&
+ support.getById && context.nodeType === 9 && documentIsHTML &&
+ Expr.relative[ tokens[1].type ] ) {
+
+ context = ( Expr.find["ID"](token.matches[0].replace(runescape, funescape), context) || [] )[0];
+ if ( !context ) {
+ return results;
+ }
+ selector = selector.slice(tokens.shift().value.length);
+ }
+
+ // Fetch a seed set for right-to-left matching
+ i = matchExpr["needsContext"].test(selector) ? 0 : tokens.length;
+ while ( i-- ) {
+ token = tokens[i];
+
+ // Abort if we hit a combinator
+ if ( Expr.relative[ (type = token.type) ] ) {
+ break;
+ }
+ if ( (find = Expr.find[ type ]) ) {
+ // Search, expanding context for leading sibling combinators
+ if ( (seed = find(
+ token.matches[0].replace(runescape, funescape),
+ rsibling.test(tokens[0].type) && testContext(context.parentNode) || context
+ )) ) {
+
+ // If seed is empty or no tokens remain, we can return early
+ tokens.splice(i, 1);
+ selector = seed.length && toSelector(tokens);
+ if ( !selector ) {
+ push.apply(results, seed);
+ 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,
+ !documentIsHTML,
+ results,
+ rsibling.test(selector) && testContext(context.parentNode) || context
+ );
+ return results;
+ }
+
+// One-time assignments
+
+// Sort stability
+ support.sortStable = expando.split("").sort(sortOrder).join("") === expando;
+
+// Support: Chrome<14
+// Always assume duplicates if they aren't passed to the comparison function
+ support.detectDuplicates = !!hasDuplicate;
+
+// Initialize against the default document
+ setDocument();
+
+// Support: Webkit<537.32 - Safari 6.0.3/Chrome 25 (fixed in Chrome 27)
+// Detached nodes confoundingly follow *each other*
+ support.sortDetached = assert(function (div1) {
+ // Should return 1, but returns 4 (following)
+ return div1.compareDocumentPosition(document.createElement("div")) & 1;
+ });
+
+// Support: IE<8
+// Prevent attribute/property "interpolation"
+// http://msdn.microsoft.com/en-us/library/ms536429%28VS.85%29.aspx
+ if ( !assert(function (div) {
+ div.innerHTML = "<a href='#'></a>";
+ return div.firstChild.getAttribute("href") === "#";
+ }) ) {
+ addHandle("type|href|height|width", function (elem, name, isXML) {
+ if ( !isXML ) {
+ return elem.getAttribute(name, name.toLowerCase() === "type" ? 1 : 2);
+ }
+ });
+ }
+
+// Support: IE<9
+// Use defaultValue in place of getAttribute("value")
+ if ( !support.attributes || !assert(function (div) {
+ div.innerHTML = "<input/>";
+ div.firstChild.setAttribute("value", "");
+ return div.firstChild.getAttribute("value") === "";
+ }) ) {
+ addHandle("value", function (elem, name, isXML) {
+ if ( !isXML && elem.nodeName.toLowerCase() === "input" ) {
+ return elem.defaultValue;
+ }
+ });
+ }
+
+// Support: IE<9
+// Use getAttributeNode to fetch booleans when getAttribute lies
+ if ( !assert(function (div) {
+ return div.getAttribute("disabled") == null;
+ }) ) {
+ addHandle(booleans, function (elem, name, isXML) {
+ var val;
+ if ( !isXML ) {
+ return elem[ name ] === true ? name.toLowerCase() :
+ (val = elem.getAttributeNode(name)) && val.specified ?
+ val.value :
+ null;
+ }
+ });
+ }
+
+ return Sizzle;
+
+ })(window);
+
+
+ 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;
+
+
+ var rneedsContext = jQuery.expr.match.needsContext;
+
+ var rsingleTag = (/^<(\w+)\s*\/?>(?:<\/\1>|)$/);
+
+
+ var risSimple = /^.[^:#\[\.,]*$/;
+
+// Implement the identical functionality for filter and not
+ function winnow(elements, qualifier, not) {
+ if ( jQuery.isFunction(qualifier) ) {
+ return jQuery.grep(elements, function (elem, i) {
+ /* jshint -W018 */
+ return !!qualifier.call(elem, i, elem) !== not;
+ });
+
+ }
+
+ if ( qualifier.nodeType ) {
+ return jQuery.grep(elements, function (elem) {
+ return ( elem === qualifier ) !== not;
+ });
+
+ }
+
+ if ( typeof qualifier === "string" ) {
+ if ( risSimple.test(qualifier) ) {
+ return jQuery.filter(qualifier, elements, not);
+ }
+
+ qualifier = jQuery.filter(qualifier, elements);
+ }
+
+ return jQuery.grep(elements, function (elem) {
+ return ( indexOf.call(qualifier, elem) >= 0 ) !== not;
+ });
+ }
+
+ jQuery.filter = function (expr, elems, not) {
+ var elem = elems[ 0 ];
+
+ if ( not ) {
+ expr = ":not(" + expr + ")";
+ }
+
+ return elems.length === 1 && elem.nodeType === 1 ?
+ jQuery.find.matchesSelector(elem, expr) ? [ elem ] : [] :
+ jQuery.find.matches(expr, jQuery.grep(elems, function (elem) {
+ return elem.nodeType === 1;
+ }));
+ };
+
+ jQuery.fn.extend({
+ find: function (selector) {
+ var i,
+ len = this.length,
+ ret = [],
+ self = this;
+
+ if ( typeof selector !== "string" ) {
+ return this.pushStack(jQuery(selector).filter(function () {
+ for ( i = 0; i < len; i++ ) {
+ if ( jQuery.contains(self[ i ], this) ) {
+ return true;
+ }
+ }
+ }));
+ }
+
+ for ( i = 0; i < len; i++ ) {
+ jQuery.find(selector, self[ i ], ret);
+ }
+
+ // Needed because $( selector, context ) becomes $( context ).find( selector )
+ ret = this.pushStack(len > 1 ? jQuery.unique(ret) : ret);
+ ret.selector = this.selector ? this.selector + " " + selector : selector;
+ return ret;
+ },
+ filter: function (selector) {
+ return this.pushStack(winnow(this, selector || [], false));
+ },
+ not: function (selector) {
+ return this.pushStack(winnow(this, selector || [], true));
+ },
+ is: function (selector) {
+ return !!winnow(
+ this,
+
+ // 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".
+ typeof selector === "string" && rneedsContext.test(selector) ?
+ jQuery(selector) :
+ selector || [],
+ false
+ ).length;
+ }
+ });
+
+
+// Initialize a jQuery object
+
+
+// A central reference to the root jQuery(document)
+ var rootjQuery,
+
+ // A simple way to check for HTML strings
+ // Prioritize #id over <tag> to avoid XSS via location.hash (#9521)
+ // Strict HTML recognition (#11290: must start with <)
+ rquickExpr = /^(?:\s*(<[\w\W]+>)[^>]*|#([\w-]*))$/,
+
+ init = jQuery.fn.init = function (selector, context) {
+ var match, elem;
+
+ // HANDLE: $(""), $(null), $(undefined), $(false)
+ if ( !selector ) {
+ return this;
+ }
+
+ // Handle HTML strings
+ if ( typeof selector === "string" ) {
+ if ( selector[0] === "<" && selector[ selector.length - 1 ] === ">" && selector.length >= 3 ) {
+ // Assume that strings that start and end with <> are HTML and skip the regex check
+ match = [ null, selector, null ];
+
+ } else {
+ match = rquickExpr.exec(selector);
+ }
+
+ // Match html or make sure no context is specified for #id
+ if ( match && (match[1] || !context) ) {
+
+ // HANDLE: $(html) -> $(array)
+ if ( match[1] ) {
+ context = context instanceof jQuery ? context[0] : context;
+
+ // scripts is true for back-compat
+ // Intentionally let the error be thrown if parseHTML is not present
+ jQuery.merge(this, jQuery.parseHTML(
+ match[1],
+ context && context.nodeType ? context.ownerDocument || context : document,
+ true
+ ));
+
+ // HANDLE: $(html, props)
+ if ( rsingleTag.test(match[1]) && jQuery.isPlainObject(context) ) {
+ for ( match in context ) {
+ // Properties of context are called as methods if possible
+ if ( jQuery.isFunction(this[ match ]) ) {
+ this[ match ](context[ match ]);
+
+ // ...and otherwise set as attributes
+ } else {
+ this.attr(match, context[ match ]);
+ }
+ }
+ }
+
+ return this;
+
+ // HANDLE: $(#id)
+ } else {
+ elem = document.getElementById(match[2]);
+
+ // Check parentNode to catch when Blackberry 4.6 returns
+ // nodes that are no longer in the document #6963
+ if ( elem && elem.parentNode ) {
+ // Inject the element directly into the jQuery object
+ this.length = 1;
+ this[0] = elem;
+ }
+
+ this.context = document;
+ this.selector = selector;
+ return this;
+ }
+
+ // HANDLE: $(expr, $(...))
+ } else if ( !context || context.jquery ) {
+ return ( context || rootjQuery ).find(selector);
+
+ // HANDLE: $(expr, context)
+ // (which is just equivalent to: $(context).find(expr)
+ } else {
+ return this.constructor(context).find(selector);
+ }
+
+ // HANDLE: $(DOMElement)
+ } else if ( selector.nodeType ) {
+ this.context = this[0] = selector;
+ this.length = 1;
+ return this;
+
+ // HANDLE: $(function)
+ // Shortcut for document ready
+ } else if ( jQuery.isFunction(selector) ) {
+ return typeof rootjQuery.ready !== "undefined" ?
+ rootjQuery.ready(selector) :
+ // Execute immediately if ready is not present
+ selector(jQuery);
+ }
+
+ if ( selector.selector !== undefined ) {
+ this.selector = selector.selector;
+ this.context = selector.context;
+ }
+
+ return jQuery.makeArray(selector, this);
+ };
+
+// Give the init function the jQuery prototype for later instantiation
+ init.prototype = jQuery.fn;
+
+// Initialize central reference
+ rootjQuery = jQuery(document);
+
+
+ var rparentsprev = /^(?:parents|prev(?:Until|All))/,
+ // methods guaranteed to produce a unique set when starting from a unique set
+ guaranteedUnique = {
+ children: true,
+ contents: true,
+ next: true,
+ prev: true
+ };
+
+ jQuery.extend({
+ dir: function (elem, dir, until) {
+ var matched = [],
+ truncate = until !== undefined;
+
+ while ( (elem = elem[ dir ]) && elem.nodeType !== 9 ) {
+ if ( elem.nodeType === 1 ) {
+ if ( truncate && jQuery(elem).is(until) ) {
+ break;
+ }
+ matched.push(elem);
+ }
+ }
+ return matched;
+ },
+
+ sibling: function (n, elem) {
+ var matched = [];
+
+ for ( ; n; n = n.nextSibling ) {
+ if ( n.nodeType === 1 && n !== elem ) {
+ matched.push(n);
+ }
+ }
+
+ return matched;
+ }
+ });
+
+ jQuery.fn.extend({
+ has: function (target) {
+ var targets = jQuery(target, this),
+ l = targets.length;
+
+ return this.filter(function () {
+ var i = 0;
+ for ( ; i < l; i++ ) {
+ if ( jQuery.contains(this, targets[i]) ) {
+ return true;
+ }
+ }
+ });
+ },
+
+ closest: function (selectors, context) {
+ var cur,
+ i = 0,
+ l = this.length,
+ matched = [],
+ pos = rneedsContext.test(selectors) || typeof selectors !== "string" ?
+ jQuery(selectors, context || this.context) :
+ 0;
+
+ for ( ; i < l; i++ ) {
+ for ( cur = this[i]; cur && cur !== context; cur = cur.parentNode ) {
+ // Always skip document fragments
+ if ( cur.nodeType < 11 && (pos ?
+ pos.index(cur) > -1 :
+
+ // Don't pass non-elements to Sizzle
+ cur.nodeType === 1 &&
+ jQuery.find.matchesSelector(cur, selectors)) ) {
+
+ matched.push(cur);
+ break;
+ }
+ }
+ }
+
+ return this.pushStack(matched.length > 1 ? jQuery.unique(matched) : matched);
+ },
+
+ // Determine the position of an element within
+ // the matched set of elements
+ index: function (elem) {
+
+ // No argument, return index in parent
+ if ( !elem ) {
+ return ( this[ 0 ] && this[ 0 ].parentNode ) ? this.first().prevAll().length : -1;
+ }
+
+ // index in selector
+ if ( typeof elem === "string" ) {
+ return indexOf.call(jQuery(elem), this[ 0 ]);
+ }
+
+ // Locate the position of the desired element
+ return indexOf.call(this,
+
+ // If it receives a jQuery object, the first element is used
+ elem.jquery ? elem[ 0 ] : elem
+ );
+ },
+
+ add: function (selector, context) {
+ return this.pushStack(
+ jQuery.unique(
+ jQuery.merge(this.get(), jQuery(selector, context))
+ )
+ );
+ },
+
+ addBack: function (selector) {
+ return this.add(selector == null ?
+ this.prevObject : this.prevObject.filter(selector)
+ );
+ }
+ });
+
+ function sibling(cur, dir) {
+ while ( (cur = cur[dir]) && 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 elem.contentDocument || jQuery.merge([], elem.childNodes);
+ }
+ }, function (name, fn) {
+ jQuery.fn[ name ] = function (until, selector) {
+ var matched = jQuery.map(this, fn, until);
+
+ if ( name.slice(-5) !== "Until" ) {
+ selector = until;
+ }
+
+ if ( selector && typeof selector === "string" ) {
+ matched = jQuery.filter(selector, matched);
+ }
+
+ if ( this.length > 1 ) {
+ // Remove duplicates
+ if ( !guaranteedUnique[ name ] ) {
+ jQuery.unique(matched);
+ }
+
+ // Reverse order for parents* and prev-derivatives
+ if ( rparentsprev.test(name) ) {
+ matched.reverse();
+ }
+ }
+
+ return this.pushStack(matched);
+ };
+ });
+ var rnotwhite = (/\S+/g);
+
+
+// String to Object options format cache
+ var optionsCache = {};
+
+// Convert String-formatted options into Object-formatted ones and store in cache
+ function createOptions(options) {
+ var object = optionsCache[ options ] = {};
+ jQuery.each(options.match(rnotwhite) || [], function (_, flag) {
+ object[ flag ] = true;
+ });
+ return object;
+ }
+
+ /*
+ * Create a callback list using the following parameters:
+ *
+ * options: an optional list of space-separated options that will change how
+ * the callback list behaves or a more traditional option object
+ *
+ * By default a callback list will act like an event callback list and can be
+ * "fired" multiple times.
+ *
+ * Possible options:
+ *
+ * once: will ensure the callback list can only be fired once (like a Deferred)
+ *
+ * memory: will keep track of previous values and will call any callback added
+ * after the list has been fired right away with the latest "memorized"
+ * values (like a Deferred)
+ *
+ * unique: will ensure a callback can only be added once (no duplicate in the list)
+ *
+ * stopOnFalse: interrupt callings when a callback returns false
+ *
+ */
+ jQuery.Callbacks = function (options) {
+
+ // Convert options from String-formatted to Object-formatted if needed
+ // (we check in cache first)
+ options = typeof options === "string" ?
+ ( optionsCache[ options ] || createOptions(options) ) :
+ jQuery.extend({}, options);
+
+ var // 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;
+ },
+ // Check if a given callback is in the list.
+ // If no argument is given, return whether or not list has callbacks attached.
+ has: function (fn) {
+ return fn ? jQuery.inArray(fn, list) > -1 : !!( list && list.length );
+ },
+ // Remove all callbacks from the list
+ empty: function () {
+ list = [];
+ firingLength = 0;
+ 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) {
+ if ( list && ( !fired || stack ) ) {
+ args = args || [];
+ args = [ context, args.slice ? args.slice() : args ];
+ 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 fn = jQuery.isFunction(fns[ i ]) && fns[ i ];
+ // deferred[ done | fail | progress ] for forwarding actions to newDefer
+ deferred[ tuple[1] ](function () {
+ var returned = fn && fn.apply(this, arguments);
+ if ( returned && jQuery.isFunction(returned.promise) ) {
+ returned.promise()
+ .done(newDefer.resolve)
+ .fail(newDefer.reject)
+ .progress(newDefer.notify);
+ } else {
+ newDefer[ tuple[ 0 ] + "With" ](this === promise ? newDefer.promise() : this, fn ? [ returned ] : arguments);
+ }
+ });
+ });
+ fns = null;
+ }).promise();
+ },
+ // Get a promise for this deferred
+ // If obj is provided, the promise aspect is added to the object
+ promise: function (obj) {
+ return obj != null ? jQuery.extend(obj, promise) : promise;
+ }
+ },
+ deferred = {};
+
+ // Keep pipe for back-compat
+ promise.pipe = promise.then;
+
+ // Add list-specific methods
+ jQuery.each(tuples, function (i, tuple) {
+ var list = tuple[ 2 ],
+ stateString = tuple[ 3 ];
+
+ // promise[ done | fail | progress ] = list.add
+ promise[ tuple[1] ] = list.add;
+
+ // Handle state
+ if ( stateString ) {
+ list.add(function () {
+ // state = [ resolved | rejected ]
+ state = stateString;
+
+ // [ reject_list | resolve_list ].disable; progress_list.lock
+ }, tuples[ i ^ 1 ][ 2 ].disable, tuples[ 2 ][ 2 ].lock);
+ }
+
+ // deferred[ resolve | reject | notify ]
+ deferred[ tuple[0] ] = function () {
+ deferred[ tuple[0] + "With" ](this === deferred ? promise : this, arguments);
+ return this;
+ };
+ deferred[ tuple[0] + "With" ] = list.fireWith;
+ });
+
+ // Make the deferred a promise
+ promise.promise(deferred);
+
+ // Call given func if any
+ if ( func ) {
+ func.call(deferred, deferred);
+ }
+
+ // All done!
+ return deferred;
+ },
+
+ // Deferred helper
+ when: function (subordinate /* , ..., subordinateN */) {
+ var i = 0,
+ resolveValues = 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 ? 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();
+ }
+ });
+
+
+// The deferred used on DOM ready
+ var readyList;
+
+ jQuery.fn.ready = function (fn) {
+ // Add the callback
+ jQuery.ready.promise().done(fn);
+
+ return this;
+ };
+
+ jQuery.extend({
+ // 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;
+ }
+
+ // 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");
+ }
+ }
+ });
+
+ /**
+ * The ready event handler and self cleanup method
+ */
+ function completed() {
+ document.removeEventListener("DOMContentLoaded", completed, false);
+ window.removeEventListener("load", completed, false);
+ jQuery.ready();
+ }
+
+ 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);
+
+ } else {
+
+ // Use the handy event callback
+ document.addEventListener("DOMContentLoaded", completed, false);
+
+ // A fallback to window.onload, that will always work
+ window.addEventListener("load", completed, false);
+ }
+ }
+ return readyList.promise(obj);
+ };
+
+// Kick off the DOM ready check even if the user does not
+ jQuery.ready.promise();
+
+
+// Multifunctional method to get and set values of a collection
+// The value/s can optionally be executed if it's a function
+ var access = jQuery.access = function (elems, fn, key, value, chainable, emptyGet, raw) {
+ var i = 0,
+ len = elems.length,
+ bulk = key == null;
+
+ // Sets many values
+ if ( jQuery.type(key) === "object" ) {
+ chainable = true;
+ for ( i in key ) {
+ jQuery.access(elems, fn, i, key[i], true, emptyGet, raw);
+ }
+
+ // Sets one value
+ } else if ( value !== undefined ) {
+ chainable = true;
+
+ if ( !jQuery.isFunction(value) ) {
+ raw = true;
+ }
+
+ if ( bulk ) {
+ // Bulk operations run against the entire set
+ if ( raw ) {
+ fn.call(elems, value);
+ fn = null;
+
+ // ...except when executing function values
+ } else {
+ bulk = fn;
+ fn = function (elem, key, value) {
+ return bulk.call(jQuery(elem), value);
+ };
+ }
+ }
+
+ if ( fn ) {
+ for ( ; i < len; i++ ) {
+ fn(elems[i], key, raw ? value : value.call(elems[i], i, fn(elems[i], key)));
+ }
+ }
+ }
+
+ return chainable ?
+ elems :
+
+ // Gets
+ bulk ?
+ fn.call(elems) :
+ len ? fn(elems[0], key) : emptyGet;
+ };
+
+
+ /**
+ * Determines whether an object can have data
+ */
+ jQuery.acceptData = function (owner) {
+ // Accepts only:
+ // - Node
+ // - Node.ELEMENT_NODE
+ // - Node.DOCUMENT_NODE
+ // - Object
+ // - Any
+ /* jshint -W018 */
+ return owner.nodeType === 1 || owner.nodeType === 9 || !( +owner.nodeType );
+ };
+
+
+ function Data() {
+ // Support: Android < 4,
+ // Old WebKit does not have Object.preventExtensions/freeze method,
+ // return new empty object instead with no [[set]] accessor
+ Object.defineProperty(this.cache = {}, 0, {
+ get: function () {
+ return {};
+ }
+ });
+
+ this.expando = jQuery.expando + Math.random();
+ }
+
+ Data.uid = 1;
+ Data.accepts = jQuery.acceptData;
+
+ Data.prototype = {
+ key: function (owner) {
+ // We can accept data for non-element nodes in modern browsers,
+ // but we should not, see #8335.
+ // Always return the key for a frozen object.
+ if ( !Data.accepts(owner) ) {
+ return 0;
+ }
+
+ var descriptor = {},
+ // Check if the owner object already has a cache key
+ unlock = owner[ this.expando ];
+
+ // If not, create one
+ if ( !unlock ) {
+ unlock = Data.uid++;
+
+ // Secure it in a non-enumerable, non-writable property
+ try {
+ descriptor[ this.expando ] = { value: unlock };
+ Object.defineProperties(owner, descriptor);
+
+ // Support: Android < 4
+ // Fallback to a less secure definition
+ } catch (e) {
+ descriptor[ this.expando ] = unlock;
+ jQuery.extend(owner, descriptor);
+ }
+ }
+
+ // Ensure the cache object
+ if ( !this.cache[ unlock ] ) {
+ this.cache[ unlock ] = {};
+ }
+
+ return unlock;
+ },
+ set: function (owner, data, value) {
+ var prop,
+ // There may be an unlock assigned to this node,
+ // if there is no entry for this "owner", create one inline
+ // and set the unlock as though an owner entry had always existed
+ unlock = this.key(owner),
+ cache = this.cache[ unlock ];
+
+ // Handle: [ owner, key, value ] args
+ if ( typeof data === "string" ) {
+ cache[ data ] = value;
+
+ // Handle: [ owner, { properties } ] args
+ } else {
+ // Fresh assignments by object are shallow copied
+ if ( jQuery.isEmptyObject(cache) ) {
+ jQuery.extend(this.cache[ unlock ], data);
+ // Otherwise, copy the properties one-by-one to the cache object
+ } else {
+ for ( prop in data ) {
+ cache[ prop ] = data[ prop ];
+ }
+ }
+ }
+ return cache;
+ },
+ get: function (owner, key) {
+ // Either a valid cache is found, or will be created.
+ // New caches will be created and the unlock returned,
+ // allowing direct access to the newly created
+ // empty data object. A valid owner object must be provided.
+ var cache = this.cache[ this.key(owner) ];
+
+ return key === undefined ?
+ cache : cache[ key ];
+ },
+ access: function (owner, key, value) {
+ var stored;
+ // In cases where either:
+ //
+ // 1. No key was specified
+ // 2. A string key was specified, but no value provided
+ //
+ // Take the "read" path and allow the get method to determine
+ // which value to return, respectively either:
+ //
+ // 1. The entire cache object
+ // 2. The data stored at the key
+ //
+ if ( key === undefined ||
+ ((key && typeof key === "string") && value === undefined) ) {
+
+ stored = this.get(owner, key);
+
+ return stored !== undefined ?
+ stored : this.get(owner, jQuery.camelCase(key));
+ }
+
+ // [*]When the key is not a string, or both a key and value
+ // are specified, set or extend (existing objects) with either:
+ //
+ // 1. An object of properties
+ // 2. A key and value
+ //
+ this.set(owner, key, value);
+
+ // Since the "set" path can have two possible entry points
+ // return the expected data based on which path was taken[*]
+ return value !== undefined ? value : key;
+ },
+ remove: function (owner, key) {
+ var i, name, camel,
+ unlock = this.key(owner),
+ cache = this.cache[ unlock ];
+
+ if ( key === undefined ) {
+ this.cache[ unlock ] = {};
+
+ } else {
+ // Support array or space separated string of keys
+ if ( jQuery.isArray(key) ) {
+ // If "name" is an array of keys...
+ // When data is initially created, via ("key", "val") signature,
+ // keys will be converted to camelCase.
+ // Since there is no way to tell _how_ a key was added, remove
+ // both plain key and camelCase key. #12786
+ // This will only penalize the array argument path.
+ name = key.concat(key.map(jQuery.camelCase));
+ } else {
+ camel = jQuery.camelCase(key);
+ // Try the string as a key before any manipulation
+ if ( key in cache ) {
+ name = [ key, camel ];
+ } else {
+ // If a key with the spaces exists, use it.
+ // Otherwise, create an array by matching non-whitespace
+ name = camel;
+ name = name in cache ?
+ [ name ] : ( name.match(rnotwhite) || [] );
+ }
+ }
+
+ i = name.length;
+ while ( i-- ) {
+ delete cache[ name[ i ] ];
+ }
+ }
+ },
+ hasData: function (owner) {
+ return !jQuery.isEmptyObject(
+ this.cache[ owner[ this.expando ] ] || {}
+ );
+ },
+ discard: function (owner) {
+ if ( owner[ this.expando ] ) {
+ delete this.cache[ owner[ this.expando ] ];
+ }
+ }
+ };
+ var data_priv = new Data();
+
+ var data_user = new Data();
+
+
+ /*
+ Implementation Summary
+
+ 1. Enforce API surface and semantic compatibility with 1.9.x branch
+ 2. Improve the module's maintainability by reducing the storage
+ paths to a single mechanism.
+ 3. Use the same single mechanism to support "private" and "user" data.
+ 4. _Never_ expose "private" data to user code (TODO: Drop _data, _removeData)
+ 5. Avoid exposing implementation details on user objects (eg. expando properties)
+ 6. Provide a clear path for implementation upgrade to WeakMap in 2014
+ */
+ var rbrace = /^(?:\{[\w\W]*\}|\[[\w\W]*\])$/,
+ rmultiDash = /([A-Z])/g;
+
+ function dataAttr(elem, key, data) {
+ var name;
+
+ // If nothing was found internally, try to fetch any
+ // data from the HTML5 data-* attribute
+ if ( data === undefined && elem.nodeType === 1 ) {
+ 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
+ data_user.set(elem, key, data);
+ } else {
+ data = undefined;
+ }
+ }
+ return data;
+ }
+
+ jQuery.extend({
+ hasData: function (elem) {
+ return data_user.hasData(elem) || data_priv.hasData(elem);
+ },
+
+ data: function (elem, name, data) {
+ return data_user.access(elem, name, data);
+ },
+
+ removeData: function (elem, name) {
+ data_user.remove(elem, name);
+ },
+
+ // TODO: Now that all calls to _data and _removeData have been replaced
+ // with direct calls to data_priv methods, these can be deprecated.
+ _data: function (elem, name, data) {
+ return data_priv.access(elem, name, data);
+ },
+
+ _removeData: function (elem, name) {
+ data_priv.remove(elem, name);
+ }
+ });
+
+ jQuery.fn.extend({
+ data: function (key, value) {
+ var i, name, data,
+ elem = this[ 0 ],
+ attrs = elem && elem.attributes;
+
+ // Gets all values
+ if ( key === undefined ) {
+ if ( this.length ) {
+ data = data_user.get(elem);
+
+ if ( elem.nodeType === 1 && !data_priv.get(elem, "hasDataAttrs") ) {
+ i = attrs.length;
+ while ( i-- ) {
+ name = attrs[ i ].name;
+
+ if ( name.indexOf("data-") === 0 ) {
+ name = jQuery.camelCase(name.slice(5));
+ dataAttr(elem, name, data[ name ]);
+ }
+ }
+ data_priv.set(elem, "hasDataAttrs", true);
+ }
+ }
+
+ return data;
+ }
+
+ // Sets multiple values
+ if ( typeof key === "object" ) {
+ return this.each(function () {
+ data_user.set(this, key);
+ });
+ }
+
+ return access(this, function (value) {
+ var data,
+ camelKey = jQuery.camelCase(key);
+
+ // The calling jQuery object (element matches) is not empty
+ // (and therefore has an element appears at this[ 0 ]) and the
+ // `value` parameter was not undefined. An empty jQuery object
+ // will result in `undefined` for elem = this[ 0 ] which will
+ // throw an exception if an attempt to read a data cache is made.
+ if ( elem && value === undefined ) {
+ // Attempt to get data from the cache
+ // with the key as-is
+ data = data_user.get(elem, key);
+ if ( data !== undefined ) {
+ return data;
+ }
+
+ // Attempt to get data from the cache
+ // with the key camelized
+ data = data_user.get(elem, camelKey);
+ if ( data !== undefined ) {
+ return data;
+ }
+
+ // Attempt to "discover" the data in
+ // HTML5 custom data-* attrs
+ data = dataAttr(elem, camelKey, undefined);
+ if ( data !== undefined ) {
+ return data;
+ }
+
+ // We tried really hard, but the data doesn't exist.
+ return;
+ }
+
+ // Set the data...
+ this.each(function () {
+ // First, attempt to store a copy or reference of any
+ // data that might've been store with a camelCased key.
+ var data = data_user.get(this, camelKey);
+
+ // For HTML5 data-* attribute interop, we have to
+ // store property names with dashes in a camelCase form.
+ // This might not apply to all properties...*
+ data_user.set(this, camelKey, value);
+
+ // *... In the case of properties that might _actually_
+ // have dashes, we need to also store a copy of that
+ // unchanged property.
+ if ( key.indexOf("-") !== -1 && data !== undefined ) {
+ data_user.set(this, key, value);
+ }
+ });
+ }, null, value, arguments.length > 1, null, true);
+ },
+
+ removeData: function (key) {
+ return this.each(function () {
+ data_user.remove(this, key);
+ });
+ }
+ });
+
+
+ jQuery.extend({
+ queue: function (elem, type, data) {
+ var queue;
+
+ if ( elem ) {
+ type = ( type || "fx" ) + "queue";
+ queue = data_priv.get(elem, type);
+
+ // Speed up dequeue by getting out quickly if this is just a lookup
+ if ( data ) {
+ if ( !queue || jQuery.isArray(data) ) {
+ queue = data_priv.access(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 data_priv.get(elem, key) || data_priv.access(elem, key, {
+ empty: jQuery.Callbacks("once memory").add(function () {
+ data_priv.remove(elem, [ type + "queue", key ]);
+ })
+ });
+ }
+ });
+
+ jQuery.fn.extend({
+ queue: function (type, data) {
+ var setter = 2;
+
+ if ( typeof type !== "string" ) {
+ data = type;
+ type = "fx";
+ setter--;
+ }
+
+ if ( arguments.length < setter ) {
+ return jQuery.queue(this[0], type);
+ }
+
+ return data === undefined ?
+ this :
+ this.each(function () {
+ var queue = jQuery.queue(this, type, data);
+
+ // ensure a hooks for this queue
+ jQuery._queueHooks(this, type);
+
+ if ( type === "fx" && queue[0] !== "inprogress" ) {
+ jQuery.dequeue(this, type);
+ }
+ });
+ },
+ dequeue: function (type) {
+ return this.each(function () {
+ jQuery.dequeue(this, type);
+ });
+ },
+ 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 = data_priv.get(elements[ i ], type + "queueHooks");
+ if ( tmp && tmp.empty ) {
+ count++;
+ tmp.empty.add(resolve);
+ }
+ }
+ resolve();
+ return defer.promise(obj);
+ }
+ });
+ var pnum = (/[+-]?(?:\d*\.|)\d+(?:[eE][+-]?\d+|)/).source;
+
+ var cssExpand = [ "Top", "Right", "Bottom", "Left" ];
+
+ var isHidden = function (elem, el) {
+ // isHidden might be called from jQuery#filter function;
+ // in that case, element will be second argument
+ elem = el || elem;
+ return jQuery.css(elem, "display") === "none" || !jQuery.contains(elem.ownerDocument, elem);
+ };
+
+ var rcheckableType = (/^(?:checkbox|radio)$/i);
+
+
+ (function () {
+ var fragment = document.createDocumentFragment(),
+ div = fragment.appendChild(document.createElement("div"));
+
+ // #11217 - WebKit loses check when the name is after the checked attribute
+ div.innerHTML = "<input type='radio' checked='checked' name='t'/>";
+
+ // Support: Safari 5.1, iOS 5.1, Android 4.x, Android 2.3
+ // old WebKit doesn't clone checked state correctly in fragments
+ support.checkClone = div.cloneNode(true).cloneNode(true).lastChild.checked;
+
+ // Make sure textarea (and checkbox) defaultValue is properly cloned
+ // Support: IE9-IE11+
+ div.innerHTML = "<textarea>x</textarea>";
+ support.noCloneChecked = !!div.cloneNode(true).lastChild.defaultValue;
+ })();
+ var strundefined = typeof undefined;
+
+
+ support.focusinBubbles = "onfocusin" in window;
+
+
+ var
+ rkeyEvent = /^key/,
+ rmouseEvent = /^(?:mouse|contextmenu)|click/,
+ rfocusMorph = /^(?:focusinfocus|focusoutblur)$/,
+ rtypenamespace = /^([^.]*)(?:\.(.+)|)$/;
+
+ function returnTrue() {
+ return true;
+ }
+
+ function returnFalse() {
+ return false;
+ }
+
+ function safeActiveElement() {
+ try {
+ return document.activeElement;
+ } catch (err) {
+ }
+ }
+
+ /*
+ * Helper functions for managing events -- not part of the public interface.
+ * Props to Dean Edwards' addEvent library for many of the ideas.
+ */
+ jQuery.event = {
+
+ global: {},
+
+ add: function (elem, types, handler, data, selector) {
+
+ var handleObjIn, eventHandle, tmp,
+ events, t, handleObj,
+ special, handlers, type, namespaces, origType,
+ elemData = data_priv.get(elem);
+
+ // Don't attach events to noData or text/comment nodes (but allow plain objects)
+ if ( !elemData ) {
+ return;
+ }
+
+ // Caller can pass in an object of custom data in lieu of the handler
+ if ( handler.handler ) {
+ handleObjIn = handler;
+ handler = handleObjIn.handler;
+ selector = handleObjIn.selector;
+ }
+
+ // Make sure that the handler has a unique ID, used to find/remove it later
+ if ( !handler.guid ) {
+ handler.guid = jQuery.guid++;
+ }
+
+ // Init the element's event structure and main handler, if this is the first
+ if ( !(events = elemData.events) ) {
+ events = elemData.events = {};
+ }
+ if ( !(eventHandle = elemData.handle) ) {
+ eventHandle = elemData.handle = function (e) {
+ // Discard the second event of a jQuery.event.trigger() and
+ // when an event is called after a page has unloaded
+ return typeof jQuery !== strundefined && jQuery.event.triggered !== e.type ?
+ jQuery.event.dispatch.apply(elem, arguments) : undefined;
+ };
+ }
+
+ // Handle multiple events separated by a space
+ types = ( types || "" ).match(rnotwhite) || [ "" ];
+ t = types.length;
+ while ( t-- ) {
+ tmp = rtypenamespace.exec(types[t]) || [];
+ type = origType = tmp[1];
+ namespaces = ( tmp[2] || "" ).split(".").sort();
+
+ // There *must* be a type, no attaching namespace-only handlers
+ if ( !type ) {
+ continue;
+ }
+
+ // If event changes its type, use the special event handlers for the changed type
+ special = jQuery.event.special[ type ] || {};
+
+ // If selector defined, determine special event api type, otherwise given type
+ type = ( selector ? special.delegateType : special.bindType ) || type;
+
+ // Update special based on newly reset type
+ special = jQuery.event.special[ type ] || {};
+
+ // handleObj is passed to all event handlers
+ handleObj = jQuery.extend({
+ type: type,
+ origType: origType,
+ data: data,
+ handler: handler,
+ guid: handler.guid,
+ selector: selector,
+ needsContext: selector && jQuery.expr.match.needsContext.test(selector),
+ namespace: namespaces.join(".")
+ }, handleObjIn);
+
+ // Init the event handler queue if we're the first
+ if ( !(handlers = events[ type ]) ) {
+ handlers = events[ type ] = [];
+ handlers.delegateCount = 0;
+
+ // Only use addEventListener if the special events handler returns false
+ if ( !special.setup || special.setup.call(elem, data, namespaces, eventHandle) === false ) {
+ if ( elem.addEventListener ) {
+ elem.addEventListener(type, eventHandle, false);
+ }
+ }
+ }
+
+ 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;
+ }
+
+ },
+
+ // Detach an event or set of events from an element
+ remove: function (elem, types, handler, selector, mappedTypes) {
+
+ var j, origCount, tmp,
+ events, t, handleObj,
+ special, handlers, type, namespaces, origType,
+ elemData = data_priv.hasData(elem) && data_priv.get(elem);
+
+ if ( !elemData || !(events = elemData.events) ) {
+ return;
+ }
+
+ // Once for each type.namespace in types; type may be omitted
+ types = ( types || "" ).match(rnotwhite) || [ "" ];
+ t = types.length;
+ while ( t-- ) {
+ tmp = rtypenamespace.exec(types[t]) || [];
+ type = origType = tmp[1];
+ namespaces = ( tmp[2] || "" ).split(".").sort();
+
+ // Unbind all events (on this namespace, if provided) for the element
+ if ( !type ) {
+ for ( type in events ) {
+ jQuery.event.remove(elem, type + types[ t ], handler, selector, true);
+ }
+ continue;
+ }
+
+ special = jQuery.event.special[ type ] || {};
+ type = ( selector ? special.delegateType : special.bindType ) || type;
+ handlers = events[ type ] || [];
+ tmp = tmp[2] && new RegExp("(^|\\.)" + namespaces.join("\\.(?:.*\\.|)") + "(\\.|$)");
+
+ // Remove matching events
+ origCount = j = handlers.length;
+ while ( j-- ) {
+ handleObj = handlers[ j ];
+
+ if ( ( mappedTypes || origType === handleObj.origType ) &&
+ ( !handler || handler.guid === handleObj.guid ) &&
+ ( !tmp || tmp.test(handleObj.namespace) ) &&
+ ( !selector || selector === handleObj.selector || selector === "**" && handleObj.selector ) ) {
+ handlers.splice(j, 1);
+
+ if ( handleObj.selector ) {
+ handlers.delegateCount--;
+ }
+ if ( special.remove ) {
+ special.remove.call(elem, handleObj);
+ }
+ }
+ }
+
+ // Remove generic event handler if we removed something and no more handlers exist
+ // (avoids potential for endless recursion during removal of special event handlers)
+ if ( origCount && !handlers.length ) {
+ if ( !special.teardown || special.teardown.call(elem, namespaces, elemData.handle) === false ) {
+ jQuery.removeEvent(elem, type, elemData.handle);
+ }
+
+ delete events[ type ];
+ }
+ }
+
+ // Remove the expando if it's no longer used
+ if ( jQuery.isEmptyObject(events) ) {
+ delete elemData.handle;
+ data_priv.remove(elem, "events");
+ }
+ },
+
+ trigger: function (event, data, elem, onlyHandlers) {
+
+ var i, cur, tmp, bubbleType, ontype, handle, special,
+ eventPath = [ elem || document ],
+ type = hasOwn.call(event, "type") ? event.type : event,
+ namespaces = hasOwn.call(event, "namespace") ? event.namespace.split(".") : [];
+
+ cur = tmp = elem = elem || document;
+
+ // Don't do events on text and comment nodes
+ if ( elem.nodeType === 3 || elem.nodeType === 8 ) {
+ return;
+ }
+
+ // focus/blur morphs to focusin/out; ensure we're not firing them right now
+ if ( rfocusMorph.test(type + jQuery.event.triggered) ) {
+ return;
+ }
+
+ if ( type.indexOf(".") >= 0 ) {
+ // Namespaced trigger; create a regexp to match event type in handle()
+ namespaces = type.split(".");
+ type = namespaces.shift();
+ namespaces.sort();
+ }
+ ontype = type.indexOf(":") < 0 && "on" + type;
+
+ // Caller can pass in a jQuery.Event object, Object, or just an event type string
+ event = event[ jQuery.expando ] ?
+ event :
+ new jQuery.Event(type, typeof event === "object" && event);
+
+ // Trigger bitmask: & 1 for native handlers; & 2 for jQuery (always true)
+ event.isTrigger = onlyHandlers ? 2 : 3;
+ event.namespace = namespaces.join(".");
+ event.namespace_re = event.namespace ?
+ new RegExp("(^|\\.)" + namespaces.join("\\.(?:.*\\.|)") + "(\\.|$)") :
+ null;
+
+ // Clean up the event in case it is being reused
+ event.result = undefined;
+ if ( !event.target ) {
+ event.target = elem;
+ }
+
+ // Clone any incoming data and prepend the event, creating the handler arg list
+ data = data == null ?
+ [ event ] :
+ jQuery.makeArray(data, [ event ]);
+
+ // Allow special events to draw outside the lines
+ special = jQuery.event.special[ type ] || {};
+ if ( !onlyHandlers && special.trigger && special.trigger.apply(elem, data) === false ) {
+ return;
+ }
+
+ // Determine event propagation path in advance, per W3C events spec (#9951)
+ // Bubble up to document, then to window; watch for a global ownerDocument var (#9724)
+ if ( !onlyHandlers && !special.noBubble && !jQuery.isWindow(elem) ) {
+
+ bubbleType = special.delegateType || type;
+ if ( !rfocusMorph.test(bubbleType + type) ) {
+ cur = cur.parentNode;
+ }
+ for ( ; cur; cur = cur.parentNode ) {
+ eventPath.push(cur);
+ tmp = cur;
+ }
+
+ // Only add window if we got to document (e.g., not plain obj or detached DOM)
+ if ( tmp === (elem.ownerDocument || document) ) {
+ eventPath.push(tmp.defaultView || tmp.parentWindow || window);
+ }
+ }
+
+ // Fire handlers on the event path
+ i = 0;
+ while ( (cur = eventPath[i++]) && !event.isPropagationStopped() ) {
+
+ event.type = i > 1 ?
+ bubbleType :
+ special.bindType || type;
+
+ // jQuery handler
+ handle = ( data_priv.get(cur, "events") || {} )[ event.type ] && data_priv.get(cur, "handle");
+ if ( handle ) {
+ handle.apply(cur, data);
+ }
+
+ // Native handler
+ handle = ontype && cur[ ontype ];
+ if ( handle && handle.apply && jQuery.acceptData(cur) ) {
+ event.result = handle.apply(cur, data);
+ if ( event.result === 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(eventPath.pop(), data) === false) &&
+ jQuery.acceptData(elem) ) {
+
+ // Call a native DOM method on the target with the same name name as the event.
+ // Don't do default actions on window, that's where global variables be (#6170)
+ if ( ontype && jQuery.isFunction(elem[ type ]) && !jQuery.isWindow(elem) ) {
+
+ // Don't re-trigger an onFOO event when we call its FOO() method
+ tmp = elem[ ontype ];
+
+ if ( tmp ) {
+ elem[ ontype ] = null;
+ }
+
+ // Prevent re-triggering of the same event, since we already bubbled it above
+ jQuery.event.triggered = type;
+ elem[ type ]();
+ jQuery.event.triggered = undefined;
+
+ if ( tmp ) {
+ elem[ ontype ] = tmp;
+ }
+ }
+ }
+ }
+
+ return event.result;
+ },
+
+ dispatch: function (event) {
+
+ // Make a writable jQuery.Event from the native event object
+ event = jQuery.event.fix(event);
+
+ var i, j, ret, matched, handleObj,
+ handlerQueue = [],
+ args = slice.call(arguments),
+ handlers = ( data_priv.get(this, "events") || {} )[ event.type ] || [],
+ special = jQuery.event.special[ event.type ] || {};
+
+ // Use the fix-ed jQuery.Event rather than the (read-only) native event
+ args[0] = event;
+ event.delegateTarget = this;
+
+ // Call the preDispatch hook for the mapped type, and let it bail if desired
+ if ( special.preDispatch && special.preDispatch.call(this, event) === false ) {
+ return;
+ }
+
+ // Determine handlers
+ handlerQueue = jQuery.event.handlers.call(this, event, handlers);
+
+ // Run delegates first; they may want to stop propagation beneath us
+ i = 0;
+ while ( (matched = handlerQueue[ i++ ]) && !event.isPropagationStopped() ) {
+ event.currentTarget = matched.elem;
+
+ j = 0;
+ while ( (handleObj = matched.handlers[ j++ ]) && !event.isImmediatePropagationStopped() ) {
+
+ // Triggered event must either 1) have no namespace, or
+ // 2) have namespace(s) a subset or equal to those in the bound event (both can have no namespace).
+ if ( !event.namespace_re || event.namespace_re.test(handleObj.namespace) ) {
+
+ event.handleObj = handleObj;
+ event.data = handleObj.data;
+
+ ret = ( (jQuery.event.special[ handleObj.origType ] || {}).handle || handleObj.handler )
+ .apply(matched.elem, args);
+
+ if ( ret !== undefined ) {
+ if ( (event.result = ret) === false ) {
+ event.preventDefault();
+ event.stopPropagation();
+ }
+ }
+ }
+ }
+ }
+
+ // Call the postDispatch hook for the mapped type
+ if ( special.postDispatch ) {
+ special.postDispatch.call(this, event);
+ }
+
+ return event.result;
+ },
+
+ handlers: function (event, handlers) {
+ var i, matches, sel, handleObj,
+ handlerQueue = [],
+ delegateCount = handlers.delegateCount,
+ cur = event.target;
+
+ // Find delegate handlers
+ // Black-hole SVG <use> instance trees (#13180)
+ // Avoid non-left-click bubbling in Firefox (#3861)
+ if ( delegateCount && cur.nodeType && (!event.button || event.type !== "click") ) {
+
+ for ( ; cur !== this; cur = cur.parentNode || this ) {
+
+ // Don't process clicks on disabled elements (#6911, #8165, #11382, #11764)
+ if ( cur.disabled !== true || event.type !== "click" ) {
+ matches = [];
+ for ( i = 0; i < delegateCount; i++ ) {
+ handleObj = handlers[ i ];
+
+ // Don't conflict with Object.prototype properties (#13203)
+ sel = handleObj.selector + " ";
+
+ if ( matches[ sel ] === undefined ) {
+ matches[ sel ] = handleObj.needsContext ?
+ jQuery(sel, this).index(cur) >= 0 :
+ jQuery.find(sel, this, null, [ cur ]).length;
+ }
+ if ( matches[ sel ] ) {
+ matches.push(handleObj);
+ }
+ }
+ if ( matches.length ) {
+ handlerQueue.push({ elem: cur, handlers: matches });
+ }
+ }
+ }
+ }
+
+ // Add the remaining (directly-bound) handlers
+ if ( delegateCount < handlers.length ) {
+ handlerQueue.push({ elem: this, handlers: handlers.slice(delegateCount) });
+ }
+
+ return handlerQueue;
+ },
+
+ // Includes some event props shared by KeyEvent and MouseEvent
+ props: "altKey bubbles cancelable ctrlKey currentTarget eventPhase metaKey relatedTarget shiftKey target timeStamp view which".split(" "),
+
+ fixHooks: {},
+
+ keyHooks: {
+ props: "char charCode key keyCode".split(" "),
+ filter: function (event, original) {
+
+ // Add which for key events
+ if ( event.which == null ) {
+ event.which = original.charCode != null ? original.charCode : original.keyCode;
+ }
+
+ return event;
+ }
+ },
+
+ mouseHooks: {
+ props: "button buttons clientX clientY offsetX offsetY pageX pageY screenX screenY toElement".split(" "),
+ filter: function (event, original) {
+ var eventDoc, doc, body,
+ button = original.button;
+
+ // 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 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, copy,
+ type = event.type,
+ originalEvent = event,
+ fixHook = this.fixHooks[ type ];
+
+ if ( !fixHook ) {
+ this.fixHooks[ type ] = fixHook =
+ rmouseEvent.test(type) ? this.mouseHooks :
+ rkeyEvent.test(type) ? this.keyHooks :
+ {};
+ }
+ copy = fixHook.props ? this.props.concat(fixHook.props) : this.props;
+
+ event = new jQuery.Event(originalEvent);
+
+ i = copy.length;
+ while ( i-- ) {
+ prop = copy[ i ];
+ event[ prop ] = originalEvent[ prop ];
+ }
+
+ // Support: Cordova 2.5 (WebKit) (#13255)
+ // All events should have a target; Cordova deviceready doesn't
+ if ( !event.target ) {
+ event.target = document;
+ }
+
+ // Support: Safari 6.0+, Chrome < 28
+ // Target should not be a text node (#504, #13143)
+ if ( event.target.nodeType === 3 ) {
+ event.target = event.target.parentNode;
+ }
+
+ return fixHook.filter ? fixHook.filter(event, originalEvent) : event;
+ },
+
+ special: {
+ load: {
+ // Prevent triggered image.load events from bubbling to window.load
+ noBubble: true
+ },
+ focus: {
+ // Fire native event if possible so blur/focus sequence is correct
+ trigger: function () {
+ if ( this !== safeActiveElement() && this.focus ) {
+ this.focus();
+ return false;
+ }
+ },
+ delegateType: "focusin"
+ },
+ blur: {
+ trigger: function () {
+ if ( this === safeActiveElement() && this.blur ) {
+ this.blur();
+ return false;
+ }
+ },
+ delegateType: "focusout"
+ },
+ click: {
+ // For checkbox, fire native event so checked state will be right
+ trigger: function () {
+ if ( this.type === "checkbox" && this.click && jQuery.nodeName(this, "input") ) {
+ this.click();
+ return false;
+ }
+ },
+
+ // For cross-browser consistency, don't fire native .click() on links
+ _default: function (event) {
+ return jQuery.nodeName(event.target, "a");
+ }
+ },
+
+ beforeunload: {
+ postDispatch: function (event) {
+
+ // Support: Firefox 20+
+ // Firefox doesn't alert if the returnValue field is not set.
+ if ( event.result !== undefined ) {
+ event.originalEvent.returnValue = event.result;
+ }
+ }
+ }
+ },
+
+ simulate: function (type, elem, event, bubble) {
+ // Piggyback on a donor event to simulate a different one.
+ // Fake originalEvent to avoid donor's stopPropagation, but if the
+ // simulated event prevents default then we do the same on the donor.
+ var e = jQuery.extend(
+ new jQuery.Event(),
+ event,
+ {
+ type: type,
+ isSimulated: true,
+ originalEvent: {}
+ }
+ );
+ if ( bubble ) {
+ jQuery.event.trigger(e, null, elem);
+ } else {
+ jQuery.event.dispatch.call(elem, e);
+ }
+ if ( e.isDefaultPrevented() ) {
+ event.preventDefault();
+ }
+ }
+ };
+
+ jQuery.removeEvent = function (elem, type, handle) {
+ if ( elem.removeEventListener ) {
+ elem.removeEventListener(type, handle, false);
+ }
+ };
+
+ 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 ||
+ // Support: Android < 4.0
+ src.defaultPrevented === undefined &&
+ src.getPreventDefault && src.getPreventDefault() ?
+ returnTrue :
+ returnFalse;
+
+ // Event type
+ } else {
+ this.type = src;
+ }
+
+ // Put explicitly provided properties onto the event object
+ if ( props ) {
+ jQuery.extend(this, props);
+ }
+
+ // Create a timestamp if incoming event doesn't have one
+ this.timeStamp = src && src.timeStamp || jQuery.now();
+
+ // Mark it as fixed
+ this[ jQuery.expando ] = true;
+ };
+
+// jQuery.Event is based on DOM3 Events as specified by the ECMAScript Language Binding
+// http://www.w3.org/TR/2003/WD-DOM-Level-3-Events-20030331/ecma-script-binding.html
+ jQuery.Event.prototype = {
+ isDefaultPrevented: returnFalse,
+ isPropagationStopped: returnFalse,
+ isImmediatePropagationStopped: returnFalse,
+
+ preventDefault: function () {
+ var e = this.originalEvent;
+
+ this.isDefaultPrevented = returnTrue;
+
+ if ( e && e.preventDefault ) {
+ e.preventDefault();
+ }
+ },
+ stopPropagation: function () {
+ var e = this.originalEvent;
+
+ this.isPropagationStopped = returnTrue;
+
+ if ( e && e.stopPropagation ) {
+ e.stopPropagation();
+ }
+ },
+ stopImmediatePropagation: function () {
+ this.isImmediatePropagationStopped = returnTrue;
+ this.stopPropagation();
+ }
+ };
+
+// Create mouseenter/leave events using mouseover/out and event-time checks
+// Support: Chrome 15+
+ jQuery.each({
+ mouseenter: "mouseover",
+ mouseleave: "mouseout"
+ }, function (orig, fix) {
+ jQuery.event.special[ orig ] = {
+ delegateType: fix,
+ bindType: fix,
+
+ handle: function (event) {
+ var ret,
+ target = this,
+ related = event.relatedTarget,
+ handleObj = event.handleObj;
+
+ // For mousenter/leave call the handler if related is outside the target.
+ // NB: No relatedTarget if the mouse left/entered the browser window
+ if ( !related || (related !== target && !jQuery.contains(target, related)) ) {
+ event.type = handleObj.origType;
+ ret = handleObj.handler.apply(this, arguments);
+ event.type = fix;
+ }
+ return ret;
+ }
+ };
+ });
+
+// Create "bubbling" focus and blur events
+// Support: Firefox, Chrome, Safari
+ if ( !support.focusinBubbles ) {
+ jQuery.each({ focus: "focusin", blur: "focusout" }, function (orig, fix) {
+
+ // Attach a single capturing handler on the document while someone wants focusin/focusout
+ var handler = function (event) {
+ jQuery.event.simulate(fix, event.target, jQuery.event.fix(event), true);
+ };
+
+ jQuery.event.special[ fix ] = {
+ setup: function () {
+ var doc = this.ownerDocument || this,
+ attaches = data_priv.access(doc, fix);
+
+ if ( !attaches ) {
+ doc.addEventListener(orig, handler, true);
+ }
+ data_priv.access(doc, fix, ( attaches || 0 ) + 1);
+ },
+ teardown: function () {
+ var doc = this.ownerDocument || this,
+ attaches = data_priv.access(doc, fix) - 1;
+
+ if ( !attaches ) {
+ doc.removeEventListener(orig, handler, true);
+ data_priv.remove(doc, fix);
+
+ } else {
+ data_priv.access(doc, fix, attaches);
+ }
+ }
+ };
+ });
+ }
+
+ 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" ) {
+ // ( 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);
+ });
+ },
+
+ trigger: function (type, data) {
+ return this.each(function () {
+ jQuery.event.trigger(type, data, this);
+ });
+ },
+ triggerHandler: function (type, data) {
+ var elem = this[0];
+ if ( elem ) {
+ return jQuery.event.trigger(type, data, elem, true);
+ }
+ }
+ });
+
+
+ var
+ rxhtmlTag = /<(?!area|br|col|embed|hr|img|input|link|meta|param)(([\w:]+)[^>]*)\/>/gi,
+ rtagName = /<([\w:]+)/,
+ rhtml = /<|&#?\w+;/,
+ rnoInnerhtml = /<(?:script|style|link)/i,
+ // checked="checked" or checked
+ rchecked = /checked\s*(?:[^=]|=\s*.checked.)/i,
+ rscriptType = /^$|\/(?:java|ecma)script/i,
+ rscriptTypeMasked = /^true\/(.*)/,
+ rcleanScript = /^\s*<!(?:\[CDATA\[|--)|(?:\]\]|--)>\s*$/g,
+
+ // We have to close these tags to support XHTML (#13200)
+ wrapMap = {
+
+ // Support: IE 9
+ option: [ 1, "<select multiple='multiple'>", "</select>" ],
+
+ thead: [ 1, "<table>", "</table>" ],
+ col: [ 2, "<table><colgroup>", "</colgroup></table>" ],
+ tr: [ 2, "<table><tbody>", "</tbody></table>" ],
+ td: [ 3, "<table><tbody><tr>", "</tr></tbody></table>" ],
+
+ _default: [ 0, "", "" ]
+ };
+
+// Support: IE 9
+ wrapMap.optgroup = wrapMap.option;
+
+ wrapMap.tbody = wrapMap.tfoot = wrapMap.colgroup = wrapMap.caption = wrapMap.thead;
+ wrapMap.th = wrapMap.td;
+
+// Support: 1.x compatibility
+// Manipulating tables requires a tbody
+ function manipulationTarget(elem, content) {
+ return jQuery.nodeName(elem, "table") &&
+ jQuery.nodeName(content.nodeType !== 11 ? content : content.firstChild, "tr") ?
+
+ elem.getElementsByTagName("tbody")[0] ||
+ elem.appendChild(elem.ownerDocument.createElement("tbody")) :
+ elem;
+ }
+
+// Replace/restore the type attribute of script elements for safe DOM manipulation
+ function disableScript(elem) {
+ elem.type = (elem.getAttribute("type") !== null) + "/" + elem.type;
+ return elem;
+ }
+
+ function restoreScript(elem) {
+ var match = rscriptTypeMasked.exec(elem.type);
+
+ if ( match ) {
+ elem.type = match[ 1 ];
+ } else {
+ elem.removeAttribute("type");
+ }
+
+ return elem;
+ }
+
+// Mark scripts as having already been evaluated
+ function setGlobalEval(elems, refElements) {
+ var i = 0,
+ l = elems.length;
+
+ for ( ; i < l; i++ ) {
+ data_priv.set(
+ elems[ i ], "globalEval", !refElements || data_priv.get(refElements[ i ], "globalEval")
+ );
+ }
+ }
+
+ function cloneCopyEvent(src, dest) {
+ var i, l, type, pdataOld, pdataCur, udataOld, udataCur, events;
+
+ if ( dest.nodeType !== 1 ) {
+ return;
+ }
+
+ // 1. Copy private data: events, handlers, etc.
+ if ( data_priv.hasData(src) ) {
+ pdataOld = data_priv.access(src);
+ pdataCur = data_priv.set(dest, pdataOld);
+ events = pdataOld.events;
+
+ if ( events ) {
+ delete pdataCur.handle;
+ pdataCur.events = {};
+
+ for ( type in events ) {
+ for ( i = 0, l = events[ type ].length; i < l; i++ ) {
+ jQuery.event.add(dest, type, events[ type ][ i ]);
+ }
+ }
+ }
+ }
+
+ // 2. Copy user data
+ if ( data_user.hasData(src) ) {
+ udataOld = data_user.access(src);
+ udataCur = jQuery.extend({}, udataOld);
+
+ data_user.set(dest, udataCur);
+ }
+ }
+
+ function getAll(context, tag) {
+ var ret = context.getElementsByTagName ? context.getElementsByTagName(tag || "*") :
+ context.querySelectorAll ? context.querySelectorAll(tag || "*") :
+ [];
+
+ return tag === undefined || tag && jQuery.nodeName(context, tag) ?
+ jQuery.merge([ context ], ret) :
+ ret;
+ }
+
+// Support: IE >= 9
+ function fixInput(src, dest) {
+ var nodeName = dest.nodeName.toLowerCase();
+
+ // Fails to persist the checked state of a cloned checkbox or radio button.
+ if ( nodeName === "input" && rcheckableType.test(src.type) ) {
+ dest.checked = src.checked;
+
+ // Fails to return the selected option to the default selected state when cloning options
+ } else if ( nodeName === "input" || nodeName === "textarea" ) {
+ dest.defaultValue = src.defaultValue;
+ }
+ }
+
+ jQuery.extend({
+ clone: function (elem, dataAndEvents, deepDataAndEvents) {
+ var i, l, srcElements, destElements,
+ clone = elem.cloneNode(true),
+ inPage = jQuery.contains(elem.ownerDocument, elem);
+
+ // Support: IE >= 9
+ // Fix Cloning issues
+ if ( !support.noCloneChecked && ( elem.nodeType === 1 || elem.nodeType === 11 ) && !jQuery.isXMLDoc(elem) ) {
+
+ // We eschew Sizzle here for performance reasons: http://jsperf.com/getall-vs-sizzle/2
+ destElements = getAll(clone);
+ srcElements = getAll(elem);
+
+ for ( i = 0, l = srcElements.length; i < l; i++ ) {
+ fixInput(srcElements[ i ], destElements[ i ]);
+ }
+ }
+
+ // Copy the events from the original to the clone
+ if ( dataAndEvents ) {
+ if ( deepDataAndEvents ) {
+ srcElements = srcElements || getAll(elem);
+ destElements = destElements || getAll(clone);
+
+ for ( i = 0, l = srcElements.length; i < l; i++ ) {
+ cloneCopyEvent(srcElements[ i ], destElements[ i ]);
+ }
+ } else {
+ cloneCopyEvent(elem, clone);
+ }
+ }
+
+ // Preserve script evaluation history
+ destElements = getAll(clone, "script");
+ if ( destElements.length > 0 ) {
+ setGlobalEval(destElements, !inPage && getAll(elem, "script"));
+ }
+
+ // Return the cloned set
+ return clone;
+ },
+
+ buildFragment: function (elems, context, scripts, selection) {
+ var elem, tmp, tag, wrap, contains, j,
+ fragment = context.createDocumentFragment(),
+ nodes = [],
+ i = 0,
+ l = elems.length;
+
+ for ( ; i < l; i++ ) {
+ elem = elems[ i ];
+
+ if ( elem || elem === 0 ) {
+
+ // Add nodes directly
+ if ( jQuery.type(elem) === "object" ) {
+ // Support: QtWebKit
+ // jQuery.merge because push.apply(_, arraylike) throws
+ jQuery.merge(nodes, elem.nodeType ? [ elem ] : elem);
+
+ // Convert non-html into a text node
+ } else if ( !rhtml.test(elem) ) {
+ nodes.push(context.createTextNode(elem));
+
+ // Convert html into DOM nodes
+ } else {
+ tmp = tmp || fragment.appendChild(context.createElement("div"));
+
+ // Deserialize a standard representation
+ tag = ( rtagName.exec(elem) || [ "", "" ] )[ 1 ].toLowerCase();
+ wrap = wrapMap[ tag ] || wrapMap._default;
+ tmp.innerHTML = wrap[ 1 ] + elem.replace(rxhtmlTag, "<$1></$2>") + wrap[ 2 ];
+
+ // Descend through wrappers to the right content
+ j = wrap[ 0 ];
+ while ( j-- ) {
+ tmp = tmp.lastChild;
+ }
+
+ // Support: QtWebKit
+ // jQuery.merge because push.apply(_, arraylike) throws
+ jQuery.merge(nodes, tmp.childNodes);
+
+ // Remember the top-level container
+ tmp = fragment.firstChild;
+
+ // Fixes #12346
+ // Support: Webkit, IE
+ tmp.textContent = "";
+ }
+ }
+ }
+
+ // Remove wrapper from fragment
+ fragment.textContent = "";
+
+ i = 0;
+ while ( (elem = nodes[ i++ ]) ) {
+
+ // #4087 - If origin and destination elements are the same, and this is
+ // that element, do not do anything
+ if ( selection && jQuery.inArray(elem, selection) !== -1 ) {
+ continue;
+ }
+
+ contains = jQuery.contains(elem.ownerDocument, elem);
+
+ // Append to fragment
+ tmp = getAll(fragment.appendChild(elem), "script");
+
+ // Preserve script evaluation history
+ if ( contains ) {
+ setGlobalEval(tmp);
+ }
+
+ // Capture executables
+ if ( scripts ) {
+ j = 0;
+ while ( (elem = tmp[ j++ ]) ) {
+ if ( rscriptType.test(elem.type || "") ) {
+ scripts.push(elem);
+ }
+ }
+ }
+ }
+
+ return fragment;
+ },
+
+ cleanData: function (elems) {
+ var data, elem, events, type, key, j,
+ special = jQuery.event.special,
+ i = 0;
+
+ for ( ; (elem = elems[ i ]) !== undefined; i++ ) {
+ if ( jQuery.acceptData(elem) ) {
+ key = elem[ data_priv.expando ];
+
+ if ( key && (data = data_priv.cache[ key ]) ) {
+ events = Object.keys(data.events || {});
+ if ( events.length ) {
+ for ( j = 0; (type = events[j]) !== undefined; j++ ) {
+ 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);
+ }
+ }
+ }
+ if ( data_priv.cache[ key ] ) {
+ // Discard any remaining `private` data
+ delete data_priv.cache[ key ];
+ }
+ }
+ }
+ // Discard any remaining `user` data
+ delete data_user.cache[ elem[ data_user.expando ] ];
+ }
+ }
+ });
+
+ jQuery.fn.extend({
+ text: function (value) {
+ return access(this, function (value) {
+ return value === undefined ?
+ jQuery.text(this) :
+ this.empty().each(function () {
+ if ( this.nodeType === 1 || this.nodeType === 11 || this.nodeType === 9 ) {
+ this.textContent = value;
+ }
+ });
+ }, null, value, arguments.length);
+ },
+
+ append: function () {
+ return this.domManip(arguments, function (elem) {
+ if ( this.nodeType === 1 || this.nodeType === 11 || this.nodeType === 9 ) {
+ var target = manipulationTarget(this, elem);
+ target.appendChild(elem);
+ }
+ });
+ },
+
+ prepend: function () {
+ return this.domManip(arguments, function (elem) {
+ if ( this.nodeType === 1 || this.nodeType === 11 || this.nodeType === 9 ) {
+ var target = manipulationTarget(this, elem);
+ target.insertBefore(elem, target.firstChild);
+ }
+ });
+ },
+
+ before: function () {
+ return this.domManip(arguments, function (elem) {
+ if ( this.parentNode ) {
+ this.parentNode.insertBefore(elem, this);
+ }
+ });
+ },
+
+ after: function () {
+ return this.domManip(arguments, function (elem) {
+ if ( this.parentNode ) {
+ this.parentNode.insertBefore(elem, this.nextSibling);
+ }
+ });
+ },
+
+ remove: function (selector, keepData /* Internal Use Only */) {
+ var elem,
+ elems = selector ? jQuery.filter(selector, this) : this,
+ i = 0;
+
+ for ( ; (elem = elems[i]) != null; i++ ) {
+ if ( !keepData && elem.nodeType === 1 ) {
+ jQuery.cleanData(getAll(elem));
+ }
+
+ if ( elem.parentNode ) {
+ if ( keepData && jQuery.contains(elem.ownerDocument, elem) ) {
+ setGlobalEval(getAll(elem, "script"));
+ }
+ elem.parentNode.removeChild(elem);
+ }
+ }
+
+ return this;
+ },
+
+ empty: function () {
+ var elem,
+ i = 0;
+
+ for ( ; (elem = this[i]) != null; i++ ) {
+ if ( elem.nodeType === 1 ) {
+
+ // Prevent memory leaks
+ jQuery.cleanData(getAll(elem, false));
+
+ // Remove any remaining nodes
+ elem.textContent = "";
+ }
+ }
+
+ 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 access(this, function (value) {
+ var elem = this[ 0 ] || {},
+ i = 0,
+ l = this.length;
+
+ if ( value === undefined && elem.nodeType === 1 ) {
+ return elem.innerHTML;
+ }
+
+ // See if we can take a shortcut and just use innerHTML
+ if ( typeof value === "string" && !rnoInnerhtml.test(value) && !wrapMap[ ( rtagName.exec(value) || [ "", "" ] )[ 1 ].toLowerCase() ] ) {
+
+ value = value.replace(rxhtmlTag, "<$1></$2>");
+
+ try {
+ for ( ; i < l; i++ ) {
+ elem = this[ i ] || {};
+
+ // Remove element nodes and prevent memory leaks
+ if ( elem.nodeType === 1 ) {
+ jQuery.cleanData(getAll(elem, false));
+ elem.innerHTML = value;
+ }
+ }
+
+ elem = 0;
+
+ // If using innerHTML throws an exception, use the fallback method
+ } catch (e) {
+ }
+ }
+
+ if ( elem ) {
+ this.empty().append(value);
+ }
+ }, null, value, arguments.length);
+ },
+
+ replaceWith: function () {
+ var arg = arguments[ 0 ];
+
+ // Make the changes, replacing each context element with the new content
+ this.domManip(arguments, function (elem) {
+ arg = this.parentNode;
+
+ jQuery.cleanData(getAll(this));
+
+ if ( arg ) {
+ arg.replaceChild(elem, this);
+ }
+ });
+
+ // Force removal if there was no new content (e.g., from empty arguments)
+ return arg && (arg.length || arg.nodeType) ? this : this.remove();
+ },
+
+ detach: function (selector) {
+ return this.remove(selector, true);
+ },
+
+ domManip: function (args, callback) {
+
+ // Flatten any nested arrays
+ args = concat.apply([], args);
+
+ var fragment, first, scripts, hasScripts, node, doc,
+ i = 0,
+ l = this.length,
+ set = this,
+ iNoClone = l - 1,
+ value = args[ 0 ],
+ isFunction = jQuery.isFunction(value);
+
+ // We can't cloneNode fragments that contain checked, in WebKit
+ if ( isFunction ||
+ ( l > 1 && typeof value === "string" && !support.checkClone && rchecked.test(value) ) ) {
+ return this.each(function (index) {
+ var self = set.eq(index);
+ if ( isFunction ) {
+ args[ 0 ] = value.call(this, index, self.html());
+ }
+ self.domManip(args, callback);
+ });
+ }
+
+ if ( l ) {
+ fragment = jQuery.buildFragment(args, this[ 0 ].ownerDocument, false, this);
+ first = fragment.firstChild;
+
+ if ( fragment.childNodes.length === 1 ) {
+ fragment = first;
+ }
+
+ if ( first ) {
+ scripts = jQuery.map(getAll(fragment, "script"), disableScript);
+ hasScripts = scripts.length;
+
+ // Use the original fragment for the last item instead of the first because it can end up
+ // being emptied incorrectly in certain situations (#8070).
+ for ( ; i < l; i++ ) {
+ node = fragment;
+
+ if ( i !== iNoClone ) {
+ node = jQuery.clone(node, true, true);
+
+ // Keep references to cloned scripts for later restoration
+ if ( hasScripts ) {
+ // Support: QtWebKit
+ // jQuery.merge because push.apply(_, arraylike) throws
+ jQuery.merge(scripts, getAll(node, "script"));
+ }
+ }
+
+ callback.call(this[ i ], node, i);
+ }
+
+ if ( hasScripts ) {
+ doc = scripts[ scripts.length - 1 ].ownerDocument;
+
+ // Reenable scripts
+ jQuery.map(scripts, restoreScript);
+
+ // Evaluate executable scripts on first document insertion
+ for ( i = 0; i < hasScripts; i++ ) {
+ node = scripts[ i ];
+ if ( rscriptType.test(node.type || "") && !data_priv.access(node, "globalEval") && jQuery.contains(doc, node) ) {
+
+ if ( node.src ) {
+ // Optional AJAX dependency, but won't run scripts if not present
+ if ( jQuery._evalUrl ) {
+ jQuery._evalUrl(node.src);
+ }
+ } else {
+ jQuery.globalEval(node.textContent.replace(rcleanScript, ""));
+ }
+ }
+ }
+ }
+ }
+ }
+
+ return this;
+ }
+ });
+
+ jQuery.each({
+ appendTo: "append",
+ prependTo: "prepend",
+ insertBefore: "before",
+ insertAfter: "after",
+ replaceAll: "replaceWith"
+ }, function (name, original) {
+ jQuery.fn[ name ] = function (selector) {
+ var elems,
+ ret = [],
+ insert = jQuery(selector),
+ last = insert.length - 1,
+ i = 0;
+
+ for ( ; i <= last; i++ ) {
+ elems = i === last ? this : this.clone(true);
+ jQuery(insert[ i ])[ original ](elems);
+
+ // Support: QtWebKit
+ // .get() because push.apply(_, arraylike) throws
+ push.apply(ret, elems.get());
+ }
+
+ return this.pushStack(ret);
+ };
+ });
+
+
+ var iframe,
+ elemdisplay = {};
+
+ /**
+ * Retrieve the actual display of a element
+ * @param {String} name nodeName of the element
+ * @param {Object} doc Document object
+ */
+// Called only from within defaultDisplay
+ function actualDisplay(name, doc) {
+ var elem = jQuery(doc.createElement(name)).appendTo(doc.body),
+
+ // getDefaultComputedStyle might be reliably used only on attached element
+ display = window.getDefaultComputedStyle ?
+
+ // Use of this method is a temporary fix (more like optmization) until something better comes along,
+ // since it was removed from specification and supported only in FF
+ window.getDefaultComputedStyle(elem[ 0 ]).display : jQuery.css(elem[ 0 ], "display");
+
+ // We don't have any data stored on the element,
+ // so use "detach" method as fast way to get rid of the element
+ elem.detach();
+
+ return display;
+ }
+
+ /**
+ * Try to determine the default display value of an element
+ * @param {String} nodeName
+ */
+ function defaultDisplay(nodeName) {
+ var doc = document,
+ display = elemdisplay[ nodeName ];
+
+ if ( !display ) {
+ display = actualDisplay(nodeName, doc);
+
+ // If the simple way fails, read from inside an iframe
+ if ( display === "none" || !display ) {
+
+ // Use the already-created iframe if possible
+ iframe = (iframe || jQuery("<iframe frameborder='0' width='0' height='0'/>")).appendTo(doc.documentElement);
+
+ // Always write a new HTML skeleton so Webkit and Firefox don't choke on reuse
+ doc = iframe[ 0 ].contentDocument;
+
+ // Support: IE
+ doc.write();
+ doc.close();
+
+ display = actualDisplay(nodeName, doc);
+ iframe.detach();
+ }
+
+ // Store the correct default display
+ elemdisplay[ nodeName ] = display;
+ }
+
+ return display;
+ }
+
+ var rmargin = (/^margin/);
+
+ var rnumnonpx = new RegExp("^(" + pnum + ")(?!px)[a-z%]+$", "i");
+
+ var getStyles = function (elem) {
+ return elem.ownerDocument.defaultView.getComputedStyle(elem, null);
+ };
+
+
+ function curCSS(elem, name, computed) {
+ var width, minWidth, maxWidth, ret,
+ style = elem.style;
+
+ computed = computed || getStyles(elem);
+
+ // Support: IE9
+ // getPropertyValue is only needed for .css('filter') in IE9, see #12537
+ if ( computed ) {
+ ret = computed.getPropertyValue(name) || computed[ name ];
+ }
+
+ if ( computed ) {
+
+ if ( ret === "" && !jQuery.contains(elem.ownerDocument, elem) ) {
+ ret = jQuery.style(elem, name);
+ }
+
+ // Support: iOS < 6
+ // A tribute to the "awesome hack by Dean Edwards"
+ // iOS < 6 (at least) returns percentage for a larger set of values, but width seems to be reliably pixels
+ // this is against the CSSOM draft spec: http://dev.w3.org/csswg/cssom/#resolved-values
+ if ( rnumnonpx.test(ret) && rmargin.test(name) ) {
+
+ // Remember the original values
+ width = style.width;
+ minWidth = style.minWidth;
+ maxWidth = style.maxWidth;
+
+ // Put in the new values to get a computed value out
+ style.minWidth = style.maxWidth = style.width = ret;
+ ret = computed.width;
+
+ // Revert the changed values
+ style.width = width;
+ style.minWidth = minWidth;
+ style.maxWidth = maxWidth;
+ }
+ }
+
+ return ret !== undefined ?
+ // Support: IE
+ // IE returns zIndex value as an integer.
+ ret + "" :
+ ret;
+ }
+
+
+ function addGetHookIf(conditionFn, hookFn) {
+ // Define the hook, we'll check on the first run if it's really needed.
+ return {
+ get: function () {
+ if ( conditionFn() ) {
+ // Hook not needed (or it's not possible to use it due to missing dependency),
+ // remove it.
+ // Since there are no other hooks for marginRight, remove the whole object.
+ delete this.get;
+ return;
+ }
+
+ // Hook needed; redefine it so that the support test is not executed again.
+
+ return (this.get = hookFn).apply(this, arguments);
+ }
+ };
+ }
+
+
+ (function () {
+ var pixelPositionVal, boxSizingReliableVal,
+ // Support: Firefox, Android 2.3 (Prefixed box-sizing versions).
+ divReset = "padding:0;margin:0;border:0;display:block;-webkit-box-sizing:content-box;" +
+ "-moz-box-sizing:content-box;box-sizing:content-box",
+ docElem = document.documentElement,
+ container = document.createElement("div"),
+ div = document.createElement("div");
+
+ div.style.backgroundClip = "content-box";
+ div.cloneNode(true).style.backgroundClip = "";
+ support.clearCloneStyle = div.style.backgroundClip === "content-box";
+
+ container.style.cssText = "border:0;width:0;height:0;position:absolute;top:0;left:-9999px;" +
+ "margin-top:1px";
+ container.appendChild(div);
+
+ // Executing both pixelPosition & boxSizingReliable tests require only one layout
+ // so they're executed at the same time to save the second computation.
+ function computePixelPositionAndBoxSizingReliable() {
+ // Support: Firefox, Android 2.3 (Prefixed box-sizing versions).
+ div.style.cssText = "-webkit-box-sizing:border-box;-moz-box-sizing:border-box;" +
+ "box-sizing:border-box;padding:1px;border:1px;display:block;width:4px;margin-top:1%;" +
+ "position:absolute;top:1%";
+ docElem.appendChild(container);
+
+ var divStyle = window.getComputedStyle(div, null);
+ pixelPositionVal = divStyle.top !== "1%";
+ boxSizingReliableVal = divStyle.width === "4px";
+
+ docElem.removeChild(container);
+ }
+
+ // Use window.getComputedStyle because jsdom on node.js will break without it.
+ if ( window.getComputedStyle ) {
+ jQuery.extend(support, {
+ pixelPosition: function () {
+ // This test is executed only once but we still do memoizing
+ // since we can use the boxSizingReliable pre-computing.
+ // No need to check if the test was already performed, though.
+ computePixelPositionAndBoxSizingReliable();
+ return pixelPositionVal;
+ },
+ boxSizingReliable: function () {
+ if ( boxSizingReliableVal == null ) {
+ computePixelPositionAndBoxSizingReliable();
+ }
+ return boxSizingReliableVal;
+ },
+ reliableMarginRight: function () {
+ // Support: Android 2.3
+ // Check if div with explicit width and no margin-right incorrectly
+ // gets computed margin-right based on width of container. (#3333)
+ // WebKit Bug 13343 - getComputedStyle returns wrong value for margin-right
+ // This support function is only executed once so no memoizing is needed.
+ var ret,
+ marginDiv = div.appendChild(document.createElement("div"));
+ marginDiv.style.cssText = div.style.cssText = divReset;
+ marginDiv.style.marginRight = marginDiv.style.width = "0";
+ div.style.width = "1px";
+ docElem.appendChild(container);
+
+ ret = !parseFloat(window.getComputedStyle(marginDiv, null).marginRight);
+
+ docElem.removeChild(container);
+
+ // Clean up the div for other support tests.
+ div.innerHTML = "";
+
+ return ret;
+ }
+ });
+ }
+ })();
+
+
+// A method for quickly swapping in/out CSS properties to get correct calculations.
+ jQuery.swap = function (elem, options, callback, args) {
+ var ret, name,
+ old = {};
+
+ // Remember the old values, and insert the new ones
+ for ( name in options ) {
+ old[ name ] = elem.style[ name ];
+ elem.style[ name ] = options[ name ];
+ }
+
+ ret = callback.apply(elem, args || []);
+
+ // Revert the old values
+ for ( name in options ) {
+ elem.style[ name ] = old[ name ];
+ }
+
+ return ret;
+ };
+
+
+ var
+ // 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]).+)/,
+ rnumsplit = new RegExp("^(" + pnum + ")(.*)$", "i"),
+ rrelNum = new RegExp("^([+-])=(" + pnum + ")", "i"),
+
+ cssShow = { position: "absolute", visibility: "hidden", display: "block" },
+ cssNormalTransform = {
+ letterSpacing: 0,
+ fontWeight: 400
+ },
+
+ cssPrefixes = [ "Webkit", "O", "Moz", "ms" ];
+
+// return a css property mapped to a potentially vendor prefixed property
+ function vendorPropName(style, name) {
+
+ // shortcut for names that are not vendor prefixed
+ if ( name in style ) {
+ return name;
+ }
+
+ // check for vendor prefixed names
+ var capName = name[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 setPositiveNumber(elem, value, subtract) {
+ var matches = rnumsplit.exec(value);
+ return matches ?
+ // Guard against undefined "subtract", e.g., when used as in cssHooks
+ Math.max(0, matches[ 1 ] - ( subtract || 0 )) + ( matches[ 2 ] || "px" ) :
+ value;
+ }
+
+ function augmentWidthOrHeight(elem, name, extra, isBorderBox, styles) {
+ var i = extra === ( isBorderBox ? "border" : "content" ) ?
+ // If we already have the right measurement, avoid augmentation
+ 4 :
+ // Otherwise initialize for horizontal or vertical properties
+ name === "width" ? 1 : 0,
+
+ val = 0;
+
+ for ( ; i < 4; i += 2 ) {
+ // both box models exclude margin, so add it if we want it
+ if ( extra === "margin" ) {
+ val += jQuery.css(elem, extra + cssExpand[ i ], true, styles);
+ }
+
+ if ( isBorderBox ) {
+ // border-box includes padding, so remove it if we want content
+ if ( extra === "content" ) {
+ val -= jQuery.css(elem, "padding" + cssExpand[ i ], true, styles);
+ }
+
+ // at this point, extra isn't border nor margin, so remove border
+ if ( extra !== "margin" ) {
+ val -= jQuery.css(elem, "border" + cssExpand[ i ] + "Width", true, styles);
+ }
+ } else {
+ // at this point, extra isn't content, so add padding
+ val += jQuery.css(elem, "padding" + cssExpand[ i ], true, styles);
+
+ // at this point, extra isn't content nor padding, so add border
+ if ( extra !== "padding" ) {
+ val += jQuery.css(elem, "border" + cssExpand[ i ] + "Width", true, styles);
+ }
+ }
+ }
+
+ return val;
+ }
+
+ function getWidthOrHeight(elem, name, extra) {
+
+ // Start with offset property, which is equivalent to the border-box value
+ var valueIsBorderBox = true,
+ val = name === "width" ? elem.offsetWidth : elem.offsetHeight,
+ styles = getStyles(elem),
+ isBorderBox = jQuery.css(elem, "boxSizing", false, styles) === "border-box";
+
+ // some non-html elements return undefined for offsetWidth, so check for null/undefined
+ // svg - https://bugzilla.mozilla.org/show_bug.cgi?id=649285
+ // MathML - https://bugzilla.mozilla.org/show_bug.cgi?id=491668
+ if ( val <= 0 || val == null ) {
+ // Fall back to computed then uncomputed css if necessary
+ val = curCSS(elem, name, styles);
+ if ( val < 0 || val == null ) {
+ val = elem.style[ name ];
+ }
+
+ // Computed unit is not pixels. Stop here and return.
+ if ( rnumnonpx.test(val) ) {
+ return val;
+ }
+
+ // we need the check for style in case a browser which returns unreliable values
+ // for getComputedStyle silently falls back to the reliable elem.style
+ valueIsBorderBox = isBorderBox &&
+ ( support.boxSizingReliable() || val === elem.style[ name ] );
+
+ // Normalize "", auto, and prepare for extra
+ val = parseFloat(val) || 0;
+ }
+
+ // use the active box-sizing model to add/subtract irrelevant styles
+ return ( val +
+ augmentWidthOrHeight(
+ elem,
+ name,
+ extra || ( isBorderBox ? "border" : "content" ),
+ valueIsBorderBox,
+ styles
+ )
+ ) + "px";
+ }
+
+ function showHide(elements, show) {
+ var display, elem, hidden,
+ values = [],
+ index = 0,
+ length = elements.length;
+
+ for ( ; index < length; index++ ) {
+ elem = elements[ index ];
+ if ( !elem.style ) {
+ continue;
+ }
+
+ values[ index ] = data_priv.get(elem, "olddisplay");
+ display = elem.style.display;
+ if ( show ) {
+ // Reset the inline display of this element to learn if it is
+ // being hidden by cascaded rules or not
+ if ( !values[ index ] && display === "none" ) {
+ elem.style.display = "";
+ }
+
+ // Set elements which have been overridden with display: none
+ // in a stylesheet to whatever the default browser style is
+ // for such an element
+ if ( elem.style.display === "" && isHidden(elem) ) {
+ values[ index ] = data_priv.access(elem, "olddisplay", defaultDisplay(elem.nodeName));
+ }
+ } else {
+
+ if ( !values[ index ] ) {
+ hidden = isHidden(elem);
+
+ if ( display && display !== "none" || !hidden ) {
+ data_priv.set(elem, "olddisplay", hidden ? display : jQuery.css(elem, "display"));
+ }
+ }
+ }
+ }
+
+ // Set the display of most of the elements in a second loop
+ // to avoid the constant reflow
+ for ( index = 0; index < length; index++ ) {
+ elem = elements[ index ];
+ if ( !elem.style ) {
+ continue;
+ }
+ if ( !show || elem.style.display === "none" || elem.style.display === "" ) {
+ elem.style.display = show ? values[ index ] || "" : "none";
+ }
+ }
+
+ return elements;
+ }
+
+ jQuery.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;
+ }
+ }
+ }
+ },
+
+ // Don't automatically add "px" to these possibly-unitless properties
+ cssNumber: {
+ "columnCount": true,
+ "fillOpacity": true,
+ "fontWeight": true,
+ "lineHeight": true,
+ "opacity": true,
+ "order": 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": "cssFloat"
+ },
+
+ // 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 null and NaN values aren't set. See: #7116
+ if ( value == null || value !== value ) {
+ return;
+ }
+
+ // If a number was passed in, add 'px' to the (except for certain CSS properties)
+ if ( type === "number" && !jQuery.cssNumber[ origName ] ) {
+ value += "px";
+ }
+
+ // Fixes #8908, it can be done more correctly by specifying setters in cssHooks,
+ // but it would mean to define eight (for every problematic property) identical functions
+ if ( !support.clearCloneStyle && value === "" && name.indexOf("background") === 0 ) {
+ style[ name ] = "inherit";
+ }
+
+ // If a hook was provided, use that value, otherwise just set the specified value
+ if ( !hooks || !("set" in hooks) || (value = hooks.set(elem, value, extra)) !== undefined ) {
+ // Support: Chrome, Safari
+ // Setting style to blank string required to delete "style: x !important;"
+ style[ name ] = "";
+ style[ name ] = value;
+ }
+
+ } else {
+ // If a hook was provided get the non-computed value from there
+ if ( hooks && "get" in hooks && (ret = hooks.get(elem, false, extra)) !== undefined ) {
+ return ret;
+ }
+
+ // Otherwise just get the value from the style object
+ return style[ name ];
+ }
+ },
+
+ css: function (elem, name, extra, styles) {
+ var 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, styles);
+ }
+
+ //convert "normal" to computed value
+ if ( val === "normal" && name in cssNormalTransform ) {
+ val = cssNormalTransform[ name ];
+ }
+
+ // Return, converting to number if forced or a qualifier was provided and val looks numeric
+ if ( extra === "" || extra ) {
+ num = parseFloat(val);
+ return extra === true || jQuery.isNumeric(num) ? num || 0 : val;
+ }
+ return val;
+ }
+ });
+
+ 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
+ return elem.offsetWidth === 0 && rdisplayswap.test(jQuery.css(elem, "display")) ?
+ jQuery.swap(elem, cssShow, function () {
+ return getWidthOrHeight(elem, name, extra);
+ }) :
+ getWidthOrHeight(elem, name, extra);
+ }
+ },
+
+ set: function (elem, value, extra) {
+ var styles = extra && getStyles(elem);
+ return setPositiveNumber(elem, value, extra ?
+ augmentWidthOrHeight(
+ elem,
+ name,
+ extra,
+ jQuery.css(elem, "boxSizing", false, styles) === "border-box",
+ styles
+ ) : 0
+ );
+ }
+ };
+ });
+
+// Support: Android 2.3
+ jQuery.cssHooks.marginRight = addGetHookIf(support.reliableMarginRight,
+ function (elem, computed) {
+ if ( 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" },
+ curCSS, [ elem, "marginRight" ]);
+ }
+ }
+ );
+
+// 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 = 0,
+ expanded = {},
+
+ // assumes a single number if not a string
+ parts = typeof value === "string" ? value.split(" ") : [ value ];
+
+ for ( ; 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;
+ }
+ });
+
+ jQuery.fn.extend({
+ css: function (name, value) {
+ return access(this, function (elem, name, value) {
+ var styles, len,
+ map = {},
+ i = 0;
+
+ if ( jQuery.isArray(name) ) {
+ styles = getStyles(elem);
+ len = name.length;
+
+ for ( ; i < len; i++ ) {
+ map[ name[ i ] ] = jQuery.css(elem, name[ i ], false, styles);
+ }
+
+ return map;
+ }
+
+ return value !== undefined ?
+ jQuery.style(elem, name, value) :
+ jQuery.css(elem, name);
+ }, name, value, arguments.length > 1);
+ },
+ show: function () {
+ return showHide(this, true);
+ },
+ hide: function () {
+ return showHide(this);
+ },
+ toggle: function (state) {
+ if ( typeof state === "boolean" ) {
+ return state ? this.show() : this.hide();
+ }
+
+ return this.each(function () {
+ if ( isHidden(this) ) {
+ jQuery(this).show();
+ } else {
+ jQuery(this).hide();
+ }
+ });
+ }
+ });
+
+
+ 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 an empty string as a 3rd 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, "");
+ // 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;
+ }
+ }
+ }
+ };
+
+// Support: IE9
+// 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.easing = {
+ linear: function (p) {
+ return p;
+ },
+ swing: function (p) {
+ return 0.5 - Math.cos(p * Math.PI) / 2;
+ }
+ };
+
+ jQuery.fx = Tween.prototype.init;
+
+// Back Compat <1.8 extension point
+ jQuery.fx.step = {};
+
+
+ var
+ fxNow, timerId,
+ rfxtypes = /^(?:toggle|show|hide)$/,
+ rfxnum = new RegExp("^(?:([+-])=|)(" + pnum + ")([a-z%]*)$", "i"),
+ rrun = /queueHooks$/,
+ animationPrefilters = [ defaultPrefilter ],
+ tweeners = {
+ "*": [ function (prop, value) {
+ var tween = this.createTween(prop, value),
+ target = tween.cur(),
+ parts = rfxnum.exec(value),
+ unit = parts && parts[ 3 ] || ( jQuery.cssNumber[ prop ] ? "" : "px" ),
+
+ // Starting value computation is required for potential unit mismatches
+ start = ( jQuery.cssNumber[ prop ] || unit !== "px" && +target ) &&
+ rfxnum.exec(jQuery.css(tween.elem, prop)),
+ scale = 1,
+ maxIterations = 20;
+
+ if ( start && start[ 3 ] !== unit ) {
+ // Trust units reported by jQuery.css
+ unit = unit || start[ 3 ];
+
+ // Make sure we update the tween properties later on
+ parts = parts || [];
+
+ // Iteratively approximate from a nonzero starting point
+ start = +target || 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 );
+ }
+
+ // Update tween properties
+ if ( parts ) {
+ start = tween.start = +start || +target || 0;
+ tween.unit = unit;
+ // If a +=/-= token was provided, we're doing a relative animation
+ tween.end = parts[ 1 ] ?
+ start + ( parts[ 1 ] + 1 ) * parts[ 2 ] :
+ +parts[ 2 ];
+ }
+
+ return tween;
+ } ]
+ };
+
+// Animations created synchronously will run synchronously
+ function createFxNow() {
+ setTimeout(function () {
+ fxNow = undefined;
+ });
+ return ( fxNow = jQuery.now() );
+ }
+
+// Generate parameters to create a standard animation
+ function genFx(type, includeWidth) {
+ var which,
+ i = 0,
+ attrs = { height: type };
+
+ // 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;
+ }
+
+ function createTween(value, prop, animation) {
+ var tween,
+ collection = ( tweeners[ prop ] || [] ).concat(tweeners[ "*" ]),
+ index = 0,
+ length = collection.length;
+ for ( ; index < length; index++ ) {
+ if ( (tween = collection[ index ].call(animation, prop, value)) ) {
+
+ // we're done with this property
+ return tween;
+ }
+ }
+ }
+
+ function defaultPrefilter(elem, props, opts) {
+ /* jshint validthis: true */
+ var prop, value, toggle, tween, hooks, oldfire, display,
+ anim = this,
+ orig = {},
+ style = elem.style,
+ hidden = elem.nodeType && isHidden(elem),
+ dataShow = data_priv.get(elem, "fxshow");
+
+ // 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 IE9-10 do 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
+ display = jQuery.css(elem, "display");
+ // Get default display if display is currently "none"
+ if ( display === "none" ) {
+ display = defaultDisplay(elem.nodeName);
+ }
+ if ( display === "inline" &&
+ jQuery.css(elem, "float") === "none" ) {
+
+ style.display = "inline-block";
+ }
+ }
+
+ if ( opts.overflow ) {
+ style.overflow = "hidden";
+ anim.always(function () {
+ style.overflow = opts.overflow[ 0 ];
+ style.overflowX = opts.overflow[ 1 ];
+ style.overflowY = opts.overflow[ 2 ];
+ });
+ }
+
+ // show/hide pass
+ for ( prop in props ) {
+ value = props[ prop ];
+ if ( rfxtypes.exec(value) ) {
+ delete props[ prop ];
+ toggle = toggle || value === "toggle";
+ if ( value === ( hidden ? "hide" : "show" ) ) {
+
+ // If there is dataShow left over from a stopped hide or show and we are going to proceed with show, we should pretend to be hidden
+ if ( value === "show" && dataShow && dataShow[ prop ] !== undefined ) {
+ hidden = true;
+ } else {
+ continue;
+ }
+ }
+ orig[ prop ] = dataShow && dataShow[ prop ] || jQuery.style(elem, prop);
+ }
+ }
+
+ if ( !jQuery.isEmptyObject(orig) ) {
+ if ( dataShow ) {
+ if ( "hidden" in dataShow ) {
+ hidden = dataShow.hidden;
+ }
+ } else {
+ dataShow = data_priv.access(elem, "fxshow", {});
+ }
+
+ // 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;
+
+ data_priv.remove(elem, "fxshow");
+ for ( prop in orig ) {
+ jQuery.style(elem, prop, orig[ prop ]);
+ }
+ });
+ for ( prop in orig ) {
+ tween = createTween(hidden ? dataShow[ prop ] : 0, prop, anim);
+
+ if ( !( prop in dataShow ) ) {
+ dataShow[ prop ] = tween.start;
+ if ( hidden ) {
+ tween.end = tween.start;
+ tween.start = prop === "width" || prop === "height" ? 1 : 0;
+ }
+ }
+ }
+ }
+ }
+
+ 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;
+ }
+ }
+ }
+
+ function Animation(elem, properties, options) {
+ var result,
+ stopped,
+ index = 0,
+ length = animationPrefilters.length,
+ deferred = jQuery.Deferred().always(function () {
+ // don't match elem in the :animated selector
+ delete tick.elem;
+ }),
+ tick = function () {
+ if ( stopped ) {
+ return false;
+ }
+ 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) {
+ 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;
+ if ( stopped ) {
+ return this;
+ }
+ stopped = true;
+ 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;
+ }
+ }
+
+ jQuery.map(props, createTween, animation);
+
+ if ( jQuery.isFunction(animation.opts.start) ) {
+ animation.opts.start.call(elem, animation);
+ }
+
+ jQuery.fx.timer(
+ jQuery.extend(tick, {
+ elem: elem,
+ anim: animation,
+ queue: animation.opts.queue
+ })
+ );
+
+ // 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);
+ }
+
+ 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);
+ }
+ }
+ });
+
+ 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.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, or finishing resolves immediately
+ if ( empty || data_priv.get(this, "finish") ) {
+ anim.stop(true);
+ }
+ };
+ doAnimation.finish = doAnimation;
+
+ 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 = data_priv.get(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);
+ }
+ });
+ },
+ finish: function (type) {
+ if ( type !== false ) {
+ type = type || "fx";
+ }
+ return this.each(function () {
+ var index,
+ data = data_priv.get(this),
+ queue = data[ type + "queue" ],
+ hooks = data[ type + "queueHooks" ],
+ timers = jQuery.timers,
+ length = queue ? queue.length : 0;
+
+ // enable finishing flag on private data
+ data.finish = true;
+
+ // empty the queue first
+ jQuery.queue(this, type, []);
+
+ if ( hooks && hooks.stop ) {
+ hooks.stop.call(this, true);
+ }
+
+ // look for any active animations, and finish them
+ for ( index = timers.length; index--; ) {
+ if ( timers[ index ].elem === this && timers[ index ].queue === type ) {
+ timers[ index ].anim.stop(true);
+ timers.splice(index, 1);
+ }
+ }
+
+ // look for any animations in the old queue and finish them
+ for ( index = 0; index < length; index++ ) {
+ if ( queue[ index ] && queue[ index ].finish ) {
+ queue[ index ].finish.call(this);
+ }
+ }
+
+ // turn off finishing flag
+ delete data.finish;
+ });
+ }
+ });
+
+ 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" ?
+ cssFn.apply(this, arguments) :
+ this.animate(genFx(name, true), speed, easing, callback);
+ };
+ });
+
+// 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.timers = [];
+ jQuery.fx.tick = function () {
+ var timer,
+ i = 0,
+ timers = jQuery.timers;
+
+ 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) {
+ jQuery.timers.push(timer);
+ if ( timer() ) {
+ jQuery.fx.start();
+ } else {
+ jQuery.timers.pop();
+ }
+ };
+
+ jQuery.fx.interval = 13;
+
+ jQuery.fx.start = function () {
+ if ( !timerId ) {
+ timerId = setInterval(jQuery.fx.tick, jQuery.fx.interval);
+ }
+ };
+
+ jQuery.fx.stop = function () {
+ clearInterval(timerId);
+ timerId = null;
+ };
+
+ jQuery.fx.speeds = {
+ slow: 600,
+ fast: 200,
+ // Default speed
+ _default: 400
+ };
+
+
+// Based off of the plugin by Clint Helfers, with permission.
+// http://blindsignals.com/index.php/2009/07/jquery-delay/
+ jQuery.fn.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);
+ };
+ });
+ };
+
+
+ (function () {
+ var input = document.createElement("input"),
+ select = document.createElement("select"),
+ opt = select.appendChild(document.createElement("option"));
+
+ input.type = "checkbox";
+
+ // Support: iOS 5.1, Android 4.x, Android 2.3
+ // Check the default checkbox/radio value ("" on old WebKit; "on" elsewhere)
+ support.checkOn = input.value !== "";
+
+ // Must access the parent to make an option select properly
+ // Support: IE9, IE10
+ support.optSelected = opt.selected;
+
+ // 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;
+
+ // Check if an input maintains its value after becoming a radio
+ // Support: IE9, IE10
+ input = document.createElement("input");
+ input.value = "t";
+ input.type = "radio";
+ support.radioValue = input.value === "t";
+ })();
+
+
+ var nodeHook, boolHook,
+ attrHandle = jQuery.expr.attrHandle;
+
+ jQuery.fn.extend({
+ attr: function (name, value) {
+ return access(this, jQuery.attr, name, value, arguments.length > 1);
+ },
+
+ removeAttr: function (name) {
+ return this.each(function () {
+ jQuery.removeAttr(this, name);
+ });
+ }
+ });
+
+ jQuery.extend({
+ attr: function (elem, name, value) {
+ var hooks, ret,
+ nType = elem.nodeType;
+
+ // don't get/set attributes on text, comment and attribute nodes
+ if ( !elem || nType === 3 || nType === 8 || nType === 2 ) {
+ return;
+ }
+
+ // Fallback to prop when attributes are not supported
+ if ( typeof elem.getAttribute === strundefined ) {
+ return jQuery.prop(elem, name, value);
+ }
+
+ // All attributes are lowercase
+ // Grab necessary hook if one is defined
+ if ( nType !== 1 || !jQuery.isXMLDoc(elem) ) {
+ name = name.toLowerCase();
+ hooks = jQuery.attrHooks[ name ] ||
+ ( jQuery.expr.match.bool.test(name) ? boolHook : nodeHook );
+ }
+
+ if ( value !== undefined ) {
+
+ if ( value === null ) {
+ jQuery.removeAttr(elem, name);
+
+ } else if ( hooks && "set" in hooks && (ret = hooks.set(elem, value, name)) !== undefined ) {
+ return ret;
+
+ } else {
+ elem.setAttribute(name, value + "");
+ return value;
+ }
+
+ } else if ( hooks && "get" in hooks && (ret = hooks.get(elem, name)) !== null ) {
+ return ret;
+
+ } else {
+ ret = jQuery.find.attr(elem, name);
+
+ // Non-existent attributes return null, we normalize to undefined
+ return ret == null ?
+ undefined :
+ ret;
+ }
+ },
+
+ removeAttr: function (elem, value) {
+ var name, propName,
+ i = 0,
+ attrNames = value && value.match(rnotwhite);
+
+ if ( attrNames && elem.nodeType === 1 ) {
+ while ( (name = attrNames[i++]) ) {
+ propName = jQuery.propFix[ name ] || name;
+
+ // Boolean attributes get special treatment (#10870)
+ if ( jQuery.expr.match.bool.test(name) ) {
+ // Set corresponding property to false
+ elem[ propName ] = false;
+ }
+
+ elem.removeAttribute(name);
+ }
+ }
+ },
+
+ attrHooks: {
+ type: {
+ set: function (elem, value) {
+ if ( !support.radioValue && value === "radio" &&
+ jQuery.nodeName(elem, "input") ) {
+ // Setting the type on a radio button after the value resets the value in IE6-9
+ // Reset value to default in case type is set after value during creation
+ var val = elem.value;
+ elem.setAttribute("type", value);
+ if ( val ) {
+ elem.value = val;
+ }
+ return value;
+ }
+ }
+ }
+ }
+ });
+
+// Hooks for boolean attributes
+ boolHook = {
+ set: function (elem, value, name) {
+ if ( value === false ) {
+ // Remove boolean attributes when set to false
+ jQuery.removeAttr(elem, name);
+ } else {
+ elem.setAttribute(name, name);
+ }
+ return name;
+ }
+ };
+ jQuery.each(jQuery.expr.match.bool.source.match(/\w+/g), function (i, name) {
+ var getter = attrHandle[ name ] || jQuery.find.attr;
+
+ attrHandle[ name ] = function (elem, name, isXML) {
+ var ret, handle;
+ if ( !isXML ) {
+ // Avoid an infinite loop by temporarily removing this function from the getter
+ handle = attrHandle[ name ];
+ attrHandle[ name ] = ret;
+ ret = getter(elem, name, isXML) != null ?
+ name.toLowerCase() :
+ null;
+ attrHandle[ name ] = handle;
+ }
+ return ret;
+ };
+ });
+
+
+ var rfocusable = /^(?:input|select|textarea|button)$/i;
+
+ jQuery.fn.extend({
+ prop: function (name, value) {
+ return access(this, jQuery.prop, name, value, arguments.length > 1);
+ },
+
+ removeProp: function (name) {
+ return this.each(function () {
+ delete this[ jQuery.propFix[ name ] || name ];
+ });
+ }
+ });
+
+ jQuery.extend({
+ propFix: {
+ "for": "htmlFor",
+ "class": "className"
+ },
+
+ 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 ) {
+ return hooks && "set" in hooks && (ret = hooks.set(elem, value, name)) !== undefined ?
+ ret :
+ ( elem[ name ] = value );
+
+ } else {
+ return hooks && "get" in hooks && (ret = hooks.get(elem, name)) !== null ?
+ ret :
+ elem[ name ];
+ }
+ },
+
+ propHooks: {
+ tabIndex: {
+ get: function (elem) {
+ return elem.hasAttribute("tabindex") || rfocusable.test(elem.nodeName) || elem.href ?
+ elem.tabIndex :
+ -1;
+ }
+ }
+ }
+ });
+
+// Support: IE9+
+// Selectedness for an option in an optgroup can be inaccurate
+ if ( !support.optSelected ) {
+ jQuery.propHooks.selected = {
+ get: function (elem) {
+ var parent = elem.parentNode;
+ if ( parent && parent.parentNode ) {
+ parent.parentNode.selectedIndex;
+ }
+ return null;
+ }
+ };
+ }
+
+ jQuery.each([
+ "tabIndex",
+ "readOnly",
+ "maxLength",
+ "cellSpacing",
+ "cellPadding",
+ "rowSpan",
+ "colSpan",
+ "useMap",
+ "frameBorder",
+ "contentEditable"
+ ], function () {
+ jQuery.propFix[ this.toLowerCase() ] = this;
+ });
+
+
+ var rclass = /[\t\r\n\f]/g;
+
+ jQuery.fn.extend({
+ addClass: function (value) {
+ var classes, elem, cur, clazz, j, finalValue,
+ proceed = typeof value === "string" && value,
+ i = 0,
+ len = this.length;
+
+ if ( jQuery.isFunction(value) ) {
+ return this.each(function (j) {
+ jQuery(this).addClass(value.call(this, j, this.className));
+ });
+ }
+
+ if ( proceed ) {
+ // The disjunction here is for better compressibility (see removeClass)
+ classes = ( value || "" ).match(rnotwhite) || [];
+
+ for ( ; i < len; i++ ) {
+ elem = this[ i ];
+ cur = elem.nodeType === 1 && ( elem.className ?
+ ( " " + elem.className + " " ).replace(rclass, " ") :
+ " "
+ );
+
+ if ( cur ) {
+ j = 0;
+ while ( (clazz = classes[j++]) ) {
+ if ( cur.indexOf(" " + clazz + " ") < 0 ) {
+ cur += clazz + " ";
+ }
+ }
+
+ // only assign if different to avoid unneeded rendering.
+ finalValue = jQuery.trim(cur);
+ if ( elem.className !== finalValue ) {
+ elem.className = finalValue;
+ }
+ }
+ }
+ }
+
+ return this;
+ },
+
+ removeClass: function (value) {
+ var classes, elem, cur, clazz, j, finalValue,
+ proceed = arguments.length === 0 || typeof value === "string" && value,
+ i = 0,
+ len = this.length;
+
+ if ( jQuery.isFunction(value) ) {
+ return this.each(function (j) {
+ jQuery(this).removeClass(value.call(this, j, this.className));
+ });
+ }
+ if ( proceed ) {
+ classes = ( value || "" ).match(rnotwhite) || [];
+
+ for ( ; i < len; i++ ) {
+ elem = this[ i ];
+ // This expression is here for better compressibility (see addClass)
+ cur = elem.nodeType === 1 && ( elem.className ?
+ ( " " + elem.className + " " ).replace(rclass, " ") :
+ ""
+ );
+
+ if ( cur ) {
+ j = 0;
+ while ( (clazz = classes[j++]) ) {
+ // Remove *all* instances
+ while ( cur.indexOf(" " + clazz + " ") >= 0 ) {
+ cur = cur.replace(" " + clazz + " ", " ");
+ }
+ }
+
+ // only assign if different to avoid unneeded rendering.
+ finalValue = value ? jQuery.trim(cur) : "";
+ if ( elem.className !== finalValue ) {
+ elem.className = finalValue;
+ }
+ }
+ }
+ }
+
+ return this;
+ },
+
+ toggleClass: function (value, stateVal) {
+ var type = typeof value;
+
+ if ( typeof stateVal === "boolean" && type === "string" ) {
+ return stateVal ? this.addClass(value) : this.removeClass(value);
+ }
+
+ 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),
+ classNames = value.match(rnotwhite) || [];
+
+ while ( (className = classNames[ i++ ]) ) {
+ // check each className given, space separated list
+ if ( self.hasClass(className) ) {
+ self.removeClass(className);
+ } else {
+ self.addClass(className);
+ }
+ }
+
+ // Toggle whole class name
+ } else if ( type === strundefined || type === "boolean" ) {
+ if ( this.className ) {
+ // store className if set
+ data_priv.set(this, "__className__", this.className);
+ }
+
+ // If the element has a class name or if we're passed "false",
+ // then remove the whole classname (if there was one, the above saved it).
+ // Otherwise bring back whatever was previously saved (if anything),
+ // falling back to the empty string if nothing was stored.
+ this.className = this.className || value === false ? "" : data_priv.get(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;
+ }
+ });
+
+
+ var rreturn = /\r/g;
+
+ jQuery.fn.extend({
+ 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;
+
+ if ( this.nodeType !== 1 ) {
+ return;
+ }
+
+ if ( isFunction ) {
+ val = value.call(this, i, jQuery(this).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: {
+ 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 ];
+
+ // IE6-9 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
+ ( 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 optionSet, option,
+ options = elem.options,
+ values = jQuery.makeArray(value),
+ i = options.length;
+
+ while ( i-- ) {
+ option = options[ i ];
+ if ( (option.selected = jQuery.inArray(jQuery(option).val(), values) >= 0) ) {
+ optionSet = true;
+ }
+ }
+
+ // force browsers to behave consistently when non-matching value is set
+ if ( !optionSet ) {
+ elem.selectedIndex = -1;
+ }
+ return values;
+ }
+ }
+ }
+ });
+
+// Radios and checkboxes getter/setter
+ jQuery.each([ "radio", "checkbox" ], function () {
+ jQuery.valHooks[ this ] = {
+ set: function (elem, value) {
+ if ( jQuery.isArray(value) ) {
+ return ( elem.checked = jQuery.inArray(jQuery(elem).val(), value) >= 0 );
+ }
+ }
+ };
+ if ( !support.checkOn ) {
+ jQuery.valHooks[ this ].get = function (elem) {
+ // Support: Webkit
+ // "" is returned instead of "on" if a value isn't specified
+ return elem.getAttribute("value") === null ? "on" : elem.value;
+ };
+ }
+ });
+
+
+// Return jQuery for attributes-only inclusion
+
+
+ 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) {
+ return arguments.length > 0 ?
+ this.on(name, null, data, fn) :
+ this.trigger(name);
+ };
+ });
+
+ jQuery.fn.extend({
+ hover: function (fnOver, fnOut) {
+ return this.mouseenter(fnOver).mouseleave(fnOut || fnOver);
+ },
+
+ bind: function (types, data, fn) {
+ return this.on(types, null, data, fn);
+ },
+ unbind: function (types, fn) {
+ return this.off(types, null, fn);
+ },
+
+ delegate: function (selector, types, data, fn) {
+ return this.on(types, selector, data, fn);
+ },
+ undelegate: function (selector, types, fn) {
+ // ( namespace ) or ( selector, types [, fn] )
+ return arguments.length === 1 ? this.off(selector, "**") : this.off(types, selector || "**", fn);
+ }
+ });
+
+
+ var nonce = jQuery.now();
+
+ var rquery = (/\?/);
+
+
+// Support: Android 2.3
+// Workaround failure to string-cast null input
+ jQuery.parseJSON = function (data) {
+ return JSON.parse(data + "");
+ };
+
+
+// Cross-browser xml parsing
+ jQuery.parseXML = function (data) {
+ var xml, tmp;
+ if ( !data || typeof data !== "string" ) {
+ return null;
+ }
+
+ // Support: IE9
+ try {
+ tmp = new DOMParser();
+ xml = tmp.parseFromString(data, "text/xml");
+ } catch (e) {
+ xml = undefined;
+ }
+
+ if ( !xml || xml.getElementsByTagName("parsererror").length ) {
+ jQuery.error("Invalid XML: " + data);
+ }
+ return xml;
+ };
+
+
+ var
+ // Document location
+ ajaxLocParts,
+ ajaxLocation,
+
+ rhash = /#.*$/,
+ rts = /([?&])_=[^&]*/,
+ rheaders = /^(.*?):[ \t]*([^\r\n]*)$/mg,
+ // #7653, #8125, #8152: local protocol detection
+ rlocalProtocol = /^(?:about|app|app-storage|.+-extension|file|res|widget):$/,
+ rnoContent = /^(?:GET|HEAD)$/,
+ rprotocol = /^\/\//,
+ rurl = /^([\w.+-]+:)(?:\/\/(?:[^\/?#]*@|)([^\/?#:]*)(?::(\d+)|)|)/,
+
+ /* 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 = "*/".concat("*");
+
+// #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,
+ i = 0,
+ dataTypes = dataTypeExpression.toLowerCase().match(rnotwhite) || [];
+
+ if ( jQuery.isFunction(func) ) {
+ // For each dataType in the dataTypeExpression
+ while ( (dataType = dataTypes[i++]) ) {
+ // Prepend if requested
+ if ( dataType[0] === "+" ) {
+ dataType = dataType.slice(1) || "*";
+ (structure[ dataType ] = structure[ dataType ] || []).unshift(func);
+
+ // Otherwise append
+ } else {
+ (structure[ dataType ] = structure[ dataType ] || []).push(func);
+ }
+ }
+ }
+ };
+ }
+
+// Base inspection function for prefilters and transports
+ function inspectPrefiltersOrTransports(structure, options, originalOptions, jqXHR) {
+
+ var inspected = {},
+ seekingTransport = ( structure === transports );
+
+ function inspect(dataType) {
+ var selected;
+ inspected[ dataType ] = true;
+ jQuery.each(structure[ dataType ] || [], function (_, prefilterOrFactory) {
+ var dataTypeOrTransport = prefilterOrFactory(options, originalOptions, jqXHR);
+ if ( typeof dataTypeOrTransport === "string" && !seekingTransport && !inspected[ dataTypeOrTransport ] ) {
+ options.dataTypes.unshift(dataTypeOrTransport);
+ inspect(dataTypeOrTransport);
+ return false;
+ } else if ( seekingTransport ) {
+ return !( selected = dataTypeOrTransport );
+ }
+ });
+ return selected;
+ }
+
+ return inspect(options.dataTypes[ 0 ]) || !inspected[ "*" ] && inspect("*");
+ }
+
+// 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);
+ }
+
+ return target;
+ }
+
+ /* Handles responses to an ajax request:
+ * - 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;
+
+ // 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
+ * Also sets the responseXXX fields on the jqXHR instance
+ */
+ function ajaxConvert(s, response, jqXHR, isSuccess) {
+ var conv2, current, conv, tmp, prev,
+ converters = {},
+ // Work with a copy of dataTypes in case we need to modify it for conversion
+ dataTypes = s.dataTypes.slice();
+
+ // Create converters map with lowercased keys
+ if ( dataTypes[ 1 ] ) {
+ for ( conv in s.converters ) {
+ converters[ conv.toLowerCase() ] = s.converters[ conv ];
+ }
+ }
+
+ current = dataTypes.shift();
+
+ // Convert to each sequential dataType
+ while ( current ) {
+
+ if ( s.responseFields[ current ] ) {
+ jqXHR[ s.responseFields[ current ] ] = response;
+ }
+
+ // Apply the dataFilter if provided
+ if ( !prev && isSuccess && s.dataFilter ) {
+ response = s.dataFilter(response, s.dataType);
+ }
+
+ prev = current;
+ current = dataTypes.shift();
+
+ if ( current ) {
+
+ // There's only work to do if current dataType is non-auto
+ if ( current === "*" ) {
+
+ current = prev;
+
+ // Convert response if prev dataType is non-auto and differs from current
+ } else 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.unshift(tmp[ 1 ]);
+ }
+ 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 };
+ }
+ }
+ }
+ }
+ }
+ }
+
+ return { state: "success", data: response };
+ }
+
+ jQuery.extend({
+
+ // Counter for holding the number of active queries
+ active: 0,
+
+ // Last-Modified header cache for next request
+ lastModified: {},
+ etag: {},
+
+ ajaxSettings: {
+ url: ajaxLocation,
+ type: "GET",
+ isLocal: rlocalProtocol.test(ajaxLocParts[ 1 ]),
+ global: true,
+ processData: true,
+ async: true,
+ contentType: "application/x-www-form-urlencoded; charset=UTF-8",
+ /*
+ timeout: 0,
+ data: null,
+ dataType: null,
+ username: null,
+ password: null,
+ cache: null,
+ throws: false,
+ traditional: false,
+ headers: {},
+ */
+
+ accepts: {
+ "*": allTypes,
+ text: "text/plain",
+ html: "text/html",
+ xml: "application/xml, text/xml",
+ json: "application/json, text/javascript"
+ },
+
+ contents: {
+ xml: /xml/,
+ html: /html/,
+ json: /json/
+ },
+
+ responseFields: {
+ xml: "responseXML",
+ text: "responseText",
+ json: "responseJSON"
+ },
+
+ // Data converters
+ // Keys separate source (or catchall "*") and destination types with a single space
+ converters: {
+
+ // Convert anything to text
+ "* text": 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: {
+ url: true,
+ context: true
+ }
+ },
+
+ // 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) {
+ return settings ?
+
+ // Building a settings object
+ ajaxExtend(ajaxExtend(target, jQuery.ajaxSettings), settings) :
+
+ // Extending ajaxSettings
+ ajaxExtend(jQuery.ajaxSettings, target);
+ },
+
+ 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 transport,
+ // URL without anti-cache param
+ cacheURL,
+ // Response headers
+ responseHeadersString,
+ responseHeaders,
+ // 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 is callbackContext if it is a DOM node or jQuery collection
+ globalEventContext = s.context && ( callbackContext.nodeType || callbackContext.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,
+
+ // 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 == null ? null : match;
+ },
+
+ // Raw string
+ getAllResponseHeaders: function () {
+ return state === 2 ? responseHeadersString : null;
+ },
+
+ // Caches the header
+ setRequestHeader: function (name, value) {
+ var lname = name.toLowerCase();
+ if ( !state ) {
+ name = requestHeadersNames[ lname ] = requestHeadersNames[ lname ] || name;
+ requestHeaders[ name ] = value;
+ }
+ return this;
+ },
+
+ // Overrides response content-type header
+ overrideMimeType: function (type) {
+ if ( !state ) {
+ s.mimeType = type;
+ }
+ return this;
+ },
+
+ // Status-dependent callbacks
+ statusCode: function (map) {
+ var code;
+ if ( map ) {
+ if ( state < 2 ) {
+ for ( code in map ) {
+ // Lazy-add the new callback in a way that preserves old ones
+ statusCode[ code ] = [ statusCode[ code ], map[ code ] ];
+ }
+ } else {
+ // Execute the appropriate callbacks
+ jqXHR.always(map[ jqXHR.status ]);
+ }
+ }
+ return this;
+ },
+
+ // Cancel the request
+ abort: function (statusText) {
+ var finalText = statusText || strAbort;
+ if ( transport ) {
+ transport.abort(finalText);
+ }
+ done(0, finalText);
+ return this;
+ }
+ };
+
+ // Attach deferreds
+ deferred.promise(jqXHR).complete = completeDeferred.add;
+ jqXHR.success = jqXHR.done;
+ jqXHR.error = jqXHR.fail;
+
+ // Remove hash character (#7531: and string promotion)
+ // Add protocol if not provided (prefilters might expect it)
+ // Handle falsy url in the settings object (#10093: consistency with old signature)
+ // We also use the url parameter if available
+ s.url = ( ( url || s.url || ajaxLocation ) + "" ).replace(rhash, "")
+ .replace(rprotocol, ajaxLocParts[ 1 ] + "//");
+
+ // Alias method option to type as per ticket #12004
+ s.type = options.method || options.type || s.method || s.type;
+
+ // Extract dataTypes list
+ s.dataTypes = jQuery.trim(s.dataType || "*").toLowerCase().match(rnotwhite) || [ "" ];
+
+ // 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;
+
+ // Watch for a new set of requests
+ if ( fireGlobals && jQuery.active++ === 0 ) {
+ jQuery.event.trigger("ajaxStart");
+ }
+
+ // Uppercase the type
+ s.type = s.type.toUpperCase();
+
+ // Determine if request has content
+ s.hasContent = !rnoContent.test(s.type);
+
+ // Save the URL in case we're toying with the If-Modified-Since
+ // and/or If-None-Match header later on
+ cacheURL = s.url;
+
+ // More options handling for requests with no content
+ if ( !s.hasContent ) {
+
+ // If data is available, append data to url
+ if ( s.data ) {
+ cacheURL = ( s.url += ( rquery.test(cacheURL) ? "&" : "?" ) + s.data );
+ // #9682: remove data so that it's not used in an eventual retry
+ delete s.data;
+ }
+
+ // Add anti-cache in url if needed
+ if ( s.cache === false ) {
+ s.url = rts.test(cacheURL) ?
+
+ // If there is already a '_' parameter, set its value
+ cacheURL.replace(rts, "$1_=" + nonce++) :
+
+ // Otherwise add one to the end
+ cacheURL + ( rquery.test(cacheURL) ? "&" : "?" ) + "_=" + nonce++;
+ }
+ }
+
+ // Set the If-Modified-Since and/or If-None-Match header, if in ifModified mode.
+ if ( s.ifModified ) {
+ if ( jQuery.lastModified[ cacheURL ] ) {
+ jqXHR.setRequestHeader("If-Modified-Since", jQuery.lastModified[ cacheURL ]);
+ }
+ if ( jQuery.etag[ cacheURL ] ) {
+ jqXHR.setRequestHeader("If-None-Match", jQuery.etag[ cacheURL ]);
+ }
+ }
+
+ // 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 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;
+ }
+ }
+ }
+
+ // Callback for when everything is done
+ 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;
+
+ // Determine if successful
+ isSuccess = status >= 200 && status < 300 || status === 304;
+
+ // Get response data
+ if ( responses ) {
+ response = ajaxHandleResponses(s, jqXHR, responses);
+ }
+
+ // Convert no matter what (that way responseXXX fields are always set)
+ response = ajaxConvert(s, response, jqXHR, isSuccess);
+
+ // If successful, handle type chaining
+ if ( isSuccess ) {
+
+ // 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[ cacheURL ] = modified;
+ }
+ modified = jqXHR.getResponseHeader("etag");
+ if ( modified ) {
+ jQuery.etag[ cacheURL ] = modified;
+ }
+ }
+
+ // if no content
+ if ( status === 204 || s.type === "HEAD" ) {
+ statusText = "nocontent";
+
+ // if not modified
+ } else if ( status === 304 ) {
+ statusText = "notmodified";
+
+ // If we have data, let's convert it
+ } else {
+ statusText = response.state;
+ success = response.data;
+ error = response.error;
+ isSuccess = !error;
+ }
+ } else {
+ // We extract error from statusText
+ // then normalize statusText and status for non-aborts
+ error = statusText;
+ if ( status || !statusText ) {
+ 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(isSuccess ? "ajaxSuccess" : "ajaxError",
+ [ 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");
+ }
+ }
+ }
+
+ return jqXHR;
+ },
+
+ getJSON: function (url, data, callback) {
+ return jQuery.get(url, data, callback, "json");
+ },
+
+ getScript: function (url, callback) {
+ return jQuery.get(url, undefined, callback, "script");
+ }
+ });
+
+ 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({
+ url: url,
+ type: method,
+ dataType: type,
+ data: data,
+ success: callback
+ });
+ };
+ });
+
+// Attach a bunch of functions for handling common AJAX events
+ jQuery.each([ "ajaxStart", "ajaxStop", "ajaxComplete", "ajaxError", "ajaxSuccess", "ajaxSend" ], function (i, type) {
+ jQuery.fn[ type ] = function (fn) {
+ return this.on(type, fn);
+ };
+ });
+
+
+ jQuery._evalUrl = function (url) {
+ return jQuery.ajax({
+ url: url,
+ type: "GET",
+ dataType: "script",
+ async: false,
+ global: false,
+ "throws": true
+ });
+ };
+
+
+ jQuery.fn.extend({
+ wrapAll: function (html) {
+ var wrap;
+
+ 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
+ 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.firstElementChild ) {
+ elem = elem.firstElementChild;
+ }
+
+ 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();
+ }
+ });
+
+
+ jQuery.expr.filters.hidden = function (elem) {
+ // Support: Opera <= 12.12
+ // Opera reports offsetWidths and offsetHeights less than zero on some elements
+ return elem.offsetWidth <= 0 && elem.offsetHeight <= 0;
+ };
+ jQuery.expr.filters.visible = function (elem) {
+ return !jQuery.expr.filters.hidden(elem);
+ };
+
+
+ var r20 = /%20/g,
+ rbracket = /\[\]$/,
+ rCRLF = /\r?\n/g,
+ rsubmitterTypes = /^(?:submit|button|image|reset|file)$/i,
+ rsubmittable = /^(?:input|select|textarea|keygen)/i;
+
+ 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 {
+ // Item is non-scalar (array or object), encode its numeric index.
+ 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);
+ }
+ }
+
+// 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, "+");
+ };
+
+ jQuery.fn.extend({
+ serialize: function () {
+ return jQuery.param(this.serializeArray());
+ },
+ serializeArray: function () {
+ return this.map(function () {
+ // Can add propHook for "elements" to filter or add form elements
+ var elements = jQuery.prop(this, "elements");
+ return elements ? jQuery.makeArray(elements) : this;
+ })
+ .filter(function () {
+ var type = this.type;
+
+ // Use .is( ":disabled" ) so that fieldset[disabled] works
+ return this.name && !jQuery(this).is(":disabled") &&
+ rsubmittable.test(this.nodeName) && !rsubmitterTypes.test(type) &&
+ ( this.checked || !rcheckableType.test(type) );
+ })
+ .map(function (i, elem) {
+ var val = jQuery(this).val();
+
+ return val == null ?
+ null :
+ jQuery.isArray(val) ?
+ jQuery.map(val, function (val) {
+ return { name: elem.name, value: val.replace(rCRLF, "\r\n") };
+ }) :
+ { name: elem.name, value: val.replace(rCRLF, "\r\n") };
+ }).get();
+ }
+ });
+
+
+ jQuery.ajaxSettings.xhr = function () {
+ try {
+ return new XMLHttpRequest();
+ } catch (e) {
+ }
+ };
+
+ var xhrId = 0,
+ xhrCallbacks = {},
+ xhrSuccessStatus = {
+ // file protocol always yields status code 0, assume 200
+ 0: 200,
+ // Support: IE9
+ // #1450: sometimes IE returns 1223 when it should be 204
+ 1223: 204
+ },
+ xhrSupported = jQuery.ajaxSettings.xhr();
+
+// Support: IE9
+// Open requests must be manually aborted on unload (#5280)
+ if ( window.ActiveXObject ) {
+ jQuery(window).on("unload", function () {
+ for ( var key in xhrCallbacks ) {
+ xhrCallbacks[ key ]();
+ }
+ });
+ }
+
+ support.cors = !!xhrSupported && ( "withCredentials" in xhrSupported );
+ support.ajax = xhrSupported = !!xhrSupported;
+
+ jQuery.ajaxTransport(function (options) {
+ var callback;
+
+ // Cross domain only allowed if supported through XMLHttpRequest
+ if ( support.cors || xhrSupported && !options.crossDomain ) {
+ return {
+ send: function (headers, complete) {
+ var i,
+ xhr = options.xhr(),
+ id = ++xhrId;
+
+ xhr.open(options.type, options.url, options.async, options.username, options.password);
+
+ // Apply custom fields if provided
+ if ( options.xhrFields ) {
+ for ( i in options.xhrFields ) {
+ xhr[ i ] = options.xhrFields[ i ];
+ }
+ }
+
+ // Override mime type if needed
+ if ( options.mimeType && xhr.overrideMimeType ) {
+ xhr.overrideMimeType(options.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 ( !options.crossDomain && !headers["X-Requested-With"] ) {
+ headers["X-Requested-With"] = "XMLHttpRequest";
+ }
+
+ // Set headers
+ for ( i in headers ) {
+ xhr.setRequestHeader(i, headers[ i ]);
+ }
+
+ // Callback
+ callback = function (type) {
+ return function () {
+ if ( callback ) {
+ delete xhrCallbacks[ id ];
+ callback = xhr.onload = xhr.onerror = null;
+
+ if ( type === "abort" ) {
+ xhr.abort();
+ } else if ( type === "error" ) {
+ complete(
+ // file: protocol always yields status 0; see #8605, #14207
+ xhr.status,
+ xhr.statusText
+ );
+ } else {
+ complete(
+ xhrSuccessStatus[ xhr.status ] || xhr.status,
+ xhr.statusText,
+ // Support: IE9
+ // Accessing binary-data responseText throws an exception
+ // (#11426)
+ typeof xhr.responseText === "string" ? {
+ text: xhr.responseText
+ } : undefined,
+ xhr.getAllResponseHeaders()
+ );
+ }
+ }
+ };
+ };
+
+ // Listen to events
+ xhr.onload = callback();
+ xhr.onerror = callback("error");
+
+ // Create the abort callback
+ callback = xhrCallbacks[ id ] = callback("abort");
+
+ // Do send the request
+ // This may raise an exception which is actually
+ // handled in jQuery.ajax (so no try/catch here)
+ xhr.send(options.hasContent && options.data || null);
+ },
+
+ abort: function () {
+ if ( callback ) {
+ callback();
+ }
+ }
+ };
+ }
+ });
+
+
+// Install script dataType
+ jQuery.ajaxSetup({
+ accepts: {
+ script: "text/javascript, application/javascript, application/ecmascript, application/x-ecmascript"
+ },
+ contents: {
+ script: /(?:java|ecma)script/
+ },
+ converters: {
+ "text script": function (text) {
+ jQuery.globalEval(text);
+ return text;
+ }
+ }
+ });
+
+// Handle cache's special case and crossDomain
+ jQuery.ajaxPrefilter("script", function (s) {
+ if ( s.cache === undefined ) {
+ s.cache = false;
+ }
+ if ( s.crossDomain ) {
+ s.type = "GET";
+ }
+ });
+
+// Bind script tag hack transport
+ jQuery.ajaxTransport("script", function (s) {
+ // This transport only deals with cross domain requests
+ if ( s.crossDomain ) {
+ var script, callback;
+ return {
+ send: function (_, complete) {
+ script = jQuery("<script>").prop({
+ async: true,
+ charset: s.scriptCharset,
+ src: s.url
+ }).on(
+ "load error",
+ callback = function (evt) {
+ script.remove();
+ callback = null;
+ if ( evt ) {
+ complete(evt.type === "error" ? 404 : 200, evt.type);
+ }
+ }
+ );
+ document.head.appendChild(script[ 0 ]);
+ },
+ abort: function () {
+ if ( callback ) {
+ callback();
+ }
+ }
+ };
+ }
+ });
+
+
+ var oldCallbacks = [],
+ rjsonp = /(=)\?(?=&|$)|\?\?/;
+
+// 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,
+ jsonProp = s.jsonp !== false && ( rjsonp.test(s.url) ?
+ "url" :
+ typeof s.data === "string" && !( s.contentType || "" ).indexOf("application/x-www-form-urlencoded") && rjsonp.test(s.data) && "data"
+ );
+
+ // Handle iff the expected data type is "jsonp" or we have a parameter to set
+ if ( jsonProp || s.dataTypes[ 0 ] === "jsonp" ) {
+
+ // Get callback name, remembering preexisting value associated with it
+ callbackName = s.jsonpCallback = jQuery.isFunction(s.jsonpCallback) ?
+ s.jsonpCallback() :
+ s.jsonpCallback;
+
+ // Insert callback into url or form data
+ if ( jsonProp ) {
+ s[ jsonProp ] = s[ jsonProp ].replace(rjsonp, "$1" + callbackName);
+ } else if ( s.jsonp !== false ) {
+ s.url += ( rquery.test(s.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
+ overwritten = window[ callbackName ];
+ 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";
+ }
+ });
+
+
+// data: string of html
+// context (optional): If specified, the fragment will be created in this context, defaults to document
+// keepScripts (optional): If true, will include scripts passed in the html string
+ jQuery.parseHTML = function (data, context, keepScripts) {
+ if ( !data || typeof data !== "string" ) {
+ return null;
+ }
+ if ( typeof context === "boolean" ) {
+ keepScripts = context;
+ context = false;
+ }
+ context = context || document;
+
+ var parsed = rsingleTag.exec(data),
+ scripts = !keepScripts && [];
+
+ // Single tag
+ if ( parsed ) {
+ return [ context.createElement(parsed[1]) ];
+ }
+
+ parsed = jQuery.buildFragment([ data ], context, scripts);
+
+ if ( scripts && scripts.length ) {
+ jQuery(scripts).remove();
+ }
+
+ return jQuery.merge([], parsed.childNodes);
+ };
+
+
+// Keep a copy of the old load method
+ var _load = jQuery.fn.load;
+
+ /**
+ * Load a url into a page
+ */
+ jQuery.fn.load = function (url, params, callback) {
+ if ( typeof url !== "string" && _load ) {
+ return _load.apply(this, arguments);
+ }
+
+ var selector, type, response,
+ self = this,
+ off = url.indexOf(" ");
+
+ if ( off >= 0 ) {
+ selector = url.slice(off);
+ 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";
+ }
+
+ // If we have elements to modify, make the request
+ if ( self.length > 0 ) {
+ jQuery.ajax({
+ url: url,
+
+ // if "type" variable is undefined, then "GET" method will be used
+ type: type,
+ dataType: "html",
+ data: params
+ }).done(function (responseText) {
+
+ // Save response for use in complete callback
+ response = arguments;
+
+ self.html(selector ?
+
+ // If a selector was specified, locate the right elements in a dummy div
+ // Exclude scripts to avoid IE 'Permission Denied' errors
+ jQuery("<div>").append(jQuery.parseHTML(responseText)).find(selector) :
+
+ // Otherwise use the full result
+ responseText);
+
+ }).complete(callback && function (jqXHR, status) {
+ self.each(callback, response || [ jqXHR.responseText, status, jqXHR ]);
+ });
+ }
+
+ return this;
+ };
+
+
+ jQuery.expr.filters.animated = function (elem) {
+ return jQuery.grep(jQuery.timers, function (fn) {
+ return elem === fn.elem;
+ }).length;
+ };
+
+
+ var docElem = window.document.documentElement;
+
+ /**
+ * Gets a window from an element
+ */
+ function getWindow(elem) {
+ return jQuery.isWindow(elem) ? elem : elem.nodeType === 9 && elem.defaultView;
+ }
+
+ jQuery.offset = {
+ setOffset: function (elem, options, i) {
+ var curPosition, curLeft, curCSSTop, curTop, curOffset, curCSSLeft, calculatePosition,
+ position = jQuery.css(elem, "position"),
+ curElem = jQuery(elem),
+ props = {};
+
+ // Set position first, in-case top/left are set even on static elem
+ if ( position === "static" ) {
+ elem.style.position = "relative";
+ }
+
+ curOffset = curElem.offset();
+ curCSSTop = jQuery.css(elem, "top");
+ curCSSLeft = jQuery.css(elem, "left");
+ calculatePosition = ( position === "absolute" || position === "fixed" ) &&
+ ( curCSSTop + curCSSLeft ).indexOf("auto") > -1;
+
+ // 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({
+ offset: function (options) {
+ if ( arguments.length ) {
+ return options === undefined ?
+ this :
+ this.each(function (i) {
+ jQuery.offset.setOffset(this, options, i);
+ });
+ }
+
+ var docElem, win,
+ elem = this[ 0 ],
+ box = { top: 0, left: 0 },
+ doc = elem && elem.ownerDocument;
+
+ if ( !doc ) {
+ return;
+ }
+
+ 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 !== strundefined ) {
+ box = elem.getBoundingClientRect();
+ }
+ win = getWindow(doc);
+ return {
+ top: box.top + win.pageYOffset - docElem.clientTop,
+ left: box.left + win.pageXOffset - docElem.clientLeft
+ };
+ },
+
+ position: function () {
+ if ( !this[ 0 ] ) {
+ return;
+ }
+
+ var offsetParent, offset,
+ elem = this[ 0 ],
+ parentOffset = { top: 0, left: 0 };
+
+ // Fixed elements are offset from window (parentOffset = {top:0, left: 0}, because it is its only offset parent
+ if ( jQuery.css(elem, "position") === "fixed" ) {
+ // We assume that getBoundingClientRect is available when computed position is fixed
+ offset = elem.getBoundingClientRect();
+
+ } else {
+ // Get *real* offsetParent
+ offsetParent = this.offsetParent();
+
+ // Get correct offsets
+ offset = this.offset();
+ if ( !jQuery.nodeName(offsetParent[ 0 ], "html") ) {
+ parentOffset = offsetParent.offset();
+ }
+
+ // Add offsetParent borders
+ parentOffset.top += jQuery.css(offsetParent[ 0 ], "borderTopWidth", true);
+ parentOffset.left += jQuery.css(offsetParent[ 0 ], "borderLeftWidth", true);
+ }
+
+ // Subtract parent offsets and element margins
+ return {
+ top: offset.top - parentOffset.top - jQuery.css(elem, "marginTop", true),
+ left: offset.left - parentOffset.left - jQuery.css(elem, "marginLeft", true)
+ };
+ },
+
+ offsetParent: function () {
+ return this.map(function () {
+ var offsetParent = this.offsetParent || docElem;
+
+ while ( offsetParent && ( !jQuery.nodeName(offsetParent, "html") && jQuery.css(offsetParent, "position") === "static" ) ) {
+ offsetParent = offsetParent.offsetParent;
+ }
+
+ return offsetParent || docElem;
+ });
+ }
+ });
+
+// Create scrollLeft and scrollTop methods
+ jQuery.each({ scrollLeft: "pageXOffset", scrollTop: "pageYOffset" }, function (method, prop) {
+ var top = "pageYOffset" === prop;
+
+ jQuery.fn[ method ] = function (val) {
+ return access(this, function (elem, method, val) {
+ var win = getWindow(elem);
+
+ if ( val === undefined ) {
+ return win ? win[ prop ] : elem[ method ];
+ }
+
+ if ( win ) {
+ win.scrollTo(
+ !top ? val : window.pageXOffset,
+ top ? val : window.pageYOffset
+ );
+
+ } else {
+ elem[ method ] = val;
+ }
+ }, method, val, arguments.length, null);
+ };
+ });
+
+// Add the top/left cssHooks using jQuery.fn.position
+// 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
+ jQuery.each([ "top", "left" ], function (i, prop) {
+ jQuery.cssHooks[ prop ] = addGetHookIf(support.pixelPosition,
+ function (elem, computed) {
+ if ( computed ) {
+ computed = curCSS(elem, prop);
+ // if curCSS returns percentage, fallback to offset
+ return rnumnonpx.test(computed) ?
+ jQuery(elem).position()[ prop ] + "px" :
+ computed;
+ }
+ }
+ );
+ });
+
+
+// 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 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
+ 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, extra) :
+
+ // Set width or height on the element
+ jQuery.style(elem, type, value, extra);
+ }, type, chainable ? margin : undefined, chainable, null);
+ };
+ });
+ });
+
+
+// The number of elements contained in the matched element set
+ jQuery.fn.size = function () {
+ return this.length;
+ };
+
+ jQuery.fn.andSelf = jQuery.fn.addBack;
+
+
+// Register as a named AMD module, since jQuery can be concatenated with other
+// files that may use define, but not via 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("jquery", [], function () {
+ return jQuery;
+ });
+ }
+
+
+ var
+ // Map over jQuery in case of overwrite
+ _jQuery = window.jQuery,
+
+ // Map over the $ in case of overwrite
+ _$ = window.$;
+
+ jQuery.noConflict = function (deep) {
+ if ( window.$ === jQuery ) {
+ window.$ = _$;
+ }
+
+ if ( deep && window.jQuery === jQuery ) {
+ window.jQuery = _jQuery;
+ }
+
+ return jQuery;
+ };
+
+// Expose jQuery and $ identifiers, even in
+// AMD (#7102#comment:10, https://github.com/jquery/jquery/pull/557)
+// and CommonJS for browser emulators (#13566)
+ if ( typeof noGlobal === strundefined ) {
+ window.jQuery = window.$ = jQuery;
+ }
+
+
+ return jQuery;
+
+}));
\ No newline at end of file
--- /dev/null
+// Underscore.js 1.6.0
+// http://underscorejs.org
+// (c) 2009-2014 Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors
+// Underscore may be freely distributed under the MIT license.
+
+(function() {
+
+ // Baseline setup
+ // --------------
+
+ // Establish the root object, `window` in the browser, or `exports` on the server.
+ var root = this;
+
+ // Save the previous value of the `_` variable.
+ var previousUnderscore = root._;
+
+ // Establish the object that gets returned to break out of a loop iteration.
+ var breaker = {};
+
+ // Save bytes in the minified (but not gzipped) version:
+ var ArrayProto = Array.prototype, ObjProto = Object.prototype, FuncProto = Function.prototype;
+
+ // Create quick reference variables for speed access to core prototypes.
+ var
+ push = ArrayProto.push,
+ slice = ArrayProto.slice,
+ concat = ArrayProto.concat,
+ toString = ObjProto.toString,
+ hasOwnProperty = ObjProto.hasOwnProperty;
+
+ // All **ECMAScript 5** native function implementations that we hope to use
+ // are declared here.
+ var
+ nativeForEach = ArrayProto.forEach,
+ nativeMap = ArrayProto.map,
+ nativeReduce = ArrayProto.reduce,
+ nativeReduceRight = ArrayProto.reduceRight,
+ nativeFilter = ArrayProto.filter,
+ nativeEvery = ArrayProto.every,
+ nativeSome = ArrayProto.some,
+ nativeIndexOf = ArrayProto.indexOf,
+ nativeLastIndexOf = ArrayProto.lastIndexOf,
+ nativeIsArray = Array.isArray,
+ nativeKeys = Object.keys,
+ nativeBind = FuncProto.bind;
+
+ // Create a safe reference to the Underscore object for use below.
+ var _ = function(obj) {
+ if (obj instanceof _) return obj;
+ if (!(this instanceof _)) return new _(obj);
+ this._wrapped = obj;
+ };
+
+ // Export the Underscore object for **Node.js**, with
+ // backwards-compatibility for the old `require()` API. If we're in
+ // the browser, add `_` as a global object via a string identifier,
+ // for Closure Compiler "advanced" mode.
+ if (typeof exports !== 'undefined') {
+ if (typeof module !== 'undefined' && module.exports) {
+ exports = module.exports = _;
+ }
+ exports._ = _;
+ } else {
+ root._ = _;
+ }
+
+ // Current version.
+ _.VERSION = '1.6.0';
+
+ // Collection Functions
+ // --------------------
+
+ // The cornerstone, an `each` implementation, aka `forEach`.
+ // Handles objects with the built-in `forEach`, arrays, and raw objects.
+ // Delegates to **ECMAScript 5**'s native `forEach` if available.
+ var each = _.each = _.forEach = function(obj, iterator, context) {
+ if (obj == null) return obj;
+ if (nativeForEach && obj.forEach === nativeForEach) {
+ obj.forEach(iterator, context);
+ } else if (obj.length === +obj.length) {
+ for (var i = 0, length = obj.length; i < length; i++) {
+ if (iterator.call(context, obj[i], i, obj) === breaker) return;
+ }
+ } else {
+ var keys = _.keys(obj);
+ for (var i = 0, length = keys.length; i < length; i++) {
+ if (iterator.call(context, obj[keys[i]], keys[i], obj) === breaker) return;
+ }
+ }
+ return obj;
+ };
+
+ // Return the results of applying the iterator to each element.
+ // Delegates to **ECMAScript 5**'s native `map` if available.
+ _.map = _.collect = function(obj, iterator, context) {
+ var results = [];
+ if (obj == null) return results;
+ if (nativeMap && obj.map === nativeMap) return obj.map(iterator, context);
+ each(obj, function(value, index, list) {
+ results.push(iterator.call(context, value, index, list));
+ });
+ return results;
+ };
+
+ var reduceError = 'Reduce of empty array with no initial value';
+
+ // **Reduce** builds up a single result from a list of values, aka `inject`,
+ // or `foldl`. Delegates to **ECMAScript 5**'s native `reduce` if available.
+ _.reduce = _.foldl = _.inject = function(obj, iterator, memo, context) {
+ var initial = arguments.length > 2;
+ if (obj == null) obj = [];
+ if (nativeReduce && obj.reduce === nativeReduce) {
+ if (context) iterator = _.bind(iterator, context);
+ return initial ? obj.reduce(iterator, memo) : obj.reduce(iterator);
+ }
+ each(obj, function(value, index, list) {
+ if (!initial) {
+ memo = value;
+ initial = true;
+ } else {
+ memo = iterator.call(context, memo, value, index, list);
+ }
+ });
+ if (!initial) throw new TypeError(reduceError);
+ return memo;
+ };
+
+ // The right-associative version of reduce, also known as `foldr`.
+ // Delegates to **ECMAScript 5**'s native `reduceRight` if available.
+ _.reduceRight = _.foldr = function(obj, iterator, memo, context) {
+ var initial = arguments.length > 2;
+ if (obj == null) obj = [];
+ if (nativeReduceRight && obj.reduceRight === nativeReduceRight) {
+ if (context) iterator = _.bind(iterator, context);
+ return initial ? obj.reduceRight(iterator, memo) : obj.reduceRight(iterator);
+ }
+ var length = obj.length;
+ if (length !== +length) {
+ var keys = _.keys(obj);
+ length = keys.length;
+ }
+ each(obj, function(value, index, list) {
+ index = keys ? keys[--length] : --length;
+ if (!initial) {
+ memo = obj[index];
+ initial = true;
+ } else {
+ memo = iterator.call(context, memo, obj[index], index, list);
+ }
+ });
+ if (!initial) throw new TypeError(reduceError);
+ return memo;
+ };
+
+ // Return the first value which passes a truth test. Aliased as `detect`.
+ _.find = _.detect = function(obj, predicate, context) {
+ var result;
+ any(obj, function(value, index, list) {
+ if (predicate.call(context, value, index, list)) {
+ result = value;
+ return true;
+ }
+ });
+ return result;
+ };
+
+ // Return all the elements that pass a truth test.
+ // Delegates to **ECMAScript 5**'s native `filter` if available.
+ // Aliased as `select`.
+ _.filter = _.select = function(obj, predicate, context) {
+ var results = [];
+ if (obj == null) return results;
+ if (nativeFilter && obj.filter === nativeFilter) return obj.filter(predicate, context);
+ each(obj, function(value, index, list) {
+ if (predicate.call(context, value, index, list)) results.push(value);
+ });
+ return results;
+ };
+
+ // Return all the elements for which a truth test fails.
+ _.reject = function(obj, predicate, context) {
+ return _.filter(obj, _.negate(predicate), context);
+ };
+
+ // Determine whether all of the elements match a truth test.
+ // Delegates to **ECMAScript 5**'s native `every` if available.
+ // Aliased as `all`.
+ _.every = _.all = function(obj, predicate, context) {
+ predicate || (predicate = _.identity);
+ var result = true;
+ if (obj == null) return result;
+ if (nativeEvery && obj.every === nativeEvery) return obj.every(predicate, context);
+ each(obj, function(value, index, list) {
+ if (!(result = result && predicate.call(context, value, index, list))) return breaker;
+ });
+ return !!result;
+ };
+
+ // Determine if at least one element in the object matches a truth test.
+ // Delegates to **ECMAScript 5**'s native `some` if available.
+ // Aliased as `any`.
+ var any = _.some = _.any = function(obj, predicate, context) {
+ predicate || (predicate = _.identity);
+ var result = false;
+ if (obj == null) return result;
+ if (nativeSome && obj.some === nativeSome) return obj.some(predicate, context);
+ each(obj, function(value, index, list) {
+ if (result || (result = predicate.call(context, value, index, list))) return breaker;
+ });
+ return !!result;
+ };
+
+ // Determine if the array or object contains a given value (using `===`).
+ // Aliased as `include`.
+ _.contains = _.include = function(obj, target) {
+ if (obj == null) return false;
+ if (nativeIndexOf && obj.indexOf === nativeIndexOf) return obj.indexOf(target) != -1;
+ return any(obj, function(value) {
+ return value === target;
+ });
+ };
+
+ // Invoke a method (with arguments) on every item in a collection.
+ _.invoke = function(obj, method) {
+ var args = slice.call(arguments, 2);
+ var isFunc = _.isFunction(method);
+ return _.map(obj, function(value) {
+ return (isFunc ? method : value[method]).apply(value, args);
+ });
+ };
+
+ // Convenience version of a common use case of `map`: fetching a property.
+ _.pluck = function(obj, key) {
+ return _.map(obj, _.property(key));
+ };
+
+ // Convenience version of a common use case of `filter`: selecting only objects
+ // containing specific `key:value` pairs.
+ _.where = function(obj, attrs) {
+ return _.filter(obj, _.matches(attrs));
+ };
+
+ // Convenience version of a common use case of `find`: getting the first object
+ // containing specific `key:value` pairs.
+ _.findWhere = function(obj, attrs) {
+ return _.find(obj, _.matches(attrs));
+ };
+
+ // Return the maximum element or (element-based computation).
+ _.max = function(obj, iterator, context) {
+ var result = -Infinity, lastComputed = -Infinity,
+ value, computed;
+ if (!iterator && _.isArray(obj)) {
+ for (var i = 0, length = obj.length; i < length; i++) {
+ value = obj[i];
+ if (value > result) {
+ result = value;
+ }
+ }
+ } else {
+ each(obj, function(value, index, list) {
+ computed = iterator ? iterator.call(context, value, index, list) : value;
+ if (computed > lastComputed) {
+ result = value;
+ lastComputed = computed;
+ }
+ });
+ }
+ return result;
+ };
+
+ // Return the minimum element (or element-based computation).
+ _.min = function(obj, iterator, context) {
+ var result = Infinity, lastComputed = Infinity,
+ value, computed;
+ if (!iterator && _.isArray(obj)) {
+ for (var i = 0, length = obj.length; i < length; i++) {
+ value = obj[i];
+ if (value < result) {
+ result = value;
+ }
+ }
+ } else {
+ each(obj, function(value, index, list) {
+ computed = iterator ? iterator.call(context, value, index, list) : value;
+ if (computed < lastComputed) {
+ result = value;
+ lastComputed = computed;
+ }
+ });
+ }
+ return result;
+ };
+
+ // Shuffle an array, using the modern version of the
+ // [Fisher-Yates shuffle](http://en.wikipedia.org/wiki/Fisher–Yates_shuffle).
+ _.shuffle = function(obj) {
+ var rand;
+ var index = 0;
+ var shuffled = [];
+ each(obj, function(value) {
+ rand = _.random(index++);
+ shuffled[index - 1] = shuffled[rand];
+ shuffled[rand] = value;
+ });
+ return shuffled;
+ };
+
+ // Sample **n** random values from a collection.
+ // If **n** is not specified, returns a single random element.
+ // The internal `guard` argument allows it to work with `map`.
+ _.sample = function(obj, n, guard) {
+ if (n == null || guard) {
+ if (obj.length !== +obj.length) obj = _.values(obj);
+ return obj[_.random(obj.length - 1)];
+ }
+ return _.shuffle(obj).slice(0, Math.max(0, n));
+ };
+
+ // An internal function to generate lookup iterators.
+ var lookupIterator = function(value) {
+ if (value == null) return _.identity;
+ if (_.isFunction(value)) return value;
+ return _.property(value);
+ };
+
+ // Sort the object's values by a criterion produced by an iterator.
+ _.sortBy = function(obj, iterator, context) {
+ iterator = lookupIterator(iterator);
+ return _.pluck(_.map(obj, function(value, index, list) {
+ return {
+ value: value,
+ index: index,
+ criteria: iterator.call(context, value, index, list)
+ };
+ }).sort(function(left, right) {
+ var a = left.criteria;
+ var b = right.criteria;
+ if (a !== b) {
+ if (a > b || a === void 0) return 1;
+ if (a < b || b === void 0) return -1;
+ }
+ return left.index - right.index;
+ }), 'value');
+ };
+
+ // An internal function used for aggregate "group by" operations.
+ var group = function(behavior) {
+ return function(obj, iterator, context) {
+ var result = {};
+ iterator = lookupIterator(iterator);
+ each(obj, function(value, index) {
+ var key = iterator.call(context, value, index, obj);
+ behavior(result, key, value);
+ });
+ return result;
+ };
+ };
+
+ // Groups the object's values by a criterion. Pass either a string attribute
+ // to group by, or a function that returns the criterion.
+ _.groupBy = group(function(result, key, value) {
+ _.has(result, key) ? result[key].push(value) : result[key] = [value];
+ });
+
+ // Indexes the object's values by a criterion, similar to `groupBy`, but for
+ // when you know that your index values will be unique.
+ _.indexBy = group(function(result, key, value) {
+ result[key] = value;
+ });
+
+ // Counts instances of an object that group by a certain criterion. Pass
+ // either a string attribute to count by, or a function that returns the
+ // criterion.
+ _.countBy = group(function(result, key) {
+ _.has(result, key) ? result[key]++ : result[key] = 1;
+ });
+
+ // Use a comparator function to figure out the smallest index at which
+ // an object should be inserted so as to maintain order. Uses binary search.
+ _.sortedIndex = function(array, obj, iterator, context) {
+ iterator = lookupIterator(iterator);
+ var value = iterator.call(context, obj);
+ var low = 0, high = array.length;
+ while (low < high) {
+ var mid = (low + high) >>> 1;
+ iterator.call(context, array[mid]) < value ? low = mid + 1 : high = mid;
+ }
+ return low;
+ };
+
+ // Safely create a real, live array from anything iterable.
+ _.toArray = function(obj) {
+ if (!obj) return [];
+ if (_.isArray(obj)) return slice.call(obj);
+ if (obj.length === +obj.length) return _.map(obj, _.identity);
+ return _.values(obj);
+ };
+
+ // Return the number of elements in an object.
+ _.size = function(obj) {
+ if (obj == null) return 0;
+ return (obj.length === +obj.length) ? obj.length : _.keys(obj).length;
+ };
+
+ // Array Functions
+ // ---------------
+
+ // Get the first element of an array. Passing **n** will return the first N
+ // values in the array. Aliased as `head` and `take`. The **guard** check
+ // allows it to work with `_.map`.
+ _.first = _.head = _.take = function(array, n, guard) {
+ if (array == null) return void 0;
+ if ((n == null) || guard) return array[0];
+ if (n < 0) return [];
+ return slice.call(array, 0, n);
+ };
+
+ // Returns everything but the last entry of the array. Especially useful on
+ // the arguments object. Passing **n** will return all the values in
+ // the array, excluding the last N. The **guard** check allows it to work with
+ // `_.map`.
+ _.initial = function(array, n, guard) {
+ return slice.call(array, 0, array.length - ((n == null) || guard ? 1 : n));
+ };
+
+ // Get the last element of an array. Passing **n** will return the last N
+ // values in the array. The **guard** check allows it to work with `_.map`.
+ _.last = function(array, n, guard) {
+ if (array == null) return void 0;
+ if ((n == null) || guard) return array[array.length - 1];
+ return slice.call(array, Math.max(array.length - n, 0));
+ };
+
+ // Returns everything but the first entry of the array. Aliased as `tail` and `drop`.
+ // Especially useful on the arguments object. Passing an **n** will return
+ // the rest N values in the array. The **guard**
+ // check allows it to work with `_.map`.
+ _.rest = _.tail = _.drop = function(array, n, guard) {
+ return slice.call(array, (n == null) || guard ? 1 : n);
+ };
+
+ // Trim out all falsy values from an array.
+ _.compact = function(array) {
+ return _.filter(array, _.identity);
+ };
+
+ // Internal implementation of a recursive `flatten` function.
+ var flatten = function(input, shallow, strict, output) {
+ if (shallow && _.every(input, _.isArray)) {
+ return concat.apply(output, input);
+ }
+ for (var i = 0, length = input.length; i < length; i++) {
+ var value = input[i];
+ if (!_.isArray(value) && !_.isArguments(value)) {
+ if (!strict) output.push(value);
+ } else if (shallow) {
+ push.apply(output, value);
+ } else {
+ flatten(value, shallow, strict, output);
+ }
+ }
+ return output;
+ };
+
+ // Flatten out an array, either recursively (by default), or just one level.
+ _.flatten = function(array, shallow) {
+ return flatten(array, shallow, false, []);
+ };
+
+ // Return a version of the array that does not contain the specified value(s).
+ _.without = function(array) {
+ return _.difference(array, slice.call(arguments, 1));
+ };
+
+ // Split an array into two arrays: one whose elements all satisfy the given
+ // predicate, and one whose elements all do not satisfy the predicate.
+ _.partition = function(obj, predicate, context) {
+ predicate = lookupIterator(predicate);
+ var pass = [], fail = [];
+ each(obj, function(elem) {
+ (predicate.call(context, elem) ? pass : fail).push(elem);
+ });
+ return [pass, fail];
+ };
+
+ // Produce a duplicate-free version of the array. If the array has already
+ // been sorted, you have the option of using a faster algorithm.
+ // Aliased as `unique`.
+ _.uniq = _.unique = function(array, isSorted, iterator, context) {
+ if (array == null) return [];
+ if (_.isFunction(isSorted)) {
+ context = iterator;
+ iterator = isSorted;
+ isSorted = false;
+ }
+ var result = [];
+ var seen = [];
+ for (var i = 0, length = array.length; i < length; i++) {
+ var value = array[i];
+ if (iterator) value = iterator.call(context, value, i, array);
+ if (isSorted ? (!i || seen !== value) : !_.contains(seen, value)) {
+ if (isSorted) seen = value;
+ else seen.push(value);
+ result.push(array[i]);
+ }
+ }
+ return result;
+ };
+
+ // Produce an array that contains the union: each distinct element from all of
+ // the passed-in arrays.
+ _.union = function() {
+ return _.uniq(flatten(arguments, true, true, []));
+ };
+
+ // Produce an array that contains every item shared between all the
+ // passed-in arrays.
+ _.intersection = function(array) {
+ var rest = slice.call(arguments, 1);
+ return _.filter(_.uniq(array), function(item) {
+ return _.every(rest, function(other) {
+ return _.contains(other, item);
+ });
+ });
+ };
+
+ // Take the difference between one array and a number of other arrays.
+ // Only the elements present in just the first array will remain.
+ _.difference = function(array) {
+ var rest = flatten(slice.call(arguments, 1), true, true, []);
+ return _.filter(array, function(value){ return !_.contains(rest, value); });
+ };
+
+ // Zip together multiple lists into a single array -- elements that share
+ // an index go together.
+ _.zip = function() {
+ var length = _.max(_.pluck(arguments, 'length').concat(0));
+ var results = new Array(length);
+ for (var i = 0; i < length; i++) {
+ results[i] = _.pluck(arguments, '' + i);
+ }
+ return results;
+ };
+
+ // Converts lists into objects. Pass either a single array of `[key, value]`
+ // pairs, or two parallel arrays of the same length -- one of keys, and one of
+ // the corresponding values.
+ _.object = function(list, values) {
+ if (list == null) return {};
+ var result = {};
+ for (var i = 0, length = list.length; i < length; i++) {
+ if (values) {
+ result[list[i]] = values[i];
+ } else {
+ result[list[i][0]] = list[i][1];
+ }
+ }
+ return result;
+ };
+
+ // If the browser doesn't supply us with indexOf (I'm looking at you, **MSIE**),
+ // we need this function. Return the position of the first occurrence of an
+ // item in an array, or -1 if the item is not included in the array.
+ // Delegates to **ECMAScript 5**'s native `indexOf` if available.
+ // If the array is large and already in sort order, pass `true`
+ // for **isSorted** to use binary search.
+ _.indexOf = function(array, item, isSorted) {
+ if (array == null) return -1;
+ var i = 0, length = array.length;
+ if (isSorted) {
+ if (typeof isSorted == 'number') {
+ i = (isSorted < 0 ? Math.max(0, length + isSorted) : isSorted);
+ } else {
+ i = _.sortedIndex(array, item);
+ return array[i] === item ? i : -1;
+ }
+ }
+ if (nativeIndexOf && array.indexOf === nativeIndexOf) return array.indexOf(item, isSorted);
+ for (; i < length; i++) if (array[i] === item) return i;
+ return -1;
+ };
+
+ // Delegates to **ECMAScript 5**'s native `lastIndexOf` if available.
+ _.lastIndexOf = function(array, item, from) {
+ if (array == null) return -1;
+ var hasIndex = from != null;
+ if (nativeLastIndexOf && array.lastIndexOf === nativeLastIndexOf) {
+ return hasIndex ? array.lastIndexOf(item, from) : array.lastIndexOf(item);
+ }
+ var i = (hasIndex ? from : array.length);
+ while (i--) if (array[i] === item) return i;
+ return -1;
+ };
+
+ // Generate an integer Array containing an arithmetic progression. A port of
+ // the native Python `range()` function. See
+ // [the Python documentation](http://docs.python.org/library/functions.html#range).
+ _.range = function(start, stop, step) {
+ if (arguments.length <= 1) {
+ stop = start || 0;
+ start = 0;
+ }
+ step = arguments[2] || 1;
+
+ var length = Math.max(Math.ceil((stop - start) / step), 0);
+ var idx = 0;
+ var range = new Array(length);
+
+ while(idx < length) {
+ range[idx++] = start;
+ start += step;
+ }
+
+ return range;
+ };
+
+ // Function (ahem) Functions
+ // ------------------
+
+ // Reusable constructor function for prototype setting.
+ var ctor = function(){};
+
+ // Create a function bound to a given object (assigning `this`, and arguments,
+ // optionally). Delegates to **ECMAScript 5**'s native `Function.bind` if
+ // available.
+ _.bind = function(func, context) {
+ var args, bound;
+ if (nativeBind && func.bind === nativeBind) return nativeBind.apply(func, slice.call(arguments, 1));
+ if (!_.isFunction(func)) throw new TypeError;
+ args = slice.call(arguments, 2);
+ return bound = function() {
+ if (!(this instanceof bound)) return func.apply(context, args.concat(slice.call(arguments)));
+ ctor.prototype = func.prototype;
+ var self = new ctor;
+ ctor.prototype = null;
+ var result = func.apply(self, args.concat(slice.call(arguments)));
+ if (Object(result) === result) return result;
+ return self;
+ };
+ };
+
+ // Partially apply a function by creating a version that has had some of its
+ // arguments pre-filled, without changing its dynamic `this` context. _ acts
+ // as a placeholder, allowing any combination of arguments to be pre-filled.
+ _.partial = function(func) {
+ var boundArgs = slice.call(arguments, 1);
+ return function() {
+ var position = 0;
+ var args = boundArgs.slice();
+ for (var i = 0, length = args.length; i < length; i++) {
+ if (args[i] === _) args[i] = arguments[position++];
+ }
+ while (position < arguments.length) args.push(arguments[position++]);
+ return func.apply(this, args);
+ };
+ };
+
+ // Bind a number of an object's methods to that object. Remaining arguments
+ // are the method names to be bound. Useful for ensuring that all callbacks
+ // defined on an object belong to it.
+ _.bindAll = function(obj) {
+ var funcs = slice.call(arguments, 1);
+ if (funcs.length === 0) throw new Error('bindAll must be passed function names');
+ each(funcs, function(f) { obj[f] = _.bind(obj[f], obj); });
+ return obj;
+ };
+
+ // Memoize an expensive function by storing its results.
+ _.memoize = function(func, hasher) {
+ var memo = {};
+ hasher || (hasher = _.identity);
+ return function() {
+ var key = hasher.apply(this, arguments);
+ return _.has(memo, key) ? memo[key] : (memo[key] = func.apply(this, arguments));
+ };
+ };
+
+ // Delays a function for the given number of milliseconds, and then calls
+ // it with the arguments supplied.
+ _.delay = function(func, wait) {
+ var args = slice.call(arguments, 2);
+ return setTimeout(function(){ return func.apply(null, args); }, wait);
+ };
+
+ // Defers a function, scheduling it to run after the current call stack has
+ // cleared.
+ _.defer = function(func) {
+ return _.delay.apply(_, [func, 1].concat(slice.call(arguments, 1)));
+ };
+
+ // Returns a function, that, when invoked, will only be triggered at most once
+ // during a given window of time. Normally, the throttled function will run
+ // as much as it can, without ever going more than once per `wait` duration;
+ // but if you'd like to disable the execution on the leading edge, pass
+ // `{leading: false}`. To disable execution on the trailing edge, ditto.
+ _.throttle = function(func, wait, options) {
+ var context, args, result;
+ var timeout = null;
+ var previous = 0;
+ options || (options = {});
+ var later = function() {
+ previous = options.leading === false ? 0 : _.now();
+ timeout = null;
+ result = func.apply(context, args);
+ context = args = null;
+ };
+ return function() {
+ var now = _.now();
+ if (!previous && options.leading === false) previous = now;
+ var remaining = wait - (now - previous);
+ context = this;
+ args = arguments;
+ if (remaining <= 0 || remaining > wait) {
+ clearTimeout(timeout);
+ timeout = null;
+ previous = now;
+ result = func.apply(context, args);
+ context = args = null;
+ } else if (!timeout && options.trailing !== false) {
+ timeout = setTimeout(later, remaining);
+ }
+ return result;
+ };
+ };
+
+ // Returns a function, that, as long as it continues to be invoked, will not
+ // be triggered. The function will be called after it stops being called for
+ // N milliseconds. If `immediate` is passed, trigger the function on the
+ // leading edge, instead of the trailing.
+ _.debounce = function(func, wait, immediate) {
+ var timeout, args, context, timestamp, result;
+
+ var later = function() {
+ var last = _.now() - timestamp;
+
+ if (last < wait && last > 0) {
+ timeout = setTimeout(later, wait - last);
+ } else {
+ timeout = null;
+ if (!immediate) {
+ result = func.apply(context, args);
+ context = args = null;
+ }
+ }
+ };
+
+ return function() {
+ context = this;
+ args = arguments;
+ timestamp = _.now();
+ var callNow = immediate && !timeout;
+ if (!timeout) {
+ timeout = setTimeout(later, wait);
+ }
+ if (callNow) {
+ result = func.apply(context, args);
+ context = args = null;
+ }
+
+ return result;
+ };
+ };
+
+ // Returns a function that will be executed at most one time, no matter how
+ // often you call it. Useful for lazy initialization.
+ _.once = function(func) {
+ var ran = false, memo;
+ return function() {
+ if (ran) return memo;
+ ran = true;
+ memo = func.apply(this, arguments);
+ func = null;
+ return memo;
+ };
+ };
+
+ // Returns the first function passed as an argument to the second,
+ // allowing you to adjust arguments, run code before and after, and
+ // conditionally execute the original function.
+ _.wrap = function(func, wrapper) {
+ return _.partial(wrapper, func);
+ };
+
+ // Returns a negated version of the passed-in predicate.
+ _.negate = function(predicate) {
+ return function() {
+ return !predicate.apply(this, arguments);
+ };
+ };
+
+ // Returns a function that is the composition of a list of functions, each
+ // consuming the return value of the function that follows.
+ _.compose = function() {
+ var funcs = arguments;
+ return function() {
+ var args = arguments;
+ for (var i = funcs.length - 1; i >= 0; i--) {
+ args = [funcs[i].apply(this, args)];
+ }
+ return args[0];
+ };
+ };
+
+ // Returns a function that will only be executed after being called N times.
+ _.after = function(times, func) {
+ return function() {
+ if (--times < 1) {
+ return func.apply(this, arguments);
+ }
+ };
+ };
+
+ // Object Functions
+ // ----------------
+
+ // Retrieve the names of an object's properties.
+ // Delegates to **ECMAScript 5**'s native `Object.keys`
+ _.keys = function(obj) {
+ if (!_.isObject(obj)) return [];
+ if (nativeKeys) return nativeKeys(obj);
+ var keys = [];
+ for (var key in obj) if (_.has(obj, key)) keys.push(key);
+ return keys;
+ };
+
+ // Retrieve the values of an object's properties.
+ _.values = function(obj) {
+ var keys = _.keys(obj);
+ var length = keys.length;
+ var values = new Array(length);
+ for (var i = 0; i < length; i++) {
+ values[i] = obj[keys[i]];
+ }
+ return values;
+ };
+
+ // Convert an object into a list of `[key, value]` pairs.
+ _.pairs = function(obj) {
+ var keys = _.keys(obj);
+ var length = keys.length;
+ var pairs = new Array(length);
+ for (var i = 0; i < length; i++) {
+ pairs[i] = [keys[i], obj[keys[i]]];
+ }
+ return pairs;
+ };
+
+ // Invert the keys and values of an object. The values must be serializable.
+ _.invert = function(obj) {
+ var result = {};
+ var keys = _.keys(obj);
+ for (var i = 0, length = keys.length; i < length; i++) {
+ result[obj[keys[i]]] = keys[i];
+ }
+ return result;
+ };
+
+ // Return a sorted list of the function names available on the object.
+ // Aliased as `methods`
+ _.functions = _.methods = function(obj) {
+ var names = [];
+ for (var key in obj) {
+ if (_.isFunction(obj[key])) names.push(key);
+ }
+ return names.sort();
+ };
+
+ // Extend a given object with all the properties in passed-in object(s).
+ _.extend = function(obj) {
+ each(slice.call(arguments, 1), function(source) {
+ if (source) {
+ for (var prop in source) {
+ obj[prop] = source[prop];
+ }
+ }
+ });
+ return obj;
+ };
+
+ // Return a copy of the object only containing the whitelisted properties.
+ _.pick = function(obj, iterator, context) {
+ var result = {};
+ if (_.isFunction(iterator)) {
+ for (var key in obj) {
+ var value = obj[key];
+ if (iterator.call(context, value, key, obj)) result[key] = value;
+ }
+ } else {
+ var keys = concat.apply(ArrayProto, slice.call(arguments, 1));
+ for (var i = 0, length = keys.length; i < length; i++) {
+ var key = keys[i];
+ if (key in obj) result[key] = obj[key];
+ }
+ }
+ return result;
+ };
+
+ // Return a copy of the object without the blacklisted properties.
+ _.omit = function(obj, iterator, context) {
+ var keys;
+ if (_.isFunction(iterator)) {
+ iterator = _.negate(iterator);
+ } else {
+ keys = concat.apply(ArrayProto, slice.call(arguments, 1));
+ iterator = function(value, key) { return !_.contains(keys, key); };
+ }
+ return _.pick(obj, iterator, context);
+ };
+
+ // Fill in a given object with default properties.
+ _.defaults = function(obj) {
+ each(slice.call(arguments, 1), function(source) {
+ if (source) {
+ for (var prop in source) {
+ if (obj[prop] === void 0) obj[prop] = source[prop];
+ }
+ }
+ });
+ return obj;
+ };
+
+ // Create a (shallow-cloned) duplicate of an object.
+ _.clone = function(obj) {
+ if (!_.isObject(obj)) return obj;
+ return _.isArray(obj) ? obj.slice() : _.extend({}, obj);
+ };
+
+ // Invokes interceptor with the obj, and then returns obj.
+ // The primary purpose of this method is to "tap into" a method chain, in
+ // order to perform operations on intermediate results within the chain.
+ _.tap = function(obj, interceptor) {
+ interceptor(obj);
+ return obj;
+ };
+
+ // Internal recursive comparison function for `isEqual`.
+ var eq = function(a, b, aStack, bStack) {
+ // Identical objects are equal. `0 === -0`, but they aren't identical.
+ // See the [Harmony `egal` proposal](http://wiki.ecmascript.org/doku.php?id=harmony:egal).
+ if (a === b) return a !== 0 || 1 / a == 1 / b;
+ // A strict comparison is necessary because `null == undefined`.
+ if (a == null || b == null) return a === b;
+ // Unwrap any wrapped objects.
+ if (a instanceof _) a = a._wrapped;
+ if (b instanceof _) b = b._wrapped;
+ // Compare `[[Class]]` names.
+ var className = toString.call(a);
+ if (className != toString.call(b)) return false;
+ switch (className) {
+ // Strings, numbers, dates, and booleans are compared by value.
+ case '[object String]':
+ // Primitives and their corresponding object wrappers are equivalent; thus, `"5"` is
+ // equivalent to `new String("5")`.
+ return a == String(b);
+ case '[object Number]':
+ // `NaN`s are equivalent, but non-reflexive. An `egal` comparison is performed for
+ // other numeric values.
+ return a != +a ? b != +b : (a == 0 ? 1 / a == 1 / b : a == +b);
+ case '[object Date]':
+ case '[object Boolean]':
+ // Coerce dates and booleans to numeric primitive values. Dates are compared by their
+ // millisecond representations. Note that invalid dates with millisecond representations
+ // of `NaN` are not equivalent.
+ return +a == +b;
+ // RegExps are compared by their source patterns and flags.
+ case '[object RegExp]':
+ return a.source == b.source &&
+ a.global == b.global &&
+ a.multiline == b.multiline &&
+ a.ignoreCase == b.ignoreCase;
+ }
+ if (typeof a != 'object' || typeof b != 'object') return false;
+ // Assume equality for cyclic structures. The algorithm for detecting cyclic
+ // structures is adapted from ES 5.1 section 15.12.3, abstract operation `JO`.
+ var length = aStack.length;
+ while (length--) {
+ // Linear search. Performance is inversely proportional to the number of
+ // unique nested structures.
+ if (aStack[length] == a) return bStack[length] == b;
+ }
+ // Objects with different constructors are not equivalent, but `Object`s
+ // from different frames are.
+ var aCtor = a.constructor, bCtor = b.constructor;
+ if (aCtor !== bCtor && !(_.isFunction(aCtor) && (aCtor instanceof aCtor) &&
+ _.isFunction(bCtor) && (bCtor instanceof bCtor))
+ && ('constructor' in a && 'constructor' in b)) {
+ return false;
+ }
+ // Add the first object to the stack of traversed objects.
+ aStack.push(a);
+ bStack.push(b);
+ var size = 0, result = true;
+ // Recursively compare objects and arrays.
+ if (className == '[object Array]') {
+ // Compare array lengths to determine if a deep comparison is necessary.
+ size = a.length;
+ result = size == b.length;
+ if (result) {
+ // Deep compare the contents, ignoring non-numeric properties.
+ while (size--) {
+ if (!(result = eq(a[size], b[size], aStack, bStack))) break;
+ }
+ }
+ } else {
+ // Deep compare objects.
+ for (var key in a) {
+ if (_.has(a, key)) {
+ // Count the expected number of properties.
+ size++;
+ // Deep compare each member.
+ if (!(result = _.has(b, key) && eq(a[key], b[key], aStack, bStack))) break;
+ }
+ }
+ // Ensure that both objects contain the same number of properties.
+ if (result) {
+ for (key in b) {
+ if (_.has(b, key) && !(size--)) break;
+ }
+ result = !size;
+ }
+ }
+ // Remove the first object from the stack of traversed objects.
+ aStack.pop();
+ bStack.pop();
+ return result;
+ };
+
+ // Perform a deep comparison to check if two objects are equal.
+ _.isEqual = function(a, b) {
+ return eq(a, b, [], []);
+ };
+
+ // Is a given array, string, or object empty?
+ // An "empty" object has no enumerable own-properties.
+ _.isEmpty = function(obj) {
+ if (obj == null) return true;
+ if (_.isArray(obj) || _.isString(obj)) return obj.length === 0;
+ for (var key in obj) if (_.has(obj, key)) return false;
+ return true;
+ };
+
+ // Is a given value a DOM element?
+ _.isElement = function(obj) {
+ return !!(obj && obj.nodeType === 1);
+ };
+
+ // Is a given value an array?
+ // Delegates to ECMA5's native Array.isArray
+ _.isArray = nativeIsArray || function(obj) {
+ return toString.call(obj) == '[object Array]';
+ };
+
+ // Is a given variable an object?
+ _.isObject = function(obj) {
+ return obj === Object(obj);
+ };
+
+ // Add some isType methods: isArguments, isFunction, isString, isNumber, isDate, isRegExp.
+ each(['Arguments', 'Function', 'String', 'Number', 'Date', 'RegExp'], function(name) {
+ _['is' + name] = function(obj) {
+ return toString.call(obj) == '[object ' + name + ']';
+ };
+ });
+
+ // Define a fallback version of the method in browsers (ahem, IE), where
+ // there isn't any inspectable "Arguments" type.
+ if (!_.isArguments(arguments)) {
+ _.isArguments = function(obj) {
+ return !!(obj && _.has(obj, 'callee'));
+ };
+ }
+
+ // Optimize `isFunction` if appropriate.
+ if (typeof (/./) !== 'function') {
+ _.isFunction = function(obj) {
+ return typeof obj === 'function';
+ };
+ }
+
+ // Is a given object a finite number?
+ _.isFinite = function(obj) {
+ return isFinite(obj) && !isNaN(parseFloat(obj));
+ };
+
+ // Is the given value `NaN`? (NaN is the only number which does not equal itself).
+ _.isNaN = function(obj) {
+ return _.isNumber(obj) && obj != +obj;
+ };
+
+ // Is a given value a boolean?
+ _.isBoolean = function(obj) {
+ return obj === true || obj === false || toString.call(obj) == '[object Boolean]';
+ };
+
+ // Is a given value equal to null?
+ _.isNull = function(obj) {
+ return obj === null;
+ };
+
+ // Is a given variable undefined?
+ _.isUndefined = function(obj) {
+ return obj === void 0;
+ };
+
+ // Shortcut function for checking if an object has a given property directly
+ // on itself (in other words, not on a prototype).
+ _.has = function(obj, key) {
+ return hasOwnProperty.call(obj, key);
+ };
+
+ // Utility Functions
+ // -----------------
+
+ // Run Underscore.js in *noConflict* mode, returning the `_` variable to its
+ // previous owner. Returns a reference to the Underscore object.
+ _.noConflict = function() {
+ root._ = previousUnderscore;
+ return this;
+ };
+
+ // Keep the identity function around for default iterators.
+ _.identity = function(value) {
+ return value;
+ };
+
+ _.constant = function(value) {
+ return function() {
+ return value;
+ };
+ };
+
+ _.noop = function(){};
+
+ _.property = function(key) {
+ return function(obj) {
+ return obj[key];
+ };
+ };
+
+ // Returns a predicate for checking whether an object has a given set of `key:value` pairs.
+ _.matches = function(attrs) {
+ return function(obj) {
+ if (obj === attrs) return true;
+ for (var key in attrs) {
+ if (attrs[key] !== obj[key])
+ return false;
+ }
+ return true;
+ }
+ };
+
+ // Run a function **n** times.
+ _.times = function(n, iterator, context) {
+ var accum = Array(Math.max(0, n));
+ for (var i = 0; i < n; i++) accum[i] = iterator.call(context, i);
+ return accum;
+ };
+
+ // Return a random integer between min and max (inclusive).
+ _.random = function(min, max) {
+ if (max == null) {
+ max = min;
+ min = 0;
+ }
+ return min + Math.floor(Math.random() * (max - min + 1));
+ };
+
+ // A (possibly faster) way to get the current timestamp as an integer.
+ _.now = Date.now || function() { return new Date().getTime(); };
+
+ // List of HTML entities for escaping.
+ var entityMap = {
+ escape: {
+ '&': '&',
+ '<': '<',
+ '>': '>',
+ '"': '"',
+ "'": '''
+ }
+ };
+ entityMap.unescape = _.invert(entityMap.escape);
+
+ // Regexes containing the keys and values listed immediately above.
+ var entityRegexes = {
+ escape: new RegExp('[' + _.keys(entityMap.escape).join('') + ']', 'g'),
+ unescape: new RegExp('(' + _.keys(entityMap.unescape).join('|') + ')', 'g')
+ };
+
+ // Functions for escaping and unescaping strings to/from HTML interpolation.
+ _.each(['escape', 'unescape'], function(method) {
+ _[method] = function(string) {
+ if (string == null) return '';
+ return ('' + string).replace(entityRegexes[method], function(match) {
+ return entityMap[method][match];
+ });
+ };
+ });
+
+ // If the value of the named `property` is a function then invoke it with the
+ // `object` as context; otherwise, return it.
+ _.result = function(object, property) {
+ if (object == null) return void 0;
+ var value = object[property];
+ return _.isFunction(value) ? value.call(object) : value;
+ };
+
+ // Add your own custom functions to the Underscore object.
+ _.mixin = function(obj) {
+ each(_.functions(obj), function(name) {
+ var func = _[name] = obj[name];
+ _.prototype[name] = function() {
+ var args = [this._wrapped];
+ push.apply(args, arguments);
+ return result.call(this, func.apply(_, args));
+ };
+ });
+ };
+
+ // Generate a unique integer id (unique within the entire client session).
+ // Useful for temporary DOM ids.
+ var idCounter = 0;
+ _.uniqueId = function(prefix) {
+ var id = ++idCounter + '';
+ return prefix ? prefix + id : id;
+ };
+
+ // By default, Underscore uses ERB-style template delimiters, change the
+ // following template settings to use alternative delimiters.
+ _.templateSettings = {
+ evaluate : /<%([\s\S]+?)%>/g,
+ interpolate : /<%=([\s\S]+?)%>/g,
+ escape : /<%-([\s\S]+?)%>/g
+ };
+
+ // When customizing `templateSettings`, if you don't want to define an
+ // interpolation, evaluation or escaping regex, we need one that is
+ // guaranteed not to match.
+ var noMatch = /(.)^/;
+
+ // Certain characters need to be escaped so that they can be put into a
+ // string literal.
+ var escapes = {
+ "'": "'",
+ '\\': '\\',
+ '\r': 'r',
+ '\n': 'n',
+ '\t': 't',
+ '\u2028': 'u2028',
+ '\u2029': 'u2029'
+ };
+
+ var escaper = /\\|'|\r|\n|\t|\u2028|\u2029/g;
+
+ // JavaScript micro-templating, similar to John Resig's implementation.
+ // Underscore templating handles arbitrary delimiters, preserves whitespace,
+ // and correctly escapes quotes within interpolated code.
+ _.template = function(text, data, settings) {
+ var render;
+ settings = _.defaults({}, settings, _.templateSettings);
+
+ // Combine delimiters into one regular expression via alternation.
+ var matcher = new RegExp([
+ (settings.escape || noMatch).source,
+ (settings.interpolate || noMatch).source,
+ (settings.evaluate || noMatch).source
+ ].join('|') + '|$', 'g');
+
+ // Compile the template source, escaping string literals appropriately.
+ var index = 0;
+ var source = "__p+='";
+ text.replace(matcher, function(match, escape, interpolate, evaluate, offset) {
+ source += text.slice(index, offset)
+ .replace(escaper, function(match) { return '\\' + escapes[match]; });
+
+ if (escape) {
+ source += "'+\n((__t=(" + escape + "))==null?'':_.escape(__t))+\n'";
+ }
+ if (interpolate) {
+ source += "'+\n((__t=(" + interpolate + "))==null?'':__t)+\n'";
+ }
+ if (evaluate) {
+ source += "';\n" + evaluate + "\n__p+='";
+ }
+ index = offset + match.length;
+ return match;
+ });
+ source += "';\n";
+
+ // If a variable is not specified, place data values in local scope.
+ if (!settings.variable) source = 'with(obj||{}){\n' + source + '}\n';
+
+ source = "var __t,__p='',__j=Array.prototype.join," +
+ "print=function(){__p+=__j.call(arguments,'');};\n" +
+ source + "return __p;\n";
+
+ try {
+ render = new Function(settings.variable || 'obj', '_', source);
+ } catch (e) {
+ e.source = source;
+ throw e;
+ }
+
+ if (data) return render(data, _);
+ var template = function(data) {
+ return render.call(this, data, _);
+ };
+
+ // Provide the compiled function source as a convenience for precompilation.
+ template.source = 'function(' + (settings.variable || 'obj') + '){\n' + source + '}';
+
+ return template;
+ };
+
+ // Add a "chain" function, which will delegate to the wrapper.
+ _.chain = function(obj) {
+ return _(obj).chain();
+ };
+
+ // OOP
+ // ---------------
+ // If Underscore is called as a function, it returns a wrapped object that
+ // can be used OO-style. This wrapper holds altered versions of all the
+ // underscore functions. Wrapped objects may be chained.
+
+ // Helper function to continue chaining intermediate results.
+ var result = function(obj) {
+ return this._chain ? _(obj).chain() : obj;
+ };
+
+ // Add all of the Underscore functions to the wrapper object.
+ _.mixin(_);
+
+ // Add all mutator Array functions to the wrapper.
+ each(['pop', 'push', 'reverse', 'shift', 'sort', 'splice', 'unshift'], function(name) {
+ var method = ArrayProto[name];
+ _.prototype[name] = function() {
+ var obj = this._wrapped;
+ method.apply(obj, arguments);
+ if ((name == 'shift' || name == 'splice') && obj.length === 0) delete obj[0];
+ return result.call(this, obj);
+ };
+ });
+
+ // Add all accessor Array functions to the wrapper.
+ each(['concat', 'join', 'slice'], function(name) {
+ var method = ArrayProto[name];
+ _.prototype[name] = function() {
+ return result.call(this, method.apply(this._wrapped, arguments));
+ };
+ });
+
+ _.extend(_.prototype, {
+
+ // Start chaining a wrapped Underscore object.
+ chain: function() {
+ this._chain = true;
+ return this;
+ },
+
+ // Extracts the result from a wrapped and chained object.
+ value: function() {
+ return this._wrapped;
+ }
+
+ });
+
+ // AMD registration happens at the end for compatibility with AMD loaders
+ // that may not enforce next-turn semantics on modules. Even though general
+ // practice for AMD registration is to be anonymous, underscore registers
+ // as a named module because, like jQuery, it is a base library that is
+ // popular enough to be bundled in a third party lib, but not be part of
+ // an AMD load request. Those cases could generate an error when an
+ // anonymous define() is called outside of a loader request.
+ if (typeof define === 'function' && define.amd) {
+ define('underscore', [], function() {
+ return _;
+ });
+ }
+}).call(this);
\ No newline at end of file
--- /dev/null
+define(['modules/panel.inputs', 'helper.history'], function(panelInputs, history) {
+
+ getBlockByID = function(id) {
+
+ var id = id.toString().replace('block-', '');
+
+ return $i('.block[data-id="' + id + '"]');
+
+ }
+
+
+ getBlock = function(element) {
+ //If invalid selector, do not go any further
+ if ( $(element).length === 0 )
+ return $();
+
+ //Find the actual block node
+ if ( $(element).hasClass('block') ) {
+ block = $(element);
+ } else if ( $(element).parents('.block').length === 1 ) {
+ block = $(element).parents('.block');
+ } else {
+ block = false;
+ }
+
+ return block;
+ }
+
+
+ getBlockID = function(element) {
+
+ var block = getBlock(element);
+
+ if ( !block ) {
+ return false;
+ }
+
+ //Pull out ID
+ return block.data('id');
+
+ }
+
+
+ getBlockWrapper = function(element) {
+
+ var block = getBlock(element);
+
+ return block.closest('.wrapper');
+
+ }
+
+
+ getBlockType = function(element) {
+
+ var block = getBlock(element);
+
+ if ( !block ) {
+ return false;
+ }
+
+ return block.data('type');
+ }
+
+
+ getBlockTypeNice = function(type) {
+
+ if ( typeof type != 'string' ) {
+ return false;
+ }
+
+ return getBlockTypeObject(type).name;
+
+ }
+
+
+ getBlockTypeIcon = function(blockType, blockInfo) {
+
+ if ( typeof blockInfo == 'undefined' )
+ blockInfo = false;
+
+ if ( typeof Headway.allBlockTypes[blockType] != 'object' )
+ return null;
+
+ if ( blockInfo === true )
+ return Headway.blockTypeURLs[blockType] + '/icon-white.png';
+
+ return Headway.blockTypeURLs[blockType] + '/icon.png';
+
+ }
+
+
+ getBlockTypeObject = function(blockType) {
+
+ var blockTypes = Headway.allBlockTypes;
+
+ if ( typeof blockTypes[blockType] === 'undefined' )
+ return {'fixed-height': false};
+
+ return blockTypes[blockType];
+
+ }
+
+
+ getBlockGridWidth = function(element) {
+
+ var block = getBlock(element);
+
+ if ( !block ) {
+ return false;
+ }
+
+ return block.attr('data-width');
+
+ }
+
+
+ setBlockGridWidth = function(element, gridWidth) {
+
+ var block = getBlock(element);
+
+ if ( !block ) {
+ return false;
+ }
+
+ var previousGridWidth = block.attr('data-width');
+
+ /* Remove previous grid width */
+ if ( previousGridWidth )
+ block.removeClass('grid-width-' + previousGridWidth);
+
+ /* Set new grid width */
+ block.css('width', '');
+ block.addClass('grid-width-' + gridWidth);
+
+ block.attr('data-width', String(gridWidth).replace('grid-width-', ''));
+
+ return block;
+
+ }
+
+
+ getBlockGridLeft = function(element) {
+
+ var block = getBlock(element);
+
+ if ( !block ) {
+ return false;
+ }
+
+ return block.attr('data-grid-left');
+
+ }
+
+
+ setBlockGridLeft = function(element, gridLeft) {
+
+ var block = getBlock(element);
+
+ if ( !block ) {
+ return false;
+ }
+
+ var previousGridLeft = getBlockGridLeft(block);
+
+ /* Remove previous grid left */
+ if ( previousGridLeft )
+ block.removeClass('grid-left-' + previousGridLeft);
+
+ /* Set new grid left */
+ block.addClass('grid-left-' + gridLeft);
+ block.attr('data-grid-left', String(gridLeft).replace('grid-left-', ''));
+
+ return block;
+
+ }
+
+
+ getBlockDimensions = function(element) {
+
+ var block = getBlock(element);
+
+ if ( !block ) {
+ return false;
+ }
+
+ return {
+ width: getBlockGridWidth(block),
+ height: block.attr('data-height')
+ }
+
+ }
+
+
+ getBlockDimensionsPixels = function(element) {
+
+ var block = getBlock(element);
+
+ if ( !block ) {
+ return false;
+ }
+
+ return {
+ width: block.width(),
+ height: block.height()
+ }
+
+ }
+
+
+ getBlockPosition = function(element) {
+
+ var block = getBlock(element);
+
+ if ( !block ) {
+ return false;
+ }
+
+ return {
+ left: getBlockGridLeft(block),
+ top: block.attr('data-grid-top')
+ }
+
+ }
+
+
+ getBlockPositionPixels = function(element) {
+
+ var block = getBlock(element);
+
+ if ( !block ) {
+ return false;
+ }
+
+ return {
+ left: block.position().left,
+ top: block.position().top
+ }
+
+ }
+
+
+ isBlockMirrored = function(element) {
+
+ var block = getBlock(element);
+
+ return block.hasClass('block-mirrored');
+
+ }
+
+
+ getBlockMirrorOrigin = function(element) {
+
+ var block = getBlock(element);
+
+ if ( !isBlockMirrored(block) )
+ return false;
+
+ return block.data('block-mirror');
+
+ }
+
+
+ getBlockMirrorLayoutName = function(element) {
+
+ var block = getBlock(element);
+
+ if ( !isBlockMirrored(block) )
+ return false;
+
+ return block.data('block-mirror-layout-name');
+
+ }
+
+
+ updateBlockContentCover = function(block) {
+
+ if ( Headway.mode != 'grid' )
+ return false;
+
+ /* Delete previous block content cover if it exists. */
+ block.children('.block-content-cover').remove();
+
+ var blockType = getBlockType(block);
+ var blockTypeNice = getBlockTypeNice(blockType);
+ var blockID = '';
+
+ if ( block.data('temp-id') )
+ blockID = ' <span>Unsaved</span>';
+
+ if ( !blockTypeNice )
+ blockTypeNice = 'Select Block Type';
+
+ if ( block.data('alias') )
+ blockTypeNice = block.data('alias') + ' - ' + blockTypeNice;
+
+ /* If grid mode then add a layer that makes sure the dragging still works as expected */
+ block.append('\
+ <div class="block-content-cover">\
+ <svg xmlns="http://www.w3.org/2000/svg" version="1.1">\
+ <line class="x-line" x1="0" y1="0" x2="100%" y2="100%" />\
+ <line class="x-line" x1="0" y1="100%" x2="100%" y2="0" />\
+ </svg>\
+ \
+ <span class="block-type-and-id">' + blockTypeNice + blockID + '</span>\
+ </div>\
+ ');
+
+ return block.find('div.block-content-cover');
+
+ }
+
+
+ loadBlockContent = function(args) {
+
+ var settings = {};
+
+ var defaults = {
+ blockElement: false,
+ blockSettings: {},
+ blockOrigin: false,
+ blockDefault: false,
+ callback: function(args){},
+ callbackArgs: null
+ };
+
+ $.extend(settings, defaults, args);
+
+ var blockContent = settings.blockElement.find('div.block-content');
+ var blockType = getBlockType(settings.blockElement);
+
+ if ( Headway.gridSafeMode == 1 )
+ return blockContent.html('<div class="alert alert-red block-safe-mode"><p>Grid Safe mode enabled. Block content not outputted.</p></div>');
+
+ if ( Headway.mode == 'grid' && !getBlockTypeObject(blockType)['show-content-in-grid'] ) {
+
+ if ( typeof settings.callback == 'function' )
+ settings.callback(settings.callbackArgs);
+
+ return blockContent.html('');
+
+ }
+
+ createCog(blockContent, true, true, Headway.iframe.contents(), 1);
+
+ return $.ajax({
+ url: Headway.ajaxURL,
+ cache: false,
+ type: 'POST',
+ dataType: 'text',
+ data: {
+ security: Headway.security,
+ action: 'headway_visual_editor',
+ method: 'load_block_content',
+ unsaved_block_settings: settings.blockSettings,
+ block_origin: settings.blockOrigin,
+ block_default: settings.blockDefault,
+ layout: Headway.currentLayout,
+ mode: Headway.mode
+ }
+ }).done(function(data) {
+
+ if ( typeof settings.callback == 'function' )
+ settings.callback(settings.callbackArgs);
+
+ /* Remove script tags from Grid mode */
+ if ( Headway.mode == 'grid' ) {
+
+ var data = data.replace(/script/g, 'SCRIPTTOCHECK');
+
+ var content = $($.parseHTML(data));
+
+ content.find('SCRIPTTOCHECK').remove();
+
+ } else {
+
+ var content = $(data);
+
+ }
+ /* End removing script tags from grid mode */
+
+ if ( typeof window.frames['content'].jQuery != 'undefined' && window.frames['content'].jQuery('#block-' + getBlockID(settings.blockElement)).html(content).length ) {
+
+ if ( Headway.mode == 'design' )
+ refreshInspector();
+
+ return window.frames['content'].jQuery('#block-' + getBlockID(settings.blockElement));
+
+ }
+
+ /* Re-initiate inspector to make sure the block elements are still editable */
+ blockContent.html(content);
+
+ if ( Headway.mode == 'design' )
+ refreshInspector();
+
+ return blockContent;
+
+ });
+
+ }
+
+
+ refreshBlockContent = function(blockID, callback, args, throttled) {
+
+ if ( typeof blockID == 'undefined' || !blockID )
+ return false;
+
+ if ( typeof throttled == 'undefined' )
+ var throttled = true;
+
+ /* Setup throttledFunction */
+ var throttledFunction = function() {
+
+ var blockElement = $i('.block[data-id="' + blockID + '"]');
+ var newBlockSettings = GLOBALunsavedValues['blocks'][blockID]['settings'];
+
+ /* Update the block content */
+ loadBlockContent({
+ blockElement: blockElement,
+ blockSettings: {
+ settings: newBlockSettings,
+ dimensions: getBlockDimensions(blockElement),
+ position: getBlockPosition(blockElement)
+ },
+ blockOrigin: blockID,
+ blockDefault: {
+ type: getBlockType(blockElement),
+ id: 0,
+ layout: Headway.currentLayout
+ },
+ callback: callback,
+ callbackArgs: args
+ });
+
+ }
+
+ if ( !throttled ) {
+ return throttledFunction();
+ }
+
+ /* Flood Control */
+ if ( typeof updateBlockContentFloodTimeoutAfter != 'undefined' )
+ clearTimeout(updateBlockContentFloodTimeoutAfter);
+
+ if ( typeof updateBlockContentFloodTimeout == 'undefined' ) {
+
+ throttledFunction.call();
+
+ updateBlockContentFloodTimeout = setTimeout(function() {
+
+ delete updateBlockContentFloodTimeout;
+
+ }, 500);
+
+ } else {
+
+ updateBlockContentFloodTimeoutAfter = setTimeout(function() {
+
+ throttledFunction.call();
+
+ delete updateBlockContentFloodTimeoutAfter;
+
+ }, 600);
+
+ }
+
+ }
+
+
+ setupBlockContextMenu = function(showDelete) {
+
+ if ( typeof showDelete == 'undefined' )
+ var showDelete = true;
+
+ setupContextMenu({
+ id: 'block',
+ elements: '.block:visible',
+ title: function(event) {
+
+ var block = getBlock(event.currentTarget);
+
+ var blockID = getBlockID(block);
+ var blockType = getBlockType(block);
+ var blockTypeNice = blockType ? getBlockTypeNice(blockType) + ' ' : '';
+
+ var blockTypeIconURL = getBlockTypeIcon(blockType, true);
+ var blockTypeIconStyle = blockTypeIconURL ? ' style="background-image:url(' + blockTypeIconURL + ');"' : null;
+
+ return '<span class="type type-' + blockType + '" ' + blockTypeIconStyle + '></span>' + blockTypeNice + 'Block';
+
+ },
+ contentsCallback: function(event) {
+
+ var contextMenu = $(this);
+
+ var block = getBlock(event.currentTarget);
+
+ var blockID = getBlockID(block);
+ var blockType = getBlockType(block);
+ var blockTypeNice = getBlockTypeNice(blockType);
+
+ var contextMenuClickEvent = !Headway.touch ? 'click' : 'tap';
+
+ /* Block options */
+ $('<li class="context-menu-block-options"><span>Open Block Options</span></li>').appendTo(contextMenu).on(contextMenuClickEvent, function() {
+ openBlockOptions(block);
+ });
+
+ /* Switch block type */
+ $('<li class="context-menu-block-switch-type"><span>Switch Block Type</span></li>').appendTo(contextMenu).on(contextMenuClickEvent, function() {
+ openBlockTypeSelector(block);
+ });
+
+ /* Set Block Alias */
+ $('<li class="context-menu-set-alias"><span>Set Block Alias</span></li>').appendTo(contextMenu).on(contextMenuClickEvent, function() {
+
+ var blockAlias = prompt('Please enter the desired block alias.', block.data('alias'));
+
+ if ( !blockAlias )
+ return;
+
+ dataSetBlockOption(getBlockID(block), 'alias', blockAlias);
+ block.data('alias', blockAlias)
+ updateBlockContentCover(block);
+
+ });
+
+ /* Unmirror Block */
+ if ( isBlockMirrored(block) ) {
+
+ $('<li class="context-menu-block-unmirror"><span>Unmirror Block</span></li>').appendTo(contextMenu).on(contextMenuClickEvent, function() {
+ if ( !confirm("Are you sure you want to unmirror this block?\n\nIt will no longer copy the options and styling from the block it is currently mirroring.") )
+ return;
+
+ updateBlockMirrorStatus(false, block, '');
+ dataSetBlockOption(getBlockID(block), 'mirror-block', '');
+ reloadBlockOptions(getBlockID(block));
+
+ });
+
+ }
+
+ /* Delete block */
+ if ( showDelete ) {
+
+ $('<li class="context-menu-block-delete"><span>Delete Block</span></li>').appendTo(contextMenu).on(contextMenuClickEvent, function(event) {
+
+ if ( !confirm('Are you sure you want to delete this block?') )
+ return false;
+
+ deleteBlock(block);
+
+ });
+
+ }
+
+ }
+ });
+
+ }
+
+
+ bindBlockDimensionsTooltip = function() {
+
+ if ( Headway.touch )
+ return false;
+
+ $i('body').delegate('.block', 'mouseenter', function(event) {
+
+ var self = this;
+ var firstSetup = typeof $(this).data('qtip') == 'undefined' ? true : false;
+
+ if ( typeof Headway.disableBlockDimensions !== 'undefined' && Headway.disableBlockDimensions )
+ return false;
+
+ if ( firstSetup ) {
+
+ addBlockDimensionsTooltip($(this));
+
+ $(this).data('hoverWaitTimeout', setTimeout(function() {
+
+ $(self).qtip('reposition');
+ $(self).qtip('show');
+
+ if ( typeof $(self).data('qtip') != 'undefined' )
+ $i('#qtip-' + $(self).data('qtip').id).show();
+
+ }, 300));
+
+ }
+
+ });
+
+ $i('body').delegate('.block', 'mouseleave', function(event) {
+
+ clearTimeout($(this).data('hoverWaitTimeout'));
+
+ });
+
+ }
+
+
+ addBlockDimensionsTooltip = function(block) {
+
+ if ( Headway.touch )
+ return false;
+
+ $(block).qtip({
+ style: {
+ classes: 'qtip-headway qtip-block-dimensions'
+ },
+ position: {
+ my: 'top center',
+ at: 'bottom center',
+ container: Headway.iframe.contents().find('body'),
+ viewport: $('#iframe-container'),
+ effect: false
+ },
+ show: {
+ delay: 300,
+ solo: true,
+ effect: false
+ },
+ hide: {
+ delay: 25,
+ effect: false
+ },
+ content: {
+ text: blockDimensionsTooltipContent
+ }
+ });
+
+ return $(block).qtip('api');
+
+ }
+
+
+ blockDimensionsTooltipContent = function(api) {
+
+ var block = getBlock(this);
+ var blockID = getBlockID(block);
+
+ var blockWidth = getBlockDimensionsPixels(block).width;
+ var blockHeight = getBlockDimensionsPixels(block).height;
+ var blockType = getBlockType(block);
+
+ /* Block Info (only if existing block) */
+ if ( typeof blockType != 'undefined' ) {
+
+ var blockTypeNice = getBlockTypeNice(blockType);
+ var blockTypeIconURL = getBlockTypeIcon(blockType, true);
+ var blockTypeIconStyle = blockTypeIconURL ? ' style="background-image:url(' + blockTypeIconURL + ');"' : null;
+
+ var blockAlias = block.data('alias') ? ': ' + block.data('alias') : '';
+ var blockMirroredLayoutName = getBlockMirrorLayoutName(block) ? ' from ' + getBlockMirrorLayoutName(block) : '';
+
+ var blockMirrored = isBlockMirrored(block) ? '<span class="block-info-mirroring">Mirroring' + blockMirroredLayoutName + '</span>' : '';
+ var mainBlockInfoClass = isBlockMirrored(block) ? 'main-block-info main-block-info-mirrored' : 'main-block-info';
+
+ var blockInfo = '<div class="block-info">' +
+ '<span class="block-info-type" ' + blockTypeIconStyle + '></span>' +
+ '<span class="' + mainBlockInfoClass + '">' +
+ blockTypeNice + ' ' + blockAlias +
+ '</span>' +
+ blockMirrored +
+ '</div>';
+
+ } else {
+
+ var blockInfo = '';
+
+ }
+
+ /* Block Dimensions */
+ if ( getBlockTypeObject(blockType)['fixed-height'] ) {
+
+ var blockHeight = blockHeight;
+ var heightText = 'Height';
+
+ } else {
+
+ var blockHeight = Headway.mode == 'grid' ? blockHeight : block.css('minHeight').replace('px', '');
+ var heightText = 'Min. Height';
+
+ }
+
+ var height = '<span class="block-height"><strong>' + heightText + ':</strong> ' + blockHeight + '<small>px</small></span>';
+ var width = '<span class="block-width"><strong>Width:</strong> ' + blockWidth + '<small>px</small></span>';
+
+ //Show different width info if it's responsive
+ if ( $('#input-enable-responsive-grid label.checkbox-checked').length == 1 || (Headway.mode != 'grid' && Headway.responsiveGrid) )
+ var width = '<span class="block-width"><strong>Max Width:</strong> <small>~</small>' + blockWidth + '<small>px</small></span>';
+
+ var fluidMessage = !getBlockTypeObject(blockType)['fixed-height'] ? '<span class="block-fluid-height-message">Height will auto-expand</span>' : '';
+
+ /* Output */
+ return blockInfo + width + ' <span class="block-dimensions-separator">☓</span> ' + height + fluidMessage + '<span class="right-click-message">Right-click to open block options</span>' ;
+
+ }
+
+
+ openBlockOptions = function(block, subTab) {
+
+ if ( typeof block.target != 'undefined' || !block )
+ var block = getBlock(this);
+
+ if ( typeof subTab == 'undefined' )
+ var subTab = null;
+
+ if ( !block || block.hasClass('block-type-unknown') )
+ return false;
+
+ var blockID = getBlockID(block);
+ var blockType = getBlockType(block);
+ var blockTypeName = getBlockTypeNice(blockType);
+
+ var readyTabs = function() {
+
+ var tab = $('div#block-' + blockID + '-tab');
+
+ /* Ready tab, sliders, and inputs */
+ tab.tabs();
+ panelInputs.bind('div#block-' + blockID + '-tab');
+
+ /* Refresh tooltips */
+ setupTooltips();
+
+ /* Call the open callback for the box panel */
+ var callback = eval(tab.find('ul.sub-tabs').attr('data-open-js-callback'));
+ if ( typeof callback == 'function' ) {
+ callback({
+ block: block,
+ blockID: blockID,
+ blockType: blockType
+ });
+ }
+
+ /* Show and hide elements based on toggle options */
+ handleInputTogglesInContainer(tab.find('div.sub-tabs-content'));
+
+ /* If subTab is defined, switch to that subTab */
+ if ( subTab )
+ selectTab(subTab, $('div#block-' + blockID + '-tab'));
+
+ /* If it's a mirrored block, then hide the other tabs */
+ if ( $('div#block-' + blockID + '-tab').find('select#input-' + blockID + '-mirror-block').val() != '' ) {
+
+ $('div#block-' + blockID + '-tab ul.sub-tabs li:not(#sub-tab-config)').hide();
+ selectTab('sub-tab-config', $('div#block-' + blockID + '-tab'));
+
+ }
+
+ }
+
+ var blockTypeIconURL = getBlockTypeIcon(blockType, true);
+ var blockTypeIconStyle = blockTypeIconURL ? 'background-image:url(' + blockTypeIconURL + ');' : null;
+
+ var blockTabName = blockTypeName + ' Block';
+
+ if ( block.data('alias') && block.data('alias').length ) {
+ blockTabName = block.data('alias');
+ }
+
+ addPanelTab('block-' + blockID, '<span class="block-type-icon" style="' + blockTypeIconStyle + '"></span>' + blockTabName, {
+ url: Headway.ajaxURL,
+ data: {
+ security: Headway.security,
+ action: 'headway_visual_editor',
+ method: 'load_block_options',
+ block_type: blockType,
+ block_id: blockID,
+ unsaved_block_options: getUnsavedBlockOptionValues(blockID),
+ layout: Headway.currentLayout
+ },
+ callback: readyTabs}, true, true, 'block-type-' + blockType);
+
+ $('div#panel').tabs('option', 'active', $('#panel-top').children('li[role="tab"]').index($('[aria-controls="block-' + blockID + '-tab"]')));
+
+ }
+
+
+ reloadBlockOptions = function(blockID, subTab) {
+
+ /* Make sure the block options are open to begin with */
+ if ( !$('ul#panel-top').find('[aria-controls="block-' + blockID + '-tab"]').length )
+ return;
+
+ /* If block ID isn't provided then just pull it from the active tab */
+ if ( typeof blockID == 'undefined' || !blockID )
+ var blockID = $('ul#panel-top > li.ui-state-active').attr('aria-controls').replace('block-', '').replace('-tab', '');
+
+ /* Make sure we have a real block ID and it's not something like setup tab trying to be reloaded */
+ if ( $('ul#panel-top > li.ui-state-active').attr('aria-controls').indexOf('block-') !== 0 )
+ return false;
+
+ if ( typeof subTab == 'undefined' || !subTab )
+ var subTab = $('div#block-' + blockID + '-tab ul.sub-tabs .ui-state-active a').attr('href').replace('#', '');
+
+ removePanelTab('block-' + blockID);
+
+ return openBlockOptions(getBlockByID(blockID), subTab);
+
+ }
+
+
+ getUnsavedBlockOptionValues = function(blockID) {
+
+ if (
+ typeof GLOBALunsavedValues == 'object' &&
+ typeof GLOBALunsavedValues['blocks'] == 'object' &&
+ typeof GLOBALunsavedValues['blocks'][blockID] == 'object' &&
+ typeof GLOBALunsavedValues['blocks'][blockID]['settings'] == 'object'
+ )
+ var unsavedBlockSettings = GLOBALunsavedValues['blocks'][blockID]['settings'];
+
+ return (typeof unsavedBlockSettings == 'object' && Object.keys(unsavedBlockSettings).length > 0) ? unsavedBlockSettings : null;
+
+ }
+
+
+ openBlockTypeSelector = function(block) {
+
+ var blockID = getBlockID(block);
+
+ /* Create blank panel */
+ removePanelTab('block-' + blockID);
+ addPanelTab('block-' + blockID, 'Select Block Type', '', true, true);
+
+ var tab = $('#block-' + blockID + '-tab');
+
+ /* Clone block type selector in and bind it */
+ var blockTypeSelector = $('.block-type-selector-original').clone()
+ .removeClass('block-type-selector-original')
+ .appendTo(tab)
+ .show();
+
+ blockTypeSelector.find('div.block-type').addClass('tooltip');
+ setupTooltips();
+
+ blockTypeSelector.find('div.block-type').bind('click', function(event) {
+
+ var blockType = $(this).attr('id').replace('block-type-', '');
+
+ /* If new block then create it */
+ if ( block.hasClass('blank-block') ) {
+
+ block.parents('.wrapper').headwayGrid('setupBlankBlock', blockType);
+
+ /* Otherwise we're switching an existing block's type */
+ } else if ( confirm('Are you sure you wish to switch block types? All settings for this block will be lost.') ) {
+
+ var switchedBlockTypeBlockID = switchBlockType(block, blockType);
+
+ blockID = switchedBlockTypeBlockID;
+
+ }
+
+ /* Hide all tooltips that way the tooltip doesn't continue showing for the hovered block type */
+ $('.qtip').qtip('hide');
+
+ /* Open options now */
+ removePanelTab('block-' + blockID);
+ openBlockOptions(getBlockByID(blockID));
+
+ });
+
+ /* Bind unfocus events */
+ if ( block.hasClass('blank-block') ) {
+
+ $('.wrapper').bind('mousedown', {block: block}, hideBlankBlockTypeSelector);
+
+ $(document).bind('keyup.esc', {block: block}, hideBlankBlockTypeSelector);
+ $i('html').bind('keyup.esc', {block: block}, hideBlankBlockTypeSelector);
+
+ /* Make sure that when closing the block type selector with the tab close button on a blank block that the blank block is also removed. */
+ $('ul#panel-top li a[href="#block-' + blockID + '-tab"]').siblings('span.close').bind('mouseup', {block: block}, hideBlankBlockTypeSelector);
+
+ }
+
+ /* Select the tab */
+ $('div#panel').tabs('option', 'active', $('#panel-top').children('li[role="tab"]').index($('[aria-controls="block-' + blockID + '-tab"]')));
+
+ return;
+
+ }
+
+
+ hideBlankBlockTypeSelector = function(event) {
+
+ var block = event.data.block;
+
+ /* If blank block then unbind things and delete it. Make sure that the block isn't being clicked inside of. */
+ if ( block.hasClass('blank-block') && $(event.target).parents('.block').first().get(0) != $(block).get(0) ) {
+
+ removePanelTab('block-' + getBlockID(block));
+
+ block.remove();
+
+ $('.wrapper').unbind('mousedown', hideBlankBlockTypeSelector);
+
+ $(document).unbind('keyup.esc', hideBlankBlockTypeSelector);
+ $i('html').unbind('keyup.esc', hideBlankBlockTypeSelector);
+
+ }
+
+ return true;
+
+ }
+
+
+ switchBlockType = function(block, blockType, loadContent) {
+
+ var blockTypeIconURL = getBlockTypeIcon(blockType, true);
+
+ var oldType = getBlockType(block);
+ var blockID = getBlockID(block);
+
+ block.removeClass('block-type-' + oldType);
+ block.addClass('block-type-' + blockType);
+ block.data('type', blockType);
+
+ if ( typeof loadContent == 'undefined' || loadContent ) {
+
+ loadBlockContent({
+ blockElement: block,
+ blockOrigin: {
+ type: blockType,
+ id: 0,
+ layout: Headway.currentLayout
+ },
+ blockSettings: {
+ dimensions: getBlockDimensions(block),
+ position: getBlockPosition(block)
+ },
+ });
+
+ }
+
+ //Set the fluid/fixed height class so the fluid height message is shown correctly
+ if ( getBlockTypeObject(blockType)['fixed-height'] === true ) {
+
+ block.removeClass('block-fluid-height');
+ block.addClass('block-fixed-height');
+
+ if ( block.css('min-height').replace('px', '') != '0' ) {
+
+ block.css({
+ height: block.css('min-height')
+ });
+
+ }
+
+ } else {
+
+ block.removeClass('block-fixed-height');
+ block.addClass('block-fluid-height');
+
+ if ( block.css('height').replace('px', '') != 'auto' ) {
+
+ block.css({
+ height: block.css('height')
+ });
+
+ }
+
+ }
+
+ //Set the hide-content-in-grid depending on the block type
+ if ( !getBlockTypeObject(blockType)['show-content-in-grid'] ) {
+
+ block.addClass('hide-content-in-grid');
+
+ } else {
+
+ block.removeClass('hide-content-in-grid');
+
+ }
+
+ //Remove block type unknown class
+ block.removeClass('block-type-unknown');
+
+ //Prepare for hiddens
+ oldBlockID = blockID;
+ var temporaryID = Math.ceil(Math.random() * 1000000000);
+
+ //Update the ID on the block
+ block
+ .attr('id', 'block-' + temporaryID)
+ .removeData('id')
+ .removeData('temp-id')
+ .attr('data-id', temporaryID)
+ .attr('data-temp-id', temporaryID);
+
+ //Delete the old block optiosn tab if it exists
+ removePanelTab('block-' + oldBlockID);
+
+ //Add hiddens to delete old block and add new block in its place
+ dataDeleteBlock(oldBlockID);
+ dataAddBlock(block);
+ dataSetBlockPosition(temporaryID, getBlockPosition(block));
+ dataSetBlockDimensions(temporaryID, getBlockDimensions(block));
+ dataSetBlockWrapper(temporaryID, getBlockWrapper(block).attr('id'));
+
+ //Update content overlay
+ updateBlockContentCover(block);
+
+ //Update mirroring status
+ updateBlockMirrorStatus(false, block, '', false);
+
+ //Allow saving now that the type has been switched
+ allowSaving();
+
+ /* Hide all tooltips that way the tooltip doesn't continue showing for the hovered block type */
+ $('.qtip').qtip('hide');
+
+ return temporaryID;
+
+ }
+
+
+ blockIntersectCheck = function(originBlock, container) {
+
+ if ( typeof container == 'undefined' || !container )
+ var container = block.parents('.grid-container').first();
+
+ var intersectors = blockIntersectCheckCallback(originBlock, container.find('.block'));
+
+ //If there are two elements in the intersection array (the original one will be included since we're doing a general '.block' search), then we throw an error
+ if ( intersectors.length > 1 ) {
+
+ intersectors.addClass('block-error');
+
+ var output = false;
+
+ } else {
+
+ //Set up variable for next loop
+ var blockErrorCount = 0;
+
+ //Since there could still be errors after this one if fixed, we must loop through all other blocks that have errors
+ container.find('.block-error').each(function(){
+ var intersectors = blockIntersectCheckCallback(this, container.find('.block'));
+
+ if ( intersectors.length === 1 || !intersectors ) {
+ $(this).removeClass('block-error');
+ } else {
+ blockErrorCount++;
+ }
+ });
+
+ //If there aren't any touching blocks, then we can save. Otherwise, we cannot.
+ var output = ( blockErrorCount === 0 ) ? true : false;
+
+ }
+
+ /* If there are overlapping blocks, then show a red notice */
+ if ( !output ) {
+
+ Headway.overlappingBlocks = true;
+
+ showErrorNotification({
+ id: 'overlapping-blocks',
+ message: 'There are <strong>overlapping blocks</strong>.<br />Please separate them before saving.',
+ closeTimer: false
+ });
+
+ } else {
+
+ Headway.overlappingBlocks = false;
+ hideNotification('overlapping-blocks');
+
+ }
+
+ return output;
+
+ }
+
+
+ blockIntersectCheckCallback = function(targetSelector, intersectorsSelector) {
+
+ if ( targetSelector == false || intersectorsSelector == false || !$(targetSelector).is(':visible') ) {
+ return false;
+ }
+
+ var intersectors = [];
+ var xTolerance = 5; /* Tolerance for when gutter width is very little */
+
+ var $target = $(targetSelector);
+ var tAxis = $target.offset();
+ var t_x = [tAxis.left, tAxis.left + $target.outerWidth()];
+ var t_y = [tAxis.top, tAxis.top + $target.outerHeight()];
+
+ $(intersectorsSelector).each(function() {
+
+ var $this = $(this);
+
+ if ( !$this.is(':visible') )
+ return;
+
+ var thisPos = $this.offset();
+ var i_x = [thisPos.left, thisPos.left + $this.outerWidth()]
+ var i_y = [thisPos.top, thisPos.top + $this.outerHeight()];
+
+ if ( (t_x[0] + xTolerance) < i_x[1] && (t_x[1] - xTolerance) > i_x[0] &&
+ t_y[0] < i_y[1] && (t_y[1]) > i_y[0]) {
+ intersectors.push(this);
+ }
+
+ });
+
+ return $(intersectors);
+
+ }
+
+
+ deleteBlock = function(element) {
+
+ if ( typeof element != 'object' )
+ var element = $i('.block[data-id="' + element + '"]');
+
+ var deleteBlockID = getBlockID(element);
+ var deleteBlock = getBlock(element);
+ var deleteBlockContainer = deleteBlock.parents('.grid-container');
+
+ Headway.history.add({
+ description: 'Deleted block',
+ up: function() {
+
+ //Get the container for the block intersect check
+
+ //Remove the block!
+ deleteBlock.hide();
+
+ //Remove block options tab from panel
+ removePanelTab('block-' + deleteBlockID);
+
+ //Add the hidden input flag
+ dataDeleteBlock(deleteBlockID);
+
+ //Set block to false for the intersect check
+ blockIntersectCheck(false, deleteBlockContainer);
+
+ },
+ down: function() {
+
+ deleteBlock.show();
+
+ if ( typeof GLOBALunsavedValues['blocks'][getBlockID(deleteBlock)]['delete'] != 'undefined' ) {
+ delete GLOBALunsavedValues['blocks'][getBlockID(deleteBlock)]['delete'];
+ }
+
+ blockIntersectCheck(deleteBlock, deleteBlockContainer);
+
+ }
+ });
+
+ allowSaving();
+
+ }
+
+ exportBlockSettingsButtonCallback = function(args) {
+
+ var params = {
+ 'security': Headway.security,
+ 'action': 'headway_visual_editor',
+ 'method': 'export_block_settings',
+ 'block-id': args.blockID
+ }
+
+ var exportURL = Headway.ajaxURL + '?' + $.param(params);
+
+ return window.open(exportURL);
+
+ }
+
+ initiateBlockSettingsImport = function(args) {
+
+ var input = args.input;
+ var blockID = args.blockID;
+ var fileInput = $(input).parents('.ui-tabs-panel').first().find('input[name="block-import-settings-file"]');
+
+ var importOptions = hwBoolean($(input).parents('.ui-tabs-panel').first().find('input[name="block-import-settings-include-options"]').val());
+ var importDesign = hwBoolean($(input).parents('.ui-tabs-panel').first().find('input[name="block-import-settings-include-design"]').val());
+
+ if ( !fileInput.val() )
+ return alert('You must select a block settings export file before importing.');
+
+ if ( !importOptions && !importDesign )
+ return alert('You must import at least the options or design when importing block settings.');
+
+ var blockSettingsFile = fileInput.get(0).files[0];
+
+ if ( blockSettingsFile && typeof blockSettingsFile.name != 'undefined' && typeof blockSettingsFile.type != 'undefined' ) {
+
+ var blockSettingsReader = new FileReader();
+
+ blockSettingsReader.onload = function(e) {
+
+ var contents = e.target.result;
+ var blockSettingsImportArray = JSON.parse(contents);
+
+ /* Check to be sure that the JSON file is a block settings export file */
+ if ( blockSettingsImportArray['data-type'] != 'block-settings' )
+ return alert('Cannot load block settings. Please insure that the block settings are a proper Headway block settings export.');
+
+ /* Make sure block type matches */
+ if ( getBlockType(getBlockByID(blockID)) != blockSettingsImportArray['type'] )
+ return alert('Block type mismatch. Be sure that the block settings export is the same type of block type that you\'re importing to.');
+
+ /* Handle the fun stuff */
+ if ( typeof blockSettingsImportArray['image-definitions'] != 'undefined' && Object.keys(blockSettingsImportArray['image-definitions']).length ) {
+
+ showNotification({
+ id: 'importing-images',
+ message: 'Currently importing images.',
+ closeTimer: 10000
+ });
+
+ $.post(Headway.ajaxURL, {
+ security: Headway.security,
+ action: 'headway_visual_editor',
+ method: 'import_images',
+ importFile: blockSettingsImportArray
+ }, function(response) {
+
+ var blockSettings = response;
+
+ /* If there's an error when sideloading images, then hault import. */
+ if ( typeof blockSettings['error'] != 'undefined' )
+ return alert('Error while importing images for block: ' + blockSettings['error']);
+
+ importBlockSettingsAJAXCallback(blockID, blockSettings, importOptions, importDesign);
+
+ });
+
+ } else {
+
+ importBlockSettingsAJAXCallback(blockID, blockSettingsImportArray, importOptions, importDesign);
+
+ }
+
+ }; /* end blockSettingsReader.onload */
+
+ blockSettingsReader.readAsText(blockSettingsFile);
+
+ } else {
+
+ alert('Cannot load block settings. Please insure that the block settings are a proper Headway block settings export.');
+
+ }
+
+ }
+
+
+ importBlockSettingsAJAXCallback = function(blockID, block, importOptions, importDesign) {
+
+ /* Import block options */
+ if ( importOptions ) {
+
+ /* Delete existing block and re-add it so it has fresh settings */
+ var blockID = switchBlockType(getBlockByID(blockID), getBlockType(getBlockByID(blockID)));
+
+ /* Import block settings */
+ importBlockSettings(block['settings'], blockID);
+
+ /* Reload block settings */
+ removePanelTab('block-' + blockID);
+ openBlockOptions(getBlockByID(blockID));
+
+ }
+
+ /* Import block design */
+ if ( importDesign && typeof block['styling'] != 'undefined' && typeof block['id'] != 'undefined' ) {
+
+ dataPrepareDesignEditor();
+
+ $.each(block['styling'], function(instanceID, instanceInfo) {
+
+ /* Replace the block ID instance ID of the correct block ID */
+ var oldBlockID = block['id'];
+ var newBlockID = blockID;
+
+ var instanceID = instanceID.replace('block-' + oldBlockID, 'block-' + newBlockID);
+
+ $.each(instanceInfo.properties, function(property, value) {
+
+ dataSetDesignEditorProperty({
+ element: instanceInfo.element,
+ property: property,
+ value: (value !== null ? value.toString() : null),
+ specialElementType: "instance",
+ specialElementMeta: instanceID
+ });
+
+ });
+
+ });
+
+ showNotification({
+ id: 'block-design-imported-' + blockID,
+ message: 'Block design successfully imported',
+ closeTimer: 6000,
+ success: true
+ });
+
+ }
+
+ /* All done, allow saving */
+ allowSaving();
+
+ }
+
+ importBlockSettings = function(importBlockSettings, blockID) {
+
+ /* Send the block settings data to the unsaved data */
+ dataPrepareBlock(blockID);
+
+ GLOBALunsavedValues['blocks'][blockID]['settings'] = importBlockSettings;
+
+ /* Force reload block content */
+ refreshBlockContent(blockID);
+
+ /* Show notification */
+ showNotification({
+ id: 'block-settings-imported-' + blockID,
+ message: 'Block settings successfully imported',
+ closeTimer: 6000,
+ success: true
+ });
+
+ }
+
+ updateBlockMirrorStatus = function(input, block, value, updateTooltips) {
+
+ /* If there is no input provided, then create an empty jQuery so no errors show up */
+ if ( typeof input == 'undefined' || input == false )
+ input = $();
+
+ if ( typeof updateTooltips == 'undefined' )
+ updateTooltips = true;
+
+ if ( typeof block != 'object' )
+ var block = getBlock($i('.block[data-id="' + block + '"]'));
+
+ if ( typeof value == 'undefined' || value == '' ) {
+
+ input.parents(".panel").find("ul.sub-tabs li:not(#sub-tab-config)").show();
+
+ /* Change ID attribute to the block's real ID */
+ block.attr('id', 'block-' + block.data('id'));
+
+ /* Get rid of data-block-mirror */
+ block.data('block-mirror', false);
+
+ /* Remove mirrored class */
+ block.removeClass('block-mirrored');
+
+ } else {
+
+ input.parents(".panel").find("ul.sub-tabs li:not(#sub-tab-config)").hide();
+
+ /* Update ID attribute to the mirrored block ID */
+ block.attr('id', 'block-' + value);
+
+ /* Update data-block-mirror */
+ block.data('block-mirror', value);
+
+ /* Add class */
+ block.addClass('block-mirrored');
+
+ }
+
+ }
+
+});
+
--- /dev/null
+define(['modules/iframe', 'deps/jquery.pep'], function(iframe) {
+
+ /* BOX FUNCTIONS */
+ createBox = function(args) {
+ var settings = {};
+
+ var defaults = {
+ id: null,
+ title: null,
+ description: null,
+ content: null,
+ src: null,
+ load: null,
+ width: 500,
+ height: 300,
+ center: true,
+ closable: true,
+ resizable: false,
+ draggable: true,
+ deleteWhenClosed: false,
+ blackOverlay: false,
+ blackOverlayOpacity: .6,
+ blackOverlayIframe: false
+ };
+
+ $.extend(settings, defaults, args);
+
+ /* Create box */
+ var box = $('<div class="box" id="box-' + settings.id + '"><div class="box-top"></div><div class="box-content-bg"><div class="box-content"></div></div></div>');
+
+ box.attr('black_overlay', settings.blackOverlay);
+ box.attr('black_overlay_opacity', settings.blackOverlayOpacity);
+ box.attr('black_overlay_iframe', settings.blackOverlayIframe);
+ box.attr('load_with_ajax', false);
+
+ /* Move box into document */
+ box.appendTo('div#boxes');
+
+ /* Inject everything */
+ /* If regular content and not iframe, just put it in */
+ if ( typeof settings.src !== 'string' ) {
+
+ box.find('.box-content').html(settings.content);
+
+ /* Else use iframe */
+ } else {
+
+ box.find('.box-content').addClass('box-content-with-iframe');
+ box.find('.box-content').html('<iframe src="' + settings.src + '"></iframe>');
+
+ if ( typeof settings.load === 'function' ) {
+
+ box.find('.box-content iframe').bind('load', settings.load);
+
+ }
+
+ }
+
+ box.find('.box-top').append('<strong>' + settings.title + '</strong>');
+
+ if ( typeof settings.description === 'string' ) {
+ box.find('.box-top').append('<span>' + settings.description + '</span>');
+ }
+
+ /* Setup box */
+ setupBox(settings.id, settings);
+
+ return box;
+ }
+
+
+ setupBox = function(id, args) {
+
+ var settings = {};
+
+ var defaults = {
+ width: 600,
+ height: 300,
+ center: true,
+ closable: true,
+ deleteWhenClosed: false,
+ draggable: false,
+ resizable: false
+ };
+
+ $.extend(settings, defaults, args);
+
+ var box = $('div#box-' + id);
+
+ /* Handle draggable */
+ if ( settings.draggable ) {
+
+ box.draggable({
+ handle: box.find('.box-top'),
+ start: showIframeOverlay,
+ stop: hideIframeOverlay,
+ shouldEase: false
+ });
+
+ box.find('.box-top').css('cursor', 'move');
+
+ }
+
+ /* Make box closable */
+ if ( settings.closable ) {
+
+ /* If close button doesn't exist, create it. */
+ box.find('.box-top').append('<span class="box-close">X</span>');
+
+ box.find('.box-close').bind('click', function(){
+ closeBox(id, settings.deleteWhenClosed);
+ });
+
+ }
+
+ /* Make box resizable */
+ if ( settings.resizable ) {
+
+ /* If close button doesn't exist, create it. */
+ box.resizable({
+ start: showIframeOverlay,
+ stop: hideIframeOverlay,
+ handles: 'n, e, s, w, ne, se, sw, nw',
+ minWidth: settings.minWidth,
+ minHeight: settings.minHeight
+ });
+
+ }
+
+ /* Set box dimensions */
+ box.css({
+ width: settings.width,
+ height: settings.height
+ });
+
+ /* Center Box */
+ if ( settings.center ) {
+
+ var marginLeft = -(box.width() / 2);
+ var marginTop = -(box.height() / 2);
+
+ box.css({
+ top: '50%',
+ left: '50%',
+ marginLeft: marginLeft,
+ marginTop: marginTop,
+ });
+
+ }
+
+ }
+
+
+ setupStaticBoxes = function() {
+
+ $('div.box').each(function() {
+
+ /* Fetch settings */
+ var draggable = hwBoolean($(this).attr('draggable'));
+ var closable = hwBoolean($(this).attr('closable'));
+ var resizable = hwBoolean($(this).attr('resizable'));
+ var center = hwBoolean($(this).attr('center'));
+ var width = $(this).attr('width');
+ var height = $(this).attr('height');
+ var minWidth = $(this).attr('min_width');
+ var minHeight = $(this).attr('min_height');
+
+ var id = $(this).attr('id').replace('box-', '');
+
+ setupBox(id, {
+ draggable: draggable,
+ closable: closable,
+ resizable: resizable,
+ center: center,
+ width: width,
+ height: height,
+ minWidth: minWidth,
+ minHeight: minHeight
+ });
+
+ /* Remove settings attributes */
+ $(this).attr('draggable', null);
+ $(this).attr('closable', null);
+ $(this).attr('resizable', null);
+ $(this).attr('center', null);
+ $(this).attr('width', null);
+ $(this).attr('height', null);
+ $(this).attr('min_width', null);
+ $(this).attr('min_height', null);
+
+ });
+
+ }
+
+
+ openBox = function(id) {
+
+ var id = id.replace('box-', '');
+ var box = $('div#box-' + id);
+
+ if ( box.length === 0 )
+ return false;
+
+ var blackOverlay = hwBoolean(box.attr('black_overlay'));
+ var blackOverlayOpacity = box.attr('black_overlay_opacity');
+ var blackOverlayIframe = hwBoolean(box.attr('black_overlay_iframe'));
+ var loadWithAjax = hwBoolean(box.attr('load_with_ajax'));
+
+ if ( blackOverlay && !boxOpen(id) ) {
+
+ var overlay = $('<div class="black-overlay"></div>')
+ .hide()
+ .attr('id', 'black-overlay-box-' + id)
+ .appendTo('#boxes');
+
+ if ( blackOverlayIframe === true )
+ overlay.css('zIndex', 4);
+
+ if ( !isNaN(blackOverlayOpacity) )
+ overlay.css('background', 'rgba(0, 0, 0, ' + blackOverlayOpacity + ')');
+
+ overlay.show();
+
+ }
+
+ if ( loadWithAjax && !box.data('currently-ajax-loading') ) {
+
+ /* Remove all data such as jQuery UI widgets. jQuery UI upgrade to 1.10 required this */
+ box.find('*').removeData();
+ box.find('.box-content *').remove();
+
+ /* Add the loading cog */
+ createCog(box.find('.box-content'), true);
+
+ /* Add loading flag */
+ box.data('currently-ajax-loading', true);
+
+ box.find('.box-content').load(Headway.ajaxURL, {
+ security: Headway.security,
+ action: 'headway_visual_editor',
+ method: 'load_box_ajax_content',
+ box_id: id,
+ layout: Headway.currentLayout
+ }, function() {
+
+ var loadWithAjaxCallback = eval(box.attr('load_with_ajax_callback'));
+
+ loadWithAjaxCallback.call();
+
+ /* Remove loading flag */
+ box.removeData('currently-ajax-loading');
+
+ });
+
+ }
+
+ return box.show();
+
+ }
+
+
+ closeBox = function(id, deleteWhenClosed) {
+
+ var id = id.replace('box-', '');
+ var box = $('div#box-' + id);
+
+ box.hide();
+
+ if ( typeof deleteWhenClosed != 'undefined' && deleteWhenClosed == true )
+ box.remove();
+
+ $('div#black-overlay-box-' + id).remove();
+
+ return true;
+
+ }
+
+
+ boxOpen = function(id) {
+
+ return $('div#box-' + id).is(':visible');
+
+ }
+
+
+ boxExists = function(id) {
+
+ if ( $('div#box-' + id).length === 1 ) {
+
+ return true;
+
+ } else {
+
+ return false;
+
+ }
+
+ }
+
+
+ toggleBox = function(id) {
+
+ if ( !boxOpen(id) ) {
+
+ openBox(id);
+
+ } else {
+
+ closeBox(id);
+
+ }
+
+ }
+ /* END BOX FUNCTIONS */
+
+ /* BOXES */
+ setupStaticBoxes();
+
+ /* Make clicking box overlay close visible box for lazy people like me. */
+ $('#boxes').on('click', 'div.black-overlay', function(){
+
+ var id = $(this).attr('id').replace('black-overlay-', '');
+
+ if ( $('#' + id).length === 0 )
+ return;
+
+ if ( $('.qtip-tour').is(':visible') )
+ return;
+
+ closeBox(id);
+
+ });
+ /* END BOXES */
+
+});
\ No newline at end of file
--- /dev/null
+/* CONTEXT MENU FUNCTIONALITY */
+ setupContextMenu = function(args) {
+
+ if ( typeof args != 'object' )
+ return false;
+
+ var args = $.extend(true, {}, {
+ isIframeElement: true
+ }, args);
+
+ /*
+ ### Argument Example setup###
+
+ {
+ id: 'inspector',
+ elements: '.wrapper',
+ title: function(event) { //Can be string or function
+ return 'Example Wrapper';
+ },
+ contentsCallback: function(contextMenu, event) { },
+ onItemClick: function(contextMenu, originalRightClickEvent) { },
+ onBeforeShow: function(event) { },
+ onHide: function(contextMenu) { },
+ isIframeElement: true
+ }
+ */
+
+ /* Unbind any existing of the same context menu */
+ deactivateContextMenu(args.id);
+
+ /* Bind the right click on the element(s) */
+ var contextMenuOpenEvent = !Headway.touch ? 'contextmenu.contextMenu' + args.id : 'taphold.contextMenu' + args.id;
+
+ /* Get to binding! */
+ if ( args.isIframeElement ) {
+
+ $iDocument().on(contextMenuOpenEvent, args.elements, function(event, eventArgs) {
+ event.data = eventArgs;
+ contextMenuCreator(args, event, true);
+ });
+
+ } else {
+
+ $(document).on(contextMenuOpenEvent, args.elements, function(event, eventArgs) {
+ event.data = eventArgs;
+ contextMenuCreator(args, event, false);
+ });
+
+ }
+
+ /* Bind click on anything else to close */
+ var clickToClose = function(event) {
+
+ if ( (event.which !== 0 && event.which !== 1) || $(event.originalEvent.target).parents('#context-menu-' + args.id).length )
+ return;
+
+ var contextMenu = $('#context-menu-' + args.id);
+
+ if ( typeof args.onHide == 'function' )
+ args.onHide.apply(contextMenu);
+
+ contextMenu.remove();
+
+ }
+
+ /* Bind mouseup to close context menu normally and tap for touch support */
+ var contextMenuCloseEvent = !Headway.touch ? 'click' : 'touchstart';
+
+ $('body').on(contextMenuCloseEvent + '.contextMenu' + args.id, clickToClose);
+ $i('body').on(contextMenuCloseEvent + '.contextMenu' + args.id, clickToClose);
+ /* End binding click on anything to close */
+
+ }
+
+
+ deactivateContextMenu = function(id) {
+
+ $(document).off('.contextMenu' + id);
+ $iDocument().off('.contextMenu' + id);
+
+ $('body').off('.contextMenu' + id);
+ $i('body').off('.contextMenu' + id);
+
+ return true;
+
+ }
+
+
+ contextMenuCreator = function(args, event, iframe) {
+
+ event.stopPropagation(); /* Keep other context menus from opening */
+
+ if ( typeof args != 'object' )
+ return false;
+
+ /* Hide any other context menus */
+ $('.context-menu').remove();
+
+ /* Create context menu */
+ var contextMenuTitle = typeof args.title == 'function' ? args.title.apply(undefined, [event]) : args.title;
+ var contextMenu = $('<ul id="context-menu-' + args.id + '" class="context-menu"><h3>' + contextMenuTitle + '</h3></ul>');
+
+ /* Trigger onShow callback */
+ if ( typeof args.onShow == 'function' )
+ args.onShow.apply(contextMenu, [event]);
+
+ /* Fire contentsCallback to insert items */
+ args.contentsCallback.apply(contextMenu, [event]);
+
+ /* Bind click of items */
+ var originalRightClickEvent = event;
+
+ var contextMenuItemClick = function(event) {
+
+ if ( typeof args.onItemClick == 'function' )
+ args.onItemClick.apply(this, [contextMenu, originalRightClickEvent]);
+
+ if ( typeof args.onHide == 'function' )
+ args.onHide.apply(contextMenu);
+
+ contextMenu.remove();
+
+ };
+
+ var contextMenuClickEvent = !Headway.touch ? 'click' : 'tap';
+ contextMenu.delegate('span', contextMenuClickEvent, contextMenuItemClick);
+
+ /* Context menu positioning */
+ if ( typeof event.originalEvent != 'undefined' && typeof event.originalEvent.clientX != 'undefined' ) {
+
+ var contextMenuX = event.originalEvent.clientX;
+ var contextMenuY = event.originalEvent.clientY + 40;
+
+ } else {
+
+ var contextMenuX = event.data.x;
+ var contextMenuY = event.data.y + 40;
+
+ }
+
+
+ contextMenu.css({
+ left: contextMenuX,
+ top: contextMenuY
+ });
+
+ /* Delegate hover event on context menu sub menus for the lovely window right bleeding */
+ contextMenu.delegate('li:has(ul) span', 'hover', function() {
+
+ var childMenu = $(this).siblings('ul');
+ var childMenuOffset = childMenu.offset();
+
+ if ( !childMenuOffset || ((childMenu.offset().left + childMenu.outerWidth()) < $('iframe.content').width()) )
+ return;
+
+ childMenu.css('right', childMenu.css('left'));
+ childMenu.css('left', 'auto');
+
+ childMenu.css('width', '190px');
+
+ childMenu.css('zIndex', '999999');
+
+ });
+
+ /* Add context menu to iframe */
+ contextMenu.appendTo($('body'));
+
+ /* Context Menu overflow */
+ /* X overflow */
+ if ( (contextMenuX + contextMenu.outerWidth()) > $(window).width() ) {
+
+ var overflow = $(window).width() - (contextMenuX + contextMenu.outerWidth());
+ contextMenu.css('left', contextMenuX + overflow - 20);
+
+ }
+
+ /* Y overflow */
+ if ( (contextMenuY + contextMenu.outerHeight()) > $(window).height() ) {
+
+ var overflow = $(window).height() - (contextMenuY + contextMenu.outerHeight());
+ contextMenu.css('top', contextMenuY + overflow - 20);
+
+ }
+ /* End Context Menu Overflow */
+
+ /* Prevent regular context menu from opening */
+ event.preventDefault();
+ return false;
+
+ }
+/* END CONTEXT MENU FUNCTIONALITY */
\ No newline at end of file
--- /dev/null
+define(['underscore'], function(_) {
+
+ /* DATA HANDLING FUNCTIONS */
+ dataHandleInput = function(input, value, additionalCallbackArgs) {
+
+ var input = $(input);
+
+ /* Make sure input exists */
+ if ( !input.length )
+ return false;
+
+ /* Build variables */
+ if ( typeof value == 'undefined' )
+ var value = input.val();
+
+ var optionID = input.attr('name').toLowerCase();
+ var optionGroup = input.attr('data-group').toLowerCase();
+
+ var callback = eval(input.attr('data-callback'));
+ var dataHandlerOverrideCallback = eval(input.attr('data-data-handler-callback')) || null;
+
+ /* Set up arguments */
+ var panelArgs = input.parents('.sub-tabs-content-container').first().data('panel-args') || {};
+ var callbackArgs = $.extend({}, {
+ input: input,
+ value: value
+ }, panelArgs);
+
+ /* Add in additionalCallbackArgs which is used for things like image uploader input */
+ if ( typeof additionalCallbackArgs == 'object' )
+ callbackArgs = $.extend({}, callbackArgs, additionalCallbackArgs);
+
+ /* Allow saving */
+ allowSaving();
+
+ /* Handle repeater inputs */
+ if ( !input.hasClass('repeater-group-input') && input.parents('.repeater-group').length ) {
+
+ updateRepeaterValues(input.parents('.repeater'));
+
+ if ( typeof callback == 'function' )
+ callback(callbackArgs);
+
+ return input.parents('.repeater-group');
+
+ }
+
+ /* If no save flag is present then stop here */
+ if ( input.attr('data-no-save') ) {
+
+ if ( typeof callback == 'function' )
+ callback(callbackArgs);
+
+ return input;
+
+ }
+
+ /* Route to the proper place to save the data */
+ /* Data Handler Override */
+ if ( typeof dataHandlerOverrideCallback == 'function' ) {
+
+ dataHandlerOverrideCallback(callbackArgs);
+
+ /* Block Option */
+ } else if ( typeof panelArgs.block != 'undefined' && panelArgs.block ) {
+
+ var blockID = panelArgs.blockID;
+
+ dataSetBlockOption(blockID, optionID, value);
+ refreshBlockContent(blockID, callback, callbackArgs);
+
+ return input;
+
+ /* Wrapper Option */
+ } else if ( typeof panelArgs.wrapper != 'undefined' && panelArgs.wrapper ) {
+
+ dataSetWrapperOption(panelArgs.wrapper.id, optionID, value);
+
+ /* Regular Option */
+ } else {
+
+ dataSetOption(optionGroup, optionID, value);
+
+ }
+
+ /* Fire callback as long as it's not block setting (it would've returned above so this won't execute if it's a block setting... callback needs to fire after block content is loaded via AJAX) */
+ if ( typeof callback == 'function' )
+ callback(callbackArgs);
+
+ /* Done */
+ return input;
+
+ }
+
+
+ /* REGULAR OPTIONS DATA */
+ dataSetOption = function(group, option, value) {
+
+ dataPrepareOptionGroup(group);
+
+ GLOBALunsavedValues['options'][group][option] = value;
+
+ allowSaving();
+
+ return GLOBALunsavedValues['options'][group];
+
+ }
+
+
+ dataPrepareOptionGroup = function(group) {
+
+ if ( typeof GLOBALunsavedValues != 'object' )
+ GLOBALunsavedValues = {};
+
+ if ( typeof GLOBALunsavedValues['options'] != 'object' )
+ GLOBALunsavedValues['options'] = {};
+
+ if ( typeof GLOBALunsavedValues['options'][group] != 'object' )
+ GLOBALunsavedValues['options'][group] = {};
+
+ return GLOBALunsavedValues['options'][group];
+
+ }
+ /* END REGULAR OPTIONS DATA */
+
+
+ /* BLOCK SAVING FUNCTIONS */
+ dataSetBlockOption = function(blockID, option, value) {
+
+ dataPrepareBlock(blockID);
+
+ GLOBALunsavedValues['blocks'][blockID]['settings'][option] = value;
+
+ allowSaving();
+
+ return GLOBALunsavedValues['blocks'][blockID];
+
+ }
+
+
+ dataSetBlockPosition = function(blockID, position) {
+
+ if ( typeof blockID === 'string' && blockID.indexOf('block-') !== -1 )
+ var blockID = blockID.replace('block-', '');
+
+ var position = position.left + ',' + position.top;
+
+ dataPrepareBlock(blockID);
+
+ GLOBALunsavedValues['blocks'][blockID]['position'] = position;
+
+ allowSaving();
+
+ return GLOBALunsavedValues['blocks'][blockID];
+
+ }
+
+
+ dataSetBlockDimensions = function(blockID, dimensions) {
+
+ if ( typeof blockID === 'string' && blockID.indexOf('block-') !== -1 )
+ var blockID = blockID.replace('block-', '');
+
+ var dimensions = dimensions.width + ',' + dimensions.height;
+
+ dataPrepareBlock(blockID);
+
+ GLOBALunsavedValues['blocks'][blockID]['dimensions'] = dimensions;
+
+ allowSaving();
+
+ return GLOBALunsavedValues['blocks'][blockID];
+
+ }
+
+
+ dataSetBlockWrapper = function(blockID, newWrapperID) {
+
+ dataPrepareBlock(blockID);
+
+ GLOBALunsavedValues['blocks'][blockID]['wrapper'] = newWrapperID.toString().replace('wrapper-', '');
+
+ allowSaving();
+
+ return GLOBALunsavedValues['blocks'][blockID];
+
+ }
+
+
+ dataDeleteBlock = function(blockID) {
+
+ if ( typeof blockID === 'string' && blockID.indexOf('block-') !== -1 )
+ var blockID = blockID.replace('block-', '');
+
+ dataPrepareBlock(blockID);
+
+ GLOBALunsavedValues['blocks'][blockID]['delete'] = true;
+
+ allowSaving();
+
+ return GLOBALunsavedValues['blocks'][blockID];
+
+ }
+
+
+ dataAddBlock = function(block) {
+
+ var blockID, blockType;
+
+ if ( typeof block === 'string' && blockID.indexOf('block-') !== -1 ) {
+ blockID = block.replace('block-', '');
+ } else {
+ blockID = getBlockID(block);
+ }
+
+ blockType = getBlockType(block);
+
+ dataPrepareBlock(blockID);
+
+ GLOBALunsavedValues['blocks'][blockID]['new'] = blockType;
+ GLOBALunsavedValues['blocks'][blockID]['insert_id'] = block.data('desired-id');
+
+ delete GLOBALunsavedValues['blocks'][blockID]['delete'];
+
+ allowSaving();
+
+ return GLOBALunsavedValues['blocks'][blockID];
+
+ }
+
+
+ dataPrepareBlock = function(blockID) {
+
+ if ( typeof GLOBALunsavedValues != 'object' )
+ GLOBALunsavedValues = {};
+
+ if ( typeof GLOBALunsavedValues['blocks'] != 'object' )
+ GLOBALunsavedValues['blocks'] = {};
+
+ if ( typeof GLOBALunsavedValues['blocks'][blockID] != 'object' )
+ GLOBALunsavedValues['blocks'][blockID] = {};
+
+ if ( typeof GLOBALunsavedValues['blocks'][blockID]['settings'] != 'object' )
+ GLOBALunsavedValues['blocks'][blockID]['settings'] = {};
+
+ return GLOBALunsavedValues['blocks'][blockID];
+
+ }
+ /* END BLOCK HANDLING FUNCTIONS */
+
+
+ /* WRAPPER DATA */
+ dataSetWrapperOption = function(wrapperID, option, value) {
+
+ wrapperID = String(wrapperID).replace('wrapper-', '');
+
+ dataPrepareWrapper(wrapperID);
+
+ GLOBALunsavedValues['wrappers'][wrapperID]['settings'][option] = value;
+
+ allowSaving();
+
+ return GLOBALunsavedValues['wrappers'][wrapperID];
+
+ }
+
+
+ dataAddWrapper = function(wrapper, settings, position) {
+
+ wrapperID = String(wrapper.attr('id')).replace('wrapper-', '');
+
+ dataPrepareWrapper(wrapperID);
+
+ GLOBALunsavedValues['wrappers'][wrapperID] = {
+ new: true,
+ insert_id: wrapper.data('desired-id'),
+ position: position,
+ settings: jQuery.extend({}, {
+ 'columns': Headway.defaultGridColumnCount,
+ 'column-width': Headway.globalGridColumnWidth,
+ 'gutter-width': Headway.globalGridGutterWidth
+ }, settings)
+ };
+
+ dataSortWrappers();
+
+ allowSaving();
+
+ return GLOBALunsavedValues['wrappers'][wrapperID];
+
+ }
+
+
+ dataDeleteWrapper = function(wrapperID) {
+
+ wrapperID = String(wrapperID).replace('wrapper-', '');
+
+ dataPrepareWrapper(wrapperID);
+
+ GLOBALunsavedValues['wrappers'][wrapperID]['delete'] = true;
+
+ allowSaving();
+
+ return GLOBALunsavedValues['wrappers'][wrapperID];
+
+ }
+
+
+ dataSetWrapperWidth = function(wrapperID, fixedOrFluid) {
+
+ var isFluid = fixedOrFluid == 'fluid';
+
+ return dataSetWrapperOption(wrapperID, 'fluid', isFluid);
+
+ }
+
+
+ dataSetWrapperGridWidth = function(wrapperID, fixedOrFluid) {
+
+ var isFluid = fixedOrFluid == 'fluid';
+
+ return dataSetWrapperOption(wrapperID, 'fluid-grid', isFluid);
+
+ }
+
+
+ dataSortWrappers = function() {
+
+ $i('.wrapper:visible').each(function() {
+
+ var wrapperID = $(this).data('id');
+
+ dataPrepareWrapper(wrapperID);
+
+ GLOBALunsavedValues['wrappers'][wrapperID]['position'] = $i('.wrapper').index(this);
+
+ });
+
+ }
+
+
+ dataPrepareWrapper = function(wrapperID) {
+
+ wrapperID = String(wrapperID).replace('wrapper-', '');
+
+ if ( typeof GLOBALunsavedValues != 'object' )
+ GLOBALunsavedValues = {};
+
+ if ( typeof GLOBALunsavedValues['wrappers'] == 'undefined' )
+ GLOBALunsavedValues['wrappers'] = {};
+
+ if ( typeof GLOBALunsavedValues['wrappers'][wrapperID] == 'undefined' )
+ GLOBALunsavedValues['wrappers'][wrapperID] = {};
+
+ if ( typeof GLOBALunsavedValues['wrappers'][wrapperID]['settings'] == 'undefined' )
+ GLOBALunsavedValues['wrappers'][wrapperID]['settings'] = {};
+
+ }
+ /* END WRAPPER DATA */
+
+
+ /* DESIGN EDITOR DATA */
+ dataHandleDesignEditorInput = function(args) {
+
+ var hiddenInput = $(args.hiddenInput);
+ var value = args.value;
+
+ if ( !hiddenInput.length )
+ return false;
+
+ /* If it's an uncustomized property and the user somehow tabs to the input, DO NOT send the stuff to the DB. */
+ if ( hiddenInput.parents('li.uncustomized-property').length == 1 )
+ return false;
+
+ /* Get all vars */
+ var element = hiddenInput.attr('element').toLowerCase();
+ var property = hiddenInput.attr('property').toLowerCase();
+ var selector = hiddenInput.attr('element_selector') || false;
+ var specialElementType = hiddenInput.attr('special_element_type').toLowerCase() || false;
+ var specialElementMeta = hiddenInput.attr('special_element_meta').toLowerCase() || false;
+
+ /* Set the data for saving */
+ args.unit = hiddenInput.siblings('.property-unit-select').find('select').val();
+
+ dataSetDesignEditorProperty({
+ element: element,
+ property: property,
+ value: value,
+ specialElementType: specialElementType,
+ specialElementMeta: specialElementMeta,
+ unit: args.unit
+ });
+
+ /* Change null string to null */
+ if ( value === 'null' || value == 'DELETE' )
+ value = null;
+
+ /* Update hidden input value */
+ hiddenInput.val(value);
+
+ /* Update yellow dots */
+ /* Element selector node */
+ $('#design-editor-element-selector-container').find('li#element-' + element)
+ .addClass('customized-element')
+ .attr('title', 'You have customized a property in this property group.');
+
+ /* Customized parent */
+ if ( $('#design-editor-main-elements').find('.ui-state-active').length && $('#design-editor-sub-elements').find('.ui-state-active').length )
+ $('#design-editor-main-elements').find('.ui-state-active').addClass('has-customized-children');
+
+ /* Property box */
+ hiddenInput.parents('.design-editor-box').first()
+ .addClass('design-editor-box-customized');
+
+ hiddenInput.parents('.design-editor-box').first().find('.design-editor-box-title')
+ .attr('title', 'You have customized a property in this property group.');
+
+ /* Show the changes to the user */
+ return dataDesignEditorPropertyFeedback({
+ element: element,
+ property: property,
+ value: value,
+ specialElementType: specialElementType,
+ specialElementMeta: specialElementMeta,
+ unit: args.unit
+ });
+
+ }
+
+ dataDesignEditorPropertyFeedback = function(args) {
+
+ /* Set up variables */
+ var element = args.element.toLowerCase();
+ var property = args.property.toLowerCase();
+ var value = args.value;
+ var specialElementType = args.specialElementType || false;
+ var specialElementMeta = args.specialElementMeta || false;
+
+ if ( value === 'null' || value == 'DELETE' ) {
+ args.value = null;
+ value = null;
+ }
+
+ /* Figure out the selector */
+ if ( !specialElementType || specialElementType == 'layout' ) {
+
+ var selector = Headway.elements[element]['selector'];
+
+ } else {
+
+ var selector = Headway.elements[element][specialElementType + 's'][specialElementMeta]['selector'];
+
+ }
+
+ /* Call developer-defined callback */
+ if ( Headway.designEditorProperties.hasOwnProperty(property) ) {
+
+ var callback = eval('(function(params){' + Headway.designEditorProperties[property]['js-callback'] + '})');
+
+ args['selector'] = selector;
+ args['element'] = $i(selector);
+
+ if ( typeof args['unit'] == 'undefined' ) {
+ args['unit'] = '';
+ }
+
+ callback(args);
+
+ }
+
+ /* If value is null, then it's an uncustomization. Remove CSS */
+ if ( value == null && selector && property )
+ stylesheet.delete_rule_property(selector, property);
+
+ return selector;
+
+ }
+
+ dataSetDesignEditorProperty = function(args) {
+
+ /* Set up variables */
+ var element = args.element.toLowerCase();
+ var property = args.property.toLowerCase();
+ var value = args.value;
+ var unit = args.unit;
+ var specialElementType = args.specialElementType || false;
+ var specialElementMeta = args.specialElementMeta || false;
+
+ /* Add unit to value if it exists */
+ if ( unit && unit.length && value != 'null' && value != 'DELETE' ) {
+ value = value + unit;
+ }
+
+ /* Queue for saving */
+ dataPrepareDesignEditor();
+
+ if ( typeof GLOBALunsavedValues['design-editor'][element] != 'object' )
+ GLOBALunsavedValues['design-editor'][element] = {};
+
+ if ( specialElementType == false || specialElementMeta == false ) {
+
+ if ( typeof GLOBALunsavedValues['design-editor'][element]['properties'] != 'object' )
+ GLOBALunsavedValues['design-editor'][element]['properties'] = new Object();
+
+ GLOBALunsavedValues['design-editor'][element]['properties'][property] = value;
+
+ /* Change Headway.elementData as well that way other places can update before saving */
+ if ( typeof Headway.elementData != 'object' )
+ Headway.elementData = new Object();
+
+ if ( typeof Headway.elementData[element] == 'undefined' )
+ Headway.elementData[element] = {properties: {}};
+
+ if ( typeof Headway.elementData[element]['properties'] == 'undefined' )
+ Headway.elementData[element]['properties'] = {};
+
+ Headway.elementData[element]['properties'][property] = value;
+
+ } else {
+
+ if ( typeof GLOBALunsavedValues['design-editor'][element]['special-element-' + specialElementType] != 'object' )
+ GLOBALunsavedValues['design-editor'][element]['special-element-' + specialElementType] = new Object();
+
+ if ( typeof GLOBALunsavedValues['design-editor'][element]['special-element-' + specialElementType][specialElementMeta] != 'object' )
+ GLOBALunsavedValues['design-editor'][element]['special-element-' + specialElementType][specialElementMeta] = new Object();
+
+ GLOBALunsavedValues['design-editor'][element]['special-element-' + specialElementType][specialElementMeta][property] = value;
+
+ /* Change Headway.elementData as well that way other places can update before saving */
+ if ( typeof Headway.elementData != 'object' )
+ Headway.elementData = new Object();
+
+ if ( typeof Headway.elementData[element] != 'object' )
+ Headway.elementData[element] = new Object();
+
+ if ( typeof Headway.elementData[element]['special-element-' + specialElementType] != 'object' )
+ Headway.elementData[element]['special-element-' + specialElementType] = new Object();
+
+ if ( !_.isObject(Headway.elementData[element]['special-element-' + specialElementType][specialElementMeta]) || _.isArray(Headway.elementData[element]['special-element-' + specialElementType][specialElementMeta]) )
+ Headway.elementData[element]['special-element-' + specialElementType][specialElementMeta] = new Object();
+
+ Headway.elementData[element]['special-element-' + specialElementType][specialElementMeta][property] = value;
+
+ }
+
+ /* Update the properties in the tree */
+ if ( typeof designEditor != 'undefined' ) {
+
+ var elementNode = $('ul#design-editor-element-selector li.element[data-element-id="' + element + '"]');
+
+ if ( specialElementType == 'instance' ) {
+ elementNode = elementNode.filter('[data-instance-id="' + specialElementMeta + '"]');
+ } else if ( specialElementType == 'state' ) {
+ elementNode = elementNode.filter('[data-state-id="' + specialElementMeta + '"]');
+ }
+
+ designEditor.showElementPropertiesThrottled(elementNode);
+
+ }
+
+ /* Allow saving */
+ allowSaving();
+
+ return true;
+
+ }
+
+ dataPrepareDesignEditor = function() {
+
+ if ( typeof GLOBALunsavedValues != 'object' )
+ GLOBALunsavedValues = {};
+
+ if ( typeof GLOBALunsavedValues['design-editor'] != 'object' )
+ GLOBALunsavedValues['design-editor'] = {};
+
+ return GLOBALunsavedValues['design-editor'];
+
+ }
+ /* END DESIGN EDITOR DATA */
+ /* END DATA HANDLING FUNCTIONS */
+
+});
\ No newline at end of file
--- /dev/null
+define(['jquery', 'modules/iframe', 'deps/mousetrap'], function($, iframe, mousetrap) {
+
+ var Chronology = function(settings) {
+ this.settings = {
+ limit: 20,
+ call: true
+ }
+
+ /* merge settings */
+ this.set(settings)
+
+ /* initialize stacks */
+ this.clear()
+ }
+
+ // Change settings
+ Chronology.prototype.set = function(settings) {
+ for (var s in settings)
+ this.settings[s] = settings[s]
+
+ return this;
+ }
+
+ // Add occurence
+ Chronology.prototype.add = function(occurence) {
+ /* clear redo stack */
+ this.redos = [];
+
+ /* typecast occurence */
+ if (!occurence instanceof Chronology.Occurence) {
+ occurence = new Chronology.Occurence(occurence);
+ }
+
+ /* store new occurence */
+ this.undos.unshift(occurence);
+
+ /* call new current action */
+ if (occurence.call === true || (typeof occurence.call == 'undefined' && this.settings.call === true)) {
+ occurence.up();
+ }
+
+ /* trim the undos stack to length of limit */
+ if (this.settings.limit) {
+ this.undos.splice(this.settings.limit);
+ }
+
+ /* call back */
+ if (typeof this.settings.onAdd == 'function') {
+ this.settings.onAdd(occurence);
+ }
+
+ return this;
+ }
+
+ // Set the values to their initial state
+ Chronology.prototype.clear = function() {
+ /* clear arrays, retain state */
+ this.redos = [];
+ this.undos = [];
+
+ /* call back for action */
+ if (typeof this.settings.onClear == 'function') {
+ this.settings.onClear();
+ }
+
+ return this;
+ }
+
+ // Set the values to their initial state
+ Chronology.prototype.revert = function() {
+ var occurence;
+
+ /* walk back to initial state */
+ while(occurence = this.undos.shift()) {
+ occurence.down();
+ }
+
+ /* clear everything out */
+ return this.clear();
+ }
+
+ // Undo last added action
+ Chronology.prototype.undo = function() {
+ var occurence;
+
+ /* get most recent undo */
+ if (occurence = this.undos.shift()) {
+ /* move current action to redos */
+ this.redos.unshift(occurence);
+
+ /* restore to previous state */
+ occurence.down();
+
+ /* call back for action */
+ if (typeof this.settings.onUndo == 'function') {
+ this.settings.onUndo(occurence);
+ }
+
+ /* call back when reaching beginning of time */
+ if (this.undos.length == 0 && typeof this.settings.onBegin == 'function') {
+ this.settings.onBegin(occurence);
+ }
+ }
+
+ return this;
+ }
+
+ // Redo the last action
+ Chronology.prototype.redo = function() {
+ var occurence;
+
+ /* get most recent redo */
+ if (occurence = this.redos.shift()) {
+ /* move current action to undos */
+ this.undos.unshift(occurence);
+
+ /* restore to next state */
+ occurence.up();
+
+ /* call back for action */
+ if (typeof this.settings.onRedo == 'function') {
+ this.settings.onRedo(occurence);
+ }
+
+ /* call back when reaching beginning of time */
+ if (this.redos.length == 0 && typeof this.settings.onEnd == 'function') {
+ this.settings.onEnd(occurence);
+ }
+ }
+
+ return this
+ }
+
+ // Occurence class
+ Chronology.Occurence = function(states) {
+ states = states || {};
+ this.up = states.up || function() {};
+ this.down = states.down || function() {};
+ }
+
+ var history = {
+ init: function() {
+
+ Headway.history = new Chronology({limit: 0});
+
+ history.bind();
+
+ },
+
+ bind: function() {
+
+ mousetrap.bind(['ctrl+z', 'command+z'], function(event) {
+ Headway.history.undo();
+
+ /* cancel browser default */
+ return false;
+ });
+
+ mousetrap.bind(['ctrl+y', 'command+y'], function(event) {
+ Headway.history.redo();
+
+ /* cancel browser default */
+ return false;
+ });
+
+ }
+ }
+
+ return history;
+
+
+});
\ No newline at end of file
--- /dev/null
+/* NOTIFICATIONS */
+ showNotification = function(args) {
+
+ var args = $.extend({}, {
+ id: null,
+ message: null,
+ error: false,
+ success: false,
+ closeTimer: 3000,
+ closable: false,
+ closeOnEscKey: false,
+ closeCallback: function() {},
+ closeConfirmMessage: null,
+ fadeInDuration: 350,
+ timerFadeOutDuration: 1500,
+ closeFadeOutDuration: 350,
+ doNotShowAgain: false,
+ overwriteExisting: false,
+ opacity: 1
+ }, args);
+
+ /* If doNotShowAgain is true and the cookie exists, don't show the notification */
+ if ( args.doNotShowAgain && $.cookie('headway-hide-notification-' + args.id) )
+ return;
+
+ /* If notification already exists, delete it. */
+ if ( $('#notification-' + args.id).length ) {
+
+ if ( !args.overwriteExisting )
+ return $('#notification-' + args.id).fadeIn(args.fadeInDuration);
+
+ hideNotification(args.id);
+
+ }
+
+ /* Set up notification */
+ var notification = $('<div class="notification"><p>' + args.message + '</p></div>');
+
+ /* Add attributes */
+ /* ID */
+ notification.attr('id', 'notification-' + args.id);
+
+ /* Classes */
+ if ( args.error )
+ notification.addClass('notification-error');
+
+ if ( args.success )
+ notification.addClass('notification-success');
+
+ if ( args.closable )
+ notification.addClass('notification-closable');
+
+ /* Styling */
+ notification
+ .css('opacity', args.notification)
+ .hide();
+ /* End attributes */
+
+ /* Send these args to the notification's data that way callbacks, etc can be used when hide is called */
+ notification.data('notification-args', args);
+ /* Set up close button and bind it */
+ if ( args.closable ) {
+
+ var notificationCloseButton = $('<span class="close">Close</span>');
+
+ var notificationClose = function() {
+
+ if ( args.closeConfirmMessage && !confirm(args.closeConfirmMessage) )
+ return false;
+
+ hideNotification(args.id);
+
+ $(document).unbind('.notification_' + args.id);
+ $i('html').unbind('.notification_' + args.id);
+
+ }
+
+ notificationCloseButton.appendTo(notification);
+ notificationCloseButton.on('click', notificationClose);
+
+ if ( args.closeOnEscKey ) {
+
+ $(document).bind('keyup.notification_' + args.id, notificationClose);
+ $i('html').bind('keyup.notification_' + args.id, notificationClose);
+
+ }
+
+ }
+ /* End setting up close button */
+
+ /* If there's a close timer, set the timeout up */
+ if ( args.closeTimer ) {
+
+ setTimeout(function() {
+ notification.fadeOut(args.timerFadeOutDuration, function() {
+ $(this).remove();
+ });
+ }, args.closeTimer);
+
+ }
+
+ /* Move notification into notification center and make it visible */
+ notification
+ .appendTo('#notification-center')
+ .fadeIn(350);
+
+ /* All done, return the notification object */
+ return notification;
+
+ }
+
+
+ showErrorNotification = function(args) {
+
+ var args = $.extend({}, {
+ error: true,
+ closeTimer: 6000
+ }, args);
+
+ return showNotification(args);
+
+ }
+
+
+ hideNotification = function(id, fade) {
+
+ var notification = $('#notification-' + id);
+
+ if ( !notification || !notification.length )
+ return false;
+
+ var args = notification.data('notification-args');
+
+ if ( typeof args.closeCallback == 'function' )
+ args.closeCallback.apply(notification);
+
+ /* Fade or not */
+ if ( typeof fade == 'undefined' || fade ) {
+
+ notification.fadeOut(args.closeFadeOutDuration, function() {
+
+ $(this).remove();
+
+ if ( args.doNotShowAgain )
+ $.cookie('headway-hide-notification-' + args.id, true);
+
+ });
+
+ } else {
+
+ notification.remove();
+
+ if ( args.doNotShowAgain )
+ $.cookie('headway-hide-notification-' + args.id, true);
+
+ }
+
+ return notification;
+
+ }
+
+ updateNotification = function(id, content) {
+
+ var notification = $('#notification-' + id);
+
+ return notification.find('p').html(content);
+
+ }
+/* END NOTIFICATIONS */
\ No newline at end of file
--- /dev/null
+define(['modules/panel.inputs'], function(panelInputs) {
+
+ /* WRAPPER FUNCTIONS */
+ getWrapperID = function(element) {
+
+ return element.attr('id').replace('wrapper-', '');
+
+ }
+
+ openWrapperOptions = function(wrapperID) {
+
+ var wrapperID = 'wrapper-' + wrapperID;
+
+ var readyTabs = function() {
+
+ var tab = $('div#' + wrapperID + '-tab');
+
+ /* Ready tab, sliders, and inputs */
+ tab.tabs();
+ panelInputs.bind('div#' + wrapperID + '-tab');
+
+ /* Show and hide elements based on toggle options */
+ handleInputTogglesInContainer(tab.find('div.sub-tabs-content'));
+
+ /* Refresh tooltips */
+ setupTooltips();
+
+ /* Update the Grid Width Input */
+ updateGridWidthInput($('div#' + wrapperID + '-tab'));
+
+ /* If it's a mirrored wrapper, then hide the other tabs */
+ if ( $('div#' + wrapperID + '-tab').find('select[name="mirror-wrapper"]').val() ) {
+
+ $('div#' + wrapperID + '-tab ul.sub-tabs li:not(#sub-tab-config)').hide();
+ selectTab('sub-tab-config', $('div#' + wrapperID + '-tab'));
+
+ }
+
+ }
+
+ var wrapperIDForTab = wrapperID.replace('wrapper-', '');
+
+ var wrapperTabName = 'Wrapper';
+
+ if ( typeof $i('#' + wrapperID).data('alias') != 'undefined' && $i('#' + wrapperID).data('alias') )
+ wrapperTabName += ' (' + $i('#' + wrapperID).data('alias') + ')';
+
+ addPanelTab(wrapperID, wrapperTabName, {
+ url: Headway.ajaxURL,
+ data: {
+ security: Headway.security,
+ action: 'headway_visual_editor',
+ method: 'load_wrapper_options',
+ wrapper_id: wrapperID.replace('wrapper-', ''),
+ unsaved_wrapper_options: getUnsavedWrapperOptionValues(wrapperID),
+ layout: Headway.currentLayout
+ },
+ callback: readyTabs}, true, true, 'wrapper-options');
+
+ $('div#panel').tabs('option', 'active', $('#panel-top').children('li[role="tab"]').index($('[aria-controls="' + wrapperID + '-tab"]')));
+
+ }
+
+
+ getUnsavedWrapperOptionValues = function(wrapperID) {
+
+ if (
+ typeof GLOBALunsavedValues == 'object' &&
+ typeof GLOBALunsavedValues['wrappers'] == 'object' &&
+ typeof GLOBALunsavedValues['wrappers'][wrapperID] == 'object'
+ )
+ var unsavedWrapperSettings = GLOBALunsavedValues['wrappers'][wrapperID];
+
+ return (typeof unsavedWrapperSettings == 'object' && Object.keys(unsavedWrapperSettings).length > 0) ? unsavedWrapperSettings : null;
+
+ }
+
+
+ getWrapperMirror = function(wrapperID) {
+
+ return $i('div#wrapper-' + wrapperID.replace('wrapper-', '')).data('mirror-wrapper');
+
+ }
+
+
+ updateWrapperMirrorStatus = function(wrapperID, mirroredWrapperID, input) {
+
+ var wrapperID = wrapperID.replace('wrapper-', '');
+ var wrapper = $i('#wrapper-' + wrapperID);
+
+ populateWrapperMirrorNotice($i('#wrapper-' + wrapperID));
+
+ /* Update data-mirrored-wrapper and toggle the wrapper-mirrored class */
+ if ( mirroredWrapperID ) {
+
+ var mirroredWrapperID = mirroredWrapperID.replace('wrapper-', '');
+
+ wrapper.addClass('wrapper-mirrored');
+ wrapper.headwayGrid('disable');
+
+ /* Hide wrapper options */
+ if ( typeof input != 'undefined' )
+ input.parents('.panel').find('ul.sub-tabs li:not(#sub-tab-config)').hide();
+
+ /* Wrapper is not mirrored, remove class and set data-mirrored-wrapper to null */
+ } else {
+
+ wrapper.removeClass('wrapper-mirrored');
+ wrapper.headwayGrid('enable');
+
+ /* Show wrapper options */
+ if ( typeof input != 'undefined' )
+ input.parents('.panel').find('ul.sub-tabs li:not(#sub-tab-config)').show();
+
+ }
+
+ /* Recalculate wrapper height */
+ wrapper.data('ui-headwayGrid').updateGridContainerHeight();
+ wrapper.data('ui-headwayGrid').resetGridCalculations();
+ wrapper.data('ui-headwayGrid').alignAllBlocksWithGuides();
+
+ }
+ /* END WRAPPER FUNCTIONS */
+
+});
\ No newline at end of file
--- /dev/null
+define(['jquery', 'underscore', 'deps/colorpicker', 'helper.blocks'], function($, _) {
+
+ /* DESIGN EDITOR ELEMENT LOADING */
+ designEditorRequestElements = function(forceReload) {
+
+ if ( Headway.elementsRequest && (!forceReload || typeof forceReload == 'undefined') )
+ return Headway.elementsRequest;
+
+ /* Get the elements and set up bindings */
+ Headway.elementsRequest = $.post(Headway.ajaxURL, {
+ security: Headway.security,
+ action: 'headway_visual_editor',
+ method: 'get_design_editor_elements',
+ layout: Headway.currentLayout
+ }, function(elements) {
+
+ Headway.elementGroups = $.extend({}, elements.groups);
+
+ delete elements.groups;
+
+ Headway.elements = elements;
+
+ }, 'json');
+
+ return Headway.elementsRequest;
+
+ }
+
+ designEditorRequestElementData = function(forceReload) {
+
+ if ( Headway.elementDataRequest && (!forceReload || typeof forceReload == 'undefined') )
+ return Headway.elementDataRequest;
+
+ /* Get the elements and set up bindings */
+ Headway.elementDataRequest = $.post(Headway.ajaxURL, {
+ security: Headway.security,
+ action: 'headway_visual_editor',
+ method: 'get_design_editor_element_data',
+ layout: Headway.currentLayout
+ }, function(elementData) {
+
+ Headway.elementData = elementData;
+
+ }, 'json');
+
+ return Headway.elementDataRequest;
+
+ }
+ /* END DESIGN EDITOR ELEMENT LOADING */
+
+
+ /* DESIGN EDITOR TABS */
+ designEditorTabEditor = function() {
+
+ var self = this;
+
+ this._init = function() {
+
+ createCog($('#design-editor-element-selector'));
+
+ $.when(designEditorRequestElements(), designEditorRequestElementData())
+ .then(this.setupElementSelector);
+
+ this.bindElementSelector();
+
+ this.setupTabs();
+
+ this.setupBoxes();
+ this.bindDesignEditorInfo();
+
+ }
+
+ this.setupTabs = function() {
+
+ $('#side-panel-top').tabs();
+
+ }
+
+ this.setupBoxes = function() {
+
+ designEditorBindPropertyBoxToggle();
+
+ }
+
+ this.setupElementSelector = function() {
+
+ /* Load in elements */
+ $('#design-editor-element-selector').empty();
+
+ $.each(Headway.elementGroups, function(groupID, groupInfo) {
+
+ var groupNode = $('<li id="element-group-' + groupID + '" class="element-group has-children">\
+ <span class="element-group-name">' + groupInfo.name + '</span>\
+ <span class="element-expander"></span>\
+ <ul class="group-elements"></ul>\
+ </li>');
+
+ if ( typeof groupInfo.description != 'undefined' && groupInfo.description ) {
+ groupNode.find('.element-group-name').after('<small class="description">' + groupInfo.description + '</small>');
+ }
+
+ groupNode.appendTo('#design-editor-element-selector');
+
+ });
+
+ $.each(Headway.elements, designEditor.addElementToSelector);
+
+ /* Move each element to its appropriate parent */
+ $('#design-editor-element-selector li.element').each(function() {
+
+ var parentID = $(this).data('parent');
+
+ if ( !parentID )
+ return;
+
+ var parentElement = $('#design-editor-element-selector li#element-' + parentID);
+
+ /* Set parent element up to handle children */
+ if ( !parentElement.hasClass('has-children') ) {
+
+ parentElement.addClass('has-children');
+
+ parentElement.prepend('<span class="element-expander"></span>');
+ parentElement.append('<ul class="children-elements"></ul>');
+
+ }
+
+ /* Move element to its parent */
+ $(this).appendTo(parentElement.find('> ul.children-elements'));
+
+ /* If this element is customized then put the customized children flag on its parent */
+ if ( $(this).hasClass('customized-element') )
+ parentElement.addClass('had-customized-children');
+
+
+ });
+ /* End moving each element to its parent */
+
+ /* Add instances and states */
+ $('#design-editor-element-selector li.element').each(function() {
+ designEditor.addElementStates($(this));
+ designEditor.addElementInstances($(this));
+ });
+ /* End loading in elements */
+
+ /* Hide any element that's not on the page */
+ $('body').bind('headwayIframeLoad', function() {
+ designEditor.showOnlyLayoutElements();
+ });
+
+ }
+
+ this.showAllElements = function(event) {
+
+ $('#design-editor-element-selector-container').removeClass('show-only-layout-elements');
+
+ $('#design-editor-element-selector li.not-on-layout').each(function () {
+
+ $(this).show().removeClass('not-on-layout');
+
+ });
+
+ }
+
+
+ this.showOnlyLayoutElements = function() {
+
+ $('#design-editor-element-selector-container').addClass('show-only-layout-elements');
+
+ $('#design-editor-element-selector li.element').each(function () {
+
+ if ( !$(this).data('selector') )
+ return;
+
+ if ( !$i($(this).data('selector')).length && !$(this).data('state-id') ) {
+ $(this).hide().addClass('not-on-layout');
+ } else {
+ $(this).show().removeClass('not-on-layout');
+ }
+
+ });
+
+ }
+
+
+ this.bindElementSelector = function() {
+
+ var $elementSelector = $('ul#design-editor-element-selector');
+ var $deStyles = $('ul#design-editor-styles');
+
+ /* Bind the element clicks */
+ $elementSelector.on('click', designEditor.processNoElementClick);
+ $elementSelector.on('mouseenter', 'li span.element-name', designEditor.processElementMouseEnter);
+ $elementSelector.on('mouseleave', 'li span.element-name', designEditor.processElementMouseLeave);
+ $elementSelector.on('click', 'li span.element-name', designEditor.processElementClick);
+ $elementSelector.on('click', 'li span.element-expander', designEditor.processElementExpanderClick);
+ /* End binding elements */
+
+ /* Element Name Buttons */
+ $elementSelector.on('click', 'li span.element-name span.element-name-button-layout-specific', designEditor.processElementNameLayoutSpecific);
+ $elementSelector.on('click', 'li span.element-name span.element-name-button-live-css', designEditor.processElementNameLiveCSS);
+ /* End element name buttons */
+
+ /* Bind property clicks */
+ $deStyles.on('click', 'li.property .property-value', designEditor.processPropertyValueClick);
+ $deStyles.on('click', 'li.property .property-delete', designEditor.processPropertyDeleteClick);
+ /* End binding property clicks */
+
+ /* Bind Toggle */
+ $('#side-panel-collapse-arrow').on('click', toggleDesignEditor);
+
+ /* Bind Filters */
+ $('#element-selector-show-current-layout-elements').on('click', designEditor.showOnlyLayoutElements);
+ $('#element-selector-show-all-elements').on('click', designEditor.showAllElements);
+ /* End binding filters */
+
+ }
+
+
+ this.addElementToSelector = function(elementID, elementSettings) {
+
+ var elementDescription = elementSettings['description'] ? '<small class="description">' + elementSettings['description'] + '</small>' : '';
+ var elementNode = $('<li id="element-' + elementID + '" data-element-id="' + elementID + '" class="element" data-selector="' + elementSettings['selector'] + '">\
+ <span class="element-name">' + elementSettings['name'] + '</span>\
+ ' + elementDescription + '\
+ </li>');
+
+ /* Set Data */
+ elementNode.data({
+ group: elementSettings['group'],
+ parent: elementSettings['parent'],
+ selector: elementSettings['selector'],
+ id: elementID
+ });
+
+ /* Customized flag */
+ if ( elementSettings['customized'] ) {
+ elementNode.addClass('customized-element');
+ }
+
+ /* Append element to either group or parent */
+ elementNode.appendTo($('li#element-group-' + elementSettings['group'] + ' ul.group-elements'));
+
+ }
+
+
+ this.addElementInstances = function(elementNode) {
+
+ var elementID = elementNode.data('element-id');
+ var instances = designEditorGetElementObject(elementID, false).instances;
+
+ if ( _.isEmpty(instances) )
+ return false;
+
+ /* Sort instances alphabetically */
+ var instancesArray = $.map(instances, function(k, v) {
+ return [k];
+ });
+
+ instancesArray.sort(function(a, b){
+ if(a.name < b.name) return -1;
+ if(a.name > b.name) return 1;
+ return 0;
+ });
+
+ /* Add instances */
+ if ( !elementNode.hasClass('has-children') ) {
+
+ elementNode.addClass('has-children');
+ elementNode.prepend('<span class="element-expander"></span>');
+
+ elementNode.append('<ul class="children-elements"></ul>');
+
+ }
+
+ elementNode.children('.children-elements').prepend('\
+ <li id="element-' + elementID + '-instances" class="element element-instances-container has-children">\
+ <span class="element-expander"></span>\
+ <span class="element-name">Instances</span>\
+ <ul class="children-elements"></ul>\
+ </li>\
+ ');
+
+ elementNode.addClass('instances-visible');
+
+ $.each(instancesArray, function(key, instance) {
+
+ /* Build instance name */
+ var id = instance.id;
+ var instanceName = instance.name;
+
+ if ( typeof instance['state-of'] != 'undefined' && instance['state-of'] )
+ instanceName = ' -- ' + instance['state-name'];
+
+ /* Add instance to tree */
+ var instanceNode = $('<li id="element-instance-' + id + '" data-element-id="' + elementID + '" data-instance-id="' + id + '" data-selector="' + instance['selector'] + '" class="element element-instance">\
+ <span class="element-name">' + instanceName + '</span>\
+ <small class="description">' + instance['layout-name'] + '</small>\
+ </li>')
+ .appendTo(elementNode.find('> ul.children-elements > li.element-instances-container > ul.children-elements'));
+
+ /* Add instance data to node */
+ instanceNode.data({
+ selector: instance['selector']
+ });
+
+ /* Instance Customized Class */
+ if ( typeof instance['customized'] != 'undefined' && instance['customized'] )
+ instanceNode.addClass('customized-element');
+
+ });
+ /* End add instances loop */
+
+ }
+
+
+ this.addElementStates = function(elementNode) {
+
+ var elementID = elementNode.data('element-id');
+ var states = designEditorGetElementObject(elementID).states;
+
+ if ( _.isEmpty(states) )
+ return false;
+
+ /* Add states */
+ if ( !elementNode.hasClass('has-children') ) {
+
+ elementNode.addClass('has-children');
+ elementNode.prepend('<span class="element-expander"></span>');
+
+ elementNode.append('<ul class="children-elements"></ul>');
+
+ }
+
+ elementNode.children('.children-elements').prepend('\
+ <li id="element-' + elementID + '-states" class="element element-states-container has-children">\
+ <span class="element-expander"></span>\
+ <span class="element-name">States</span>\
+ <ul class="children-elements"></ul>\
+ </li>\
+ ');
+
+ elementNode.addClass('states-visible');
+
+ $.each(states, function(stateID, stateInfo) {
+
+ /* Add instance to tree */
+ var stateNode = $('<li id="element-state-' + stateID + '-for-' + elementID + '" data-element-id="' + elementID + '" data-state-id="' + stateID + '" data-selector="' + stateInfo.selector + '" class="element element-state">\
+ <span class="element-name">' + stateInfo.name + '</span>\
+ </li>')
+ .appendTo(elementNode.find('> ul.children-elements > li.element-states-container > ul.children-elements'));
+
+ /* Add instance data to node */
+ stateNode.data({
+ selector: stateInfo.selector
+ });
+
+ });
+ /* End add states loop */
+
+ }
+
+ /* Element Property Handling */
+ this.showElementProperties = function(elementNode) {
+
+ if ( typeof elementNode != 'object' )
+ var elementNode = $(this);
+
+ var elementID = elementNode.data('element-id');
+
+ /* Remove existing properties */
+ $('ul#design-editor-styles').empty().show();
+
+ /* Hide the you have nothing selected message */
+ $('.design-editor-styles-message').hide();
+
+ /* Insure that the element is customized and that there is data for it. */
+ if ( _.isEmpty(Headway.elementData[elementID]) ) {
+
+ $('ul#design-editor-styles').empty();
+
+ $('#design-editor-styles-no-styles').show();
+ $('#design-editor-styles-nothing-selected').hide();
+
+ return;
+
+ }
+
+ $('ul#design-editor-styles').prepend('<h2>' + elementNode.children('.element-name').first().text() + '</h2>');
+
+ var elementProperties = Headway.elementData[elementID];
+
+ /* Create a node that will hold the properties. We'll put it into place later that way we can insure that there are properties in it */
+ var elementPropertiesLI = $('<li class="properties"><ul></ul></li>');
+ var elementPropertiesUL = $('ul#design-editor-styles');
+
+ /* Handle regular element properties */
+ if ( !_.isEmpty(Headway.elementData[elementID]['properties']) ) {
+
+ $.each(Headway.elementData[elementID]['properties'], function(property, propertyValue) {
+ self.addElementProperty(elementPropertiesUL, property, propertyValue);
+ });
+
+ }
+
+ /* Handle special element properties */
+ var specialElementTypes = ['instance', 'state', 'layout'];
+
+ $.each(specialElementTypes, function(index, specialElementType) {
+
+ if ( !_.isEmpty(Headway.elementData[elementID]['special-element-' + specialElementType]) ) {
+
+ $.each(Headway.elementData[elementID]['special-element-' + specialElementType], function(specialElementID, specialElementProperties) {
+
+ /* Build special element name */
+ if ( specialElementType == 'layout' ) {
+
+ var specialElementName = $('#layout-selector span[data-layout-id="' + specialElementID + '"] strong').text();
+ var specialElementLayoutName = '';
+
+ } else if ( !_.isUndefined(designEditorGetElementObject(elementID, false)[specialElementType + 's'][specialElementID]) ) {
+
+ var specialElementName = designEditorGetElementObject(elementID, false)[specialElementType + 's'][specialElementID].name;
+
+ if ( typeof designEditorGetElementObject(elementID, false)[specialElementType + 's'][specialElementID]['layout-name'] != 'undefined' ) {
+ var specialElementLayoutName = ' – Layout: ' + designEditorGetElementObject(elementID, false)[specialElementType + 's'][specialElementID]['layout-name'];
+ } else {
+ var specialElementLayoutName = '';
+ }
+
+ } else {
+
+ return;
+
+ }
+
+ /* Add special element properties */
+ $.each(specialElementProperties, function(property, propertyValue) {
+ self.addElementProperty(elementPropertiesUL, property, propertyValue, {
+ type: specialElementType,
+ id: specialElementID,
+ name: specialElementName,
+ layoutName: specialElementLayoutName
+ });
+ });
+
+ });
+
+ }
+
+ });
+ /* End special element handling */
+
+ setupTooltips();
+
+ return elementPropertiesLI;
+
+ }
+
+ this.showElementPropertiesThrottled = _.throttle(this.showElementProperties, 300);
+
+ this.addElementProperty = function(context, property, propertyValue, specialElement) {
+
+ /* Do not display deleted properties */
+ if ( propertyValue == 'DELETE' )
+ return false;
+
+ if ( typeof Headway.designEditorProperties[property] == 'undefined' )
+ return false;
+
+ var formattedPropertyValue;
+ var propertyObject = Headway.designEditorProperties[property];
+ var propertyGroupID = propertyObject.group.toLowerCase().replace(' ', '-');
+
+ /* Add in group separators for the properties */
+ if ( !context.find('.property-value-group-name[data-property-group-id="' + propertyGroupID + '"]').length ) {
+ context.append('<li class="property-value-group-name" data-property-group-id="' + propertyGroupID + '">' + propertyObject.group + '</strong></li>');
+ context.append('<ul data-property-group-id="' + propertyGroupID + '"></ul>');
+ }
+
+ /* Format the property value */
+ /* Uncustomizations */
+ if ( _.isEmpty(propertyValue) ) {
+
+ formattedPropertyValue = 'Inheriting';
+
+ /* Colors */
+ } else if ( propertyObject['type'] == 'color' ) {
+
+ var colorValue = propertyValue.replace('#', '');
+
+ if ( colorValue.length == 6 )
+ colorValue = '#' + colorValue;
+
+ formattedPropertyValue = '\
+ <div class="colorpicker-box-container">\
+ <div style="background-color: ' + colorValue + '" class="colorpicker-box"></div>\
+ </div>';
+
+ if ( propertyValue.replace('#', '').toUpperCase().length == 6 )
+ formattedPropertyValue += '<span style="font-family:monospace;">#' + propertyValue.replace('#', '').toUpperCase() + '</span>';
+
+ /* Colors */
+ } else if ( propertyObject['type'] == 'image' ) {
+
+ formattedPropertyValue = '\
+ <span class="tooltip tooltip-left" title="<img src=\'' + propertyValue + '\' style=\'max-width:300px;height:auto;\' />" >Preview</span>\
+ ';
+
+ /* Integers with units */
+ } else if ( propertyObject['unit'] && propertyValue ) {
+
+ if ( typeof propertyObject['unit'] != 'object' ) {
+
+ var unitString = propertyObject['unit'];
+
+ } else {
+
+ var unitString = propertyValue.replace(/^[+-]?\d+(\.\d+)?/g, '');
+
+ if ( !unitString ) {
+
+ if ( !propertyObject['unit']['default'] ) {
+ propertyObject['unit']['default'] = 'px';
+ }
+
+ unitString = propertyObject['unit']['default'];
+
+ }
+
+ propertyValue = propertyValue.replace(unitString, '');
+
+ }
+
+ formattedPropertyValue = propertyValue + '<span class="unit">' + unitString + '</span>';
+
+ /* Font families */
+ } else if ( propertyObject['type'] == 'font-family-select' ) {
+
+ var fontFragments = propertyValue.split('|');
+ var isWebFont = (_.first(fontFragments) == 'google') ? true : false;
+
+ if ( isWebFont ) {
+ var fontName = fontFragments[1];
+ webFontQuickLoad(propertyValue);
+ } else {
+ var fontName = propertyValue;
+ }
+
+ formattedPropertyValue = '<span style="font-family:' + fontName + ';">' + fontName.capitalize() + '</span>';
+
+ /* Everything else */
+ } else if ( _.isString(propertyValue) ) {
+
+ formattedPropertyValue = propertyValue.capitalize();
+
+ }
+
+ /* Add the property value to the UL in the appropriate position */
+ /* If it's a regular element handle it like normal */
+ if ( typeof specialElement == 'undefined' ) {
+
+ var propertyNode = $('\
+ <li class="property" data-property-id="' + property + '" data-property-group-id="' + propertyGroupID + '">\
+ <strong title="' + propertyObject['name'] + '">' + propertyObject['name'] + '</strong> \
+ <span class="property-delete"></span>\
+ <span class="property-value" title="Click to Edit">' + formattedPropertyValue + '</span>\
+ </li>\
+ ');
+
+ propertyNode.appendTo(context.find('ul[data-property-group-id="' + propertyGroupID + '"]'));
+
+ /* Handle special element property values */
+ } else {
+
+ /* Insure that the property name exists... In some cases it may not if the only customizations are special elements */
+ if ( !context.find('[data-property-id="' + property + '"]:not([data-special-element-type])').length ) {
+
+ context.find('ul[data-property-group-id="' + propertyGroupID + '"]').append('\
+ <li class="property" data-property-id="' + property + '" data-property-group-id="' + propertyGroupID + '">\
+ <strong>' + propertyObject['name'] + '</strong> \
+ </li>\
+ ');
+
+ }
+
+ var propertyNode = $('\
+ <li class="property" data-property-id="' + property + '" data-property-group-id="' + propertyGroupID + '" data-special-element-type="' + specialElement.type + '" data-special-element-id="' + specialElement.id + '">\
+ <strong title="' + specialElement.name.split(' – ')[0] + specialElement.layoutName + '">' + specialElement.name.split(' – ')[0] + '</strong> \
+ <span class="property-delete"></span>\
+ <span class="property-value" title="Click to Edit">' + formattedPropertyValue + '</span>\
+ </li>\
+ ');
+
+ /* Add class to the regular element property to say that there are special elements that way we can adjust the border */
+ context.find('[data-property-id="' + property + '"]').not('[data-special-element-type]').last().addClass('has-special-element-properties');
+
+ propertyNode.insertAfter(context.find('[data-property-id="' + property + '"]').last());
+
+ }
+ /* End adding property values */
+
+ }
+
+ this.processPropertyValueClick = function() {
+
+ var elementNode = $('ul#design-editor-element-selector li.ui-state-active').first();
+ var elementID = elementNode.data('element-id');
+
+ var propertyNode = $(this).parents('li.property').first();
+ var specialElementType = propertyNode.data('special-element-type');
+ var specialElementID = propertyNode.data('special-element-id');
+
+ /* Open element */
+ if ( _.isEmpty(specialElementType) ) {
+ return elementNode.children('span.element-name').trigger('click', [propertyNode.data('property-group-id')]);
+ } else {
+ return designEditor.selectSpecialElement(elementID, specialElementType, specialElementID, propertyNode.data('property-group-id'));
+ }
+
+ }
+
+ this.processPropertyDeleteClick = function() {
+
+ var elementNode = $('ul#design-editor-element-selector li.ui-state-active').first();
+ var elementObj = designEditorGetElementObject(elementNode.data('element-id'), false);
+
+ var propertyNode = $(this).parents('li.property').first();
+ var propertyID = propertyNode.data('property-id');
+
+ var specialElementType = propertyNode.data('special-element-type');
+ var specialElementID = propertyNode.data('special-element-id');
+
+ /* Remove styling */
+ if ( _.isEmpty(specialElementType) ) {
+
+ var selector = elementObj.selector;
+
+ } else if ( specialElementType == 'layout' ) {
+
+ var selector = ('body.layout-using-' + specialElementID + ' ' + elementObj.selector).replace(' body', '');
+
+ } else {
+
+ var selector = elementObj[specialElementType + 's'][specialElementID].selector;
+
+
+ }
+
+ stylesheet.delete_rule_property(selector, propertyID);
+
+ /* Remove property node */
+ propertyNode.remove();
+
+ /* If properties are empty for an element then delete the properties */
+ if ( !elementNode.find('> .children-elements > .properties ul li').length ) {
+
+ elementNode.find('> .children-elements > .properties').remove();
+ elementNode.removeClass('properties-visible');
+
+ /* If there are no children elements then delete that as well */
+ if ( !elementNode.find('> .children-elements li').length ) {
+
+ elementNode.find('> .children-elements, > .element-expander').remove();
+
+ elementNode
+ .removeClass('has-children')
+ .removeClass('children-visible');
+
+ }
+
+ }
+
+ /* Queue it for saving */
+ dataSetDesignEditorProperty({
+ element: elementObj.id,
+ property: propertyID,
+ value: 'DELETE',
+ specialElementType: specialElementType,
+ specialElementMeta: specialElementID
+ });
+
+ }
+ /* End Element Property Handling */
+
+ this.processNoElementClick = function(event) {
+
+ /* If clicking an element, don't fire this */
+ if ( $(event.target).is('span') )
+ return;
+
+ $('body').removeClass('design-editor-element-selected');
+
+ $('ul#design-editor-element-selector').find('.ui-state-active')
+ .addClass('element-just-selected')
+ .removeClass('ui-state-active');
+
+ removeInspectorVisibleBoxModal();
+ setSelectedElement({});
+
+ $i('.inspector-element-selected').removeClass('inspector-element-selected');
+
+ /* Reset the styles tab */
+ $('#design-editor-styles-no-styles').hide();
+ $('#design-editor-styles-nothing-selected').show();
+ $('ul#design-editor-styles').empty().hide();
+
+ }
+
+ this.processElementExpanderClick = function(event) {
+ $(this).parent().toggleClass('children-visible');
+ }
+
+ this.processElementMouseEnter = function(event) {
+
+ var link = $(this).parent();
+
+ if ( link.hasClass('element-group') || link.hasClass('element-instances-container') || link.hasClass('element-states-container') )
+ return;
+
+ var elementID = link.data('element-id');
+ var elementObject = designEditorGetElementObject(elementID, false);
+
+ /* Remove .element-just-selected */
+ $('.element-just-selected').removeClass('element-just-selected');
+
+ /* Highlight [special] element in iframe */
+ $i('.inspector-element-hover').removeClass('inspector-element-hover');
+ $i(link.data('selector')).addClass('inspector-element-hover');
+
+ /* Add buttons on demand that way DOM doesn't get super clogged */
+ if ( !link.hasClass('element-name-has-buttons') ) {
+
+ var elementName = link.children('.element-name');
+
+ /* Instances, States, and Layout-specific button should not show on instances or states */
+ if ( !link.hasClass('element-instance') && !link.hasClass('element-state') ) {
+
+ /* Layout-specific */
+ elementName.append('<span class="element-name-button element-name-button-layout-specific tooltip" title="Edit Element Only On This Layout"></span>');
+
+ }
+
+ /* Live CSS */
+ elementName.append('<span class="element-name-button element-name-button-live-css tooltip" title="Edit in Live CSS"></span>');
+
+ elementName.find('.tooltip').qtip({
+ style: {
+ classes: 'qtip-headway qtip-headway-element-selector',
+ tip: false
+ },
+ position: {
+ my: 'bottom left',
+ at: 'top center',
+ viewport: $(window),
+ adjust: {
+ y: -5,
+ method: 'flipinvert'
+ }
+ },
+ });
+
+ link.addClass('element-name-has-buttons');
+
+ }
+
+ }
+
+ this.processElementMouseLeave = function(event) {
+
+ var link = $(this).parent();
+
+ if ( link.hasClass('element-group') || link.hasClass('ui-state-active') || link.hasClass('element-instances-container') )
+ return;
+
+ var element = link.data('element-id');
+ var elementObject = designEditorGetElementObject(element);
+
+ /* Unhighlight element in iframe */
+ $i(link.data('selector')).removeClass('inspector-element-hover');
+
+ /* Remove buttons */
+ link.children('.element-name').find('.element-name-button').each(function() {
+ $(this).qtip('api').destroy(true);
+ $(this).remove();
+ });
+
+ link.removeClass('element-name-has-buttons');
+
+ }
+
+ this.processElementClick = function(event, propertyGroup) {
+
+ var link = $(this).parent();
+
+ /* Do not fire element click event if an element name button is clicked */
+ if ( $(event.target).hasClass('element-name-button') || link.hasClass('element-instances-container') )
+ return;
+
+ if ( link.hasClass('element-group') )
+ return;
+
+ if ( link.hasClass('element-instance') )
+ return designEditor.selectSpecialElement(link.data('element-id'), 'instance', link.data('instance-id'), propertyGroup);
+
+ if ( link.hasClass('element-state') )
+ return designEditor.selectSpecialElement(link.data('element-id'), 'state', link.data('state-id'), propertyGroup);
+
+ /* Set up variables */
+ var elementName = getElementNodeName(link); /* Element Name */
+ var element = link.data('element-id');
+ var elementObject = designEditorGetElementObject(element, false);
+
+ /* Add class to body to insure side panel is split and property inputs are showing */
+ $('body').addClass('design-editor-element-selected');
+
+ /* If element has children, then expand it */
+ if ( link.hasClass('has-children') )
+ link.addClass('children-visible');
+
+ /* Expand elements parents */
+ $(this).parents('li.has-children').addClass('children-visible');
+
+ /* Scroll to element in element selector */
+ $('div#design-editor-element-selector-container').animate({scrollTop: link.offset().top - (150 - $('div#design-editor-element-selector-container').scrollTop())}, 300);
+
+ /* Reset regular element/element for layout buttons */
+ $('div.design-editor-info span.customize-for-regular-element').hide();
+ $('div.design-editor-info span.customize-element-for-layout').show();
+
+ /* Highlight element in iframe */
+ inspectorSelectElement(elementObject.selector);
+
+ /* Update DE info text */
+ setSelectedElement({
+ id: element,
+ name: elementName,
+ object: elementObject
+ });
+
+ /* LOAD INPUTS */
+ designEditorShowCog();
+
+ $.when(
+ designEditor.loadElementInputs(element)
+ ).then(function() {
+ designEditorShowContent(propertyGroup);
+ });
+ /* END LOAD INPUTS */
+
+ $('ul#design-editor-element-selector').find('.ui-state-active').removeClass('ui-state-active');
+ link.addClass('ui-state-active');
+
+ /* Load properties */
+ designEditor.showElementProperties(link);
+
+ }
+
+ this.processElementNameLayoutSpecific = function() {
+
+ var elementNode = $(this).parents('li.element').first();
+ var elementID = elementNode.data('element-id');
+
+ designEditor.selectSpecialElement(elementID, 'layout', Headway.currentLayout);
+
+ }
+
+ this.processElementNameLiveCSS = function() {
+
+ var elementNode = $(this).parents('li.element').first();
+ var elementSelector = elementNode.data('selector');
+
+ var liveCSSValue = ( typeof liveCSSEditor == 'undefined' || !liveCSSEditor ) ? $('textarea#live-css').val() : liveCSSEditor.getValue();
+
+ var linesBefore = liveCSSValue ? "\n\n" : '';
+ $('textarea#live-css').val(liveCSSValue + linesBefore + elementSelector + " {\n\n}");
+
+ /* Open Live CSS Editor */
+ $('#open-live-css').trigger('click');
+
+ /* Move the cursor to the new selector */
+ if ( typeof liveCSSEditor != 'undefined' ) {
+
+ liveCSSEditor.setValue($('textarea#live-css').val());
+
+ var lastLine = liveCSSEditor.session.getLength();
+ liveCSSEditor.gotoLine(lastLine - 1);
+ liveCSSEditor.focus();
+
+ }
+
+ }
+
+ this.processElementCopy = function(event) {
+
+ var currentElement = getSelectedElement();
+
+ if ( !currentElement )
+ return;
+
+ var currentElementName = (typeof currentElement.specialElementName != 'undefined') ? currentElement.specialElementName : currentElement.name;
+
+ /* Get data */
+ if ( !_.isEmpty(Headway.elementData[currentElement.id]) ) {
+
+ /* If it's a special element then we need to pull properties from there */
+ if ( currentElement.specialElementType && !_.isEmpty(Headway.elementData[currentElement.id]['special-element-' + currentElement.specialElementType]) ) {
+
+ if ( !_.isEmpty(Headway.elementData[currentElement.id]['special-element-' + currentElement.specialElementType][currentElement.specialElementID]) )
+ var elementData = Headway.elementData[currentElement.id]['special-element-' + currentElement.specialElementType][currentElement.specialElementID];
+
+ /* Otherwise looks in 'properties' for the regular elements */
+ } else if ( !_.isEmpty(Headway.elementData[currentElement.id]['properties']) ) {
+
+ var elementData = Headway.elementData[currentElement.id]['properties'];
+
+ }
+
+ }
+
+ if ( typeof elementData == 'undefined' || _.isEmpty(elementData) )
+ return false;
+
+ showNotification({
+ id: 'copied-design-properties',
+ message: 'Copied properties from <strong>' + currentElementName + '</strong>',
+ closeTimer: 2000,
+ overwriteExisting: true
+ });
+
+ Headway.designEditorClipboard = $.extend({}, elementData);
+
+ }
+
+ this.processElementPaste = function(event) {
+
+ var currentElement = getSelectedElement();
+
+ if ( !currentElement || typeof Headway.designEditorClipboard == 'undefined' )
+ return;
+
+ var currentElementName = (typeof currentElement.specialElementName != 'undefined') ? currentElement.specialElementName : currentElement.name;
+
+ /* Pull existing data that way we can modify it */
+ if ( !_.isEmpty(Headway.elementData[currentElement.id]) ) {
+
+ if ( currentElement.specialElementType && !_.isEmpty(Headway.elementData[currentElement.id]['special-element-' + currentElement.specialElementType]) ) {
+
+ if ( !_.isEmpty(Headway.elementData[currentElement.id]['special-element-' + currentElement.specialElementType][currentElement.specialElementID]) )
+ var elementData = Headway.elementData[currentElement.id]['special-element-' + currentElement.specialElementType][currentElement.specialElementID];
+
+ } else if ( !_.isEmpty(Headway.elementData[currentElement.id]['properties']) ) {
+
+ var elementData = Headway.elementData[currentElement.id]['properties'];
+
+ }
+
+ }
+
+ if ( typeof elementData == 'undefined' )
+ var elementData = {};
+
+ /* Go through existing data and set EVERYTHING to delete first */
+ $.each(elementData, function(property, value) {
+
+ dataSetDesignEditorProperty({
+ element: currentElement.id,
+ property: property,
+ value: 'DELETE',
+ specialElementType: currentElement.specialElementType,
+ specialElementMeta: currentElement.specialElementID
+ });
+
+ });
+
+ /* Merge in the pasted data */
+ $.each(Headway.designEditorClipboard, function(property, value) {
+
+ if ( typeof Headway.designEditorProperties[property]['unit'] != 'undefined' && !isNaN(value) ) {
+
+ if ( typeof Headway.designEditorProperties[property]['unit'] == 'string' ) {
+
+ value = value + Headway.designEditorProperties[property]['unit'];
+
+ } else if ( typeof Headway.designEditorProperties[property]['unit']['default'] != 'undefined' ) {
+
+ value = value + Headway.designEditorProperties[property]['unit']['default'];
+
+ }
+
+ }
+
+ dataSetDesignEditorProperty({
+ element: currentElement.id,
+ property: property,
+ value: value,
+ specialElementType: currentElement.specialElementType,
+ specialElementMeta: currentElement.specialElementID
+ });
+
+ });
+
+ /* Now loop through the element data and update it in the iframe */
+ if ( currentElement.specialElementType ) {
+ var elementData = Headway.elementData[currentElement.id]['special-element-' + currentElement.specialElementType][currentElement.specialElementID];
+ } else {
+ var elementData = Headway.elementData[currentElement.id]['properties'];
+ }
+
+ $.each(elementData, function(property, value) {
+
+ dataDesignEditorPropertyFeedback({
+ element: currentElement.id,
+ property: property,
+ value: value,
+ specialElementType: currentElement.specialElementType,
+ specialElementMeta: currentElement.specialElementID
+ });
+
+ });
+
+ showNotification({
+ id: 'copied-design-properties',
+ message: 'Pasted properties onto <strong>' + currentElementName + '</strong>',
+ closeTimer: 2000,
+ overwriteExisting: true,
+ success: true
+ });
+
+
+ }
+
+ this.loadElementInputs = function(element, specialElementInfo) {
+
+ var ajaxArgs = {
+ security: Headway.security,
+ action: 'headway_visual_editor',
+ method: 'get_element_inputs',
+ unsavedValues: designEditorGetUnsavedValues(element),
+ element: designEditorGetElementObject(element)
+ };
+
+ if ( typeof specialElementInfo == 'object' ) {
+
+ var specialElementType = Object.keys(specialElementInfo)[0];
+ var specialElementMeta = specialElementInfo[specialElementType];
+
+ ajaxArgs['specialElementType'] = specialElementType;
+ ajaxArgs['specialElementMeta'] = specialElementMeta;
+ ajaxArgs['unsavedValues'] = designEditorGetUnsavedValues(element, specialElementType, specialElementMeta);
+
+ /* If special element type is instance we need to be sure that the instance is included in the element payload that way the instance info can be pulled when displaying the property inputs */
+ if ( specialElementType == 'instance' )
+ ajaxArgs['element'] = designEditorGetElementObject(element, true, specialElementMeta)
+
+ }
+
+ return $.post(Headway.ajaxURL, ajaxArgs).success(function(inputs) {
+
+ var options = $('div.design-editor-options');
+
+ options.html(inputs);
+
+ /* Set the flags */
+ $('div.design-editor-options').data({
+ 'element': element,
+ 'specialElementType': false,
+ 'specialElementMeta': false
+ });
+
+ /* Load web fonts */
+ $('div.design-editor-options').find('.property-font-family-select').each(function() {
+ webFontQuickLoad($(this).find('span.font-name').data('webfont-value'));
+ });
+
+ /* Focus the iframe to allow immediate nudging control */
+ Headway.iframe.focus();
+
+ });
+
+ }
+
+
+ this.bindDesignEditorInfo = function() {
+
+ /* Customize for layout button */
+ $('span.customize-element-for-layout').bind('click', function() {
+
+ var currentElement = designEditor.getCurrentElement();
+ var currentElementID = currentElement.data('element-id');
+
+ designEditor.selectSpecialElement(currentElementID, 'layout', Headway.currentLayout);
+
+ });
+
+ /* Customize for regular element button */
+ $('span.customize-for-regular-element').bind('click', function() {
+ designEditor.getCurrentElement().find('> span.element-name').trigger('click');
+ });
+
+ }
+
+ this.selectSpecialElement = function(elementID, specialElementType, specialElementID, propertyGroup) {
+
+ var elementNode = $('ul#design-editor-element-selector li.element-' + specialElementType)
+ .filter('[data-' + specialElementType + '-id="' + specialElementID + '"]')
+ .filter('[data-element-id="' + elementID + '"]');
+
+ /* If the special element node isn't present then we'll use the regular element node */
+ if ( !elementNode.length )
+ elementNode = $('ul#design-editor-element-selector li.element[data-element-id="' + elementID + '"]').first();
+
+ var elementObject = designEditorGetElementObject(elementID, false);
+ var specialElementName = (specialElementType != 'layout') ? elementObject[specialElementType + 's'][specialElementID].name : Headway.currentLayoutName;
+ var elementSelector = (specialElementType != 'layout') ? elementObject[specialElementType + 's'][specialElementID].selector : elementObject.selector;
+
+ /* Add class to body to insure side panel is split and property inputs are showing */
+ $('body').addClass('design-editor-element-selected');
+
+ /* Expand elements parents */
+ elementNode.parents('li').addClass('children-visible');
+
+ /* Scroll to element in element selector */
+ $('div#design-editor-element-selector-container').animate({scrollTop: elementNode.offset().top - ($('div#design-editor-element-selector-container').height()/1.5 - $('div#design-editor-element-selector-container').scrollTop())}, 300);
+
+ /* Load styles */
+ designEditor.showElementProperties(elementNode);
+
+ /* Reset regular element/element for layout buttons */
+ if ( specialElementType == 'layout' ) {
+
+ $('div.design-editor-info span.customize-for-regular-element').show();
+ $('div.design-editor-info span.customize-element-for-layout').hide();
+
+ } else {
+
+ $('div.design-editor-info span.customize-for-regular-element').hide();
+ $('div.design-editor-info span.customize-element-for-layout').hide();
+
+ }
+
+ /* Highlight element in iframe */
+ inspectorSelectElement(elementSelector);
+
+ /* Args for DE info and inputs */
+ var argsForConditionals = {};
+ var argsForInputs = {};
+
+ argsForConditionals[specialElementType] = specialElementName;
+ argsForInputs[specialElementType] = specialElementID;
+
+ /* Update DE info */
+ setSelectedElement({
+ id: elementID,
+ selector: elementSelector,
+ name: elementObject.name,
+ specialElementType: specialElementType,
+ specialElementID: specialElementID,
+ specialElementName: specialElementName,
+ object: elementObject
+ });
+
+ /* LOAD INPUTS */
+ if ( typeof loadInputs == 'undefined' || loadInputs ) {
+
+ designEditorShowCog();
+
+ $.when(
+ designEditor.loadElementInputs(elementID, argsForInputs)
+ ).then(function() {
+ designEditorShowContent(propertyGroup);
+ });
+
+ }
+ /* END LOAD INPUTS */
+
+ $('ul#design-editor-element-selector').find('.ui-state-active').removeClass('ui-state-active');
+ elementNode.addClass('ui-state-active');
+
+ }
+
+ this.getCurrentElement = function() {
+
+ return $('ul#design-editor-element-selector li.ui-state-active');
+
+ }
+
+ this.switchLayout = function() {
+
+ /* Make sure this doesn't fire on initial load */
+ if ( typeof Headway.switchedToLayout == 'undefined' || !Headway.switchedToLayout )
+ return;
+
+ $.when(designEditorRequestElements(true)).then(function() {
+ designEditor.setupElementSelector.apply(designEditor);
+
+ $('div.design-editor-options').hide();
+ });
+
+ }
+
+ }
+ /* END DESIGN EDITOR TABS */
+
+
+ /* DESIGN EDITOR CONTAINER */
+ toggleDesignEditor = function() {
+
+ if ( $('body').hasClass('side-panel-hidden') )
+ return showDesignEditor();
+
+ return hideDesignEditor();
+
+ }
+
+
+ hideDesignEditor = function() {
+
+ //If the panel is already hidden, don't go through any trouble.
+ if ( $('body').hasClass('side-panel-hidden') )
+ return false;
+
+ $('body').addClass('side-panel-hidden');
+
+ setTimeout(repositionTooltips, 400);
+
+ /* Change arrow to pointing left arrow */
+ $('#design-editor-toggle span').text('eee');
+
+ $.cookie('hide-design-editor', true);
+
+ return true;
+
+ }
+
+
+ showDesignEditor = function() {
+
+ //If the panel is already visible, don't go through any trouble.
+ if ( !$('body').hasClass('side-panel-hidden') )
+ return false;
+
+ $('body').removeClass('side-panel-hidden');
+
+ setTimeout(repositionTooltips, 400);
+
+ /* Change arrow to pointing right arrow */
+ $('#design-editor-toggle span').text('iii');
+
+ $.cookie('hide-design-editor', false);
+
+ return true;
+
+ }
+
+ /* END DESIGN EDITOR CONTAINER */
+
+
+ /* CONTENT TOGGLING */
+ designEditorShowCog = function() {
+
+ $('div#side-panel').addClass('properties-loading');
+
+ $('div.design-editor-info').hide();
+ $('div.design-editor-options').hide();
+
+ createCog($('div#side-panel-bottom'), true, true);
+
+ }
+
+ designEditorShowContent = function(propertyGroup) {
+
+ /* Show info/options and hide cog/instructions */
+ $('div#side-panel-bottom')
+ .find('.cog-container').remove();
+
+ $('div.design-editor-info').show();
+ $('div.design-editor-options').show();
+
+ $('div#side-panel').removeClass('properties-loading');
+
+ /* If propertyGroup is present then automatically open that property group */
+ if ( !_.isEmpty(propertyGroup) )
+ $('.design-editor-box-' + propertyGroup).find('.design-editor-box-title').trigger('click');
+
+ /* Refresh Tooltips */
+ setupTooltips();
+
+ }
+ /* END CONTENT TOGGLING */
+
+
+ /* DESIGN EDITOR OPTIONS/INPUTS */
+ designEditorGetElementObject = function(element, excludeInstances, instanceToKeep) {
+
+ var elementNode = $('ul#design-editor-element-selector').find('#element-' + element);
+ var elementGroup = elementNode.data('group');
+ var elementParent = elementNode.data('parent');
+
+ if ( typeof excludeInstances == 'undefined' )
+ var excludeInstances = true;
+
+ var element = jQuery.extend(true, {}, Headway.elements[element]);
+
+ /* Delete instances if set to do so */
+ if ( excludeInstances ) {
+
+ if ( typeof instanceToKeep != 'undefined' && instanceToKeep ) {
+
+ $.each(element.instances, function(instanceID, instanceOptions) {
+
+ if ( instanceID != instanceToKeep )
+ delete element.instances[instanceID];
+
+ });
+
+ } else {
+
+ delete element.instances;
+
+ }
+
+ }
+
+ return element;
+
+ }
+
+ designEditorGetUnsavedValues = function(element, specialElementType, specialElementMeta) {
+
+ if ( typeof specialElementType == 'undefined' )
+ var specialElementType = false;
+
+ if ( typeof specialElementMeta == 'undefined' )
+ var specialElementMeta = false;
+
+ if (
+ typeof GLOBALunsavedValues == 'undefined' ||
+ typeof GLOBALunsavedValues['design-editor'] == 'undefined' ||
+ typeof GLOBALunsavedValues['design-editor'][element] == 'undefined'
+ )
+ return null;
+
+ if ( !specialElementType || !specialElementMeta ) {
+
+ if ( typeof GLOBALunsavedValues['design-editor'][element]['properties'] == 'undefined' )
+ return null;
+
+ var properties = GLOBALunsavedValues['design-editor'][element]['properties'];
+
+ } else {
+
+ if ( typeof GLOBALunsavedValues['design-editor'][element]['special-element-' + specialElementType] == 'undefined' )
+ return null;
+
+ if ( typeof GLOBALunsavedValues['design-editor'][element]['special-element-' + specialElementType][specialElementMeta] == 'undefined' )
+ return null;
+
+ var properties = GLOBALunsavedValues['design-editor'][element]['special-element-' + specialElementType][specialElementMeta];
+
+ }
+
+ return !_.isEmpty(properties) ? properties : null;
+
+ }
+
+ designEditorBindPropertyBoxToggle = function() {
+
+ $('div.design-editor-options').delegate('span.design-editor-box-title', 'click', function() {
+
+ var box = $(this).parents('div.design-editor-box');
+
+ /* Check if box was already open */
+ var boxOpen = box.hasClass('design-editor-box-open');
+
+ /* Close all other boxes */
+ $('div.design-editor-options div.design-editor-box-open').removeClass('design-editor-box-open');
+
+ /* If selected box does not have open class, then add it. Otherwise the above line will close all boxes including it so it will act as a toggle */
+ if ( !box.hasClass('design-editor-box-open') && !boxOpen )
+ box.addClass('design-editor-box-open');
+
+ });
+
+ }
+
+ designEditorBindPropertyInputs = function() {
+
+ /* Customize Buttons */
+ $('.design-editor-options-container').delegate('div.customize-property', 'click', function() {
+
+ var property = $(this).parents('li').first();
+
+ if ( property.hasClass('lockable-property') && property.parents('.box-model-inputs').hasClass('box-model-inputs-locked') )
+ var property = $(this).parents('.box-model-inputs').find('> li.lockable-property');
+
+ property.each(function() {
+
+ $(this).find('.customize-property').fadeOut(150);
+ $(this).removeClass('uncustomized-property');
+ $(this).addClass('customized-property-by-user');
+ $(this).attr('title', 'You have customized this property.');
+
+ var hidden = $(this).find('input.property-hidden-input');
+
+ /* When clicking on Customize on a property that uses a select, sometimes the first option in the select is what you want.
+ This will fill the hidden input with it */
+ var siblingInput = hidden.parent().find('select, input:not(.property-hidden-input)').first();
+
+ if ( !hidden.val() && siblingInput.length )
+ hidden.val(siblingInput.val());
+
+ dataHandleDesignEditorInput({hiddenInput: hidden, value: hidden.val()});
+
+ });
+
+ });
+
+ /* Uncustomize Button */
+ $('.design-editor-options-container').delegate('span.uncustomize-property', 'click', function() {
+
+ if ( !confirm('Are you sure you wish to delete this customization?') )
+ return false;
+
+ var property = $(this).parents('li').first();
+
+ if ( property.hasClass('lockable-property') && property.parents('.box-model-inputs').hasClass('box-model-inputs-locked') )
+ var property = $(this).parents('.box-model-inputs').find('> li.lockable-property');
+
+ property.each(function() {
+
+ var hidden = $(this).find('input.property-hidden-input');
+
+ $(this).find('div.customize-property').fadeIn(150);
+
+ dataHandleDesignEditorInput({hiddenInput: hidden, value: 'DELETE', unit: ''});
+
+ $(this).addClass('uncustomized-property', 150);
+ $(this).removeClass('customized-property-by-user');
+ $(this).attr('title', 'You have set this property to inherit.');
+
+ });
+
+ });
+
+ /* Fonts */
+ $('.design-editor-options-container').delegate('.design-editor-property-font-family span.open-font-browser', 'click', function() {
+ /* Using anonymous function because fontBrowserOpen won't be defined yet since it's loaded via $.getScript() */
+ if ( typeof fontBrowserOpen == 'function' )
+ fontBrowserOpen.apply(this);
+ });
+
+ /* Lock Sides */
+ $('.design-editor-options-container').delegate('span.design-editor-lock-sides', 'click', function() {
+
+ if ( $(this).parent().hasClass('box-model-inputs-locked') ) {
+
+ $(this)
+ .attr('data-locked', false)
+ .attr('title', 'Unlock sides')
+ .parent().removeClass('box-model-inputs-locked');
+
+ } else {
+
+ $(this)
+ .attr('data-locked', true)
+ .attr('title', 'Lock sides')
+ .parent().addClass('box-model-inputs-locked');
+
+ }
+
+ });
+
+ $('.design-editor-options-container').delegate('.box-model-inputs-locked li.lockable-property input[type="number"]', 'keyup blur change', function(event, preventRecurse) {
+
+ if ( typeof preventRecurse != 'undefined' && preventRecurse )
+ return;
+
+ $(this).parents('.box-model-inputs-locked').find('.lockable-property')
+ .removeClass('uncustomized-property');
+
+ $(this).parents('.box-model-inputs-locked').find('li.lockable-property input[type="number"]')
+ .not($(this))
+ .val($(this).val())
+ .trigger('change', [true]);
+
+ });
+
+ $('.design-editor-options-container').delegate('.box-model-inputs-locked li.lockable-property select', 'change', function (event, preventRecurse) {
+
+ if ( typeof preventRecurse != 'undefined' && preventRecurse )
+ return;
+
+ $(this).parents('.box-model-inputs-locked').find('.lockable-property')
+ .removeClass('uncustomized-property');
+
+ $(this).parents('.box-model-inputs-locked').find('li.lockable-property select')
+ .not($(this))
+ .val($(this).val())
+ .trigger('change', [true]);
+
+ });
+
+ /* Select */
+ $('.design-editor-options-container').delegate('div.property-select select', 'change', designEditorInputSelect);
+
+ /* Integer */
+ $('.design-editor-options-container').delegate('div.property-integer input', 'focus', designEditorInputIntegerFocus);
+
+ $('.design-editor-options-container').delegate('div.property-integer input', 'keyup blur change', designEditorInputIntegerChange);
+ $('.design-editor-options-container').delegate('div.property-integer .property-unit-select select', 'change', designEditorInputIntegerUnitChange);
+
+ /* Image Uploaders */
+ $('.design-editor-options-container').delegate('div.property-image span.button', 'click', designEditorInputImageUpload);
+
+ $('.design-editor-options-container').delegate('div.property-image span.delete-image', 'click', designEditorInputImageUploadDelete);
+
+ /* Color Inputs */
+ $('.design-editor-options-container').delegate('div.property-color div.colorpicker-box', 'click', designEditorInputColor);
+
+ }
+ /* END DESIGN EDITOR INPUTS */
+
+
+ /* INPUT FUNCTIONALITY */
+ /* Select */
+ designEditorInputSelect = function(event) {
+
+ var hidden = $(this).parent().siblings('input.property-hidden-input');
+
+ dataHandleDesignEditorInput({hiddenInput: hidden, value: $(this).val()});
+
+ }
+
+
+ /* Integer */
+ designEditorInputIntegerFocus = function(event) {
+
+ if ( typeof originalValues !== 'undefined' ) {
+ delete originalValues;
+ }
+
+ originalValues = new Object;
+
+ var hidden = $(this).siblings('input.property-hidden-input');
+ var id = hidden.attr('selector') + '-' + hidden.attr('property');
+
+ originalValues[id] = $(this).val();
+
+ }
+
+ designEditorInputIntegerUnitChange = function (event) {
+
+ $(this).parents('.property-integer').find('input[type="number"]').trigger('change');
+
+ }
+
+ designEditorInputIntegerChange = function(event) {
+
+ var hidden = $(this).siblings('input.property-hidden-input');
+ var value = $(this).val();
+
+ if ( event.type == 'keyup' && value == '-' )
+ return;
+
+ /* Validate the value and make sure it's a number */
+ if ( isNaN(value) ) {
+
+ /* Take the nasties out to make sure it's a number */
+ value = value.replace(/[^0-9]*/ig, '');
+
+ /* If the value is an empty string, then revert back to the original value */
+ if ( value === '' ) {
+
+ var id = hidden.attr('selector') + '-' + hidden.attr('property');
+ var value = originalValues[id];
+
+ }
+
+ /* Set the value of the input to the sanitized value */
+ $(this).val(value);
+
+ }
+
+ /* Remove leading zeroes */
+ if ( value.length > 1 && value[0] == 0 ) {
+
+ value = value.replace(/^[0]+/g, '');
+
+ /* Set the value of the input to the sanitized value */
+ $(this).val(value);
+
+ }
+
+ dataHandleDesignEditorInput({hiddenInput: hidden, value: $(this).val()});
+
+ }
+
+ /* Image Uploaders */
+ designEditorInputImageUpload = function(event) {
+
+ var self = this;
+
+ openImageUploader(function(url, filename) {
+
+ var hidden = $(self).siblings('input');
+
+ $(self).siblings('.image-input-controls-container').find('span.src').text(filename);
+ $(self).siblings('.image-input-controls-container').show();
+
+ dataHandleDesignEditorInput({hiddenInput: hidden, value: url});
+
+ });
+
+ }
+
+ designEditorInputImageUploadDelete = function(event) {
+
+ if ( !confirm('Are you sure you wish to remove this image?') ) {
+ return false;
+ }
+
+ $(this).parent('.image-input-controls-container').hide();
+ $(this).hide();
+
+ var hidden = $(this).parent().siblings('input');
+
+ dataHandleDesignEditorInput({hiddenInput: hidden, value: 'none'});
+
+ }
+
+ /* Color Inputs */
+ designEditorInputColor = function(event) {
+
+ /* Keep the design editor options container from scrolling */
+ $('div.design-editor-options-container').css('overflow-y', 'hidden');
+
+ /* Set up variables */
+ var input = $(this).parent().siblings('input');
+ var inputVal = input.val();
+
+ if ( inputVal == 'transparent' )
+ inputVal = '00FFFFFF';
+
+ var colorpickerHandleVal = function(color, inst) {
+
+ var colorValue = '#' + color.hex;
+
+ /* If alpha ISN'T 100% then use RGBa */
+ if ( color.a != 100 )
+ var colorValue = color.rgba;
+
+ dataHandleDesignEditorInput({hiddenInput: input, value: colorValue});
+
+ }
+
+ $(this).colorpicker({
+ realtime: true,
+ alpha: true,
+ alphaHex: true,
+ allowNull: false,
+ showAnim: false,
+ swatches: (typeof Headway.colorpickerSwatches == 'object' && Headway.colorpickerSwatches.length) ? Headway.colorpickerSwatches : true,
+ color: inputVal,
+ beforeShow: function(input, inst) {
+
+ /* Add iframe overlay */
+ showIframeOverlay();
+
+ },
+ onClose: function(color, inst) {
+
+ colorpickerHandleVal(color, inst);
+
+ /* Hide iframe overlay */
+ hideIframeOverlay();
+
+ /* Allow design editor options container to scroll again */
+ $('div.design-editor-options-container').css('overflow-y', 'auto');
+
+ },
+ onSelect: function(color, inst) {
+
+ colorpickerHandleVal(color, inst);
+
+ },
+ onAddSwatch: function(color, swatches) {
+
+ dataSetOption('general', 'colorpicker-swatches', swatches);
+
+ },
+ onDeleteSwatch: function(color, swatches) {
+
+ dataSetOption('general', 'colorpicker-swatches', swatches);
+
+ }
+ });
+
+ $.colorpicker._showColorpicker($(this));
+
+ setupTooltips();
+
+ }
+ /* END INPUT FUNCTIONALITY */
+
+
+ /* COMPLEX JS CALLBACKS */
+ propertyInputCallbackFontFamily = function(params) {
+
+ var selector = params.selector;
+ var value = params.value;
+ var element = params.element;
+ var cssValue = params.stack ? params.stack : params.value;
+
+ /* Uncustomization */
+ if ( !value ) {
+
+ stylesheet.delete_rule_property(selector, 'font-family');
+ return;
+
+ }
+
+ /* Non web fonts */
+ if ( !value.match(/\|/g) ) {
+
+ stylesheet.update_rule(selector, {"font-family": cssValue});
+ return;
+
+ }
+
+ /* Web Fonts */
+ var fontFragments = value.split('|');
+ var args = {};
+
+ /* Handle variants */
+ var variants = '';
+
+ if ( typeof fontFragments[2] != 'undefined' && fontFragments[2] )
+ variants = ':' + fontFragments[2];
+
+ args[fontFragments[0]] = {
+ families: [fontFragments[1] + variants]
+ };
+
+ var cssValue = fontFragments[1];
+
+ stylesheet.update_rule(selector, {"font-family": cssValue});
+
+ if ( typeof $('iframe#content').get(0).contentWindow.WebFont == 'object' )
+ $('iframe#content').get(0).contentWindow.WebFont.load(args);
+ /* End Web Font handling */
+
+ }
+
+ propertyInputCallbackBackgroundImage = function(params) {
+
+ var selector = params.selector;
+ var value = params.value;
+ var element = params.element;
+
+ if ( value != 'none' ) {
+ stylesheet.update_rule(selector, {"background-image": 'url(' + value + ')'});
+ } else if ( value == 'none' ) {
+ stylesheet.update_rule(selector, {"background-image": 'none'});
+ }
+
+ }
+
+ propertyInputCallbackFontStyling = function(params) {
+
+ var selector = params.selector;
+ var value = params.value;
+ var element = params.element;
+
+ if ( value === 'normal' ) {
+
+ stylesheet.update_rule(selector, {
+ 'font-style': 'normal',
+ 'font-weight': 'normal'
+ });
+
+ } else if ( value === 'bold' ) {
+
+ stylesheet.update_rule(selector, {
+ 'font-style': 'normal',
+ 'font-weight': 'bold'
+ });
+
+ } else if ( value === 'light' ) {
+
+ stylesheet.update_rule(selector, {
+ 'font-style': 'normal',
+ 'font-weight': 'lighter'
+ });
+
+ } else if ( value === 'italic' ) {
+
+ stylesheet.update_rule(selector, {
+ 'font-style': 'italic',
+ 'font-weight': 'normal'
+ });
+
+ } else if ( value === 'bold-italic' ) {
+
+ stylesheet.update_rule(selector, {
+ 'font-style': 'italic',
+ 'font-weight': 'bold'
+ });
+
+ } else if ( value === null ) {
+
+ stylesheet.delete_rule_property(selector, 'font-style');
+ stylesheet.delete_rule_property(selector, 'font-weight');
+
+ }
+
+ }
+
+ propertyInputCallbackCapitalization = function(params) {
+
+ var selector = params.selector;
+ var value = params.value;
+ var element = params.element;
+
+ if ( value === 'none' || value == null ) {
+
+ stylesheet.update_rule(selector, {
+ 'text-transform': 'none',
+ 'font-variant': 'normal'
+ });
+
+ } else if ( value === 'small-caps' ) {
+
+ stylesheet.update_rule(selector, {
+ 'text-transform': 'none',
+ 'font-variant': 'small-caps'
+ });
+
+ } else {
+
+ stylesheet.update_rule(selector, {
+ 'text-transform': value,
+ 'font-variant': 'normal'
+ });
+
+ }
+
+ }
+
+ propertyInputCallbackShadow = function(params) {
+
+ var selector = params.selector;
+ var value = params.value;
+ var element = params.element;
+ var property = params.property;
+
+ var shadowType = ( property.indexOf('box-shadow') === 0 ) ? 'box-shadow' : 'text-shadow';
+
+ var currentShadow = $i(selector).css(shadowType) || false;
+
+ //If the current shadow isn't set, then create an empty template to work off of.
+ if ( currentShadow == false || currentShadow == 'none' )
+ currentShadow = 'rgba(0, 0, 0, 0) 0 0 0';
+
+ //Remove all spaces inside rgba, rgb, and hsb colors and also remove all px
+ var shadowFragments = currentShadow.replace(/, /g, ',').replace(/px/g, '').split(' ');
+
+ var shadowColor = $('li[data-property-id="' + shadowType + '-color' + '"] input').val() || shadowFragments[0];
+ var shadowHOffset = $('li[data-property-id="' + shadowType + '-horizontal-offset' + '"] input').val() || shadowFragments[1];
+ var shadowVOffset = $('li[data-property-id="' + shadowType + '-vertical-offset' + '"] input').val() || shadowFragments[2];
+ var shadowBlur = $('li[data-property-id="' + shadowType + '-blur' + '"] input').val() || shadowFragments[3];
+ var shadowInset = $('li[data-property-id="' + shadowType + '-position' + '"] input').val() || shadowFragments[4];
+
+ switch ( property ) {
+
+ case shadowType + '-horizontal-offset':
+ shadowHOffset = value || 0;
+ break;
+
+ case shadowType + '-vertical-offset':
+ shadowVOffset = value || 0;
+ break;
+
+ case shadowType + '-blur':
+ shadowBlur = value || 0;
+ break;
+
+ case shadowType + '-inset':
+ shadowInset = value;
+ break;
+
+ case shadowType + '-color':
+ shadowColor = value;
+ break;
+
+ }
+
+ if ( !shadowColor )
+ return stylesheet.delete_rule_property(selector, shadowType);
+
+ /* Handle inset */
+ if ( shadowInset == 'inset' ) {
+ shadowInset = ' inset';
+ } else {
+ shadowInset = '';
+ }
+
+ var shadow = shadowColor + ' ' + shadowHOffset + 'px ' + shadowVOffset + 'px ' + shadowBlur + 'px' + shadowInset;
+
+ var properties = {};
+
+ //Use this syntax so the shadow type can feed from variable.
+ properties[shadowType] = shadow;
+
+ stylesheet.update_rule(selector, properties);
+
+ updateInspectorVisibleBoxModal();
+
+ }
+ /* END COMPLEX JS CALLBACKS */
+
+
+ /* INSPECTOR */
+ /* INSPECTOR INIT */
+ addInspector = function(refresh) {
+
+ if ( typeof Headway.elements == 'undefined' )
+ return $.when(designEditorRequestElements()).then(addInspector);
+
+ $.each(Headway.elements, function(elementID, elementSettings) {
+
+ if ( !elementSettings['inspectable'] )
+ return;
+
+ addInspectorProcessElement(elementSettings);
+
+ });
+
+ /* Build element hover tooltip */
+ if ( typeof refresh == 'undefined' || refresh !== true ) {
+
+ $i('body').qtip({
+ id: '',
+ style: {
+ classes: 'qtip-headway qtip-inspector-tooltip'
+ },
+ position: {
+ target: [-9999, -9999],
+ my: 'center',
+ at: 'center',
+ container: $i('body'),
+ viewport: $iDocument(),
+ effect: false,
+ adjust: {
+ x: 35,
+ y: 35,
+ method: 'flipinvert'
+ }
+ },
+ content: {
+ text: 'Hover over an element.'
+ },
+ show: {
+ event: false,
+ ready: true
+ },
+ hide: false,
+ events: {
+ render: function(event, api) {
+
+ delete inspectorElement;
+ delete inspectorTooltip;
+ delete inspectorElementOptions;
+
+ inspectorTooltip = api;
+
+ if ( !$('#toggle-inspector').hasClass('inspector-disabled') ) {
+ enableInspector();
+ } else {
+ disableInspector();
+ }
+
+ }
+ }
+ });
+
+ }
+
+ }
+
+ refreshInspector = function() {
+ return addInspector(true);
+ }
+
+ addInspectorProcessElement = function(value) {
+
+ if ( value['group'] == 'default-elements' )
+ return;
+
+ if ( !$i(value['selector']).length )
+ return;
+
+
+ if ( value['selector'].indexOf(':') == -1 ) {
+
+ $i(value['selector']).data({
+ inspectorElementOptions: value
+ })
+
+ $i(value['selector']).addClass('inspector-element');
+
+ }
+
+ /* Instances */
+ $.each(value['instances'], function(instanceID, instanceValue) {
+
+ if ( !$i(instanceValue['selector']).length )
+ return;
+
+ /* Simply change selector, add ID and name for instances */
+ var instanceOptions = jQuery.extend(true, {}, value);
+ instanceOptions['parentName'] = value['name'];
+ instanceOptions['instance'] = instanceValue['id'];
+ instanceOptions['name'] = instanceValue['name'];
+ instanceOptions['selector'] = instanceValue['selector'];
+ instanceOptions['instances'] = {};
+
+ /* Filter instances to only be states of this instance */
+ $.each(value['instances'], function(index, instance) {
+
+ if ( instance['state-of'] == instanceID )
+ instanceOptions['instances'][index] = instance;
+
+ });
+
+ /* Split the selector that way we can filter out :hover and :active */
+ $.each(instanceOptions['selector'].split(','), function(index, selector) {
+
+ /* Do not add elements with pseudo selectors to the inspector */
+ if ( selector.indexOf(':') != -1 )
+ return;
+
+ $i(selector).data({
+ inspectorElementOptions: instanceOptions
+ });
+
+ $i(selector).addClass('inspector-element');
+
+ });
+
+ });
+
+ }
+
+ enableInspector = function() {
+
+ if ( Headway.mode != 'design' || !Headway.designEditorSupport )
+ return false;
+
+ Headway.inspectorDisabled = false;
+ Headway.disableBlockDimensions = true;
+
+ $i('body').addClass('disable-block-hover').removeClass('inspector-disabled');
+
+ $i('.block[data-hasqtip]').each(function() {
+ var api = $(this).qtip('api');
+ api.destroy();
+ });
+
+ inspectorTooltip.show();
+
+ var inspectorMouseMoveEvent = !Headway.touch ? 'mousemove' : 'tap';
+ $i('html').bind(inspectorMouseMoveEvent, inspectorMouseMove);
+
+ setupInspectorContextMenu();
+ deactivateContextMenu('block');
+
+ /* For some reason the iframe doesn't always focus correctly so both of these bindings are needed */
+ Headway.iframe.contents().bind('keydown', inspectorNudging);
+ Headway.iframe.bind('keydown', inspectorNudging);
+
+ /* Focus iframe on mouseover */
+ Headway.iframe.bind('mouseover', function() {
+ Headway.iframe.focus();
+ });
+
+ showNotification({
+ id: 'inspector',
+ message: '<strong>Right-click</strong> highlighted elements to style them.<br /><br />Once an element is selected, you may nudge it using your arrow keys.<br /><br />The faded orange and purple are the margins and padding. These colors are only visible when the inspector is active.',
+ closeConfirmMessage: 'Please be sure you understand how the Design Editor inspector works before hiding this message.',
+ closeTimer: false,
+ closable: true,
+ doNotShowAgain: true
+ });
+
+ updateInspectorVisibleBoxModal();
+
+ $('#toggle-inspector').removeClass('inspector-disabled');
+
+ }
+
+ disableInspector = function() {
+
+ if ( Headway.mode != 'design' || !Headway.designEditorSupport )
+ return false;
+
+ Headway.inspectorDisabled = true;
+
+ delete Headway.disableBlockDimensions;
+ delete inspectorElement;
+
+ $i('.inspector-element-hover').removeClass('inspector-element-hover');
+ $i('body').removeClass('disable-block-hover').addClass('inspector-disabled');
+ $i('.block').qtip('enable');
+
+ $(inspectorTooltip.elements.tooltip).hide();
+ hideNotification('inspector');
+
+ $i('html').unbind('mousemove', inspectorMouseMove);
+
+ deactivateContextMenu('inspector');
+ setupBlockContextMenu(false);
+
+ Headway.iframe.contents().unbind('keydown', inspectorNudging);
+ Headway.iframe.unbind('keydown', inspectorNudging);
+
+ removeInspectorVisibleBoxModal();
+
+ $('#toggle-inspector').addClass('inspector-disabled');
+
+ }
+
+ toggleInspector = function() {
+
+ if ( Headway.mode != 'design' || !Headway.designEditorSupport )
+ return false;
+
+ if ( $('#toggle-inspector').hasClass('inspector-disabled') )
+ return enableInspector();
+
+ disableInspector();
+
+ }
+ /* END INSPECTOR INIT */
+
+ /* INSPECTOR ELEMENT HIGHLIGHTING */
+ inspectorSelectElement = function(selector) {
+
+ /* Unhighlight previous elements */
+ $i('.inspector-element-selected').each(function() {
+
+ $(this).removeClass('inspector-element-selected');
+
+ removeInspectorVisibleBoxModal($(this));
+
+ });
+
+ /* Mark the new selected elements */
+ $i(selector).addClass('inspector-element-selected');
+
+ updateInspectorVisibleBoxModal();
+
+ }
+ /* END INSPECTOR ELEMENT HIGHLIGHTING */
+
+ /* INSPECTOR BOX MODAL HIGHLIGHTING */
+ removeInspectorVisibleBoxModal = function(selector) {
+
+ if ( typeof selector == 'undefined' )
+ var selector = $i('.inspector-element-selected');
+
+ if ( !$(selector).data('previousBoxShadow') )
+ return false;
+
+ $(selector).data('previousBoxShadow', null);
+
+ /* Clear style attribute box shadow and rely on previous CSS */
+ return $(selector).css('boxShadow', '');
+
+ }
+
+ updateInspectorVisibleBoxModal = function() {
+
+ if ( typeof Headway.inspectorDisabled != 'undefined' && Headway.inspectorDisabled )
+ return;
+
+ /* Show padding/margin with box shadow */
+ $i('.inspector-element-selected').each(function() {
+
+ /* Remove any previous margin/padding shadows */
+ removeInspectorVisibleBoxModal($(this));
+
+ var self = this;
+ var previousBoxShadow = $(this).css('box-shadow');
+ var boxShadow = previousBoxShadow != 'none' ? previousBoxShadow.split(',') : [];
+
+ $(this).data('previousBoxShadow', previousBoxShadow);
+
+ $.each([
+ 'paddingTop',
+ 'paddingRight',
+ 'paddingBottom',
+ 'paddingLeft',
+ 'marginTop',
+ 'marginRight',
+ 'marginBottom',
+ 'marginLeft'
+ ], function(index, cssProperty) {
+
+ var cssValueUnit = $(self).css(cssProperty).replace(/^[+-]?\d+(\.\d+)?/g, '');
+ var cssValue = $(self).css(cssProperty).replace(cssValueUnit, '');
+
+ if ( cssValue == 'auto' )
+ return;
+
+ var color = cssProperty.indexOf('padding') !== -1 ? 'rgba(0, 0, 255, .15)' : 'rgba(255, 127, 0, .15)';
+ var negative = '';
+ var inset = '';
+
+ if (
+ cssProperty == 'paddingRight' ||
+ cssProperty == 'paddingBottom' ||
+ cssProperty == 'marginLeft' ||
+ cssProperty == 'marginTop'
+ )
+ negative = '-';
+
+ var value = negative + cssValue + cssValueUnit;
+
+ if ( cssProperty.toLowerCase().indexOf('left') !== -1 || cssProperty.toLowerCase().indexOf('right') !== -1 )
+ var xyValue = value + ' 0';
+ else
+ var xyValue = '0 ' + value;
+
+ if ( cssProperty.indexOf('padding') !== -1 )
+ inset = 'inset ';
+
+ boxShadow.push(inset + xyValue + ' 0 0 ' + color);
+
+ });
+
+ $(this).css({
+ boxShadow: boxShadow.join(',')
+ });
+
+ });
+
+ }
+ /* END INSPECTOR BOX MODAL HIGHLIGHTING */
+
+ /* INSPECTOR TOOLTIP */
+ inspectorMouseMove = function(event) {
+
+ if ( Headway.inspectorDisabled )
+ return;
+
+ var targetInspectorElement = $(event.target);
+
+ if ( !targetInspectorElement.hasClass('inspector-element') )
+ targetInspectorElement = targetInspectorElement.parents('.inspector-element').first();
+
+ /* Only change tooltip content if the hovered element isn't the existing inspector element */
+ if ( typeof inspectorElement == 'undefined' || !targetInspectorElement.is(inspectorElement) ) {
+
+ inspectorElement = $(event.target);
+
+ if ( !inspectorElement.hasClass('inspector-element') )
+ inspectorElement = inspectorElement.parents('.inspector-element').first();
+
+ var inspectorElementOptions = inspectorElement.data('inspectorElementOptions');
+
+ if ( typeof inspectorElementOptions == 'object' ) {
+
+ $i('.inspector-element-hover').removeClass('inspector-element-hover');
+ $i(inspectorElementOptions['selector']).addClass('inspector-element-hover');
+
+ /* Build tooltip text */
+ var elementSelectorNode = $('#design-editor-element-selector').find('li#element-' + inspectorElementOptions.id);
+
+ var elementName = elementSelectorNode.children('.element-name').text();
+
+ var tooltipText = '<span class="inspector-tooltip-element-path">';
+ var tooltipElementPath = [];
+
+ elementSelectorNode.parents('li').reverse().each(function() {
+
+ tooltipElementPath.push($(this).children('.element-group-name, .element-name').first().text());
+
+ });
+
+ /* Add info to tooltip if hovered element is an instance */
+ var insideInstanceText = '';
+
+ if ( typeof inspectorElementOptions.instance != 'undefined' ) {
+
+ if ( inspectorElementOptions.name.indexOf(' – ') !== -1 ) {
+
+ insideInstanceText = '<span class="inspector-tooltip-instance">Inside <strong>' + inspectorElementOptions.name.split(' – ')[0] + '</strong></span>';
+
+ } else {
+
+ elementName = inspectorElementOptions.name;
+
+ }
+
+ }
+
+ /* Trim down the path and omit ancestors to save space if necessary */
+ if ( tooltipElementPath.join(' > ').length + elementName.length > 40 ) {
+
+ while ( tooltipElementPath.join(' > ').length + elementName.length > 40 && elementName.length < 40 ) {
+
+ tooltipElementPath.shift();
+
+ tooltipElementPathStr = '<span class="ellipsis">...</span> ' + tooltipElementPath.join(' › ');
+
+ }
+
+ } else {
+
+ tooltipElementPathStr = tooltipElementPath.join(' › ');
+
+ }
+
+ tooltipText += tooltipElementPathStr;
+ tooltipText += ' › <strong>' + elementName + '</strong></span>';
+ tooltipText += insideInstanceText;
+
+ tooltipText += '<small class="right-click-message">Right-click to style</small>';
+
+
+ inspectorTooltip.set('content.text', tooltipText);
+
+ }
+
+ }
+
+ inspectorTooltip.show();
+
+ var tooltipWidth = $i('#ui-tooltip-inspector-tooltip').width();
+ var viewportOverflow = $i('body').width() - event.pageX - tooltipWidth + 15;
+
+ var tooltipX = viewportOverflow > 0 ? event.pageX : event.pageX + viewportOverflow;
+
+ inspectorTooltip.set('position.target', [tooltipX, event.pageY]);
+
+ }
+ /* END INSPECTOR TOOLTIP */
+
+ /* INSPECTOR CONTEXT MENU */
+ setupInspectorContextMenu = function() {
+
+ return setupContextMenu({
+ id: 'inspector',
+ elements: 'body',
+ title: function(event) {
+ return inspectorElement.data('inspectorElementOptions').name;
+ },
+ onShow: inspectorContextMenuOnShow,
+ onHide: function() {
+
+ /* Reactivate inspector tooltip */
+ inspectorTooltip.show();
+ Headway.inspectorDisabled = false;
+
+ },
+ onItemClick: inspectorContextMenuItemClick,
+ contentsCallback: inspectorContextMenuContents
+ });
+
+ }
+
+ inspectorContextMenuOnShow = function(event) {
+
+ /* Add element options object to the context menu */
+ $(this).data('element-options', inspectorElement.data('inspectorElementOptions'));
+
+ /* Disable inspector tooltip */
+ $(inspectorTooltip.elements.tooltip).hide();
+ Headway.inspectorDisabled = true;
+
+ }
+
+ inspectorContextMenuItemClick = function(contextMenu, originalRightClickEvent) {
+
+ if ( $(this).hasClass('group-title') && !$(this).hasClass('group-title-clickable') )
+ return;
+
+ /* Block Options Click */
+ if ( $(this).parents('li').first().hasClass('inspector-context-menu-block-options') ) {
+
+ openBlockOptions(getBlock($(inspectorElement)));
+
+ /* DE Click */
+ } else {
+
+ var inspectorElementOptions = contextMenu.data('element-options');
+ var instanceID = $(this).parents('li').first().data('instance-id');
+ var stateID = $(this).parents('li').first().data('state-id');
+
+ /* Reactivate inspector tooltip */
+ inspectorTooltip.show();
+ Headway.inspectorDisabled = false;
+
+ /* Remove the highlight on the previously selected elements */
+ $('#design-editor-element-selector-container .ui-state-active').removeClass('ui-state-active');
+
+ /* Instances */
+ if ( typeof instanceID != 'undefined' ) {
+
+ designEditor.selectSpecialElement(inspectorElementOptions['id'], 'instance', instanceID);
+
+ }
+
+ /* States */
+ else if ( typeof stateID != 'undefined' ) {
+
+ designEditor.selectSpecialElement(inspectorElementOptions['id'], 'state', stateID);
+
+ }
+
+ /* Handle Top Level Elements */
+ else if ( !$(this).parents('li').first().hasClass('inspector-context-menu-parent') ) {
+
+ $('ul#design-editor-element-selector li#element-' + inspectorElementOptions['id']).find('> span').trigger('click');
+
+ }
+
+ /* Layout-specific customizations */
+ if ( $(this).parents('li').first().hasClass('inspector-context-menu-edit-for-layout') ) {
+
+ designEditor.selectSpecialElement(inspectorElementOptions['id'], 'layout', Headway.currentLayout);
+
+ }
+
+ }
+
+ }
+
+ inspectorContextMenuContents = function(event) {
+
+ var contextMenu = $(this);
+ var inspectorElementOptions = contextMenu.data('element-options');
+
+ /* Set instance variable */
+ var isInstance = (typeof inspectorElementOptions.instance != 'undefined' && inspectorElementOptions.instance);
+
+ /* Add options to context menu */
+ /* Regular Element Group */
+ var regularElementGroup = contextMenu;
+
+ if ( isInstance ) {
+
+ contextMenu.append('<li class="inspector-context-menu-edit-instance" data-instance-id="' + inspectorElementOptions.instance + '"><span>Edit This Instance</span></li>');
+
+ var regularElementGroup = $('<li class="inspector-context-menu-edit-normal"><span class="group-title group-title-clickable">Edit Regular Element<small>' + inspectorElementOptions.parentName + '</small></span><ul></ul></li>').appendTo(contextMenu);
+ regularElementGroup = regularElementGroup.find('ul').first();
+
+ /* Regular Element */
+ } else {
+
+ regularElementGroup.append('<li class="inspector-context-menu-edit-normal"><span>Edit</span></li>');
+
+ }
+
+ regularElementGroup.append('<li class="inspector-context-menu-edit-for-layout"><span>Edit For This Layout</span></li>');
+
+ /* Regular Element States */
+ if ( !_.isEmpty(inspectorElementOptions.states) ) {
+
+ var statesMenu = $('<li class="inspector-context-menu-states"><span class="group-title">States</span><ul></ul></li>').appendTo(regularElementGroup);
+
+ $.each(inspectorElementOptions.states, function(stateID, stateInfo) {
+ statesMenu.find('ul').append('<li data-state-id="' + stateID + '"><span>Edit ' + stateInfo.name + '</span></li>');
+ });
+
+ }
+ /* End Regular Element */
+
+ /* Instances */
+ if ( !_.isEmpty(inspectorElementOptions.instances) ) {
+
+ if ( typeof inspectorElementOptions.instance == 'undefined' || !inspectorElementOptions.instance ) {
+ var instancesMenu = $('<li class="inspector-context-menu-instances"><span class="group-title">Instances</span><ul></ul></li>').appendTo(contextMenu);
+ } else {
+ var instancesMenu = false;
+ }
+
+ $.each(inspectorElementOptions.instances, function(instanceID, instance) {
+
+ /* Handle instance states that will be in the actual instances menu */
+ if ( instance['state-of'] == inspectorElementOptions.instance ) {
+
+ if ( !contextMenu.find('> li.inspector-context-menu-instance-states').length )
+ $('<li class="inspector-context-menu-instance-states"><span class="group-title">Instance States</span><ul></ul></li>')
+ .insertAfter(contextMenu.find('li.inspector-context-menu-edit-instance'));
+
+ contextMenu.find('> li.inspector-context-menu-instance-states ul').append('<li data-instance-id="' + instanceID + '"><span>Edit ' + instance['state-name'] + '</span></li>');
+
+ }
+
+ });
+
+ /* If the instances menu is empty somehow (one instance and that instance is selected), then delete it */
+ if ( instancesMenu && !instancesMenu.find('ul li').length )
+ instancesMenu.remove();
+
+ }
+
+ /* Parent Elements */
+ if ( inspectorElement.parents('.inspector-element').length ) {
+
+ var parentsMenu = $('<li class="inspector-context-menu-parents"><span class="group-title">Parents</span><ul></ul></li>').appendTo(contextMenu);
+
+ inspectorElement.parents('.inspector-element').each(function() {
+
+ var parentElement = $(this);
+
+ $('<li class="inspector-context-menu-parent" data-parent-id="' + $(this).data('inspectorElementOptions').id + '"><span>' + $(this).data('inspectorElementOptions').name + '</span></li>')
+ .appendTo(parentsMenu.find('ul'))
+ .bind('click', function() {
+
+ inspectorElement = parentElement;
+
+ var x = typeof event.data != 'undefined' ? event.data.x : event.originalEvent.clientX;
+ var y = typeof event.data != 'undefined' ? event.data.y : event.originalEvent.clientY;
+
+ parentElement.trigger('contextmenu', {
+ x: x,
+ y: y
+ });
+
+ });
+
+ });
+
+ }
+
+ /* Block Options */
+ if ( getBlock(inspectorElement) ) {
+
+ var block = getBlock(inspectorElement);
+ var blockID = getBlockID(block);
+ var blockType = getBlockTypeNice(getBlockType(block));
+
+ var blockOptionsNode = $('<li class="inspector-context-menu-block-options"><span>Open Block Options</span></li>').appendTo(contextMenu);
+
+ }
+ /* End block options */
+
+ }
+ /* END INSPECTOR CONTEXT MENU */
+
+ /* INSPECTOR NUDGING */
+ inspectorNudging = function(event) {
+
+ var key = event.keyCode;
+
+ if ( key < 37 || key > 40 || !$i('.inspector-element-selected').length || $i('.inspector-element-selected').is('body') )
+ return;
+
+ var interval = event.shiftKey ? 5 : 1;
+
+ /* Get the selector that way the stylesheet object can be used */
+ var methodInput = $('.design-editor-box-nudging .design-editor-property-position select', '.design-editor-options-container');
+ var methodInputHidden = methodInput.parents('.design-editor-property-position').find('input[type="hidden"]');
+
+ var selector = methodInputHidden.attr('element_selector');
+
+ /* Set the 3 nudging properties to customized */
+ $('.design-editor-box-nudging .uncustomized-property .customize-property span', '.design-editor-options-container').trigger('click');
+
+ /* Set the nudging method to whatever the position property is of the element as long as it's not static */
+ if ( $i('.inspector-element-selected').css('position') != 'static' ) {
+
+ var positionMethod = $i('.inspector-element-selected').css('position');
+
+ $i('.inspector-element-selected').css({
+ position: positionMethod
+ });
+
+ methodInput.val(positionMethod).trigger('change');
+
+ } else {
+
+ var positionMethod = 'relative';
+
+ $i('.inspector-element-selected').css({
+ position: positionMethod
+ });
+
+ methodInput.val(positionMethod).trigger('change');
+
+ }
+
+ switch ( key ) {
+
+ /* Left */
+ case 37:
+
+ var previousLeft = parseInt($i('.inspector-element-selected').css('left'));
+
+ if ( isNaN(previousLeft) )
+ var previousLeft = 0;
+
+ stylesheet.update_rule(selector, {"left": (previousLeft - interval) + 'px'});
+
+ var currentLeft = $i('.inspector-element-selected').css('left').replace('px', '');
+ $('.design-editor-box-nudging .design-editor-property-left input[type="text"]', '.design-editor-options-container').val(currentLeft).trigger('change');
+
+ break;
+
+ /* Up */
+ case 38:
+
+ var previousTop = parseInt($i('.inspector-element-selected').css('top'));
+
+ if ( isNaN(previousTop) )
+ previousTop = 0;
+
+ stylesheet.update_rule(selector, {"top": (previousTop - interval) + 'px'});
+
+ var currentTop = $i('.inspector-element-selected').css('top').replace('px', '');
+ $('.design-editor-box-nudging .design-editor-property-top input[type="text"]', '.design-editor-options-container').val(currentTop).trigger('change');
+
+ break;
+
+ /* Right */
+ case 39:
+
+ var previousLeft = parseInt($i('.inspector-element-selected').css('left'));
+
+ if ( isNaN(previousLeft) )
+ var previousLeft = 0;
+
+ stylesheet.update_rule(selector, {"left": (previousLeft + interval) + 'px'});
+
+ var currentLeft = $i('.inspector-element-selected').css('left').replace('px', '');
+ $('.design-editor-box-nudging .design-editor-property-left input[type="text"]', '.design-editor-options-container').val(currentLeft).trigger('change');
+
+ break;
+
+ /* Down */
+ case 40:
+
+ var previousTop = parseInt($i('.inspector-element-selected').css('top'));
+
+ if ( isNaN(previousTop) )
+ previousTop = 0;
+
+ stylesheet.update_rule(selector, {"top": (previousTop + interval) + 'px'});
+
+ var currentTop = $i('.inspector-element-selected').css('top').replace('px', '');
+ $('.design-editor-box-nudging .design-editor-property-top input[type="text"]', '.design-editor-options-container').val(currentTop).trigger('change');
+
+ break;
+
+ }
+
+ /* Prevent scrolling */
+ event.preventDefault();
+ return false;
+
+ }
+ /* END INSPECTOR NUDGING */
+ /* END INSPECTOR */
+
+
+ /* ELEMENT INFO */
+ getElementNodeName = function(node) {
+
+ var clonedNode = node.clone();
+
+ return clonedNode.find('> span').children().remove().end().text();
+
+ }
+
+
+ getSelectedElement = function() {
+
+ if ( typeof Headway.designEditorCurrentElement != 'undefined' )
+ return Headway.designEditorCurrentElement;
+
+ return null;
+
+ }
+
+ setSelectedElement = function(element) {
+
+ Headway.designEditorCurrentElement = element;
+
+ if ( _.isEmpty(element) )
+ return;
+
+ var details = {};
+
+ if ( typeof element.specialElementType != 'undefined' )
+ details[element.specialElementType] = element.specialElementName;
+
+ setSelectedElementDetails(details, element.object);
+
+ }
+
+ setSelectedElementDetails = function(details, element) {
+
+ var details = $.extend({}, {
+ instance: element.name,
+ layout: 'all layouts',
+ state: 'all states'
+ }, details);
+
+ var deSelectionDetails = $('span.design-editor-selection-details');
+
+ deSelectionDetails.find('.design-editor-selected-element').html(details.instance);
+ deSelectionDetails.find('strong.design-editor-selection-details-layout').html(details.layout);
+
+ if ( typeof element.states == 'undefined' || _.isEmpty(element.states) ) {
+
+ deSelectionDetails.find('span.design-editor-selection-details-state-container').hide();
+
+ } else {
+
+ deSelectionDetails.find('span.design-editor-selection-details-state-container').show();
+
+
+ if ( details.state == 'all states' ) {
+ deSelectionDetails.find('.design-editor-selection-details-state-before').text('and');
+ } else {
+ deSelectionDetails.find('.design-editor-selection-details-state-before').text('when');
+ }
+
+ if ( details.state == 'Hover' )
+ details.state = 'hovered';
+
+ deSelectionDetails.find('strong.design-editor-selection-details-state').html(details.state.toLowerCase());
+
+ }
+
+ /* Update height of DE info */
+ var deInfoHeight = $('.design-editor-info').outerHeight();
+
+ $('.design-editor-info').css('marginTop', '-' + deInfoHeight + 'px');
+ $('#side-panel-bottom').css('paddingTop', deInfoHeight + 'px');
+
+ return $('span.design-editor-selection-details');
+
+ }
+
+ sanitizeElementName = function(elementName) {
+
+ return $.trim(elementName.escapeHTML());
+
+ }
+ /* END ELEMENT INFO */
+
+ var modeDesign = {
+ init: function() {
+
+ designEditor = new designEditorTabEditor();
+ designEditor._init();
+
+ modeDesign.bind();
+
+ designEditorBindPropertyInputs();
+
+ /* Load scripts */
+ try {
+
+ /* Load editor.fonts.js */
+ $.getScript(Headway.headwayURL + '/library/visual-editor/' + Headway.scriptFolder + '/util.fonts-browser.js');
+
+ /* Load Google API */
+ $.getScript('//ajax.googleapis.com/ajax/libs/webfont/1.4.7/webfont.js');
+
+ } catch (exception) {}
+
+ /* Hide DE if cookie is set to do so */
+ if ( $.cookie('hide-design-editor') === 'true' )
+ hideDesignEditor();
+
+ },
+
+ bind: function() {
+
+ $('#toggle-inspector').bind('click', toggleInspector);
+
+ },
+
+ iframeCallback: function() {
+
+ bindBlockDimensionsTooltip();
+ addInspector();
+
+ /* Reset editor for layout switch */
+ designEditor.switchLayout();
+
+ }
+ }
+
+ return modeDesign;
+
+});
\ No newline at end of file
--- /dev/null
+bindGridWizard = function() {
+
+ /* Presets */
+ var gridWizardPresets = {
+ 'right-sidebar': [
+ {
+ top: 0,
+ left: 0,
+ width: 24,
+ height: 130,
+ type: 'header'
+ },
+
+ {
+ top: 140,
+ left: 0,
+ width: 24,
+ height: 40,
+ type: 'navigation'
+ },
+
+ {
+ top: 190,
+ left: 0,
+ width: 18,
+ height: 320,
+ type: 'content'
+ },
+
+ {
+ top: 190,
+ left: 18,
+ width: 6,
+ height: 270,
+ type: 'widget-area',
+ mirroringOrigin: 'sidebar-1'
+ },
+
+ {
+ top: 520,
+ left: 0,
+ width: 24,
+ height: 70,
+ type: 'footer'
+ },
+ ],
+
+ 'left-sidebar': [
+ {
+ top: 0,
+ left: 0,
+ width: 24,
+ height: 130,
+ type: 'header'
+ },
+
+ {
+ top: 140,
+ left: 0,
+ width: 24,
+ height: 40,
+ type: 'navigation'
+ },
+
+ {
+ top: 190,
+ left: 0,
+ width: 6,
+ height: 270,
+ type: 'widget-area',
+ mirroringOrigin: 'sidebar-1'
+ },
+
+ {
+ top: 190,
+ left: 6,
+ width: 18,
+ height: 320,
+ type: 'content'
+ },
+
+ {
+ top: 520,
+ left: 0,
+ width: 24,
+ height: 70,
+ type: 'footer'
+ }
+ ],
+
+ 'two-right': [
+ {
+ top: 0,
+ left: 0,
+ width: 24,
+ height: 130,
+ type: 'header'
+ },
+
+ {
+ top: 140,
+ left: 0,
+ width: 24,
+ height: 40,
+ type: 'navigation'
+ },
+
+ {
+ top: 190,
+ left: 0,
+ width: 16,
+ height: 320,
+ type: 'content'
+ },
+
+ {
+ top: 190,
+ left: 16,
+ width: 4,
+ height: 270,
+ type: 'widget-area',
+ mirroringOrigin: 'sidebar-1'
+ },
+
+ {
+ top: 190,
+ left: 20,
+ width: 4,
+ height: 270,
+ type: 'widget-area',
+ mirroringOrigin: 'sidebar-2'
+ },
+
+ {
+ top: 520,
+ left: 0,
+ width: 24,
+ height: 70,
+ type: 'footer'
+ }
+ ],
+
+ 'two-both': [
+ {
+ top: 0,
+ left: 0,
+ width: 24,
+ height: 130,
+ type: 'header'
+ },
+
+ {
+ top: 140,
+ left: 0,
+ width: 24,
+ height: 40,
+ type: 'navigation'
+ },
+
+ {
+ top: 190,
+ left: 0,
+ width: 4,
+ height: 270,
+ type: 'widget-area',
+ mirroringOrigin: 'sidebar-1'
+ },
+
+ {
+ top: 190,
+ left: 4,
+ width: 16,
+ height: 320,
+ type: 'content'
+ },
+
+ {
+ top: 190,
+ left: 20,
+ width: 4,
+ height: 270,
+ type: 'widget-area',
+ mirroringOrigin: 'sidebar-2'
+ },
+
+ {
+ top: 520,
+ left: 0,
+ width: 24,
+ height: 70,
+ type: 'footer'
+ }
+ ],
+
+ 'all-content': [
+ {
+ top: 0,
+ left: 0,
+ width: 24,
+ height: 130,
+ type: 'header'
+ },
+
+ {
+ top: 140,
+ left: 0,
+ width: 24,
+ height: 40,
+ type: 'navigation'
+ },
+
+ {
+ top: 190,
+ left: 0,
+ width: 24,
+ height: 320,
+ type: 'content'
+ },
+
+ {
+ top: 520,
+ left: 0,
+ width: 24,
+ height: 70,
+ type: 'footer'
+ }
+ ]
+ }
+
+
+ $('div#boxes').delegate('div#box-grid-wizard span.layout-preset', 'mousedown', function() {
+
+ $('div#box-grid-wizard span.layout-preset-selected').removeClass('layout-preset-selected');
+ $(this).addClass('layout-preset-selected');
+
+ });
+
+
+ $('div#boxes').delegate('span#grid-wizard-button-preset-next', 'click', function() {
+
+ /* Populate the step 2 panel with the proper select boxes */
+ var selectedPreset = $('div#box-grid-wizard span.layout-preset-selected').attr('id').replace('layout-', '');
+
+ switch ( selectedPreset ) {
+
+ case 'right-sidebar':
+
+ $('div#grid-wizard-presets-mirroring-select-sidebar-1').show();
+ $('div#grid-wizard-presets-mirroring-select-sidebar-2').hide();
+
+ $('div#grid-wizard-presets-mirroring-select-sidebar-1 h5').text('Right Sidebar');
+
+ break;
+
+
+ case 'left-sidebar':
+
+ $('div#grid-wizard-presets-mirroring-select-sidebar-1').show();
+ $('div#grid-wizard-presets-mirroring-select-sidebar-2').hide();
+
+ $('div#grid-wizard-presets-mirroring-select-sidebar-1 h5').text('Left Sidebar');
+
+ break;
+
+
+ case 'two-right':
+
+ $('div#grid-wizard-presets-mirroring-select-sidebar-1').show();
+ $('div#grid-wizard-presets-mirroring-select-sidebar-2').show();
+
+ $('div#grid-wizard-presets-mirroring-select-sidebar-1 h5').text('Left Sidebar');
+ $('div#grid-wizard-presets-mirroring-select-sidebar-2 h5').text('Right Sidebar');
+
+ break;
+
+
+ case 'two-both':
+
+ $('div#grid-wizard-presets-mirroring-select-sidebar-1').show();
+ $('div#grid-wizard-presets-mirroring-select-sidebar-2').show();
+
+ $('div#grid-wizard-presets-mirroring-select-sidebar-1 h5').text('Left Sidebar');
+ $('div#grid-wizard-presets-mirroring-select-sidebar-2 h5').text('Right Sidebar');
+
+ break;
+
+
+ case 'all-content':
+
+ $('div#grid-wizard-presets-mirroring-select-sidebar-1').hide();
+ $('div#grid-wizard-presets-mirroring-select-sidebar-2').hide();
+
+ break;
+
+ }
+
+
+ /* Change the buttons around */
+ $(this).hide(); //Next button
+
+ $('span#grid-wizard-button-preset-previous').show();
+ $('span#grid-wizard-button-preset-use-preset').show();
+
+
+ /* Change the content that's being displayed */
+ $('div#grid-wizard-presets-step-1').hide();
+ $('div#grid-wizard-presets-step-2').show();
+
+ });
+
+
+ $('div#boxes').delegate('span#grid-wizard-button-preset-previous', 'click', function() {
+
+ /* Change the buttons around */
+ $(this).hide(); //Previous button
+ $('span#grid-wizard-button-preset-use-preset').hide();
+
+ $('span#grid-wizard-button-preset-next').show();
+
+
+ /* Change the content that's being displayed */
+ $('div#grid-wizard-presets-step-2').hide();
+ $('div#grid-wizard-presets-step-1').show();
+
+ });
+
+
+ $('div#boxes').delegate('span#grid-wizard-button-preset-use-preset', 'click', function() {
+
+ var selectedPreset = $('div#box-grid-wizard span.layout-preset-selected').attr('id').replace('layout-', '');
+
+ //Delete any blocks that are on the grid already
+ $i('.block').each(function() {
+
+ deleteBlock(this);
+
+ });
+
+ //Put the new blocks on the layout
+ $.each(gridWizardPresets[selectedPreset], function() {
+
+ var addBlockArgs = this;;
+
+ delete addBlockArgs.mirroringOrigin;
+
+ /* Handle Mirroring */
+ var mirroringOrigin = (typeof this.mirroringOrigin != 'undefined') ? this.mirroringOrigin : this.type;
+ var mirroringSelectVal = $('div#grid-wizard-presets-mirroring-select-' + mirroringOrigin + ' select').val();
+
+ if ( mirroringSelectVal !== '' ) {
+
+ addBlockArgs.settings = {}
+ addBlockArgs.settings['mirror-block'] = mirroringSelectVal;
+
+ }
+
+ /* Add the block to the grid */
+ $i('.ui-headway-grid').first().data('ui-headwayGrid').addBlock(addBlockArgs);
+
+ });
+
+ return closeBox('grid-wizard');
+
+ });
+ /* End Presets */
+
+
+ /* Layout Cloning */
+ $('div#boxes').delegate('span#grid-wizard-button-clone-page', 'click', function() {
+
+ var layoutToClone = $('select#grid-wizard-pages-to-clone').val();
+
+ if ( layoutToClone === '' || !layoutToClone )
+ return alert('Please select a page to clone.');
+
+ if ( $(this).hasClass('button-depressed') )
+ return;
+
+ $(this).text('Cloning...').addClass('button-depressed').css('cursor', 'default');
+
+ var request = $.ajax(Headway.ajaxURL, {
+ type: 'POST',
+ async: true,
+ data: {
+ action: 'headway_visual_editor',
+ method: 'get_layout_blocks_in_json',
+ security: Headway.security,
+ layout: layoutToClone
+ },
+ success: function(data, textStatus) {
+
+ if ( textStatus == false )
+ return false;
+
+ //Delete any wrappers and blocks that are on the grid already
+ $i('.wrapper').each(function() {
+ deleteWrapper(getWrapperID($(this)), true);
+ });
+
+ var wrappers = data.wrappers;
+ var blocks = data.blocks;
+ var numberOfBlocks = Object.keys(blocks).length;
+
+ var wrapperIDTranslations = {};
+
+ $.each(wrappers, function(id, settings) {
+
+ /* Pluck wrapper styling out that way it doesn't get sent to the database */
+ var wrapperStyling = settings['styling'];
+
+ delete settings['styling'];
+ var newWrapper = addWrapper('bottom', settings['settings'], true);
+
+ /* Add old and new ID to wrapperIDTranslations that way blocks being added can be added to the correct wrapper */
+ var newWrapperID = getWrapperID(newWrapper);
+ wrapperIDTranslations[id.replace('wrapper-', '')] = newWrapperID;
+
+ if ( typeof settings['mirror_id'] != 'undefined' ) {
+ updateWrapperMirrorStatus(newWrapperID, settings['mirror_id']);
+ dataSetWrapperOption(newWrapperID, 'mirror-wrapper', settings['mirror_id']);
+ }
+
+ /* Add in styling */
+ $.each(wrapperStyling, function(property, value) {
+
+ dataSetDesignEditorProperty({
+ element: "wrapper",
+ property: property,
+ value: (value !== null ? value.toString() : null),
+ specialElementType: "instance",
+ specialElementMeta: "wrapper-" + newWrapperID
+ });
+
+ /* If margin or padding, add it in now for visible feedback */
+ if ( property.indexOf('margin') === 0 ) {
+
+ var whichMargin = property.replace('margin-', '').capitalize();
+ newWrapper.css('margin' + whichMargin, value + 'px');
+
+ } else if ( property.indexOf('padding') === 0 ) {
+
+ var whichPadding = property.replace('padding-', '').capitalize();
+ newWrapper.css('padding' + whichPadding, value + 'px');
+
+ }
+
+ });
+
+ });
+
+ $.each(blocks, function() {
+
+ var blockToMirror = this['mirror_id'] ? this['mirror_id'] : this.id;
+
+ var addBlockArgs = {
+ type: this.type,
+ top: this.position.top,
+ left: this.position.left,
+ width: this.dimensions.width,
+ height: this.dimensions.height,
+ settings: $.extend({}, this.settings, {'mirror-block': blockToMirror})
+ };
+
+ var blockWrapper = (typeof this.wrapper_id != 'undefined' && this.wrapper_id) ? this.wrapper_id : 'default';
+
+ /* If there's a wrapper ID translation, use it. Otherwise we'll put the block in the last wrapper */
+ if ( typeof wrapperIDTranslations[blockWrapper.replace('wrapper-', '')] != 'undefined' ) {
+
+ var destinationWrapperID = '#wrapper-' + wrapperIDTranslations[blockWrapper.replace('wrapper-', '')];
+ var destinationWrapper = $i('.ui-headway-grid').filter(destinationWrapperID).first();
+
+ } else {
+
+ var destinationWrapper = $i('.ui-headway-grid').last();
+
+ }
+
+ /* Add block to wrapper */
+ var newBlock = destinationWrapper.data('ui-headwayGrid').addBlock(addBlockArgs);
+ var newBlockID = getBlockID(newBlock);
+ var oldBlockID = this.id;
+
+ /* Queue styling for saving */
+ if ( typeof this.styling != 'undefined' && this.styling ) {
+
+ $.each(this.styling, function(blockInstanceID, blockInstanceInfo) {
+
+ /* Replace the block ID instance ID of the correct block ID */
+ var blockInstanceID = blockInstanceID.replace('block-' + oldBlockID, 'block-' + newBlockID);
+
+ $.each(blockInstanceInfo.properties, function(property, value) {
+
+ dataSetDesignEditorProperty({
+ group: "blocks",
+ element: blockInstanceInfo.element,
+ property: property,
+ value: (value !== null ? value.toString() : null),
+ specialElementType: "instance",
+ specialElementMeta: blockInstanceID
+ });
+
+ });
+
+ });
+
+ }
+
+ });
+
+ return closeBox('grid-wizard');
+
+ }
+ });
+
+ });
+ /* End Layout Cloning */
+
+
+ /* Template Assigning */
+ $('div#boxes').delegate('span#grid-wizard-button-assign-template', 'click', function() {
+
+ var templateToAssign = $('select#grid-wizard-assign-template').val().replace('template-' , '');
+
+ if ( templateToAssign === '' )
+ return alert('Please select a shared layout to assign.');
+
+ //Do the AJAX request to assign the template
+ $.post(Headway.ajaxURL, {
+ action: 'headway_visual_editor',
+ method: 'assign_template',
+ security: Headway.security,
+ template: templateToAssign,
+ layout: Headway.currentLayout
+ }, function(response) {
+
+ if ( typeof response === 'undefined' || response == 'failure' ) {
+ showErrorNotification({
+ id: 'error-could-not-assign-template',
+ message: 'Error: Could not assign shared layout.'
+ });
+
+ return false;
+ }
+
+ $('div#layout-selector li.layout-selected').removeClass('layout-item-customized');
+ $('div#layout-selector li.layout-selected').addClass('layout-item-template-used');
+
+ $('div#layout-selector li.layout-selected span.status-template').text(response);
+
+ //Reload iframe
+
+ showIframeLoadingOverlay();
+
+ //Change title to loading
+ changeTitle('Visual Editor: Assigning Template');
+ startTitleActivityIndicator();
+
+ Headway.currentLayoutTemplate = 'template-' + templateToAssign;
+ Headway.currentLayoutTemplateName = $('span.layout[data-layout-id="template-' + templateToAssign + '"]').find('.template-name').text();
+
+ //Reload iframe and new layout
+ headwayIframeLoadNotification = 'Template assigned successfully!';
+
+ loadIframe(Headway.instance.iframeCallback);
+
+ //End reload iframe
+
+ });
+
+ return closeBox('grid-wizard');
+
+ });
+ /* End Template Assigning */
+
+
+ /* Empty Grid */
+ $('div#boxes').delegate('span.grid-wizard-use-empty-grid', 'click', function() {
+
+ //Empty the grid out
+ $i('.block').each(function() {
+
+ deleteBlock(this);
+
+ });
+
+ closeBox('grid-wizard');
+
+ });
+ /* End Empty Grid */
+
+
+ /* Layout Import/Export */
+ /* Layout Import */
+ initiateLayoutImport = function(input) {
+
+ var layoutChooser = input;
+
+ if ( !layoutChooser.val() )
+ return alert('You must select a Headway layout file before importing.');
+
+ var layoutFile = layoutChooser.get(0).files[0];
+
+ if ( layoutFile && typeof layoutFile.name != 'undefined' && typeof layoutFile.type != 'undefined' ) {
+
+ var layoutReader = new FileReader();
+
+ layoutReader.onload = function(e) {
+
+ var contents = e.target.result;
+ var layout = JSON.parse(contents);
+
+ /* Check to be sure that the JSON file is a layout */
+ if ( layout['data-type'] != 'layout' )
+ return alert('Cannot load layout file. Please insure that the selected file is a valid Headway layout export.');
+
+ if ( typeof layout['image-definitions'] != 'undefined' && Object.keys(layout['image-definitions']).length ) {
+
+ showNotification({
+ id: 'importing-images',
+ message: 'Currently importing images.',
+ closeTimer: 10000
+ });
+
+ $.post(Headway.ajaxURL, {
+ action: 'headway_visual_editor',
+ method: 'import_images',
+ security: Headway.security,
+ importFile: layout
+ }, function(response) {
+
+ var layout = response;
+
+ /* If there's an error when sideloading images, then hault import. */
+ if ( typeof layout['error'] != 'undefined' )
+ return alert('Error while importing images for layout: ' + layout['error']);
+
+ importLayout(layout);
+
+ });
+
+ } else {
+
+ importLayout(layout);
+
+ }
+
+ }
+
+ layoutReader.readAsText(layoutFile);
+
+ } else {
+
+ alert('Cannot load layout file. Please insure that the selected file is a valid Headway layout export.');
+
+ }
+
+ }
+
+
+ importLayout = function(layout) {
+
+ /* Import all blocks */
+ /* Delete any blocks that are on the grid already */
+ $i('.block').each(function() {
+
+ deleteBlock(this);
+
+ });
+
+ var blocks = layout['blocks'];
+ var numberOfBlocks = Object.keys(blocks).length;
+
+ $.each(blocks, function() {
+
+ var addBlockArgs = {
+ type: this.type,
+ top: this.position.top,
+ left: this.position.left,
+ width: this.dimensions.width,
+ height: this.dimensions.height,
+ settings: this.settings
+ };
+
+ $i('.ui-headway-grid').first().data('ui-headwayGrid').addBlock(addBlockArgs);
+
+ });
+
+ /* Finish Up */
+ showNotification({
+ id: 'layout-successfully-imported',
+ message: 'Layout successfully imported.<br /><br />Remember to save if you wish to keep the layout.',
+ closeTimer: false,
+ closable: true,
+ success: true
+ });
+
+ closeBox('grid-wizard');
+
+ allowSaving();
+
+ return true;
+
+ }
+
+
+ $('div#boxes').delegate('#grid-wizard-import-select-file', 'click', function() {
+
+ $(this).siblings('input[type="file"]').trigger('click');
+
+ });
+
+
+ $('div#boxes').delegate('#grid-wizard-import input[type="file"]', 'change', function(event) {
+
+ if ( event.target.files[0].name.split('.').slice(-1)[0] != 'json' ) {
+
+ $(this).val(null);
+ return alert('Invalid layout file. Please be sure that the layout is a valid JSON formatted file.');
+
+ }
+
+ initiateLayoutImport($(this));
+
+ });
+
+ /* Layout Export */
+ $('div#boxes').delegate('#grid-wizard-export-download-file', 'click', function() {
+
+ var params = {
+ 'action': 'headway_visual_editor',
+ 'security': Headway.security,
+ 'method': 'export_layout',
+ 'layout': Headway.currentLayout
+ }
+
+ var exportURL = Headway.ajaxURL + '?' + $.param(params);
+
+ return window.open(exportURL);
+
+ closeBox('grid-wizard');
+
+ });
+ /* End Import/Export */
+
+
+}
--- /dev/null
+/*
+ * Headway Grid
+ *
+ * Copyright 2011-2014, Headway Themes, LLC
+ *
+ * http://headwaythemes.com
+ */
+define(['jquery', 'helper.history', 'helper.data'], function($, history) {
+
+ $.widget("ui.headwayGrid", $.ui.mouse, {
+ options: {
+ useIndependentGrid: false,
+ columns: Headway.defaultGridColumnCount,
+ columnWidth: Headway.defaultGridColumnWidth,
+ gutterWidth: Headway.defaultGridGutterWidth,
+ yGridInterval: 5,
+ minBlockHeight: 10,
+ selectedBlocksContainerClass: 'selected-blocks-container',
+ defaultBlockClass: 'block',
+ defaultBlockContentClass: 'block-content'
+ },
+
+ _create: function() {
+
+ this.wrapper = this.element;
+ this.container = this.wrapper.find('.grid-container');
+ this.iframe = $(Headway.iframe);
+ this.contents = $(this.iframe).contents();
+ this.document = $(this.iframe).contents();
+
+ /* Populate Grid Options from the Wrapper Settings. This is primarily used for generating the CSS for the Grid so the right ratios and percentages can be made */
+ this.options.useIndependentGrid = this.wrapper.data('wrapper-settings')['use-independent-grid'];
+
+ if ( this.wrapper.data('wrapper-settings')['columns'] )
+ this.options.columns = this.wrapper.data('wrapper-settings')['columns'];
+
+ if ( this.wrapper.data('wrapper-settings')['column-width'] )
+ this.options.columnWidth = this.wrapper.data('wrapper-settings')['column-width'];
+
+ if ( this.wrapper.data('wrapper-settings')['gutter-width'] )
+ this.options.gutterWidth = this.wrapper.data('wrapper-settings')['gutter-width'];
+
+ this.addColumnGuides();
+
+ /* Initialize CSS for this Grid */
+ this.updateGridCSS();
+
+ this.helperTemplate = $('<div class="ui-grid-helper block"></div>');
+ this.offset = this.container.offset();
+
+ this.wrapper.addClass('ui-headway-grid');
+ this.wrapper.disableSelection();
+
+ /* Binding */
+ this._mouseInit();
+
+ /* Click on wrapper to delete blank/new blocks if clicking and not resizing or dragging */
+ this._on(this.wrapper, {
+ mousedown: 'wrapperMouseDown'
+ });
+
+ /* Focus/unfocus mechanism */
+ this._on(this.contents, {
+ mousedown: 'iframeMouseDown',
+ mouseup: 'iframeMouseUp'
+ });
+
+ this._on(this.iframe, {
+ mouseleave: 'iframeMouseLeave'
+ });
+
+ /* z-index focusing on block hover */
+ this._on(this.contents, {
+ mousemove: 'iframeMouseMove'
+ });
+
+ /* Window resize must reset the values of columnWidth and gutterWidth */
+ this._on($(window), {
+ resize: 'resetGridCalculations'
+ });
+
+ this._on($(window), {
+ resize: 'alignAllBlocksWithGuides'
+ });
+ /* End binding */
+
+ this.initResizable(this.container.children('.' + this.options.defaultBlockClass.replace('.', '')));
+ this.initDraggable(this.container.children('.' + this.options.defaultBlockClass.replace('.', '')));
+
+ /* Update Container Height */
+ this.updateGridContainerHeight();
+
+ /* Bind Double Click */
+ this.container.delegate('.' + this.options.defaultBlockClass.replace('.', ''), 'dblclick', function(event) {
+
+ var grid = $(this).parents('.ui-headway-grid').data('ui-headwayGrid');
+
+ //If there's only one grouped block and it's being toggled off, remove all grouping
+ if ( $(this).hasClass('grouped-block') && grid.container.find('.grouped-block').length === 1 ) {
+
+ $(this).removeClass('grouped-block');
+ grid.container.removeClass('grouping-active');
+
+ hideNotification('mass-block-selection');
+
+ //Else if the block is grouped, remove its class only
+ } else if ( $(this).hasClass('grouped-block') ) {
+
+ $(this).removeClass('grouped-block');
+
+ //Else there's no grouping and we need to start it
+ } else {
+
+ $(this).addClass('grouped-block');
+ grid.container.addClass('grouping-active');
+
+ showNotification({
+ id: 'mass-block-selection',
+ message: 'Mass Block Selection Mode',
+ closable: true,
+ closeOnEscKey: true,
+ closeTimer: false,
+ opacity: .8,
+ closeCallback: function() {
+ $i('.grouped-block').removeClass('grouped-block');
+ grid.container.removeClass('grouping-active');
+ }
+ });
+
+ }
+
+ });
+ /* End Binding Double Click */
+
+ /* Insure that blocks are aligned with guides */
+ this.alignAllBlocksWithGuides();
+
+ },
+
+ resetGridCalculations: function() {
+
+ this.grid = {
+ columns: this.container.find('.grid-guide').length,
+ columnWidth: parseInt(this.container.find('.grid-guide:eq(1)').outerWidth()),
+ gutterWidth: parseInt(this.container.find('.grid-guide:eq(1)').css('marginLeft').replace('px', ''))
+ };
+
+ var self = this;
+
+ /* Reset all resizable and draggable grid intervals */
+ this.wrapper.find('.block:visible').each(function() {
+
+ if ( $(this).data('plugin_pep') ) {
+ $(this).data('plugin_pep').options.grid = [self.grid.columnWidth + self.grid.gutterWidth, self.options.yGridInterval];
+ }
+
+ if ( $(this).data('ui-resizable') ) {
+ $(this).resizable('option', 'grid', [self.grid.columnWidth + self.grid.gutterWidth, self.options.yGridInterval]);
+ $(this).resizable('option', 'maxWidth', self.grid.columns * (self.grid.columnWidth + self.grid.gutterWidth));
+ }
+
+ });
+
+ },
+
+ _destroy: function() {
+
+ /* Destroy wrapper resizable and droppable */
+ this.element.resizable('destroy');
+ //this.element.find('.ui-droppable').droppable('destroy');
+
+ /* Destroy grid */
+ this.element
+ .removeClass("ui-grid ui-grid-disabled")
+ .removeData("grid")
+ .unbind(".grid");
+ this._mouseDestroy();
+
+ /* Destroy block resizing and draggables */
+ this.element.find('.ui-resizable').resizable('destroy');
+ //this.element.find('.ui-draggable').draggable('destroy');
+
+ return this;
+
+ },
+
+ disable: function() {
+
+ this.element.resizable('disable');
+ //this.element.find('.ui-droppable').droppable('disable');
+ this.element.find('.ui-resizable').resizable('disable');
+ //this.element.find('.ui-draggable').draggable('disable');
+
+ },
+
+ enable: function() {
+
+ this.element.resizable('enable');
+ // this.element.find('.ui-droppable').droppable('enable');
+ this.element.find('.ui-resizable').resizable('enable');
+ // this.element.find('.ui-draggable').draggable('enable');
+
+ },
+
+ iframeMouseDown: function(event) {
+
+ this._iframeMouseDownEvent = event;
+ this._iframeMouseDownEventElement = $(event.originalEvent.target);
+
+ },
+
+ iframeMouseUp: function(event) {
+
+ delete this._iframeMouseDownEvent;
+ delete this._iframeMouseDownEventElement;
+
+ },
+
+ iframeMouseLeave: function(event) {
+
+ $iDocument().trigger('mouseup');
+
+ },
+
+ iframeMouseMove: function(event) {
+
+ if ( typeof this._iframeMouseDownEvent != 'undefined' || typeof this._doingHoverBlockToTop != 'undefined' || !Headway.touch )
+ return;
+
+ this._doingHoverBlockToTop = true;
+
+ setTimeout($.proxy(function() {
+
+ /* Retrieve the blocks that the mouse is inside */
+ var hoverBlocks = [];
+
+ var mouseX = event.pageX;
+ var mouseY = event.pageY;
+
+ $(this.container).find('.block').each(function() {
+
+ var $this = $(this);
+ var $thisOffset = $this.offset();
+
+ var x1 = $thisOffset.left;
+ var y1 = $thisOffset.top;
+
+ var x2 = x1 + $this.width();
+ var y2 = y1 + $this.height();
+
+ if ( mouseX < x1 || mouseX > x2 )
+ return;
+
+ if ( mouseY < y1 || mouseY > y2 )
+ return;
+
+ hoverBlocks.push($this);
+
+ });
+
+ /* Get the block with boundaries closest to mouse */
+ hoverBlocks.sort(function(a, b) {
+
+ if ( b.width() * b.height() > a.width() * a.height() )
+ return 1;
+
+ return 0;
+
+ });
+
+ this.sendBlockToTop($(hoverBlocks.pop()));
+
+ delete this._doingHoverBlockToTop;
+
+ }, this), 50);
+
+ },
+
+ wrapperMouseDown: function(event) {
+
+ if ( !event || this.container.hasClass('grouping-active') || getBlock(event.target) )
+ return;
+
+ /* Delete any blank blocks that may exist */
+ $i('.blank-block').each(function() {
+ removePanelTab('block-' + getBlockID($(this)));
+ $(this).remove();
+ });
+
+ },
+
+ _mouseStart: function(event) {
+
+ this.mouseStartPosition = [event.pageX - this.container.offset().left, event.pageY - this.container.offset().top];
+
+ var $eventTarget = $(event.target);
+
+ if (
+ !event
+ || event.ctrlKey
+ || this.container.hasClass('grouping-active')
+ || getBlock(event.target)
+ || ($eventTarget.hasClass('wrapper-handle') || $eventTarget.parents('.wrapper-handle').length)
+ || ($eventTarget.hasClass('ui-resizable-handle') && $eventTarget.parent().hasClass('wrapper'))
+ || this.wrapper.hasClass('wrapper-mirrored')
+ )
+ return true;
+
+ this._trigger("start", event);
+
+ this.helper = $(this.helperTemplate).clone().appendTo(this.container);
+
+ //Add the minimum column width to the helper
+ this.helper.css({
+ width: this.grid.columnWidth,
+ height: 0,
+ top: 0,
+ left: 0,
+ display: 'none'
+ });
+
+ /* Hide wrapper handles on drag */
+ if ( this.wrapper.hasClass('wrapper-fluid') )
+ this.wrapper.find('.wrapper-buttons').hide();
+
+ //Set dragging flag
+ this.draggingOnWrapper = true;
+
+ //Show the dimensions tooltip
+ addBlockDimensionsTooltip(this.helper);
+
+ return true;
+
+ },
+
+ _mouseDrag: function(event) {
+
+ var $eventTarget = $(event.target);
+
+ if (
+ !event
+ || !this.helper
+ || event.ctrlKey
+ || this.container.hasClass('grouping-active')
+ || (!this.helper && getBlock(event.target))
+ || ($eventTarget.hasClass('wrapper-handle') || $eventTarget.parents('.wrapper-handle').length)
+ || ($eventTarget.hasClass('ui-resizable-handle') && $eventTarget.parent().hasClass('wrapper'))
+ || (!this.draggingOnWrapper || typeof this.draggingOnWrapper == 'undefined')
+ || this.wrapper.hasClass('wrapper-mirrored')
+ )
+ return;
+
+ var $thisContainer = $(this.container);
+ var $thisContainerOffset = $thisContainer.offset();
+
+ var x1 = this.mouseStartPosition[0];
+ var y1 = this.mouseStartPosition[1];
+
+ var x2 = event.pageX - $thisContainerOffset.left;
+ var y2 = event.pageY - $thisContainerOffset.top;
+
+ if (x1 > x2) { var tmp = x2; x2 = x1; x1 = tmp; }
+ if (y1 > y2) { var tmp = y2; y2 = y1; y1 = tmp; }
+
+ var containerLeft = $thisContainerOffset.left;
+ var containerTop = $thisContainerOffset.top;
+ var containerHeight = $thisContainer.height();
+ var containerWidth = $thisContainer.width();
+
+ /* Handle Padding */
+
+ /* If both start and end points of block are inside right padding, don't draw the block. */
+ if ( x2 >= containerWidth && x1 >= containerWidth )
+ return;
+
+ /* If both start and end points of block are inside bottom padding, don't draw the block. */
+ if ( y2 >= containerHeight && y1 >= containerHeight )
+ return;
+
+ /* If they're starting the drag from the wrapper left padding, start at 0. */
+ if ( x1 < 0 )
+ x1 = 0;
+
+ /* If they're starting the drag from the wrapper top padding, start at 0. */
+ if ( y1 < 0 )
+ y1 = 0;
+
+ /* If start point is inside bottom padding, move it to absolute bottom */
+ if ( y2 > containerHeight ) {
+ y2 = containerHeight;
+ }
+
+ /* End Padding Conditionals */
+
+ var blockLeft = x1.toNearest(this.grid.columnWidth + this.grid.gutterWidth);
+ var blockTop = y1.toNearest(this.options.yGridInterval);
+ var blockWidth = x2.toNearest(this.grid.columnWidth + this.grid.gutterWidth) - blockLeft - this.grid.gutterWidth;
+ var blockHeight = y2.toNearest(this.options.yGridInterval) - y1.toNearest(this.options.yGridInterval);
+
+ Headway.blankBlockOptions = {
+ display: 'block',
+ left: blockLeft,
+ top: blockTop,
+ width: blockWidth,
+ height: blockHeight
+ };
+
+ /* Maxes */
+
+ /* Width Max */
+ if ( blockLeft + blockWidth > (this.grid.columns * (this.grid.columnWidth + this.grid.gutterWidth)) )
+ Headway.blankBlockOptions.width = containerWidth - Headway.blankBlockOptions.left;
+
+ /* If block bleeds out bottom, put a damper there. */
+ if ( event.pageY > (containerTop + containerHeight) ) {
+ Headway.blankBlockOptions.height = containerHeight - blockTop;
+ }
+
+ /* End Maxes */
+
+ /* Apply the CSS */
+ this.helper.css(Headway.blankBlockOptions);
+
+ /* Change width/left to classes to keep finicky bullshit to a minimum */
+ var widthGridNum = Math.round((Headway.blankBlockOptions.width + this.grid.gutterWidth)/(this.grid.columnWidth + this.grid.gutterWidth));
+ var leftGridNum = Math.round(Headway.blankBlockOptions.left/(this.grid.columnWidth + this.grid.gutterWidth));
+
+ if ( widthGridNum == 0 )
+ widthGridNum = 1;
+
+ if ( widthGridNum ) {
+ setBlockGridWidth(this.helper, widthGridNum);
+ }
+
+ if ( leftGridNum ) {
+ setBlockGridLeft(this.helper, leftGridNum);
+ }
+
+ this.alignBlockWithGuides(this.helper);
+ /* End adding classes */
+
+ /* Make block red if it is not big enough */
+ if ( Headway.blankBlockOptions.height < this.options.minBlockHeight ) {
+ this.helper.addClass('block-error');
+ } else if ( this.helper.hasClass('block-error') ) {
+ this.helper.removeClass('block-error');
+ }
+
+ /* Handle dimensions tooltip */
+ if ( !$.support.touch ) {
+
+ this.helper.qtip('option', 'hide.delay', 10000);
+ this.helper.qtip('option', 'show.delay', 10);
+ this.helper.qtip('show');
+ this.helper.qtip('option', 'content.text', blockDimensionsTooltipContent);
+ this.helper.qtip('reposition');
+
+ }
+
+ this._trigger("drag", event);
+
+ this.draggingOnWrapper = true;
+
+ return false;
+
+ },
+
+ _mouseStop: function(event) {
+
+ if (
+ !event
+ || event.ctrlKey
+ || this.container.hasClass('grouping-active')
+ || !this.helper
+ || this.wrapper.hasClass('wrapper-mirrored')
+ )
+ return;
+
+ this._trigger("stop", event);
+
+ Headway.blankBlockOptions = {
+ width: getBlockGridWidth(this.helper),
+ left: getBlockGridLeft(this.helper),
+ pixelWidth: this.helper.width(),
+ pixelLeft: this.helper.position().left,
+ height: this.helper.height(),
+ top: this.helper.position().top,
+ }
+
+ if ( this.helper.qtip('api') )
+ this.helper.qtip('api').destroy(true);
+
+ /* Re-show wrapper handles */
+ this.wrapper.find('.wrapper-buttons').show();
+
+ this.helper.remove();
+ delete this.helper;
+
+ //Check to make sure the block is big enough
+ if ( Headway.blankBlockOptions.pixelWidth < this.grid.columnWidth || Headway.blankBlockOptions.height < this.options.minBlockHeight )
+ return false;
+
+ this.addBlankBlock(Headway.blankBlockOptions);
+
+ this.mouseStartPosition = false;
+
+ delete this.draggingOnWrapper;
+
+ return false;
+
+ },
+
+ initResizable: function(element) {
+
+ if ( typeof element == 'string' ) {
+ var element = $(element);
+ }
+
+ element.resizable({
+ handles: 'n, e, s, w, ne, se, sw, nw',
+ grid:[this.grid.columnWidth + this.grid.gutterWidth, this.options.yGridInterval],
+ containment: this.container,
+ minHeight: this.options.minBlockHeight,
+ maxWidth: this.grid.columns * (this.grid.columnWidth + this.grid.gutterWidth),
+ start: this.resizableStart,
+ resize: this.resizableResize,
+ stop: this.resizableStop
+ });
+
+ },
+
+ resizableStart: function(event, ui) {
+
+ //this variable refers to resizabable
+
+ var block = getBlock(ui.element);
+ var grid = block.parents('.ui-headway-grid').data('ui-headwayGrid');
+
+ var minBlockHeight = parseInt(block.css('minHeight').replace('px', ''));
+ var height = block.height();
+
+ //Remove min-height
+ if ( minBlockHeight <= height ) {
+ block.css('minHeight', 0);
+ }
+
+ //Add the block hover class that keeps the controls, info, and glow visible during resizing
+ block.addClass('block-hover');
+
+ //Show the dimensions tooltip
+ block.qtip('option', 'hide.delay', 10000);
+
+ block.qtip('show');
+ block.qtip('reposition');
+
+ /* Set originals */
+ $(block).data('old-position', getBlockPosition(block));
+ $(block).data('old-position-pixels', getBlockPositionPixels(block));
+
+ $(block).data('old-dimensions', getBlockDimensions(block));
+ $(block).data('old-dimensions-pixels', getBlockDimensionsPixels(block));
+
+ /* Hide wrapper handles */
+ if ( grid.wrapper.hasClass('wrapper-fluid') )
+ grid.wrapper.find('.wrapper-buttons').hide();
+
+ },
+
+ resizableResize: function(event, ui) {
+
+ var block = getBlock(ui.element);
+ var grid = block.parents('.ui-headway-grid').data('ui-headwayGrid');
+
+ /* Set classes to get rid of finicky-ness and to make the block stay in line with guides */
+ var widthGridNum = Math.round((block.width() + grid.grid.gutterWidth)/(grid.grid.columnWidth + grid.grid.gutterWidth));
+ var leftGridNum = Math.round(block.position().left/(grid.grid.columnWidth + grid.grid.gutterWidth));
+
+ setBlockGridWidth(block, widthGridNum);
+ setBlockGridLeft(block, leftGridNum);
+
+ grid.alignBlockWithGuides(block);
+
+ //Update the dimensions tooltip
+ var qtip = block.data('qtip');
+
+ $i('#qtip-' + qtip.id).remove();
+ qtip.rendered = false;
+ qtip.render();
+ qtip.show();
+
+ },
+
+ resizableStop: function(event, ui) {
+
+ //this variable refers to resizable
+ var block = getBlock(ui.element);
+ var grid = block.parents('.ui-headway-grid').data('ui-headwayGrid');
+
+ /* Setup variables for undo/redo */
+ var oldBlockPosition = block.data('old-position');
+ var oldBlockDimensions = block.data('old-dimensions');
+
+ var newBlockPosition = {
+ left: Math.round(block.position().left / (grid.grid.columnWidth + grid.grid.gutterWidth)),
+ top: getBlockPositionPixels(block).top
+ }
+
+ var newBlockDimensions = {
+ width: Math.ceil(block.width() / (grid.grid.columnWidth + grid.grid.gutterWidth)),
+ height: getBlockDimensionsPixels(block).height
+ }
+
+ /* Re-show wrapper handles */
+ grid.wrapper.find('.wrapper-buttons').show();
+
+ var handleBlockResize = function(dimensions, position) {
+
+ //Update classes and CSS
+ setBlockGridWidth(block, dimensions.width);
+ setBlockGridLeft(block, position.left);
+
+ //Update height
+ block.height(dimensions.height);
+
+ //Update top position
+ block.css('top', position.top + 'px');
+
+ block.attr({
+ 'data-grid-top': position.top,
+ 'data-height': dimensions.height
+ });
+
+ finishBlockResize();
+
+ }
+
+ var finishBlockResize = function() {
+
+ block.css('width', '');
+ block.css('left', '');
+
+ grid.alignBlockWithGuides(block);
+
+ //Add hidden input
+ dataSetBlockDimensions(getBlockID(block), getBlockDimensions(block));
+ dataSetBlockPosition(getBlockID(block), getBlockPosition(block));
+
+ //Check for intersectors and allow saving if possible
+ blockIntersectCheck(block) ? allowSaving() : disallowSaving();
+
+ //Show the dimensions tooltip
+ block.qtip('option', 'show.delay', 300);
+ block.qtip('option', 'hide.delay', 25);
+
+ block.qtip('show');
+ block.qtip('reposition');
+
+ //Remove the block hover class that keeps the controls, info, and glow visible during resizing
+ block.removeClass('block-hover');
+
+ }
+
+ Headway.history.add({
+ description: 'Resized block',
+ up: function() {
+
+ handleBlockResize(newBlockDimensions, newBlockPosition);
+
+ },
+ down: function() {
+
+ handleBlockResize(oldBlockDimensions, oldBlockPosition);
+
+ }
+ });
+
+ },
+
+ initDraggable: function(element) {
+
+ if ( typeof element == 'string' ) {
+ element = $(element);
+ }
+
+ element.css('cursor', 'move').pep({
+ grid: [this.grid.columnWidth + this.grid.gutterWidth, this.options.yGridInterval],
+ constrainTo: 'parent',
+ shouldEase: false,
+ start: this.draggableStart,
+ stop: this.draggableStop,
+ drag: this.draggableDrag
+ });
+
+ },
+
+ draggableStart: function(event, ui) {
+
+ /* If control key used to right-click, then stop this draggable */
+ if ( event.ctrlKey )
+ return false;
+
+ if ( $(event.target).hasClass('ui-resizable-handle') ) {
+ $(ui.el).trigger('stop');
+ return false;
+ }
+
+ var block = ui.el;
+ var grid = getBlock(block).parents('.ui-headway-grid').data('ui-headwayGrid');
+
+ //Grouping Code
+ blockGroupingOriginals = {};
+
+ blockGroupingOriginals[getBlockID(block)] = {
+ top: getBlockPositionPixels(block).top,
+ left: getBlockPositionPixels(block).left
+ }
+
+ //If it's a grouped block, move group, otherwise reset group
+ if ( $(block).hasClass('grouped-block') ) {
+
+ $(block).data('plugin_pep').$el = grid.container.find('.grouped-block');
+
+ grid.container.find('.grouped-block').each(function(i) {
+
+ $(this).data('old-position', getBlockPosition($(this)));
+ $(this).data('old-position-pixels', getBlockPositionPixels($(this)));
+
+ });
+
+ //Bring the blocks to the top
+ grid.sendBlockToTop(grid.container.find('.grouped-block'));
+
+ } else {
+
+ grid.container.removeClass('grouping-active');
+ grid.container.find('.grouped-block').removeClass('grouped-block');
+
+ hideNotification('mass-block-selection');
+
+ grid.sendBlockToTop($(block));
+
+ $(block).data('plugin_pep').$el = $(block);
+ $(block).data('old-position', getBlockPosition(block));
+ $(block).data('old-position-pixels', getBlockPositionPixels(block));
+
+ }
+ //End Grouping Code
+
+ /* Hide wrapper handles */
+ if ( grid.wrapper.hasClass('wrapper-fluid') )
+ grid.wrapper.find('.wrapper-buttons').hide();
+
+ //Hide dimensions tooltip
+ $(getBlock(ui.el)).qtip('hide');
+ $(getBlock(ui.el)).qtip('disable');
+
+ },
+
+ draggableDrag: function(event, ui) {
+
+ if ( $(ui.startEvent.target).hasClass('ui-resizable-handle') ) {
+ return false;
+ }
+
+ var block = ui.el;
+ var $this = $(block);
+ var isOverlapping;
+
+ var container = getBlock($(block)).parents('.grid-container');
+ var grid = getBlock($(block)).parents('.ui-headway-grid').data('ui-headwayGrid');
+ var wrapper = getBlock($(block)).parents('.wrapper');
+
+ /* Check if mouse coordinates are overlapping another wrapper. If they are then show droppable effect. */
+ if ( $i('.grid-container').length > 1 && !grid.container.find('.grouped-block').length ) {
+
+ $i('.grid-container').not(container).each(function() {
+
+ var wrapperBounding = $(this).closest('.wrapper')[0].getBoundingClientRect();
+ var containerBounding = $(this)[0].getBoundingClientRect();
+
+ isOverlapping = ( event.pageX > wrapperBounding.left &&
+ event.pageX < wrapperBounding.right &&
+ event.pageY > wrapperBounding.top + $iDocument().scrollTop() &&
+ event.pageY < wrapperBounding.bottom + $iDocument().scrollTop() );
+
+ isOverlapping ? $(this).addClass('ui-state-hover') : $(this).removeClass('ui-state-hover');
+
+ if ( isOverlapping ) {
+
+ var clone = $(block).data('wrapper-droppable-clone');
+ var overlapOffset = {
+ top: event.pageY - containerBounding.top - $iDocument().scrollTop(),
+ left: event.pageX - containerBounding.left
+ };
+
+ /* Clone the block and move it into the possible destination wrapper */
+ if ( !clone ) {
+
+ var clone = $(block).clone()
+ .css({
+ transform: '',
+ left: $(block).position().left.toNearest(grid.grid.columnWidth + grid.grid.gutterWidth)
+ })
+ .appendTo($(this));
+
+ /* Calculate initial difference upon entry so the block left is correct */
+ clone.data('left-difference', overlapOffset.left - $(block).position().left.toNearest(grid.grid.columnWidth + grid.grid.gutterWidth));
+
+ /* Ghost the original block */
+ $(block)
+ .data('ghost-position', $(block).position())
+ .css({
+ transform: '',
+ left: blockGroupingOriginals[getBlockID($(block))].left,
+ top: blockGroupingOriginals[getBlockID($(block))].top
+ })
+ .addClass('block-ghost');
+
+ $(block).data('wrapper-droppable-clone', clone);
+
+ delete $(block).data('plugin_pep').translation;
+ delete $(block).data('plugin_pep').cssX;
+ delete $(block).data('plugin_pep').cssY;
+
+ }
+
+ /* Make sure limits aren't met with width and heights */
+ var blockTopPosition = parseInt(overlapOffset.top).toNearest(grid.options.yGridInterval);
+ var blockLeftPosition = parseInt(overlapOffset.left - clone.data('left-difference')).toNearest(grid.grid.columnWidth + grid.grid.gutterWidth);
+
+ /* Do not let block top position be less than 0... In other words, not outside the top of the container */
+ if ( blockTopPosition < 0 )
+ blockTopPosition = 0;
+
+ /* Do not allow the left position to be less than zero */
+ if ( blockLeftPosition < 0 )
+ blockLeftPosition = 0;
+
+ /* Do not left the left + width exceed the grid container width */
+ if ( parseInt(blockLeftPosition) + parseInt($(block).width()) > $(this).width() ) {
+ blockLeftPosition = $(this).width() - $(block).width();
+ }
+
+ /* Adjust height of wrapper accordingly */
+ if ( $(block).height() + blockTopPosition > $(this).height() ) {
+ blockTopPosition = $(this).height() - $(block).height();
+ }
+
+ if ( $(block).height() > $(this).height() ) {
+
+ if ( !$(this).attr('data-original-height') ) {
+ $(this).attr('data-original-height', $(this).height());
+ }
+
+ $(this).height($(block).height());
+
+ }
+
+ /* Move the clone accordingly */
+ $(clone).css({
+ transform: '',
+ top: parseInt(blockTopPosition).toNearest(grid.options.yGridInterval),
+ left: parseInt(blockLeftPosition).toNearest(grid.grid.columnWidth + grid.grid.gutterWidth)
+ });
+
+ /* If an overlap is found don't check the other wrappers */
+ return false;
+
+ }
+
+ });
+
+
+ /* If there are no overlaps then remove the clones and unghost the block */
+ if ( !isOverlapping ) {
+
+ $i('.block-ghost').each(function() {
+
+ $(this).data('wrapper-droppable-clone').remove();
+ $(this).removeData('wrapper-droppable-clone');
+
+ $(this).removeClass('block-ghost');
+
+ $(this).css({
+ left: $(this).data('ghost-position').left,
+ top: $(this).data('ghost-position').top
+ });
+
+ });
+
+ /* Change container heights back */
+ $i('[data-original-height]').each(function() {
+
+ $(this).height($(this).data('original-height'));
+ $(this).removeAttr('data-original-height');
+
+ });
+
+ }
+
+ }
+
+ /* If the block is overlapping another wrapper, keep it from moving in the current wrapper */
+ if ( isOverlapping ) {
+ return false;
+ }
+
+ //Hide dimensions tooltip
+ $(getBlock(ui.helper)).qtip('hide');
+
+ },
+
+ draggableStop: function(event, ui) {
+
+ if ( $(ui.startEvent.target).hasClass('ui-resizable-handle') ) {
+ return false;
+ }
+
+ //this variable refers to draggable
+ var block = $(ui.el);
+ var container = getBlock($(block)).parents('.grid-container');
+ var grid = getBlock($(block)).parents('.ui-headway-grid').data('ui-headwayGrid');
+ var isOverlapping;
+ var destinationContainer;
+
+ /* Handle moving block from one wrapper to another */
+ if ( $i('.grid-container').length > 1 && !grid.container.find('.grouped-block').length ) {
+
+ $i('.grid-container').not(container).each(function() {
+
+ var wrapperBounding = $(this).closest('.wrapper')[0].getBoundingClientRect();
+ isOverlapping = ( event.pageX > wrapperBounding.left &&
+ event.pageX < wrapperBounding.right &&
+ event.pageY > wrapperBounding.top + $iDocument().scrollTop() &&
+ event.pageY < wrapperBounding.bottom + $iDocument().scrollTop() );
+
+ /* Second conditional is for triggering isOverlapping when the cursor triggers the mouseup by leaving the iframe */
+ if ( isOverlapping || (!event.originalEvent && $(this).find($(block).data('wrapper-droppable-clone')).length) ) {
+ isOverlapping = true;
+ destinationContainer = $(this);
+ return false;
+ } else {
+ destinationContainer = false;
+ }
+
+ });
+
+ }
+
+ /* Remove all .ui-state-hover classes from grid containers */
+ $i('.grid-container.ui-state-hover').removeClass('ui-state-hover');
+
+ if ( isOverlapping && $i('.grid-container').length > 1 ) {
+
+ var destinationContainerHeadwayGrid = destinationContainer.parents('.wrapper').data('ui-headwayGrid');
+ var originalContainer = block.parents('.grid-container');
+
+ /* Move block to destination container */
+ destinationContainer.append(block);
+
+ /* Copy position from clone */
+ $(block).css($(block).data('wrapper-droppable-clone').position());
+
+ /* Delete clone */
+ $(block).data('wrapper-droppable-clone').remove();
+
+ $(block)
+ .removeClass('block-ghost')
+ .removeData('wrapper-droppable-clone');
+
+ setBlockGridLeft(block, Math.round($(block).position().left / (grid.grid.columnWidth + grid.grid.gutterWidth)));
+
+ $i('[data-original-height]').removeAttr('data-original-height');
+
+ /* Change draggable/resizable containment on block to destination */
+ block.resizable('destroy');
+ destinationContainer.parents('.wrapper').headwayGrid('initResizable', block);
+
+ $.pep.unbind(block);
+ destinationContainer.parents('.wrapper').headwayGrid('initDraggable', block);
+
+ /* Do block intersect check */
+ blockIntersectCheck(false, originalContainer);
+ blockIntersectCheck(false, destinationContainer);
+
+ /* Set data */
+ dataSetBlockPosition(getBlockID(block), getBlockPosition(block));
+
+ /* Change the wrapper ID for the block and queue it for saving */
+ dataSetBlockWrapper(getBlockID(block), getBlockWrapper(block).attr('id'));
+
+ /* Re-align this block with the new wrapper */
+ block.parents('.ui-headway-grid').first().data('ui-headwayGrid').alignBlockWithGuides(block);
+
+ }
+ /* End droppable handling */
+
+ //Build the list of blocks that need to be updated, if there are grouped blocks then update them (which will include the one dragged)
+ if ( grid.container.find('.grouped-block').length ) {
+
+ var blocks = grid.container.find('.grouped-block');
+
+ //Else we just have the one block to update
+ } else {
+
+ var blocks = getBlock(ui.el);
+
+ }
+
+ /* Re-show wrapper handles */
+ grid.wrapper.find('.wrapper-buttons').show();
+
+ //Move the blocks and set hiddens //
+ var blocksToMove = [];
+
+ //Loop through each block now and build the todo array
+ if ( blocks.length === 1 ) {
+ var description = 'Moved block';
+ } else {
+ var description = 'Mass Moved Blocks: ';
+ }
+
+ blocks.each(function(){
+
+ blocksToMove.push({
+ block: $(this),
+
+ newPosition: {
+ left: Math.round($(this).position().left / (grid.grid.columnWidth + grid.grid.gutterWidth)),
+ top: getBlockPositionPixels($(this)).top
+ },
+ newPositionPixels: getBlockPositionPixels($(this)),
+
+ oldPosition: $(this).data('old-position'),
+ oldPositionPixels: $(this).data('old-position-pixels')
+ });
+
+ if ( blocks.length > 1 )
+ description += ', ';
+
+ });
+
+ if ( blocks.length > 1 )
+ description = description.substring(0, description.length - 2);
+
+ //Loop through todo array and log history
+ var handleBlockDrag = function(options, reverse) {
+
+ var block = options.block;
+
+ var targetGridLeft = options.newPosition.left;
+ var targetGridTop = options.newPosition.top;
+ var targetPixelsLeft = options.newPositionPixels.left;
+
+ if ( reverse ) {
+
+ targetGridLeft = options.oldPosition.left;
+ targetGridTop = options.oldPosition.top;
+ targetPixelsLeft = options.oldPositionPixels.left;
+
+ }
+
+ //Update classes and CSS
+ setBlockGridLeft(block, targetGridLeft);
+
+ block.attr({
+ 'data-grid-top': targetGridTop
+ });
+
+ /* Remove Hardware acceleration transform and switch it to regular top/left and reset Pep */
+ block.css('top', targetGridTop + 'px');
+ block.css('left', targetPixelsLeft + 'px');
+
+ block.css({
+ 'transform': '',
+ '-webkit-transform': '',
+ '-moz-transform': '',
+ '-ms-transform': '',
+ '-o-transform': ''
+ });
+
+ delete block.data('plugin_pep').translation;
+ delete block.data('plugin_pep').cssX;
+ delete block.data('plugin_pep').cssY;
+
+ //Add hidden inputs
+ dataSetBlockPosition(getBlockID(block), getBlockPosition(block));
+ dataSetBlockWrapper(getBlockID(block), getBlockWrapper(block).attr('id'));
+
+ //Check for intersectors and allow saving if possible
+ if ( blockIntersectCheck(block) ) {
+ allowSaving();
+ } else {
+ disallowSaving();
+ }
+
+ }
+
+ /* Do the action */
+ Headway.history.add({
+ description: description,
+ up: function() {
+
+ jQuery.each(blocksToMove, function(index, options) {
+ handleBlockDrag(options, false);
+ });
+
+ },
+ down: function() {
+
+ jQuery.each(blocksToMove, function(index, options) {
+ handleBlockDrag(options, true);
+ });
+
+ }
+ });
+ //End setting hiddens
+
+ //Make sure document is focused
+ $(document).focus();
+
+ //Re-enable tooltip
+ $(getBlock(ui.el)).qtip('enable');
+ $(getBlock(ui.el)).qtip('show');
+
+ //Reposition dimensions tooltip
+ $(block).data('hoverWaitTimeout', setTimeout(function() {
+
+ $(getBlock(ui.el)).qtip('reposition');
+ $(getBlock(ui.el)).qtip('show');
+
+ }, 300));
+
+ },
+
+ addBlankBlock: function(args, usingAddBlock) {
+
+ var defaults = {
+ top: 0,
+ left: 0,
+ width: 140,
+ height: this.options.minBlockHeight,
+ id: null
+ }
+
+ args = $.extend({}, defaults, args);
+
+ if ( typeof usePixels == 'undefined' )
+ var usePixels = true;
+
+ if ( typeof usingAddBlock == 'undefined' )
+ usingAddBlock = false;
+
+ var temporaryID = Math.ceil(Math.random() * 1000000000);
+
+ Headway.blankBlock = $('<div><div class="block-content-fade block-content"></div></div>')
+ .attr('id', 'block-' + temporaryID)
+ .attr('data-id', temporaryID)
+ .attr('data-temp-id', temporaryID)
+ .attr('data-desired-id', args.id ? args.id : null)
+ .addClass(this.options.defaultBlockClass.replace('.', ''))
+ .addClass('blank-block')
+ .addClass('hide-content-in-grid');
+
+ updateBlockContentCover(Headway.blankBlock);
+
+ var block = Headway.blankBlock;
+
+ /* Setup block in DOM */
+ block.css({
+ height: parseInt(args.height),
+ top: parseInt(args.top),
+ position: 'absolute',
+ visibility: 'hidden',
+ left: '',
+ width: ''
+ });
+
+ setBlockGridLeft(block, args.left);
+ setBlockGridWidth(block, args.width);
+
+ block.attr({
+ 'data-height': parseInt(args.height),
+ 'data-grid-top': parseInt(args.top)
+ });
+
+ block.appendTo(this.container);
+
+ this.alignBlockWithGuides(block);
+ block.css('visibility', 'visible');
+
+ //Add this conditional in so addBlock doesn't take as long
+ if ( usingAddBlock == false ) {
+ openBlockTypeSelector($(Headway.blankBlock));
+ }
+
+ //Initiate stuff
+ this.initResizable(block);
+ this.initDraggable(block);
+
+ //Show the red right off the bat if the block is touching/overlapping other blocks
+ blockIntersectCheck(block);
+
+ return block;
+
+ },
+
+ setupBlankBlock: function(blockType, usingAddBlock, loadContent) {
+
+ if ( typeof loadContent == 'undefined' )
+ var loadContent = true;
+
+ if ( typeof usingAddBlock == 'undefined' )
+ var usingAddBlock = false;
+
+ Headway.blankBlock.removeClass('blank-block');
+ Headway.blankBlock.addClass('block-type-' + blockType);
+ Headway.blankBlock.data('type', blockType);
+
+ if ( loadContent ) {
+
+ loadBlockContent({
+ blockElement: Headway.blankBlock,
+ blockOrigin: {
+ type: blockType,
+ id: 0,
+ layout: Headway.currentLayout
+ },
+ blockSettings: {
+ dimensions: getBlockDimensions(Headway.blankBlock),
+ position: getBlockPosition(Headway.blankBlock)
+ },
+ });
+
+ }
+
+ //Set the fluid/fixed height class so the fluid height message is shown correctly
+ if ( getBlockTypeObject(blockType)['fixed-height'] === true ) {
+
+ Headway.blankBlock.addClass('block-fixed-height');
+
+ } else {
+
+ Headway.blankBlock.addClass('block-fluid-height');
+
+ }
+
+ //Set the hide-content-in-grid depending on the block type
+ if ( getBlockTypeObject(blockType)['show-content-in-grid'] )
+ Headway.blankBlock.removeClass('hide-content-in-grid');
+
+ //Add the hidden input flag
+ dataAddBlock(Headway.blankBlock);
+ dataSetBlockPosition(getBlockID(Headway.blankBlock), getBlockPosition(Headway.blankBlock));
+ dataSetBlockDimensions(getBlockID(Headway.blankBlock), getBlockDimensions(Headway.blankBlock));
+ dataSetBlockWrapper(getBlockID(Headway.blankBlock), Headway.blankBlock.closest('.wrapper').attr('id'));
+
+ //Check for intersectors and allow saving if possible
+ if ( blockIntersectCheck(Headway.blankBlock) ) {
+ allowSaving();
+ } else {
+ disallowSaving();
+ }
+
+ updateBlockContentCover(Headway.blankBlock);
+
+ //Save block variable to return it at the end
+ var block = Headway.blankBlock;
+
+ //Make this undoable/redoable
+ Headway.history.add({
+ description: 'Added ' + getBlockTypeNice(blockType) + ' block',
+ up: function() {
+
+ //Reshow the block
+ block.show();
+
+ if ( typeof GLOBALunsavedValues['blocks'][getBlockID(block)]['delete'] != 'undefined' ) {
+ delete GLOBALunsavedValues['blocks'][getBlockID(block)]['delete'];
+ }
+
+ blockIntersectCheck(block, block.parents('.grid-container'));
+
+ },
+ down: function() {
+
+ //Remove the block!
+ block.hide();
+
+ //Remove block options tab from panel
+ removePanelTab('block-' + getBlockID(block));
+
+ //Add the hidden input flag
+ dataDeleteBlock(getBlockID(block));
+
+ //Set block to false for the intersect check
+ blockIntersectCheck(false, block.parents('.grid-container'));
+
+ }
+ });
+
+
+ //Clear variable
+ delete Headway.blankBlock;
+ delete Headway.blankBlockOptions;
+
+ return block;
+
+ },
+
+ addBlock: function(args) {
+
+ var defaults = {
+ top: 0,
+ left: 0,
+ width: 1,
+ height: this.options.minBlockHeight,
+ type: null,
+ id: null,
+ settings: []
+ }
+
+ var args = $.extend({}, defaults, args);
+
+ if ( this.addBlankBlock(args, true) ) {
+
+ var block = this.setupBlankBlock(args.type, true, false);
+ var blockID = getBlockID(block);
+
+ $.each(args.settings, function(key, value) {
+
+ dataSetBlockOption(blockID, key, value);
+
+ if ( key == 'mirror-block' ) {
+ updateBlockMirrorStatus(false, block, value, false);
+ }
+
+ });
+
+ refreshBlockContent(blockID, false, false, false);
+
+ this.updateGridContainerHeight();
+
+ return block;
+
+ } else {
+
+ return false;
+
+ }
+
+ },
+
+ sendBlockToTop: function(block) {
+
+ if ( typeof block == 'string' )
+ var block = getBlock(block);
+
+ if ( !block || !block.length )
+ return;
+
+ $i('.block').css('zIndex', 1);
+ block.css('zIndex', 2);
+
+ },
+
+ updateGridContainerHeight: function() {
+
+ var container = this.container;
+ var wrapper = this.wrapper;
+
+ /* Reset container height */
+ container.css('height', this.wrapper.height());
+
+ /* Resize container to fit the lowest block bottom (block top + block height) */
+ if ( container.find('.block:visible').length ) {
+
+ var bottomToUse = 0;
+
+ container.find('.block:visible').each(function() {
+
+ var blockBottom = $(this).outerHeight() + $(this).position().top;
+
+ if ( blockBottom > bottomToUse )
+ bottomToUse = blockBottom;
+
+ });
+
+ container.height(bottomToUse);
+
+ }
+
+ },
+
+ addColumnGuides: function() {
+
+ var gridContainer = this.container;
+
+ /* Remove existing grid guides container */
+ gridContainer.find('.grid-guides').remove();
+
+ var gridGuidesContainer = $('<div class="grid-guides grid-guides-grey"></div><!-- #grid -->');
+
+ for ( i = 1; i <= this.options.columns; i++ )
+ gridGuidesContainer.append('<div class="grid-guide grid-width-1 grid-guide-' + i + '"></div>');
+
+ gridGuidesContainer.prependTo(gridContainer);
+
+ },
+
+ alignBlockWithGuides: function(block) {
+
+ /* SET GRID LEFT TO THE LEFT EDGE OF THE GRID GUIDE AND SET WIDTH TO THE END OF THE OTHER GRID GUIDE TO COMPENSATE FOR PERCENTAGE MISCALCULATIONS */
+ var gridGuidesContainer = this.container.children('.grid-guides:visible');
+
+ if ( !gridGuidesContainer.length )
+ return;
+
+ var leftGridNum = parseInt(getBlockGridLeft(block));
+ var widthGridNum = parseInt(getBlockGridWidth(block));
+
+ if ( typeof leftGridNum == 'undefined' || isNaN(leftGridNum) || leftGridNum < 0 )
+ leftGridNum = 0;
+
+ if ( typeof widthGridNum == 'undefined' || isNaN(widthGridNum) || widthGridNum == 0 )
+ widthGridNum = 1;
+
+ var leftGridGuideNum = ((leftGridNum + 1) < this.grid.columns) ? (leftGridNum + 1) : this.grid.columns;
+ var leftGridGuide = gridGuidesContainer.find('.grid-guide-' + leftGridGuideNum);
+
+ /* Do not search for a right grid guide that exceeds column count */
+ var rightGridGuideNum = ((leftGridNum + widthGridNum) < this.grid.columns) ? (leftGridNum + widthGridNum) : this.grid.columns;
+ var rightGridGuide = gridGuidesContainer.find('.grid-guide-' + rightGridGuideNum);
+
+ if ( !rightGridGuide.length )
+ rightGridGuide = leftGridGuide;
+
+ if ( (leftGridNum + 1) <= (leftGridNum + widthGridNum) ) {
+
+ var leftGridGuideMargin = parseInt(leftGridGuide.css('marginLeft').replace('px', ''));
+ var rightGridGuideMargin = parseInt(rightGridGuide.css('marginLeft').replace('px', ''));
+
+ var leftAmount = leftGridGuide.position().left + leftGridGuideMargin;
+ var rightAmount = (rightGridGuide.position().left + rightGridGuide.outerWidth()) - (leftGridGuide.position().left) - 1;
+
+ if ( leftGridNum == 0 )
+ rightAmount = rightAmount + rightGridGuideMargin;
+
+ block.css({
+ top: $(block).position().top,
+ transform: '',
+ left: Math.ceil(leftAmount) + 'px',
+ width: Math.ceil(rightAmount) + 'px'
+ });
+
+ }
+
+ },
+
+ alignAllBlocksWithGuides: function() {
+
+ var grid = this;
+
+ this.container.find('.block:visible').each(function() {
+
+ grid.alignBlockWithGuides($(this));
+
+ });
+
+ },
+
+ /**
+ * Used to recalculate all CSS for a wrapper and its grid. Can simply be fed column count, columnWidth, and gutterWidth and it will do the heavy lifting
+ **/
+ updateGridCSS: function() {
+
+ var self = this;
+
+ var wrapper = this.wrapper;
+ var gridWidthInputContext = $('div#wrapper-' + getWrapperID(wrapper) + '-tab');
+
+ var wrapperSelector = 'div#' + wrapper.attr('id');
+
+ if ( wrapper.attr('data-temp-id') )
+ wrapperSelector = 'div.wrapper[data-temp-id="' + wrapper.attr('data-temp-id') + '"]';
+
+ if (
+ typeof this.options.useIndependentGrid != 'undefined' &&
+ this.options.useIndependentGrid === true ||
+ ( typeof this.options.useIndependentGrid == 'string' && hwBoolean(this.options.useIndependentGrid) )
+ ) {
+ updateGridCSS(wrapperSelector, this.options.columns, this.options.columnWidth, this.options.gutterWidth, gridWidthInputContext);
+ } else {
+ updateGridCSS(wrapperSelector, this.options.columns, Headway.globalGridColumnWidth, Headway.globalGridGutterWidth, gridWidthInputContext);
+ }
+
+ /* Reset Grid Calculations */
+ this.resetGridCalculations();
+
+ /* Align all blocks with guides */
+ $($iDocument()).ready(function() {
+ self.alignAllBlocksWithGuides();
+ });
+
+ return wrapper;
+
+ }
+
+ });
+
+ $.extend($.ui.headwayGrid, {
+ version: "2.1"
+ });
+
+
+});
\ No newline at end of file
--- /dev/null
+define(['jquery', 'modules/grid/grid', 'deps/itstylesheet', 'modules/grid/wrappers', 'modules/grid/wrapper-inputs', 'modules/grid/grid-wizard', 'deps/jquery.pep', 'helper.blocks', 'helper.wrappers'], function($, hwGrid, wrappers) {
+
+ var modeGrid = {
+ init: function() {
+
+ bindGridWizard();
+
+ },
+
+ iframeCallback: function() {
+
+ /* Load block content */
+ $i('.block').each(function() {
+
+ updateBlockContentCover($(this));
+
+ loadBlockContent({
+ blockElement: $(this),
+ blockOrigin: getBlockID($(this))
+ });
+
+ });
+
+ /* Initialize Grid Stylesheet */
+ gridStylesheet = new ITStylesheet({document: Headway.iframe.contents()[0], href: '/?headway-trigger=compiler&file=ve-iframe-grid-dynamic'}, 'find');
+
+ addEdgeInsertWrapperButtons();
+
+ addWrapperButtons($i('div.wrapper'));
+ bindWrapperButtons();
+
+ setupWrapperSortables();
+ setupWrapperResizable();
+ setupWrapperContextMenu();
+
+ assignDefaultWrapperID();
+
+ /* If this is a new layout and there are no blocks, then set the Grid Container on the (only) wrapper to 500px */
+ if ( $i('.grid-container').length === 1 && !$i('.block').length ) {
+ $i('.grid-container').height(500);
+ }
+
+ /* Initiate Headway Grid */
+ $i('div.wrapper').headwayGrid();
+
+ /* Disable Grid on mirrored wrappers */
+ $i('div.wrapper-mirrored').headwayGrid('disable');
+
+ /* Update Default Grid Width Input */
+ updateGridWidthInput('#sub-tab-grid-content');
+
+ setupBlockContextMenu();
+ bindBlockDimensionsTooltip();
+
+ }
+
+
+ }
+
+ updateGridCSS = function(wrapperCSSSelector, columns, columnWidth, gutterWidth, gridWidthInputContext) {
+
+ /* Calculate Grid Width */
+ var gridWidth = (columnWidth * columns) + ((columns - 1) * gutterWidth);
+
+ /* Calculate percentages for column widths and margins */
+ var ratioColumnWidth = (columnWidth * columns) / gridWidth;
+ var ratioGutterWidth = (gutterWidth * columns) /gridWidth;
+
+ var singlePercentageColumnWidth = (100 / columns) * ratioColumnWidth;
+ var singlePercentageGutterWidth = (100 / columns) * ratioGutterWidth;
+
+ /* Define round precision in one place so it can be changed if necessary */
+ var roundPrecision = 9;
+
+ /* Wrapper CSS Prefix that way these changes don't modify other wrappers */
+ var wrapperCSSPrefix = wrapperCSSSelector + ' ';
+
+ /* Send calculated percentages to CSS */
+ /* Grid Guides */
+ gridStylesheet.update_rule(wrapperCSSPrefix + '.grid-guides .grid-guide', {margin: '0 0 0 ' + Math.round(singlePercentageGutterWidth, roundPrecision) + '%'});
+
+ /* Grid Width/Grid Left Classes */
+ for ( i = 1; i <= columns; i++ ) {
+
+ gridStylesheet.update_rule(wrapperCSSPrefix + '.grid-width-' + i, {width: Math.round((singlePercentageColumnWidth * i + ((i - 1) * singlePercentageGutterWidth)), roundPrecision) + '%'});
+ gridStylesheet.update_rule(wrapperCSSPrefix + '.grid-left-' + i, {left: '0 0 0 ' + Math.round(((singlePercentageColumnWidth + singlePercentageGutterWidth) * i), roundPrecision) + '%'});
+
+ }
+
+ /* Grid Container */
+ gridStylesheet.update_rule(wrapperCSSPrefix + 'div.grid-container', {width: (gridWidth + 1) + 'px'});
+
+ /* Wrapper */
+ gridStylesheet.update_rule(wrapperCSSSelector + '.wrapper-fixed', {width: (gridWidth) + 'px'});
+
+ /* Update Grid Width Read-Only Input If Present */
+ if ( typeof gridWidthInputContext != 'undefined' && gridWidthInputContext.length )
+ updateGridWidthInput(gridWidthInputContext);
+
+ }
+
+ return modeGrid;
+
+});
\ No newline at end of file
--- /dev/null
+
+/* WRAPPER OPTION INPUT CALLBACKS */
+ /* Grid Settings */
+ wrapperOptionCallbackIndependentGrid = function(input, value) {
+
+ var wrapper = $i("#wrapper-" + input.parents("[data-panel-args]").data("panel-args").wrapper.id);
+
+ if ( typeof wrapper == 'undefined' || !wrapper.length )
+ return false;
+
+ /* Find wrapper and Headway Grid UI widget */
+ var wrapperGridObject = wrapper.data('ui-headwayGrid');
+
+ /* Update wrapper object and the guides */
+ wrapperGridObject.options.useIndependentGrid = value;
+
+ /* Finalize: Update the Wrapper/Grid CSS and reset draggable/resizable, etc */
+ wrapperGridObject.updateGridCSS();
+
+ }
+
+
+ wrapperOptionCallbackColumnCount = function(input, value) {
+
+ var wrapper = $i("#wrapper-" + input.parents("[data-panel-args]").data("panel-args").wrapper.id);
+
+ if ( typeof wrapper == 'undefined' || !wrapper.length )
+ return false;
+
+ /* Throw error saying column count can't be changed if there are blocks in the grid */
+ if ( wrapper.find('.block:visible').length ) {
+
+ alert("This wrapper must be empty of blocks before you can change the number of columns.\n\nEither drag the blocks to another wrapper or delete them if they are no longer needed.");
+
+ return false;
+
+ }
+
+ /* Find wrapper and Headway Grid UI widget */
+ var wrapperGridObject = wrapper.data('ui-headwayGrid');
+
+ /* Update wrapper object and the guides */
+ wrapperGridObject.options.columns = value;
+
+ wrapperGridObject.addColumnGuides();
+
+ /* Finalize: Update the Wrapper/Grid CSS and reset draggable/resizable, etc */
+ wrapperGridObject.updateGridCSS();
+
+ }
+
+
+ wrapperOptionCallbackColumnWidth = function(input, value) {
+
+ var wrapper = $i("#wrapper-" + input.parents("[data-panel-args]").data("panel-args").wrapper.id);
+
+ if ( typeof wrapper == 'undefined' || !wrapper.length )
+ return false;
+
+ /* Find wrapper and Headway Grid UI widget */
+ var wrapperGridObject = wrapper.data('ui-headwayGrid');
+
+ /* Update wrapper object and the guides */
+ wrapperGridObject.options.columnWidth = value;
+
+ /* Finalize: Update the Wrapper/Grid CSS and reset draggable/resizable, etc */
+ wrapperGridObject.updateGridCSS();
+
+ }
+
+
+ wrapperOptionCallbackGutterWidth = function(input, value) {
+
+ var wrapper = $i("#wrapper-" + input.parents("[data-panel-args]").data("panel-args").wrapper.id);
+
+ if ( typeof wrapper == 'undefined' || !wrapper.length )
+ return false;
+
+ /* Find wrapper and Headway Grid UI widget */
+ var wrapperGridObject = wrapper.data('ui-headwayGrid');
+
+ /* Update wrapper object and the guides */
+ wrapperGridObject.options.gutterWidth = value;
+
+ /* Finalize: Update the Wrapper/Grid CSS and reset draggable/resizable, etc */
+ wrapperGridObject.updateGridCSS();
+ }
+
+
+ /* Wrapper Margin Inputs */
+ wrapperOptionCallbackMarginTop = function(input, value) {
+
+ var wrapper = $i("#wrapper-" + input.parents("[data-panel-args]").data("panel-args").wrapper.id);
+
+ if ( typeof wrapper == 'undefined' || !wrapper.length )
+ return false;
+
+ wrapper.css({marginTop: value});
+
+ /* Visible feedback of margin */
+ wrapperMarginFeedbackCreator(wrapper, 'top');
+
+ }
+
+ wrapperOptionCallbackMarginBottom = function(input, value) {
+
+ var wrapper = $i("#wrapper-" + input.parents("[data-panel-args]").data("panel-args").wrapper.id);
+
+ if ( typeof wrapper == 'undefined' || !wrapper.length )
+ return false;
+
+ wrapper.css({
+ marginBottom: value
+ });
+
+ /* Visible feedback of margin */
+ wrapperMarginFeedbackCreator(wrapper, 'bottom');
+
+ }
+
+ wrapperMarginFeedbackCreator = function(wrapper, topOrBottom) {
+
+ /* Remove any existing margin feedback element */
+ if ( wrapper.find('.wrapper-margin-feedback').length ) {
+
+ clearTimeout(wrapper.find('.wrapper-margin-feedback').data('fadeout-timeout'));
+ wrapper.find('.wrapper-margin-feedback').remove();
+
+ }
+
+ /* Create margin feedback element */
+ var wrapperMarginFeedback = $('<div class="wrapper-margin-feedback"></div>').prependTo(wrapper);
+
+ /* Style it */
+ var value = parseInt(wrapper.css('margin' + topOrBottom.capitalize()).replace('px', ''));
+
+ var feedbackCSS = {
+ position: 'absolute',
+ width: wrapper.outerWidth(),
+ left: 0,
+ height: value,
+ backgroundColor: 'rgba(255, 127, 0, .35)'
+ };
+
+ /* Determine where feedback helper will go based on topOrBottom (whether it's marginTop or marginBottom) */
+ feedbackCSS[topOrBottom] = '-' + value + 'px';
+
+ /* Send CSS to margin feedback helper */
+ wrapperMarginFeedback.css(feedbackCSS);
+
+ /* Set a timer to fade it out and remove it */
+ wrapperMarginFeedback.data('fadeout-timeout', setTimeout(function() {
+
+ wrapperMarginFeedback.fadeOut(200);
+
+ }, 400));
+
+ return wrapperMarginFeedback;
+
+ }
+
+ /* Default Wrapper Options */
+ updateGridWidthInput = function(context) {
+
+ var columns = $(context).find('input[name="columns"]').val();
+ var columnWidth = $(context).find('input[name="column-width"]').val();
+ var gutterWidth = $(context).find('input[name="gutter-width"]').val();
+
+ var gridWidth = (columnWidth * columns) + ((columns - 1) * gutterWidth);
+
+ return $(context).find('input[name="grid-width"]').val(gridWidth);
+
+ }
+/* END WRAPPER OPTION INPUT CALLBACKS */
+
--- /dev/null
+define(['util.custommouse', 'qtip', 'helper.data'], function() {
+
+ setupWrapperSortables = function() {
+
+ /* Wrapper Sorting */
+ return $i('#whitewrap').sortable({
+ items: 'div.wrapper',
+ handle: 'div.wrapper-drag-handle',
+ axis: 'y',
+ tolerance: 'pointer',
+ placeholder: 'wrapper-sortable-placeholder',
+ start: function(event, ui) {
+
+ /* Store previous heights of wrappers that way they can be added back after sorting */
+ $i('.wrapper').each(function() {
+ $(this).data('current-height', $(this).height());
+ });
+
+ /* Shorten grid container and hide overflow */
+ $i('.wrapper-fixed').css({
+ height: '100px'
+ });
+
+ $i('.wrapper-fluid').css({
+ height: '130px'
+ });
+
+ $i('.wrapper .grid-container').css({
+ height: '100px',
+ overflow: 'hidden'
+ });
+
+ /* Center fixed wrappers with absolute positioning because sortables doesn't like margin: 0 auto; */
+ if ( $(ui.item).hasClass('wrapper-fixed-grid') ) {
+
+ $(ui.item).css({
+ left: '50%',
+ marginLeft: '-' + ($(ui.item).outerWidth() / 2) + 'px'
+ });
+
+ }
+
+ /* Update placeholder size */
+ ui.placeholder.css({
+ width: ui.item.outerWidth(),
+ height: ui.item.outerHeight(),
+ marginTop: ui.item.css('marginTop'),
+ marginBottom: ui.item.css('marginBottom')
+ });
+
+ /* Set iframe scroll height to 500px above placeholder */
+ $('#iframe-container').scrollTop(ui.placeholder.offset().top - 300);
+
+ /* Refresh sortable since heights changed */
+ $(this).sortable('refreshPositions');
+
+ },
+ stop: function(event, ui) {
+
+ /* Un-absolute-center fixed wrappers */
+ $i('.wrapper').css({
+ marginLeft: '',
+ left: ''
+ });
+
+ /* Reset wrapper heights */
+ $i('.wrapper').each(function() {
+
+ $(this).height($(this).data('current-height'));
+
+ $(this).removeData('current-height');
+
+ });
+
+ /* Remove overflow: hidden from wrappers and grid containers */
+ $i('.wrapper, .wrapper .grid-container').css({
+ overflow: ''
+ });
+
+ /* Reset grid container heights */
+ $i('.wrapper').each(function() {
+ $(this).headwayGrid('updateGridContainerHeight');
+ });
+
+ dataSortWrappers();
+
+ }
+ });
+
+ }
+
+ setupWrapperResizable = function(wrappers) {
+
+ if ( typeof wrappers == 'undefined' )
+ var wrappers = $i('.wrapper');
+
+ wrappers.each(function() {
+
+ var wrapperMinHeight = parseInt($(this).css('minHeight').replace('px', '')) ;
+
+ $(this).resizable({
+ handles: 'n, s',
+ grid: 5,
+ minHeight: wrapperMinHeight,
+
+ start: function(event, ui) {
+
+ if ( $(event.toElement).hasClass('ui-resizable-n') ) {
+ $(this).data('resizing-position', 'n');
+ } else {
+ $(this).data('resizing-position', 's');
+ }
+
+ /* Set minHeight depending on the location and height of the lowest block */
+ if ( $(this).find('.block').length ) {
+
+ var bottomToUse = 0;
+ var topToUse = null;
+
+ $(this).find('.block:visible').each(function() {
+
+ var blockTop = $(this).position().top;
+ var blockBottom = $(this).outerHeight() + blockTop;
+
+ if ( blockBottom > bottomToUse )
+ bottomToUse = blockBottom;
+
+ if ( blockTop < topToUse || topToUse === null )
+ topToUse = blockTop;
+
+ /* Store the block's original block top */
+ $(this).data('resize-original-block-top', $(this).position().top);
+
+ });
+
+ /* If the wrapper is being resized from the top, then we can subtract the topToUse (the highest block position) from the min height that way wrapper height can be reduced from the top */
+ if ( $(this).data('resizing-position') == 'n' ) {
+ var minHeight = bottomToUse - topToUse;
+ } else {
+ var minHeight = bottomToUse;
+ }
+
+ } else {
+
+ var minHeight = wrapperMinHeight;
+
+ }
+
+ $(this).resizable('option', 'minHeight', minHeight);
+
+ },
+ resize: function(event, ui) {
+
+ var heightChange = ui.originalSize.height - ui.size.height;
+ var wrapperHeight = ui.size.height;
+
+ $(this).find('.grid-container').height(wrapperHeight);
+
+ /* Cancel out top and height added to wrapper since the grid container height will dictate the wrapper height */
+ $(this).css({
+ top: '',
+ height: ''
+ });
+
+ if ( $(this).data('resizing-position') == 'n' ) {
+
+ /* Insure that the resulting on any of the block tops isn't negative. If so, stop ALL block top changing */
+ var negativeTop = false;
+
+ $(this).find('.block').each(function() {
+
+ if ( $(this).data('resize-original-block-top') - heightChange < 0 ) {
+
+ negativeTop = true;
+ return false;
+
+ }
+
+ });
+
+ /* Change block tops if the test is passed */
+ if ( !negativeTop ) {
+
+ $(this).find('.block').each(function() {
+
+ $(this).css({
+ top: $(this).data('resize-original-block-top') - heightChange
+ });
+
+ });
+
+ }
+
+ }
+
+ },
+ stop: function() {
+
+ /* Update the position of all of the blocks in the wrapper */
+ $(this).find('.block').each(function() {
+
+ var block = $(this);
+ var blockID = getBlockID(block);
+
+ block.attr('data-grid-top', block.position().top);
+
+ dataSetBlockPosition(blockID, getBlockPosition(block));
+
+ });
+
+
+ $(this).data('resizing-position', null);
+
+ }
+ });
+
+ });
+
+ }
+
+ stopWrapperResizable = function(wrapper) {
+
+ if ( !wrapper.length || !wrapper.resizable )
+ return false;
+
+ wrapper.resizable('destroy');
+
+ setupWrapperResizable(wrapper);
+
+ }
+
+ addEdgeInsertWrapperButtons = function() {
+
+ var buttons = '<div class="add-wrapper-button-fixed tooltip" title="Add Wrapper">+</div>';
+
+ $('<div class="add-wrapper-buttons add-wrapper-buttons-top">' + buttons + '</div>')
+ .data('position', 'top')
+ .prependTo($i('body'));
+
+ $('<div class="add-wrapper-buttons add-wrapper-buttons-bottom">' + buttons + '</div>')
+ .data('position', 'bottom')
+ .appendTo($i('body'));
+
+ }
+
+ setupWrapperContextMenu = function() {
+
+ setupContextMenu({
+ id: 'wrapper',
+ elements: '.wrapper',
+ title: function(event) {
+
+ var wrapper = $(event.currentTarget);
+ var wrapperID = getWrapperID(wrapper);
+
+ return 'Wrapper';
+
+ },
+ contentsCallback: function(event) {
+
+ var contextMenu = $(this);
+ var wrapper = $(event.currentTarget);
+ var wrapperID = getWrapperID(wrapper);
+
+ /* Wrapper options */
+ $('<li class="context-menu-wrapper-options"><span>Open Wrapper Options</span></li>').appendTo(contextMenu).on('click', function() {
+
+ openWrapperOptions(wrapperID);
+
+ });
+
+ /* Wrapper type changing */
+ if ( wrapper.hasClass('wrapper-fluid') ) {
+
+ $('<li class="context-menu-wrapper-to-fixed"><span>Change Wrapper to Fixed</span></li>').appendTo(contextMenu).find('span').on('click', function() {
+
+ wrapper.removeClass('wrapper-fluid');
+ wrapper.removeClass('wrapper-fluid-grid');
+
+ wrapper.addClass('wrapper-fixed');
+ wrapper.addClass('wrapper-fixed-grid');
+
+ dataSetWrapperWidth(getWrapperID(wrapper), 'fixed');
+ dataSetWrapperGridWidth(getWrapperID(wrapper), 'fixed');
+
+ wrapper.data('ui-headwayGrid').resetGridCalculations();
+ wrapper.data('ui-headwayGrid').alignAllBlocksWithGuides();
+ wrapper.data('ui-headwayGrid').updateGridContainerHeight();
+
+ });
+
+ if ( wrapper.hasClass('wrapper-fixed-grid') ) {
+
+ $('<li class="context-menu-wrapper-grid-to-fluid"><span>Change Grid to Fluid</span></li>').appendTo(contextMenu).find('span').on('click', function() {
+
+ wrapper.removeClass('wrapper-fixed-grid');
+ wrapper.addClass('wrapper-fluid-grid');
+
+ dataSetWrapperWidth(getWrapperID(wrapper), 'fluid');
+ dataSetWrapperGridWidth(getWrapperID(wrapper), 'fluid');
+
+ wrapper.data('ui-headwayGrid').resetGridCalculations();
+ wrapper.data('ui-headwayGrid').alignAllBlocksWithGuides();
+ wrapper.data('ui-headwayGrid').updateGridContainerHeight();
+
+ });
+
+ } else if ( wrapper.hasClass('wrapper-fluid-grid') ) {
+
+ $('<li class="context-menu-wrapper-grid-to-fixed"><span>Change Grid to Fixed</span></li>').appendTo(contextMenu).find('span').on('click', function() {
+
+ wrapper.removeClass('wrapper-fluid-grid');
+ wrapper.addClass('wrapper-fixed-grid');
+
+ dataSetWrapperWidth(getWrapperID(wrapper), 'fluid');
+ dataSetWrapperGridWidth(getWrapperID(wrapper), 'fixed');
+
+ wrapper.data('ui-headwayGrid').resetGridCalculations();
+ wrapper.data('ui-headwayGrid').alignAllBlocksWithGuides();
+ wrapper.data('ui-headwayGrid').updateGridContainerHeight();
+
+ });
+
+ }
+
+ } else if ( wrapper.hasClass('wrapper-fixed') ) {
+
+ $('<li class="context-menu-wrapper-to-fluid"><span>Change Wrapper to Fluid</span></li>').appendTo(contextMenu).on('click', function() {
+
+ wrapper.removeClass('wrapper-fixed');
+
+ wrapper.addClass('wrapper-fluid');
+ wrapper.addClass('wrapper-fixed-grid');
+
+ dataSetWrapperWidth(getWrapperID(wrapper), 'fluid');
+ dataSetWrapperGridWidth(getWrapperID(wrapper), 'fixed');
+
+ wrapper.data('ui-headwayGrid').resetGridCalculations();
+ wrapper.data('ui-headwayGrid').alignAllBlocksWithGuides();
+ wrapper.data('ui-headwayGrid').updateGridContainerHeight();
+
+ });
+
+ }
+
+
+ /* Wrapper Alias */
+ $('<li class="context-menu-set-alias"><span>Set Wrapper Alias</span></li>').appendTo(contextMenu).on('click', function() {
+
+ var wrapperAlias = prompt('Please enter the desired wrapper alias.', wrapper.data('alias'));
+
+ if ( !wrapperAlias )
+ return;
+
+ dataSetWrapperOption(getWrapperID(wrapper), 'alias', wrapperAlias);
+ wrapper.data('alias', wrapperAlias);
+
+ });
+
+ /* Delete wrapper. Do not allow it to be deleted if it's the last one. */
+ if ( $i('.wrapper:visible').length >= 2 ) {
+
+ $('<li class="context-menu-wrapper-delete"><span>Delete Wrapper</span></li>').appendTo(contextMenu).on('click', function() {
+
+ deleteWrapper(wrapperID);
+
+ });
+
+ }
+
+ }
+ });
+
+ }
+
+ bindWrapperButtons = function() {
+
+ /* Add Wrapper Buttons */
+ $i('body').delegate('.add-wrapper-button-fixed', 'click', function() {
+
+ return addWrapper($(this).parents('.add-wrapper-buttons').data('position'), {
+ 'fluid': false
+ });
+
+ });
+
+ $i('body').delegate('.add-wrapper-fluid-fixed-grid', 'click', function() {
+
+ return addWrapper($(this).parents('.add-wrapper-buttons').data('position'), {
+ 'fluid': true
+ });
+ });
+
+ $i('body').delegate('.add-wrapper-fluid-fluid-grid', 'click', function() {
+
+ return addWrapper($(this).parents('.add-wrapper-buttons').data('position'), {
+ 'fluid': true,
+ 'fluid-grid': true
+ });
+
+ });
+
+ /* Wrapper Buttons */
+ $i('body').delegate('.wrapper-buttons .wrapper-options', 'click', function() {
+
+ return openWrapperOptions(getWrapperID($(this).closest('.wrapper')));
+
+ });
+
+ bindWrapperMarginButtons($i('.wrapper-buttons .wrapper-margin-handle'));
+
+
+ }
+
+ addWrapper = function(position, wrapperSettings, suppressNotice) {
+
+ if ( typeof wrapperSettings.id != 'undefined' )
+ delete wrapperSettings.id;
+
+ var wrapperSettings = $.extend({}, {
+ 'fluid': false,
+ 'fluid-grid': false,
+ 'use-independent-grid': false
+ }, wrapperSettings);
+
+ if ( typeof wrapperSettings['fluid'] != 'boolean' ) {
+ wrapperSettings['fluid'] = hwBoolean(wrapperSettings['fluid']);
+ }
+
+ if ( typeof wrapperSettings['fluid-grid'] != 'boolean' ) {
+ wrapperSettings['fluid-grid'] = hwBoolean(wrapperSettings['fluid-grid']);
+ }
+
+ /* Generate the wrapper */
+ var temporaryID = Math.ceil(Math.random() * 1000000000);
+ var wrapper = $('<div class="wrapper"><div class="grid-container"></div></div>');
+
+ wrapper
+ .attr('id', 'wrapper-' + temporaryID)
+ .attr('data-id', temporaryID)
+ .attr('data-temp-id', temporaryID)
+ .attr('data-desired-id', wrapperSettings.id ? wrapperSettings.id : null);
+
+ /* Add wrapper mirror notice/overlay */
+ wrapper.prepend('<div class="wrapper-mirror-overlay"></div>');
+
+ wrapper.find('.grid-container').append('\
+ <div class="wrapper-mirror-notice">\
+ <div>\
+ <h2>Wrapper Mirrored</h2>\
+ <p>This wrapper is mirroring blocks from another wrapper.</p>\
+ <small>Mirroring can be disabled via Wrapper Options in the right-click menu</small>\
+ </div>\
+ </div><!-- .wrapper-mirror-notice -->\
+ ');
+
+ /* Add wrapper buttons */
+ addWrapperButtons(wrapper);
+
+ /* Classes */
+ if ( wrapperSettings['fluid'] ) {
+ wrapper.addClass('wrapper-fluid');
+ } else {
+ wrapper.addClass('wrapper-fixed');
+ }
+
+ if ( wrapperSettings['fluid-grid'] ) {
+ wrapper.addClass('wrapper-fluid-grid');
+ } else {
+ wrapper.addClass('wrapper-fixed-grid');
+ }
+ /* End wrapper generation */
+
+
+ /* Position the wrapper and place it into the document */
+ switch ( position ) {
+
+ case 'top':
+ wrapper.prependTo($i('#whitewrap'));
+ break;
+
+ case 'bottom':
+ wrapper.insertBefore($i('#wrapper-buttons-template'));
+ break;
+
+ }
+
+ /* Top/Bottom Margins for Fluid Wrappers */
+ /* This will change the margin top on fluid wrappers that touch the top to 0 and margin bottoms to 0 on fluid wrappers that are the last wrapper */
+ if ( wrapperSettings['fluid'] ) {
+
+ wrapper.css('margin' + position.capitalize(), 0);
+
+ dataSetDesignEditorProperty({
+ element: 'wrapper',
+ property: 'margin-' + position,
+ value: 0,
+ specialElementType: 'instance',
+ specialElementMeta: 'wrapper-' + temporaryID
+ });
+
+ }
+
+ /* Add the hidden flag so it saves*/
+ dataAddWrapper(wrapper, wrapperSettings, $i('.wrapper').index(wrapper));
+
+ allowSaving();
+
+ /* Set height on Grid to 100px */
+ wrapper.find('.grid-container').height(100);
+
+ /* Initiate Headway Grid on new wrapper */
+ wrapper.data('wrapper-settings', wrapperSettings);
+
+ wrapper.headwayGrid();
+ setupWrapperResizable(wrapper);
+
+ bindWrapperMarginButtons(wrapper.find('.wrapper-margin-handle'));
+
+ /* Show notification */
+ var wrapperType = wrapperSettings['fluid'] ? 'Fluid' : 'Fixed';
+
+ if ( typeof suppressNotice == 'undefined' || !suppressNotice ) {
+ showNotification({
+ id: 'wrapper-created-' + temporaryID,
+ message: wrapperType + ' wrapper created.',
+ closable: true,
+ closeTimer: 5000
+ });
+ }
+
+ /* Refresh tooltips */
+ setupTooltips('iframe');
+
+ return wrapper;
+
+ }
+
+ deleteWrapper = function(wrapperID, force) {
+
+ var wrapper = $i('#wrapper-' + wrapperID);
+
+ if ( wrapper.length && (force || confirm('Are you sure you want to remove this wrapper? All blocks inside the wrapper will be deleted as well.')) ) {
+
+ dataDeleteWrapper(wrapperID);
+
+ wrapper.find('.block').each(function() {
+ deleteBlock($(this));
+ });
+
+ return wrapper.remove();;
+
+ } else {
+
+ return false;
+
+ }
+
+ }
+
+ addWrapperButtons = function(wrappers) {
+
+ wrappers.each(function() {
+
+ /* Don't add the buttons again */
+ if ( $(this).find('.wrapper-buttons').length )
+ return;
+
+ var wrapperButtons = $i('#wrapper-buttons-template').first()
+ .clone()
+ .attr('id', '')
+ .addClass('wrapper-buttons');
+
+ return wrapperButtons.prependTo($(this));
+
+ });
+
+ }
+
+ bindWrapperMarginButtons = function(elements) {
+
+ var tooltipContentCallback = function(api) {
+
+ var handle = $(api.target);
+
+ if ( !handle.length ) {
+ handle = $i('.wrapper-handle[data-dragging]').first();
+ }
+
+ var wrapper = handle.closest('.wrapper');
+ var marginPosition = handle.hasClass('wrapper-top-margin-handle') ? 'Top' : 'Bottom';
+
+ var currentMargin = '<span style="opacity: .8;">' + marginPosition + ' Margin:</span> ' + wrapper.css('margin' + marginPosition);
+ var tooltipHelp = !handle.data('dragging') ? 'Drag to change wrapper\'s <strong>' + marginPosition.toLowerCase() + ' margin</strong><br />' : '';
+
+ return tooltipHelp + currentMargin;
+
+ }
+
+ elements.qtip({
+ content: {
+ text: tooltipContentCallback
+ },
+ style: {
+ classes: 'qtip-headway'
+ },
+ show: {
+ delay: 10,
+ event: 'mouseenter'
+ },
+ position: {
+ my: 'right center',
+ at: 'left center',
+ container: Headway.iframe.contents().find('body'),
+ viewport: $('#iframe-container'),
+ effect: false
+ }
+ })
+
+ elements.custommouse({
+ mouseStart: function(e) {
+
+ this.handle = $(e.currentTarget).hasClass('wrapper-margin-handle') ? $(e.currentTarget) : $(e.currentTarget).parents('.wrapper-margin-handle').first();
+ this.dragStart = { left: e.pageX, top: e.pageY };
+ this.marginToChange = this.handle.hasClass('wrapper-top-margin-handle') ? 'marginTop' : 'marginBottom';
+
+ this.wrapper = $(e.currentTarget).closest('.wrapper');
+ this.originalWrapperMargin = parseInt(this.wrapper.css(this.marginToChange).replace('px', ''));
+
+ /* Disable sibling tooltips */
+ this.handle.siblings('.wrapper-handle[data-hasqtip], .wrapper-options[data-hasqtip]').each(function() {
+
+ var api = $(this).qtip('api');
+
+ if ( typeof api != 'undefined' && api.rendered ) {
+ api.disable();
+ api.hide();
+ }
+
+ });
+
+ /* Add wrapper drag class to keep buttons from hiding */
+ this.wrapper.addClass('wrapper-handle-in-use');
+
+ },
+
+ mouseDrag: function(e) {
+
+ /* Get amount that mouse has dragged */
+ var yValue = e.pageY - this.dragStart.top;
+
+ /* Calculate amount to change margin by. We'll use intervals of 2 that way it's not so touchy when dragging */
+ var interval = 2;
+ var marginChange = Math.round(yValue / interval);
+
+ var newMargin = this.originalWrapperMargin + marginChange;
+
+ /* Do not apply margin if newMargin is negative */
+ if ( newMargin < 0 )
+ return false;
+
+ /* Make sure tooltip is showing and set dragging flag that way it doesn't show the drag to change margin part */
+ this.handle.attr('data-dragging', true);
+ this.handle.qtip('show');
+ this.handle.qtip('reposition');
+ this.handle.qtip('option', 'content.text', tooltipContentCallback);
+
+ /* Apply the margin */
+ this.wrapper.css(this.marginToChange, newMargin);
+
+ /* Send value to DB */
+ dataSetDesignEditorProperty({
+ element: "wrapper",
+ property: "margin-" + this.marginToChange.replace('margin', '').toLowerCase(),
+ value: newMargin.toString(),
+ specialElementType: "instance",
+ specialElementMeta: "wrapper-" + getWrapperID(this.wrapper)
+ });
+
+ },
+
+ mouseStop: function(e) {
+
+ /* Change tooltip flag back */
+ this.handle.removeAttr('data-dragging');
+ this.handle.data('dragging', false);
+
+ /* Insure tooltip is hidden */
+ var qtipAPI = this.handle.qtip('api');
+
+ qtipAPI.hide();
+ $i('#qtip-' + qtipAPI.id).hide();
+
+ /* Re-enable sibling tooltips */
+ this.handle.siblings('.wrapper-handle, .wrapper-options').qtip('enable');
+
+ /* Remove wrapper drag class to make buttons hide again */
+ this.wrapper.removeClass('wrapper-handle-in-use');
+
+ }
+ });
+
+ }
+
+ populateWrapperMirrorNotice = function(wrapper) {
+
+ var wrapperMirrorID = getWrapperMirror(getWrapperID(wrapper));
+
+ if ( !wrapperMirrorID )
+ return;
+
+ wrapper.find('.wrapper-mirror-notice-id').text(wrapperMirrorID.replace('wrapper-', ''));
+
+ /* Hide the layout of the wrapper being mirrored. Todo: don't do this. */
+ wrapper.find('.wrapper-mirror-notice-layout').hide();
+
+ }
+
+ assignDefaultWrapperID = function() {
+
+ if ( $i('#wrapper-default').length ) {
+
+ var temporaryID = Math.ceil(Math.random() * 1000000000);
+ var defaultWrapper = $i('#wrapper-default');
+
+ /* Change the actual element ID */
+ defaultWrapper
+ .attr('id', 'wrapper-' + temporaryID)
+ .attr('data-id', temporaryID)
+ .attr('data-temp-id', temporaryID)
+ .attr('data-desired-id', null);
+
+ /* Create a hidden that way the new wrapper is saved to the DB */
+ dataAddWrapper(defaultWrapper, {
+ 'fluid': false,
+ 'fluid-grid': false
+ }, $i('.wrapper').index(defaultWrapper));
+
+ /* Change all of the blocks inside of the default wrapper to use the new temporary ID */
+ defaultWrapper.find('.block').each(function() {
+
+ dataSetBlockWrapper(getBlockID($(this)), temporaryID);
+
+ });
+
+ }
+
+ }
+
+});
\ No newline at end of file
--- /dev/null
+define(['jquery', 'deps/itstylesheet', 'util.saving', 'util.usability', 'util.tooltips'], function($, itstylesheet, saving) {
+
+ $i = function(element) {
+
+ if ( typeof Headway.iframe == 'undefined' || typeof Headway.iframe.contents() == 'undefined' )
+ return $();
+
+ return Headway.iframe.contents().find(element);
+
+ }
+
+ $iDocument = function() {
+
+ return $(Headway.iframe.contents());
+
+ }
+
+
+ loadIframe = function(callback, url) {
+
+ if ( typeof url == 'undefined' || !url)
+ var url = Headway.homeURL;
+
+ /* Choose contents iframe or preview iframe depending on argument */
+ var iframe = Headway.iframe;
+
+ /* Make the title talk */
+ startTitleActivityIndicator();
+ showIframeLoadingOverlay();
+
+ /* Close Grid Wizard */
+ closeBox('grid-wizard');
+
+ /* Build the URL */
+ iframeURL = url;
+ iframeURL = updateQueryStringParameter(iframeURL, 've-iframe', 'true');
+ iframeURL = updateQueryStringParameter(iframeURL, 've-layout', Headway.currentLayout);
+ iframeURL = updateQueryStringParameter(iframeURL, 've-iframe-mode', Headway.mode);
+ iframeURL = updateQueryStringParameter(iframeURL, 'rand', Math.floor(Math.random() * 100000001));
+
+ /* Clear out existing iframe contents */
+ if ( iframe.contents().find('.ui-headway-grid').length && typeof iframe.contents().find('.ui-headway-grid').headwayGrid != 'undefined' ) {
+ iframe.contents().find('.ui-headway-grid').headwayGrid('destroy');
+ }
+
+ iframe.contents().find('*')
+ .unbind()
+ .remove();
+
+ iframe[0].src = iframeURL;
+ waitForIframeLoad(callback, iframe);
+
+ }
+
+
+ waitForIframeLoad = function(callback, iframeEl) {
+
+ if ( typeof iframeEl == 'undefined' || !iframeEl )
+ var iframeEl = Headway.iframe;
+
+ /* Setup timeout */
+ if ( typeof iframeTimeout == 'undefined' )
+ iframeTimeout = setTimeout(iframe.loadTimeout, 40000);
+
+ /* Check if iframe body has iframe-loaded class which is added via inline script in the footer of the iframe */
+ if ( typeof iframeEl == 'undefined' || iframeEl.contents().find('body.iframe-loaded').length != 1 ) {
+
+ return setTimeout(function() {
+ waitForIframeLoad(callback, iframeEl);
+ }, 100);
+
+ }
+
+ /* Cancel out timeout callback */
+ clearTimeout(iframeTimeout);
+
+ return iframe.loadCallback(callback);
+
+ }
+
+
+ showIframeOverlay = function() {
+
+ var overlay = $('div#iframe-overlay');
+ overlay.show();
+
+ }
+
+
+ hideIframeOverlay = function(delay) {
+
+ if ( typeof delay != 'undefined' && delay == false )
+ return $('div#iframe-overlay').hide();
+
+ /* Add a timeout for intense draggers */
+ setTimeout(function(){
+ $('div#iframe-overlay').hide();
+ }, 250);
+
+ }
+
+
+ showIframeLoadingOverlay = function() {
+
+ /* Restrict scrolling */
+ $('div#iframe-container').css('overflow', 'hidden');
+
+ /* Position loading overlay */
+ $('div#iframe-loading-overlay').css({
+ top: $('div#iframe-container').scrollTop()
+ });
+
+ /* Only show if not already visible */
+ if ( !$('div#iframe-loading-overlay').is(':visible') ) {
+ createCog($('div#iframe-loading-overlay'), true);
+ $('div#iframe-loading-overlay').show();
+ }
+
+ return $('div#iframe-loading-overlay');
+
+ },
+
+
+ hideIframeLoadingOverlay = function() {
+
+ $('div#iframe-container').css('overflow', 'auto');
+ $('div#iframe-loading-overlay').hide().html('');
+
+ }
+
+
+ var iframe = {
+ init: function() {
+
+ $(document).ready(function() {
+
+ Headway.iframe = $('iframe#content');
+
+ iframe.bindFocusBlur();
+
+ });
+
+ },
+
+ bindFocusBlur: function() {
+
+ Headway.iframe.on('mouseleave', function() {
+ $(this).trigger('blur');
+
+ /* Hide any tooltips */
+ $i('[data-hasqtip]').qtip('disable', true);
+ });
+
+ Headway.iframe.on('mouseenter mousedown', function() {
+ //If there is another textarea/input that's focused, don't focus the iframe.
+ if ( $('textarea:focus, input:focus').length === 1 )
+ return;
+
+ $i('[data-hasqtip]').qtip('enable');
+ $(this).trigger('focus');
+ });
+
+ },
+
+ loadCallback: function(callback) {
+
+ clearUnsavedValues();
+
+ /* Fire callback if it exists */
+ if ( typeof callback === 'function' )
+ callback();
+
+ iframe.defaultLoadCallback();
+
+ iframe.stopFirefoxLoadingIndicator();
+
+ /* Fire callback! */
+ $('body').triggerHandler('headwayIframeLoad');
+
+ return true;
+
+ },
+
+ defaultLoadCallback: function() {
+
+ stopTitleActivityIndicator();
+
+ changeTitle('Visual Editor: ' + Headway.currentLayoutName);
+ $('span#current-layout').text(Headway.currentLayoutName);
+
+ /* Set up tooltips */
+ setupTooltips();
+ setupTooltips('iframe');
+ /* End Tooltips */
+
+ /* Stylesheets for more accurate live designing */
+ /* Main Headway stylesheet, used primarily by design editor */
+ stylesheet = new ITStylesheet({document: Headway.iframe.contents()[0], href: Headway.homeURL + '/?headway-trigger=compiler&file=general-design-editor'}, 'find');
+
+ /* Catch-all adhoc stylesheet used for overriding */
+ css = new ITStylesheet({document: Headway.iframe.contents()[0]}, 'load');
+ /* End stylesheets */
+
+ /* Hide iframe overlay if it exists */
+ hideIframeOverlay(false);
+
+ /* Add the template notice if it's layout mode and a template is active */
+ if ( Headway.currentLayoutTemplate ) {
+ showIframeOverlay();
+ $i('body').prepend('<div id="no-edit-notice"><div><h1>To edit this layout, remove the shared layout from this layout.</h1></div></div>');
+ }
+
+ /* Disallow certain keys so user doesn't accidentally leave the VE */
+ disableBadKeys();
+
+ /* Bind visual editor key shortcuts */
+ bindKeyShortcuts();
+
+ /* Funnel any keydown, keypress, keyup events to the parent window */
+ $i('html, body').bind('keydown', function(event) {
+ $(document).trigger(event);
+ event.stopPropagation();
+ });
+
+ $i('html, body').bind('keypress', function(event) {
+ $(document).trigger(event);
+ event.stopPropagation();
+ });
+
+ $i('html, body').bind('keyup', function(event) {
+ $(document).trigger(event);
+ event.stopPropagation();
+ });
+
+ /* Deactivate all links and buttons */
+ if ( Headway.touch )
+ Headway.iframe.contents().find('body').css('-webkit-touch-callout', 'none');
+
+ Headway.iframe.contents().find('body').delegate('a, input[type="submit"], button', 'click', function(event) {
+
+ if ( $(this).hasClass('allow-click') )
+ return;
+
+ event.preventDefault();
+
+ return false;
+
+ });
+
+ /* Show the load message */
+ if ( typeof headwayIframeLoadNotification !== 'undefined' ) {
+ showNotification({
+ id: 'iframe-load-notification',
+ message: headwayIframeLoadNotification,
+ overwriteExisting: true
+ });
+
+ delete headwayIframeLoadNotification;
+ }
+
+ /* Remove the tabs that are set to close on layout switch */
+ removeLayoutSwitchPanels();
+
+ /* Show the grid wizard if the current layout isn't customized and not using a tmeplate */
+ var layoutNode = $('div#layout-selector span.layout[data-layout-id="' + Headway.currentLayout + '"]');
+ var layoutLi = layoutNode.parent();
+
+ if (
+ !$i('.block').length
+ && !(Headway.currentLayoutCustomized && Headway.currentLayout.indexOf('template-') !== 0)
+ && !Headway.currentLayoutTemplate
+ && Headway.mode == 'grid'
+ ) {
+
+ hidePanel();
+
+ $(document).ready(function() {
+ openBox('grid-wizard');
+ });
+
+ } else {
+
+ closeBox('grid-wizard');
+
+ }
+
+ /* Clear out and disable iframe loading indicator */
+ hideIframeLoadingOverlay();
+
+ },
+
+ loadTimeout: function() {
+
+ iframeTimeout = true;
+
+ stopTitleActivityIndicator();
+
+ changeTitle('Visual Editor: Error!');
+
+ /* Hide all controls */
+ $('#iframe-container, #menu, #panel, #layout-selector-offset').hide();
+
+ alert("ERROR: There was a problem while loading the visual editor.\n\nYour browser will automatically refresh to attempt loading again.");
+
+ document.location.reload(true);
+
+ },
+
+ stopFirefoxLoadingIndicator: function() {
+
+ //http://www.shanison.com/2010/05/10/stop-the-browser-%E2%80%9Cthrobber-of-doom%E2%80%9D-while-loading-comet-forever-iframe/
+ if ( /Firefox[\/\s](\d+\.\d+)/.test(navigator.userAgent) ) {
+
+ var fake_iframe;
+
+ if ( fake_iframe == null ){
+ fake_iframe = document.createElement('iframe');
+ fake_iframe.style.display = 'none';
+ }
+
+ document.body.appendChild(fake_iframe);
+ document.body.removeChild(fake_iframe);
+
+ }
+
+ }
+
+ }
+
+ return iframe;
+
+});
\ No newline at end of file
--- /dev/null
+define(['jquery', 'ko', 'jqueryUI'], function($, ko) {
+
+ loadLayoutSelector = function(callback) {
+
+ createCog($('#layout-selector-pages'));
+ createCog($('#layout-selector-templates'));
+
+ /* Pages */
+ $.ajax(Headway.ajaxURL, {
+ type: 'POST',
+ async: true,
+ data: {
+ action: 'headway_visual_editor',
+ method: 'get_layout_selector_pages',
+ security: Headway.security,
+ currentLayout: Headway.currentLayout,
+ mode: Headway.mode
+ },
+ success: function(data, textStatus) {
+
+ /* Inject HTML */
+ $('#layout-selector-pages').html(data);
+
+ /* Run callback if it's a function */
+ if ( typeof callback == 'function' )
+ callback.call();
+
+ }
+ });
+
+ /* Templates */
+ $.ajax(Headway.ajaxURL, {
+ type: 'POST',
+ async: true,
+ data: {
+ action: 'headway_visual_editor',
+ method: 'get_layout_selector_templates',
+ security: Headway.security,
+ currentLayout: Headway.currentLayout,
+ mode: Headway.mode
+ },
+ success: function(data, textStatus) {
+
+ /* Inject HTML */
+ $('#layout-selector-templates').html(data);
+
+ }
+ });
+
+ }
+
+ showLayoutSelector = function() {
+
+ $('div#layout-selector-select')
+ .addClass('layout-selector-visible');
+
+ /* Move layout selector into correct position below the layout selector select */
+ $('div#layout-selector').css({
+ left: $('div#layout-selector-select-content').offset().left
+ });
+
+ $(document).bind('mousedown', hideLayoutSelector);
+ Headway.iframe.contents().bind('mousedown', hideLayoutSelector);
+
+ return $('div#layout-selector-select');
+
+ }
+
+ hideLayoutSelector = function(event) {
+
+ if ( event && ($(event.target).is('#layout-selector-select') || $(event.target).parents('#layout-selector-select').length === 1 ))
+ return;
+
+ $('div#layout-selector-select')
+ .removeClass('layout-selector-visible');
+
+ $(document).unbind('mousedown', hideLayoutSelector);
+ Headway.iframe.contents().unbind('mousedown', hideLayoutSelector);
+
+ return $('div#layout-selector-select');
+
+ }
+
+ toggleLayoutSelector = function() {
+
+ if ( $('div#layout-selector-select').hasClass('layout-selector-visible') ) {
+ hideLayoutSelector(false);
+ } else {
+ showLayoutSelector();
+ }
+
+ }
+
+ switchToLayout = function(layoutNode, reloadIframe, showSwitchNotification) {
+
+ if ( typeof layoutNode == 'object' && !layoutNode.hasClass('layout') )
+ layoutNode = layoutNode.find('> span.layout');
+
+ if ( layoutNode.length !== 1 )
+ return false;
+
+ changeTitle('Visual Editor: Loading');
+ startTitleActivityIndicator();
+
+ var layout = layoutNode;
+ var layoutID = layout.attr('data-layout-id');
+ var layoutURL = Headway.mode == 'grid' ? Headway.homeURL : layout.attr('data-layout-url'); /* URL is used for the sake of better WP_Query integration with block content */
+ var layoutName = layout.find('strong').text();
+
+ //Flip classes around
+ $('.layout-selected', 'div#layout-selector').removeClass('layout-selected');
+ layout.parent('li').addClass('layout-selected');
+
+ //Set global variables, these will be used in the next function to switch the iframe
+ Headway.currentLayout = layoutID;
+ Headway.currentLayoutName = layoutName;
+ Headway.currentLayoutTemplate = false;
+ Headway.currentLayoutCustomized = false;
+
+ //Set global variable to tell designEditor.switchLayout that this layout was switched to and not initial load
+ Headway.switchedToLayout = true;
+
+ //Check if layout is customized
+ Headway.currentLayoutCustomized = layout.parents('li.layout-item').first().hasClass('layout-item-customized') || layout.parents('#layout-selector-templates-container').length;
+
+ //Check if the layout node has a template assigned to it.
+ var possibleTemplateID = layout.find('.status-template').data('template-id');
+
+ if ( typeof possibleTemplateID != 'undefined' && possibleTemplateID != 'none' ) {
+ Headway.currentLayoutTemplate = possibleTemplateID;
+ Headway.currentLayoutTemplateName = $('span.layout[data-layout-id="template-' + possibleTemplateID + '"]').find('.template-name').text();
+ }
+
+
+ /* Push new layout ID to the URL */
+ window.history.pushState("", "", Headway.homeURL + "/?visual-editor=true&visual-editor-mode=" + Headway.mode + "&ve-layout=" + Headway.currentLayout);
+
+ //Reload iframe and new layout right away
+ if ( typeof reloadIframe == 'undefined' || reloadIframe == true ) {
+
+ if ( typeof showSwitchNotification == 'undefined' || showSwitchNotification == true )
+ headwayIframeLoadNotification = 'Switched to <em>' + Headway.currentLayoutName + '</em>';
+
+ loadIframe(Headway.instance.iframeCallback, layoutURL);
+
+ }
+
+ return true;
+
+ }
+
+
+ var layoutSelector = {
+
+ init: function() {
+ loadLayoutSelector();
+ layoutSelector.bind();
+ },
+
+ bind: function() {
+
+ var layoutSelectorEl = $('div#layout-selector');
+
+ /* Make open do cool stuff */
+ $('div#layout-selector-select-content').click(function(){
+
+ toggleLayoutSelector();
+
+ return false;
+
+ });
+
+ /* Tabs */
+ layoutSelectorEl.tabs();
+
+ /* Make buttons work */
+ layoutSelectorEl.delegate('span.edit', 'click', function(event){
+
+ if ( typeof allowVECloseSwitch !== 'undefined' && allowVECloseSwitch === false ) {
+
+ if ( !confirm('You have unsaved changes, are you sure you want to switch layouts?') ) {
+ return false;
+ }
+
+ }
+
+ showIframeLoadingOverlay();
+
+ //Switch layouts
+ switchToLayout($(this).parents('span.layout'));
+
+ /* Hide layout selector */
+ hideLayoutSelector();
+
+ event.preventDefault();
+
+ return $(this).parents('span.layout');
+
+ });
+
+ layoutSelectorEl.delegate('span.revert', 'click', function(event){
+
+ if ( !confirm('Are you sure you wish to reset this layout? All blocks and content will be removed from this layout.\n\nPlease note: Any block that is mirroring a block on this layout will also lose its settings.') ) {
+ return false;
+ }
+
+ var revertedLayout = $(this).parents('span.layout');
+ var revertedLayoutID = revertedLayout.attr('data-layout-id');
+ var revertedLayoutName = revertedLayout.find('strong').text();
+
+ /* Add loading indicators */
+ showIframeLoadingOverlay();
+
+ changeTitle('Visual Editor: Reverting ' + revertedLayoutName);
+ startTitleActivityIndicator();
+
+ /* Remove customized status from current layout */
+ revertedLayout.parent().removeClass('layout-item-customized');
+
+ /* Find the layout that's customized above this one */
+ var parentCustomizedLayout = $(revertedLayout.parents('.layout-item-customized:not(.layout-selected)')[0]);
+ var parentCustomizedLayoutID = parentCustomizedLayout.find('> span.layout').attr('data-layout-id');
+
+ var topLevelCustomized = $($('div#layout-selector-pages > ul > li.layout-item-customized')[0]);
+ var topLevelCustomizedID = topLevelCustomized.find('> span.layout').attr('data-layout-id');
+
+ var selectedLayout = parentCustomizedLayoutID ? parentCustomizedLayout : topLevelCustomized;
+ var selectedLayoutID = parentCustomizedLayoutID ? parentCustomizedLayoutID : topLevelCustomizedID;
+
+ /* If the user gets on a revert frenzy and reverts all pages, then it should fall back to the blog index or front page (if active) */
+ if ( typeof selectedLayoutID == 'undefined' || !selectedLayoutID ) {
+
+ selectedLayoutID = Headway.frontPage == 'posts' ? 'index' : 'front_page';
+ selectedLayout = $('div#layout-selector-pages > ul > li > span[data-layout-id="' + selectedLayoutID + '"]').parent();
+
+ }
+
+ /* Switch to the next higher-up layout */
+ switchToLayout(selectedLayout, true, false);
+
+ /* Delete everything from the reverted layout */
+ $.post(Headway.ajaxURL, {
+ security: Headway.security,
+ action: 'headway_visual_editor',
+ method: 'revert_layout',
+ layout_to_revert: revertedLayoutID
+ }, function(response) {
+
+ if ( response === 'success' ) {
+ showNotification({
+ id: 'layout-reverted',
+ message: '<em>' + revertedLayoutName + '</em> successfully reverted!',
+ success: true
+ });
+ } else {
+ showErrorNotification({
+ id: 'error-could-not-revert-layout',
+ message: 'Error: Could not revert layout.'
+ });
+ }
+
+ });
+
+ return false;
+
+ });
+
+ layoutSelectorEl.delegate('span#add-template', 'click', function(event) {
+
+ var templateName = $('#template-name-input').val();
+
+ //Do the AJAX request for the new template
+ $.post(Headway.ajaxURL, {
+ security: Headway.security,
+ action: 'headway_visual_editor',
+ method: 'add_template',
+ layout: Headway.currentLayout,
+ template_name: templateName
+ }, function(response) {
+
+ if ( typeof response === 'undefined' || !response ) {
+ showErrorNotification({
+ id: 'error-could-not-add-template',
+ message: 'Error: Could not add shared template.'
+ });
+
+ return false;
+ }
+
+ //Need to add the new template BEFORE the add button
+ var newTemplateNode = $('<li class="layout-item">\
+ <span data-layout-id="template-' + response.id + '" class="layout layout-template">\
+ <strong class="template-name">' + response.name + '</strong>\
+ \
+ <span class="delete-template" title="Delete Shared Layout">Delete</span>\
+ \
+ <span class="status status-currently-editing">Currently Editing</span>\
+ \
+ \
+ <span class="rename-template button layout-selector-button" title="Rename Shared Layout">Rename</span>\
+ <span class="assign-template button layout-selector-button">Use Layout</span>\
+ <span class="edit button layout-selector-button">Edit</span>\
+ </span>\
+ </li>');
+
+ newTemplateNode.appendTo('div#layout-selector-templates ul');
+
+ //Hide the no templates warning if it's visible
+ $('li#no-templates:visible', 'div#layout-selector').hide();
+
+ //We're all good!
+ showNotification({
+ id: 'template-added',
+ message: 'Shared layout added!',
+ success: true
+ });
+
+ //Clear template name input value
+ $('#template-name-input').val('');
+
+ }, 'json');
+
+ return false;
+
+ });
+
+ layoutSelectorEl.delegate('span.delete-template', 'click', function(event){
+
+ var templateLi = $($(this).parents('li')[0]);
+ var templateSpan = $(this).parent();
+ var template = templateSpan.attr('data-layout-id');
+ var templateID = template.replace('template-', '');
+ var templateName = templateSpan.find('strong').text();
+
+ if ( !confirm('Are you sure you wish to delete this template?') )
+ return false;
+
+ //Do the AJAX request for the new template
+ $.post(Headway.ajaxURL, {
+ security: Headway.security,
+ action: 'headway_visual_editor',
+ method: 'delete_template',
+ template_to_delete: templateID
+ }, function(response) {
+
+ if ( typeof response === 'undefined' || response == 'failure' || response != 'success' ) {
+ showErrorNotification({
+ id: 'error-could-not-deleted-template',
+ message: 'Error: Could not delete shared layout.'
+ });
+
+ return false;
+ }
+
+ //Delete the template from DOM
+ templateLi.remove();
+
+ //Show the no templates message if there are no more templates
+ if ( $('span.layout-template', 'div#layout-selector').length === 0 ) {
+ $('li#no-templates', 'div#layout-selector').show();
+ }
+
+ //We're all good!
+ showNotification({
+ id: 'template-deleted',
+ message: 'Shared Layout: <em>' + templateName + '</em> successfully deleted!',
+ success: true
+ });
+
+ //If the template that was removed was the current one, then send the user back to the blog index or front page
+ if ( template === Headway.currentLayout ) {
+
+ var defaultLayout = Headway.frontPage == 'posts' ? 'index' : 'front_page';
+
+ switchToLayout($('div#layout-selector span.layout[data-layout-id="' + defaultLayout + '"]'), true, false);
+
+ }
+
+ });
+
+ return false;
+
+ });
+
+ layoutSelectorEl.delegate('span.assign-template', 'click', function(event){
+
+ var templateNode = $($(this).parents('li')[0]);
+ var template = $(this).parent().attr('data-layout-id').replace('template-', '');
+
+ //If the current layout being edited is a template trigger an error.
+ if ( Headway.currentLayout.indexOf('template-') === 0 ) {
+ alert('You cannot assign a shared layout to another shared layout.');
+
+ return false;
+ }
+
+ //Do the AJAX request to assign the template
+ $.post(Headway.ajaxURL, {
+ security: Headway.security,
+ action: 'headway_visual_editor',
+ method: 'assign_template',
+ template: template,
+ layout: Headway.currentLayout
+ }, function(response) {
+
+ if ( typeof response === 'undefined' || response == 'failure' ) {
+ showErrorNotification({
+ id: 'error-could-not-assign-template',
+ message: 'Error: Could not assign shared layout.'
+ });
+
+ return false;
+ }
+
+ $('li.layout-selected', 'div#layout-selector').removeClass('layout-item-customized');
+ $('li.layout-selected', 'div#layout-selector').addClass('layout-item-template-used');
+
+ $('li.layout-selected > span.status-template', 'div#layout-selector').text(response);
+
+ //Reload iframe
+
+ showIframeLoadingOverlay();
+
+ //Change title to loading
+ changeTitle('Visual Editor: Assigning Shared Layout');
+ startTitleActivityIndicator();
+
+ Headway.currentLayoutTemplate = 'template-' + template;
+ Headway.currentLayoutTemplateName = $('span.layout[data-layout-id="template-' + template + '"]').find('.template-name').text();
+
+ //Reload iframe and new layout
+ headwayIframeLoadNotification = 'Shared layout assigned successfully!';
+
+ loadIframe(Headway.instance.iframeCallback);
+
+ //End reload iframe
+
+ });
+
+ return false;
+
+ });
+
+
+ layoutSelectorEl.delegate('span.rename-template', 'click', function (event) {
+
+ var layoutNode = $($(this).parents('li')[0]);
+ var layoutID = $(this).parent().attr('data-layout-id');
+
+ var nameEl = $(this).siblings('.template-name');
+ var currentName = nameEl.text();
+ var newName = prompt('Please enter new Shared Layout name', currentName);
+
+ //Do the AJAX request to assign the template
+ $.post(Headway.ajaxURL, {
+ security: Headway.security,
+ action: 'headway_visual_editor',
+ method: 'rename_layout_template',
+ layout: layoutID,
+ newName: newName,
+ }, function (response) {
+
+ if (typeof response === 'undefined' || response == 'failure') {
+ showErrorNotification({
+ id: 'error-could-not-rename-layout-template',
+ message: 'Error: Could not rename shared layout.'
+ });
+
+ return false;
+ }
+
+ nameEl.text(newName);
+
+ //We're all good!
+ return true;
+
+ });
+
+ return false;
+
+ });
+
+
+ layoutSelectorEl.delegate('span.remove-template', 'click', function(event){
+
+ var layoutNode = $($(this).parents('li')[0]);
+ var layoutID = $(this).parent().attr('data-layout-id');
+
+ if ( !confirm('Are you sure you want to remove the shared layout from ' + layoutNode.find('> span.layout strong').text() + '?') )
+ return false;
+
+ //Do the AJAX request to assign the template
+ $.post(Headway.ajaxURL, {
+ security: Headway.security,
+ action: 'headway_visual_editor',
+ method: 'remove_template_from_layout',
+ layout: layoutID
+ }, function(response) {
+
+ if ( typeof response === 'undefined' || response == 'failure' ) {
+ showErrorNotification({
+ id: 'error-could-not-remove-template-from-layout',
+ message: 'Error: Could not remove shared layout from layout.'
+ });
+
+ return false;
+ }
+
+ layoutNode.removeClass('layout-item-template-used');
+
+ if ( response === 'customized' ) {
+ layoutNode.addClass('layout-item-customized');
+ }
+
+ //If the current layout is the one with the template that we're unassigning, we need to reload the iframe.
+ if ( layoutID == Headway.currentLayout ) {
+
+ showIframeLoadingOverlay();
+
+ //Change title to loading
+ changeTitle('Visual Editor: Removing Shared Layout From Layout');
+ startTitleActivityIndicator();
+
+ Headway.currentLayoutTemplate = false;
+
+ //Reload iframe and new layout
+ headwayIframeLoadNotification = 'Shared Layout removed from layout successfully!';
+
+ loadIframe(Headway.instance.iframeCallback);
+
+ return true;
+
+ }
+
+ //We're all good!
+ return true;
+
+ });
+
+ return false;
+
+ });
+
+ /* Handle Collapsing Stuff */
+ layoutSelectorEl.delegate('span', 'click', function(event){
+
+ if ( $(this).hasClass('layout-open') ) {
+
+ $(this).removeClass('layout-open');
+ $(this).siblings('ul').hide();
+
+ } else {
+
+ $(this).addClass('layout-open');
+ $(this).siblings('ul').show();
+
+ }
+
+ });
+
+ }
+
+ }
+
+ return layoutSelector;
+
+});
\ No newline at end of file
--- /dev/null
+define(['jquery', 'util.tour'], function($, tour) {
+
+ var menu = {
+ init: function() {
+ menu.bind();
+ },
+
+ bind: function() {
+
+ /* MODE SWITCHING */
+ $('ul#modes li').on('click', function(){
+ $(this).siblings('li').removeClass('active');
+ $(this).addClass('active');
+ });
+
+ $('ul#modes li a').bind('click', function(){
+ $(this).attr('href', $(this).attr('href') + '&ve-layout=' + Headway.currentLayout);
+ });
+ /* END MODE SWITCHING */
+
+ /* VIEW SITE BUTTON */
+ $('#menu-link-view-site a').bind('click', function(){
+ $(this).attr('href', Headway.homeURL + '/?headway-trigger=layout-redirect&layout=' + Headway.currentLayout);
+ });
+ /* END VIEW SITE BUTTON */
+
+ /* SAVE BUTTON */
+ $('span#save-button').click(function() {
+
+ save();
+
+ return false;
+
+ });
+ /* END SAVE BUTTON */
+
+ /* SNAPSHOTS */
+ $('#snapshots-button').bind('click', function(){
+
+ openBox('snapshots');
+
+ });
+ /* END SNAPSHOTS */
+
+ /* TOOLS */
+ $('#tools-tour').bind('click', tour.start);
+
+ $('#tools-grid-wizard').bind('click', function(){
+
+ hidePanel();
+
+ openBox('grid-wizard');
+
+ });
+
+ $('#open-live-css').bind('click', function() {
+
+ if ( typeof liveCSSWindow != 'undefined' && !liveCSSWindow.closed )
+ return liveCSSWindow.focus();
+
+ var liveCSSConfig = {
+ width: 750,
+ height: 550
+ };
+
+ liveCSSConfig.left = ( screen.width / 2 ) - (liveCSSConfig.width / 2);
+ liveCSSConfig.top = ( screen.height / 2 ) - (liveCSSConfig.height / 2);
+
+ liveCSSWindow = window.open(Headway.homeURL + '/?headway-trigger=ace-editor&mode=css', '_blank', 'width=' + liveCSSConfig.width + ',height=' + liveCSSConfig.height + ',top=' + liveCSSConfig.top + ',left=' + liveCSSConfig.left, true);
+
+ liveCSSWindow.focus();
+
+ /* Close Live CSS when VE is closed */
+ window.onunload = function() {
+
+ if ( typeof liveCSSWindow != 'undefined' && !liveCSSWindow.closed ) {
+ liveCSSWindow.close();
+ }
+
+ }
+
+ $(liveCSSWindow).bind('load', function() {
+
+ var ace = liveCSSWindow.window.ace;
+
+ /* Set paths */
+ var acePath = Headway.headwayURL + '/library/visual-editor/' + Headway.scriptFolder + '/deps/ace/';
+
+ ace.config.set('basePath', acePath);
+ ace.config.set('modePath', acePath);
+ ace.config.set('workerPath', acePath);
+ ace.config.set('themePath', acePath);
+
+ /* Init editor */
+ liveCSSEditor = ace.edit($(liveCSSWindow.document).contents().find('#ace-editor').get(0));
+ liveCSSEditorSession = liveCSSEditor.getSession();
+
+ /* Set editor config */
+ liveCSSEditor.setTheme('ace/theme/textmate');
+ liveCSSEditorSession.setMode('ace/mode/css');
+
+ liveCSSEditor.setShowPrintMargin(false);
+
+ /* Populate the editor */
+ liveCSSEditor.setValue($('textarea#live-css').val());
+
+ /* Go to end of editor */
+ var length = liveCSSEditorSession.getLength();
+ liveCSSEditor.gotoLine(length, liveCSSEditorSession.getLine(length-1).length);
+
+ /* Bind the editor */
+ liveCSSEditorSession.on('change', function(e) {
+
+ var value = liveCSSEditor.getValue();
+ var textarea = $('textarea#live-css');
+
+ textarea.val(value);
+
+ dataHandleInput(textarea);
+ $i('style#live-css-holder').html(value);
+
+ allowSaving();
+
+ });
+
+
+ });
+
+ });
+
+ $('#tools-clear-cache').bind('click', function(){
+
+ /* Set up parameters */
+ var parameters = {
+ security: Headway.security,
+ action: 'headway_visual_editor',
+ method: 'clear_cache'
+ };
+
+ /* Do the stuff */
+ $.post(Headway.ajaxURL, parameters, function(response){
+
+ if ( response === 'success' ) {
+
+ showNotification({
+ id: 'cache-cleared',
+ message: 'The cache was successfully cleared!',
+ success: true
+ });
+
+ } else {
+
+ showErrorNotification({
+ id: 'error-could-not-clear-cache',
+ message: 'Error: Could not clear cache.'
+ });
+
+ }
+
+ });
+
+ });
+ /* END TOOLS */
+
+ }
+
+ }
+
+ return menu;
+
+
+});
\ No newline at end of file
--- /dev/null
+define(['jquery', 'deps/colorpicker', 'util.image-uploader'], function($) {
+
+ handleInputTogglesInContainer = function(container) {
+
+ container.each(function() {
+
+ $(this).find('[id*="input-"]').reverse().each(function() {
+
+ handleInputToggle($(this));
+
+ });
+
+ })
+
+ }
+
+
+ handleInputToggle = function(input, val) {
+
+ if ( !input || !input.length || typeof input.attr('data-toggle') == 'undefined' )
+ return;
+
+ var toggle = $.parseJSON(input.attr('data-toggle'));
+
+ var parentElement = '.panel';
+
+ if ( input.parents('.repeater-group').length )
+ var parentElement = '.repeater-group';
+
+ if ( typeof val == 'undefined' )
+ var val = input.val().toString();
+
+ if ( input.attr('type') == 'checkbox' ) {
+
+ if ( !input.is(':checked') ) {
+ val = 'false';
+ } else {
+ val = 'true';
+ }
+
+ }
+
+ if ( val && toggle && typeof toggle == 'object' ) {
+
+ if ( toggle.hasOwnProperty(val) ) {
+
+ /* Show */
+ if ( typeof toggle[val].show == 'string' ) {
+
+ var toShow = input.parents(parentElement).find(toggle[val].show);
+
+ toShow.show();
+
+ toShow.find('*[data-toggle]').not(input).each(function() {
+ handleInputToggle($(this));
+ });
+
+ } else if ( typeof toggle[val].show == 'object' ) {
+
+ $.each(toggle[val].show, function(index, value) {
+
+ var toShow = input.parents(parentElement).find(value).show();
+
+ toShow.show();
+
+ toShow.find('*[data-toggle]').not(input).each(function () {
+ handleInputToggle($(this));
+ });
+
+ });
+
+ }
+
+ /* Hide */
+ if ( typeof toggle[val].hide == 'string' ) {
+
+ var toHide = input.parents(parentElement).find(toggle[val].hide)
+
+ toHide.find('*[data-toggle]').not(input).each(function() {
+ handleInputToggleHideAll($(this));
+ });
+
+ toHide.hide();
+
+ } else if ( typeof toggle[val].hide == 'object' ) {
+
+ $.each(toggle[val].hide, function(index, value) {
+
+ var toHide = input.parents(parentElement).find(value);
+
+ toHide.find('*[data-toggle]').not(input).each(function() {
+ handleInputToggleHideAll($(this));
+ });
+
+ toHide.hide();
+
+ });
+
+ }
+
+ } /* end if toggle.hasOwnProperty(val) */
+
+ } /* end if ( val && toggle && typeof toggle == 'object' ) */
+
+ }
+
+
+ handleInputToggleHideAll = function(input) {
+
+ if ( !input || !input.length || typeof input.attr('data-toggle') == 'undefined' )
+ return;
+
+ var toggle = $.parseJSON(input.attr('data-toggle'));
+
+ var parentElement = '.panel';
+
+ if ( input.parents('.input').parent().attr('class') === 'repeater-group' )
+ var parentElement = '.repeater-group';
+
+ $.each(toggle, function(value, hideOrShow) {
+
+ if ( typeof hideOrShow.hide == 'undefined' || !hideOrShow.hide || !hideOrShow.hide.length )
+ return;
+
+ if ( typeof hideOrShow.hide == 'string' ) {
+
+ var toHide = input.parents(parentElement).find(hideOrShow.hide);
+ toHide.hide();
+
+ } else if ( typeof hideOrShow.hide == 'object' ) {
+
+ $.each(hideOrShow.hide, function(index, value) {
+
+ var toHide = input.parents(parentElement).find(value);
+ toHide.hide();
+
+ });
+
+ }
+
+ });
+
+ }
+
+ var panelInputs = {
+ delegate: function() {
+
+ var context = 'div#panel';
+
+ /* Selects */
+ $(context).delegate('div.input-select select', 'change', function() {
+
+ dataHandleInput($(this));
+
+ var input = $(this);
+ var val = $(this).val();
+
+ handleInputToggle(input, val);
+
+ });
+
+
+ /* Text */
+ $(context).delegate('div.input-text input', 'keyup blur', function() {
+
+ dataHandleInput($(this));
+
+ });
+
+
+ /* Textarea */
+ $(context).delegate('div.input-textarea textarea', 'keyup blur', function() {
+
+ dataHandleInput($(this));
+
+ });
+
+ $(context).delegate('div.input-textarea span.textarea-open', 'click', function() {
+
+ var textareaContainer = $(this).siblings('.textarea-container');
+ var textarea = textareaContainer.find('textarea');
+
+ var inputContainerOffset = $(this).parents('.input').offset();
+
+ textareaContainer.css({
+ top: inputContainerOffset.top - textareaContainer.outerHeight(true),
+ left: inputContainerOffset.left
+ });
+
+ /* Keep the sub tabs content container from scrolling */
+ $('div.sub-tabs-content-container').css('overflow-y', 'hidden');
+
+ if ( textareaContainer.data('visible') !== true ) {
+
+ /* Show the textarea */
+ textareaContainer.show();
+ textareaContainer.data('visible', true);
+
+ /* Put the cursor in the textarea */
+ textarea.trigger('focus');
+
+ /* Bind the document close */
+ $(document).bind('mousedown', {textareaContainer: textareaContainer}, textareaClose);
+ Headway.iframe.contents().bind('mousedown', {textareaContainer: textareaContainer}, textareaClose);
+
+ $(window).bind('resize', {textareaContainer: textareaContainer}, textareaClose);
+
+ } else {
+
+ /* Hide the textarea */
+ textareaContainer.hide();
+ textareaContainer.data('visible', false);
+
+ /* Allow sub tabs content container to scroll again */
+ $('div.sub-tabs-content-container').css('overflow-y', 'auto');
+
+ /* Remove the events */
+ $(document).unbind('mousedown', textareaClose);
+ Headway.iframe.contents().unbind('mousedown', textareaClose);
+
+ $(window).unbind('resize', textareaClose);
+
+ }
+
+ });
+
+ textareaClose = function(event) {
+
+ /* Do not trigger this if they're clicking the same button that they used to open the textarea */
+ if ( $(event.target).parents('div.input-textarea div.input-right').length === 1 )
+ return;
+
+ var textareaContainer = event.data.textareaContainer;
+
+ /* Hide the textarea */
+ textareaContainer.hide();
+ textareaContainer.data('visible', false);
+
+ /* Allow sub tabs content container to scroll again */
+ $('div.sub-tabs-content-container').css('overflow-y', 'auto');
+
+ /* Remove the events */
+ $(document).unbind('mousedown', textareaClose);
+ Headway.iframe.contents().unbind('mousedown', textareaClose);
+
+ $(window).unbind('resize', textareaClose);
+
+ }
+
+
+ /* WYSIWYG */
+ inputWYSIWYGChange = function(event) {
+
+ dataHandleInput(this.$element, this.get());
+
+ }
+
+ inputWYSIWYGTextareaChange = function() {
+
+ dataHandleInput($(this));
+
+ }
+
+ $(context).delegate('div.input-wysiwyg span.wysiwyg-open', 'click', function() {
+
+ var wysiwygContainer = $(this).siblings('.wysiwyg-container');
+
+ var inputContainerOffset = $(this).parents('.input').offset();
+ var inputContainerTop = inputContainerOffset.top - wysiwygContainer.outerHeight(true);
+
+ if ( inputContainerTop < 50 ) {
+ inputContainerTop = 50;
+ }
+
+ wysiwygContainer.css({
+ top: inputContainerTop,
+ left: inputContainerOffset.left
+ });
+
+ /* Keep the sub tabs content container from scrolling */
+ $('div.sub-tabs-content-container').css('overflow-y', 'hidden');
+
+ if ( wysiwygContainer.data('visible') !== true ) {
+
+ /* Show the WYSWIWYG */
+ wysiwygContainer.show();
+ wysiwygContainer.css('marginLeft', '');
+ wysiwygContainer.data('visible', true);
+
+ /* Make sure WYSIWYG doesn't bleed off screen */
+ if ( $('div#side-panel-container').length ) {
+ var sidePanelWidth = $('div#side-panel-container').outerWidth() - $('div#side-panel-container').css('right').replace('px', '');
+ } else {
+ var sidePanelWidth = 0;
+ }
+
+ var possibleRightBleedingDifference = $(document).width() - sidePanelWidth - (wysiwygContainer.offset().left + wysiwygContainer.width());
+
+ if ( possibleRightBleedingDifference < 0 ) {
+ wysiwygContainer.css('marginLeft', possibleRightBleedingDifference - 30);
+ }
+
+ /* Function for setting up redactor */
+ var setupRedactor = function() {
+
+ wysiwygContainer.find('textarea').redactor({
+ path: Headway.headwayURL + '/library/resources/redactor/',
+ plugins: ['fontcolor', 'fontsize'],
+ buttons: ['html', '|', 'formatting', '|', 'bold', 'italic', 'deleted', '|', 'unorderedlist', 'orderedlist', 'outdent', 'indent', '|', 'table', 'link', '|', 'image', '|', 'alignleft', 'aligncenter', 'alignright', '|', 'horizontalrule'],
+ allowedTags: ["inline", "code", "span", "div", "label", "a", "br", "p", "b", "i", "del", "strike", "u", "img", "video", "audio", "iframe", "object", "embed", "param", "blockquote", "mark", "cite", "small", "ul", "ol", "li", "hr", "dl", "dt", "dd", "sup", "sub", "big", "pre", "code", "figure", "figcaption", "strong", "em", "table", "tr", "td", "th", "tbody", "thead", "tfoot", "h1", "h2", "h3", "h4", "h5", "h6", "frame", "frameset", "script", "hgroup", "form", "label", "input", "textarea", "select", "fieldset", "legend"],
+ iframe: true,
+ css: Headway.headwayURL + '/library/resources/redactor/css/redactor-iframe.css',
+ changeCallback: inputWYSIWYGChange,
+ blurCallback: inputWYSIWYGChange,
+ imageUpload: Headway.ajaxURL + '?action=headway_visual_editor&method=redactor_upload_image&security=' + Headway.security,
+ convertDivs: false
+ });
+
+ wysiwygContainer.find('textarea')
+ .bind('keyup', inputWYSIWYGTextareaChange);
+
+ wysiwygContainer.find('textarea').redactor('focusEnd');
+
+ wysiwygContainer.data('setupRedactor', true);
+
+ }
+
+ /* Load redactor if it hasn't been before */
+ if ( $('body').data('loadedRedactor') !== true ) {
+
+ var style = $('<link>')
+ .attr({
+ rel: 'stylesheet',
+ href: Headway.headwayURL + '/library/resources/redactor/css/redactor.css',
+ type: 'text/css',
+ media: 'screen'
+ })
+ .appendTo($('head'));
+
+ var redactorRequest = jQuery.ajax({
+ dataType: 'script',
+ cache: true,
+ url: Headway.headwayURL + '/library/resources/redactor/redactor.min.js'
+ });
+
+ var redactorPluginFontColorRequest = jQuery.ajax({
+ dataType: 'script',
+ cache: true,
+ url: Headway.headwayURL + '/library/resources/redactor/fontcolor.js',
+ });
+
+ var redactorPluginFontSizeRequest = jQuery.ajax({
+ dataType: 'script',
+ cache: true,
+ url: Headway.headwayURL + '/library/resources/redactor/fontsize.js',
+ });
+
+ $.when(
+ redactorRequest,
+ redactorPluginFontColorRequest,
+ redactorPluginFontSizeRequest
+ ).then(function() {
+ setupRedactor();
+ $('body').data('loadedRedactor', true);
+ });
+
+ /* Otherwise just set up redactor if redactor has been loaded, but this input hasn't been setup */
+ } else if ( $('body').data('loadedRedactor') === true && wysiwygContainer.data('setupRedactor') !== true ) {
+
+ setupRedactor();
+
+ /* Redactor has been loaded and set up, just focus it */
+ } else {
+
+ /* Focus the input */
+ wysiwygContainer.find('textarea').redactor('focusEnd');
+
+ }
+
+ /* Bind the document close */
+ $(document).bind('mousedown', {wysiwygContainer: wysiwygContainer}, wysiwygClose);
+ Headway.iframe.contents().bind('mousedown', {wysiwygContainer: wysiwygContainer}, wysiwygClose);
+
+ $(window).bind('resize', {wysiwygContainer: wysiwygContainer}, wysiwygClose);
+
+ } else {
+
+ /* Hide the WYSIWYG */
+ wysiwygContainer.hide();
+ wysiwygContainer.data('visible', false);
+
+ /* Allow sub tabs content container to scroll again */
+ $('div.sub-tabs-content-container').css('overflow-y', 'auto');
+
+ /* Remove the events */
+ $(document).unbind('mousedown', wysiwygClose);
+ Headway.iframe.contents().unbind('mousedown', wysiwygClose);
+
+ $(window).unbind('resize', wysiwygClose);
+
+ }
+
+
+ });
+
+
+ wysiwygClose = function(event) {
+
+ /* Do not trigger this if they're clicking the same button that they used to open the textarea */
+ if (
+ $(event.target).parents('div.input-wysiwyg div.input-right').length === 1
+ || $(event.target).parents('.redactor_dropdown').length === 1
+ || $(event.target).parents('#redactor_modal').length === 1
+ )
+ return;
+
+ var wysiwygContainer = event.data.wysiwygContainer;
+
+ /* Hide the WYSIWYG */
+ wysiwygContainer.hide();
+ wysiwygContainer.data('visible', false);
+
+ /* Allow sub tabs content container to scroll again */
+ $('div.sub-tabs-content-container').css('overflow-y', 'auto');
+
+ /* Remove the events */
+ $(document).unbind('mousedown', wysiwygClose);
+ Headway.iframe.contents().unbind('mousedown', wysiwygClose);
+
+ $(window).unbind('resize', wysiwygClose);
+
+ }
+
+
+ /* Integer */
+ $(context).delegate('div.input-integer input', 'focus', function() {
+
+ if ( typeof originalValues !== 'undefined' ) {
+ delete originalValues;
+ }
+
+ originalValues = new Object;
+ originalValues[$(this).attr('name')] = $(this).val();
+
+ });
+
+ $(context).delegate('div.input-integer input', 'keyup blur', function(event) {
+
+ value = $(this).val();
+
+ if ( event.type == 'keyup' && value == '-' )
+ return;
+
+ /* Validate the value and make sure it's a number */
+ if ( isNaN(value) ) {
+
+ /* Take the nasties out to make sure it's a number */
+ value = value.replace(/[^0-9]*/ig, '');
+
+ /* If the value is an empty string, then revert back to the original value */
+ if ( value === '' ) {
+
+ var value = originalValues[$(this).attr('name')];
+
+ }
+
+ /* Set the value of the input to the sanitized value */
+ $(this).val(value);
+
+ }
+
+ /* Remove leading zeroes */
+ if ( value.length > 1 && value[0] == 0 ) {
+
+ value = value.replace(/^[0]+/g, '');
+
+ /* Set the value of the input to the sanitized value */
+ $(this).val(value);
+
+ }
+
+ dataHandleInput($(this), value);
+
+ });
+
+
+ /* Checkboxes */
+ $(context).delegate('div.input-checkbox input', 'change', function(event) {
+
+ var inputContainer = $(this).parents('.input-checkbox').first();
+ var input = inputContainer.find('input');
+ var label = inputContainer.find('label');
+
+ var val = input.is(':checked');
+
+ Headway.history.add({
+ up: function() {
+
+ input.val(val);
+ input.prop('checked', val);
+
+ dataHandleInput(input, val);
+ handleInputToggle(input, val);
+
+ input.trigger('blur');
+
+ },
+ down: function() {
+
+ var val = !val;
+
+ input.val(val);
+ input.prop('checked', val);
+
+ dataHandleInput(input, val);
+ handleInputToggle(input, val);
+
+ input.trigger('blur');
+
+ }
+ })
+
+ allowSaving();
+
+ event.preventDefault();
+ event.stopPropagation();
+
+ return false;
+
+ });
+
+
+ /* Multi-select */
+ $(context).delegate('div.input-multi-select select', 'click', function() {
+
+ dataHandleInput($(this));
+
+ });
+
+ $(context).delegate('div.input-multi-select span.multi-select-open', 'click', function() {
+
+ var multiSelectContainer = $(this).siblings('.multi-select-container');
+ var multiSelect = multiSelectContainer.find('select');
+
+ var inputContainerOffset = $(this).parents('.input').offset();
+
+ multiSelectContainer.css({
+ top: inputContainerOffset.top - multiSelectContainer.outerHeight(true),
+ left: inputContainerOffset.left
+ });
+
+ /* Keep the sub tabs content container from scrolling */
+ $('div.sub-tabs-content-container').css('overflow-y', 'hidden');
+
+ if ( multiSelectContainer.data('visible') !== true ) {
+
+ /* Show the multi-select */
+ multiSelectContainer.show();
+ multiSelectContainer.data('visible', true);
+
+ /* Bind the document close */
+ $(document).bind('mousedown', {multiSelectContainer: multiSelectContainer}, multiSelectClose);
+ Headway.iframe.contents().bind('mousedown', {multiSelectContainer: multiSelectContainer}, multiSelectClose);
+
+ $(window).bind('resize', {multiSelectContainer: multiSelectContainer}, multiSelectClose);
+
+ } else {
+
+ /* Hide the multi-select */
+ multiSelectContainer.hide();
+ multiSelectContainer.data('visible', false);
+
+ /* Allow sub tabs content container to scroll again */
+ $('div.sub-tabs-content-container').css('overflow-y', 'auto');
+
+ /* Remove the events */
+ $(document).unbind('mousedown', multiSelectClose);
+ Headway.iframe.contents().unbind('mousedown', multiSelectClose);
+
+ $(window).unbind('resize', multiSelectClose);
+
+ }
+
+ });
+
+ multiSelectClose = function(event) {
+
+ /* Do not trigger this if they're clicking the same button that they used to open the multi-select */
+ if ( $(event.target).parents('div.input-multi-select div.input-right').length === 1 )
+ return;
+
+ var multiSelectContainer = event.data.multiSelectContainer;
+
+ /* Hide the multi-select */
+ multiSelectContainer.hide();
+ multiSelectContainer.data('visible', false);
+
+ /* Allow sub tabs content container to scroll again */
+ $('div.sub-tabs-content-container').css('overflow-y', 'auto');
+
+ /* Remove the events */
+ $(document).unbind('mousedown', multiSelectClose);
+ Headway.iframe.contents().unbind('mousedown', multiSelectClose);
+
+ $(window).unbind('resize', multiSelectClose);
+
+ }
+
+
+ /* Image Uploaders */
+ $(context).delegate('div.input-image span.button', 'click', function() {
+
+ var self = this;
+
+ openImageUploader(function(url, filename) {
+
+ $(self).siblings('input').val(url);
+ $(self).siblings('span.src').show().text(filename);
+
+ $(self).siblings('span.delete-image').show();
+
+ dataHandleInput($(self).siblings('input'), url, {action: 'add'});
+
+ });
+
+ });
+
+ $(context).delegate('div.input-image span.delete-image', 'click', function() {
+
+ if ( !confirm('Are you sure you wish to remove this image?') ) {
+ return false;
+ }
+
+ $(this).siblings('.src').hide();
+ $(this).hide();
+
+ $(this).siblings('input').val('');
+
+ dataHandleInput($(this).siblings('input'), '', {action: 'delete'});
+
+ });
+
+
+ /* Repeaters */
+ updateRepeaterValues = function(repeater) {
+
+ var values = {};
+
+ repeater.find('div.repeater-group:visible').each(function(index) {
+
+ var groupValues = {};
+
+ $(this).find('select, input, textarea').each(function() {
+
+ var value = $(this).val();
+
+ if ( $(this).is('[type="checkbox"]') && !$(this).is(':checked') ) {
+ value = false;
+ }
+
+ groupValues[$(this).attr('name')] = value;
+
+ });
+
+ values[index] = groupValues;
+
+ });
+
+ return dataHandleInput(repeater.find('input.repeater-group-input'), values);
+
+ }
+
+ $(context).delegate('div.repeater .add-group', 'click', function() {
+
+ var repeater = $(this).parents('div.repeater');
+ var group = $(this).parents('div.repeater-group');
+ var groupTemplate = repeater.find('.repeater-group-template');
+
+ /* If the limit is met then don't add a new group */
+ if ( repeater.hasClass('limit-met') )
+ return;
+
+ /* Clone repeater template */
+ var newGroup = groupTemplate.clone().hide().removeClass('repeater-group-template');
+ newGroup.insertAfter(group).fadeIn(300);
+
+ /* Remove group single class since there's no longer one group */
+ repeater.find('.repeater-group-single').removeClass('repeater-group-single');
+
+ /* Add limit-met class if necessary */
+ var repeaterLimit = repeater.data('repeater-limit');
+
+ if ( !isNaN(repeaterLimit) && repeaterLimit >= 1 && repeater.find('div.repeater-group:not(.repeater-group-template):visible').length == repeaterLimit )
+ repeater.addClass('limit-met');
+
+ updateRepeaterValues(repeater);
+
+ });
+
+ $(context).delegate('div.repeater .remove-group', 'click', function() {
+
+ if ( !confirm('Are you sure?') )
+ return;
+
+ var repeater = $(this).parents('div.repeater');
+ var group = $(this).parents('div.repeater-group');
+
+ /* Fade out that way history can revert it. The updatePanelHidden will be based off of if the group is :visible or not */
+ group.fadeOut(300, function() {
+
+ /* if there's only one group left, then add the repeater group single class */
+ if ( repeater.find('div.repeater-group:visible').length === 1 )
+ repeater.find('div.repeater-group:visible').addClass('repeater-group-single');
+
+ /* Remove limit-met class if necessary */
+ var repeaterLimit = repeater.data('repeater-limit');
+
+ if ( !isNaN(repeaterLimit) && repeaterLimit >= 1 && repeater.find('div.repeater-group:not(.repeater-group-template):visible').length < repeaterLimit )
+ repeater.removeClass('limit-met');
+
+ updateRepeaterValues(repeater);
+
+ });
+
+ });
+
+
+ /* Color Inputs */
+ $(context).delegate('div.input-colorpicker div.colorpicker-box', 'click', function() {
+
+ /* Keep the sub tabs content container from scrolling */
+ $('div.sub-tabs-content-container').css('overflow-y', 'hidden');
+
+ /* Set up variables */
+ var input = $(this).parent().siblings('input');
+ var inputVal = input.val();
+
+ if ( inputVal == 'transparent' )
+ inputVal = '00FFFFFF';
+
+ var colorpickerHandleVal = function(color, inst) {
+
+ var colorValue = '#' + color.hex;
+
+ /* If alpha ISN'T 100% then use RGBa */
+ if ( color.a != 100 )
+ var colorValue = color.rgba;
+
+ input.val(colorValue);
+ dataHandleInput(input, colorValue);
+
+ /* Call developer-defined callback */
+ var callback = eval(input.attr('data-callback'));
+
+ if ( typeof callback == 'function' ) {
+
+ callback({
+ input: input,
+ value: color.rgba,
+ colorObj: color
+ });
+
+ }
+ /* End Callback */
+
+ }
+
+ $(this).colorpicker({
+ realtime: true,
+ alpha: true,
+ alphaHex: true,
+ allowNull: false,
+ swatches: (typeof Headway.colorpickerSwatches == 'object' && Headway.colorpickerSwatches.length) ? Headway.colorpickerSwatches : true,
+ color: inputVal,
+ showAnim: false,
+ beforeShow: function(input, inst) {
+
+ /* Add iframe overlay */
+ showIframeOverlay();
+
+ },
+ onClose: function(color, inst) {
+
+ colorpickerHandleVal(color, inst);
+
+ /* Hide iframe overlay */
+ hideIframeOverlay();
+
+ /* Allow sub tabs content container to scroll again */
+ $('div.sub-tabs-content-container').css('overflow-y', 'auto');
+
+ },
+ onSelect: function(color, inst) {
+
+ colorpickerHandleVal(color, inst);
+
+ },
+ onAddSwatch: function(color, swatches) {
+
+ dataSetOption('general', 'colorpicker-swatches', swatches);
+
+ },
+ onDeleteSwatch: function(color, swatches) {
+
+ dataSetOption('general', 'colorpicker-swatches', swatches);
+
+ }
+ });
+
+ $.colorpicker._showColorpicker($(this));
+
+ setupTooltips();
+
+ });
+
+
+ /* Buttons */
+ $(context).delegate('div.input-button span.button', 'click', function() {
+
+ dataHandleInput($(this));
+
+ });
+
+
+ /* Import Files */
+ $(context).delegate('div.input-import-file span.button', 'click', function() {
+
+ $(this).siblings('input[type="file"]').trigger('click');
+
+ });
+
+ $(context).delegate('div.input-import-file input[type="file"]', 'change', function(event) {
+
+ if ( event.target.files[0].name.split('.').slice(-1)[0] != 'json' ) {
+
+ $(this).val(null);
+ return alert('Invalid Headway import file. Please be sure that the Headway import file is a valid JSON formatted file.');
+
+ }
+
+ $(this).siblings('span.src').show().text($(this).val().split(/(\\|\/)/g).pop());
+ $(this).siblings('span.delete-file').show();
+
+ dataHandleInput($(this));
+
+ });
+
+ $(context).delegate('div.input-import-file .delete-file', 'click', function() {
+
+ if ( !confirm('Are you sure?') )
+ return;
+
+ $(this).fadeOut(100);
+ $(this).siblings('span.src').fadeOut(100);
+
+ var fileInput = $(this).siblings('input[type="file"]');
+ var callback = eval(fileInput.attr('data-callback'));
+
+ fileInput.val(null);
+
+ dataHandleInput(fileInput);
+
+ });
+
+ },
+
+ bind: function(contenxt) {
+
+ if ( typeof context === 'undefined' )
+ var context = 'div#panel';
+
+ /* Sliders */
+ $('div.input-slider div.input-slider-bar', context).each(function() {
+
+ var self = this;
+
+ var value = parseInt($(this).parents('.input-slider').find('input.input-slider-bar-hidden').val());
+
+ var min = parseInt($(this).attr('slider_min'));
+ var max = parseInt($(this).attr('slider_max'));
+ var interval = parseInt($(this).attr('slider_interval'));
+
+ var sliderInput = $(this).siblings('div.input-slider-bar-text').find('.input-slider-bar-input');
+
+ var handleSliderChange = function(sliderInput, value) {
+
+ Headway.history.add({
+ up: function() {
+
+ $(sliderInput).val(value);
+ $(sliderInput).prev().text(value);
+ $(sliderInput).parents('.input-slider').find('.input-slider-bar').slider( 'value', value );
+ /* Handle hidden input */
+ dataHandleInput($(sliderInput).parents('.input-slider').find('input.input-slider-bar-hidden'), value);
+
+ },
+
+ down: function() {
+
+ var value = $(sliderInput).parents('.input-slider').find('input.input-slider-bar-hidden').data('value-original');
+
+ $(sliderInput).val(value);
+ $(sliderInput).prev().text(value);
+ $(sliderInput).parents('.input-slider').find('.input-slider-bar').slider( 'value', value );
+ /* Handle hidden input */
+ dataHandleInput($(sliderInput).parents('.input-slider').find('input.input-slider-bar-hidden'), value);
+
+ }
+ });
+
+ }
+
+ $(this).slider({
+ range: 'min',
+ value: value,
+ min: min,
+ max: max,
+ step: interval,
+ start: function(event, ui) {
+ $(this).parents('.input-slider').find('input.input-slider-bar-hidden').data('value-original', ui.value);
+ },
+ slide: function( event, ui ) {
+
+ /* Update visible output */
+ //$(this).siblings('div.input-slider-bar-text').find('span.slider-value').text(ui.value);
+ $(this).siblings('div.input-slider-bar-text').find('.input-slider-bar-input').val(ui.value);
+
+ /* Update hidden input */
+ $(this).parents('.input-slider').find('input.input-slider-bar-hidden').val(ui.value);
+
+ /* Handle hidden input */
+ dataHandleInput($(this).parents('.input-slider').find('input.input-slider-bar-hidden'), ui.value);
+
+ },
+ stop: function(event, ui) {
+
+ handleSliderChange(sliderInput, ui.value);
+
+ }
+ });
+
+ sliderInput.on('keydown', function(event) {
+
+ var key = event.charCode || event.keyCode || 0;
+ // allow backspace, tab, delete, arrows, numbers and keypad numbers ONLY
+ // home, end, period, and numpad decimal
+
+ return (
+ key == 8 || /* Backspace */
+ key == 9 ||
+ key == 46 || /* Delete */
+ key == 110 ||
+ //key == 190 || /* Period */
+ (key >= 35 && key <= 40) ||
+ (key >= 48 && key <= 57) ||
+ (key >= 96 && key <= 105));
+
+ });
+
+ sliderInput.on('focus', function(event) {
+ $(this).parents('.input-slider').find('input.input-slider-bar-hidden').data('value-original', $(this).val());
+ });
+
+ sliderInput.on('keyup change', function(event) {
+
+ /* Don't fire this if the enter key is pressed */
+ if ( event.which === 13 )
+ return;
+
+ if ( this.value <= max && this.value >= min) {
+
+ var sliderInput = this;
+
+ handleSliderChange(this, this.value);
+
+ }
+
+ });
+
+ sliderInput.on('blur', function(event) {
+
+ var value = this.value;
+
+ if( this.value > max ) {
+ value = max;
+ } else if( this.value < min ) {
+ value = min;
+ }
+
+ handleSliderChange(this, value);
+
+ });
+
+ });
+
+ /* Repeaters */
+ /* Repeater Sortables */
+ $('.repeater-sortable', context).sortable({
+ items: '.repeater-group',
+ containment: 'parent',
+ forcePlaceholderSize: true,
+ handle: '.sortable-handle',
+ stop: function() {
+ updateRepeaterValues($(this));
+ }
+ });
+
+ /* Repeater Limits */
+ $('.repeater', context).each(function() {
+
+ var repeaterLimit = $(this).data('repeater-limit');
+
+ if ( !isNaN(repeaterLimit) && repeaterLimit >= 1 && $(this).find('div.repeater-group:not(.repeater-group-template):visible').length >= repeaterLimit )
+ $(this).addClass('limit-met');
+
+ });
+
+ }
+
+ }
+
+ return panelInputs;
+
+});
\ No newline at end of file
--- /dev/null
+define(['jquery', 'jqueryUI', 'deps/jquery.cookie', 'util.tooltips', 'modules/panel.inputs'], function($, jQueryUI, jQueryCookie, tooltips, panelInputs) {
+
+ selectTab = function(tab, context) {
+
+ var tabs = context.find('.ui-tabs-nav');
+ var tabLink = tabs.find('li[aria-controls="' + tab + '"] a').length ? tabs.find('li[aria-controls="' + tab + '"] a') : tabs.find('li[aria-controls="' + tab + '-content"] a');
+
+ return tabLink.trigger('click');
+
+ },
+
+ addPanelTab = function(name, title, content, closable, closeOnLayoutSwitch, panelClass) {
+
+ /* If the tab name already exists, don't try making it */
+ if ( $('ul#panel-top li a[href="#' + name + '-tab"]').length !== 0 )
+ return false;
+
+ /* Set up default variables */
+ if ( typeof closable == 'undefined' ) {
+ var closable = false;
+ }
+
+ if ( typeof closeOnLayoutSwitch == 'undefined' ) {
+ var closeOnLayoutSwitch = false;
+ }
+
+ if ( typeof panelClass == 'undefined' ) {
+ var panelClass = false;
+ }
+
+ /* Add the tab */
+ var tab = $('<li><a href="#' + name + '-tab">' + title + '</a></li>').appendTo('div#panel #panel-top');
+ var panel = $('<div id="' + name + '-tab"></div>').appendTo('div#panel');
+ var tabLink = tab.find('a');
+
+ $('div#panel').tabs('refresh');
+ $(tabLink).bind('click', showPanel);
+
+ showPanel();
+
+ /* Remove panel empty class from body so it will show again if it was empty before */
+ $('body').removeClass('panel-empty');
+
+ /* Add the panel class to the panel */
+ panel.addClass('panel');
+
+ /* If the content is static, just throw it in. Otherwise get the content with AJAX */
+ if ( typeof content == 'string' ) {
+
+ panel.html(content);
+
+ } else {
+
+ var loadURL = content.url;
+ var loadData = content.data || false;
+
+ var loadCallback = function() {
+
+ if ( typeof content.callback == 'function' )
+ content.callback.call();
+
+ };
+
+ createCog(panel, true);
+
+ $('div#panel div#' + name + '-tab').load(loadURL, loadData, loadCallback);
+
+ }
+
+ if ( panelClass )
+ panel.addClass('panel-' + panelClass);
+
+ /* Add delete to tab link if the tab is closable */
+ if ( closable ) {
+
+ tabLink.parent().append('<span class="close">X</span>');
+
+ }
+
+ /* If the panel is set to close on layout switch, add a class to the tab itself so we can target it down the road */
+ tabLink.parent().addClass('tab-close-on-layout-switch');
+
+ return tab;
+
+ },
+
+
+ removePanelTab = function(name) {
+
+ var name = name.replace('-tab', '');
+
+ /* If tab doesn't exist, don't try to delete any tabs */
+ if ( $('#' + name + '-tab').length === 0 ) {
+ return false;
+ }
+
+ $('#panel').find('#' + name + '-tab').remove();
+ $('#panel-top').find('a[href="#' + name + '-tab"]').parent().remove();
+
+ /* If panel is empty, add panel empty class to body so the entire panel is hidden */
+ if ( !$('#panel-top').find('li').length )
+ $('body').addClass('panel-empty');
+
+ return $('div#panel').tabs('refresh');
+
+ },
+
+
+ removeLayoutSwitchPanels = function() {
+
+ $('li.tab-close-on-layout-switch').each(function(){
+ var id = $(this).find('a').attr('href').replace('#', '');
+
+ removePanelTab(id);
+ });
+
+ },
+
+ togglePanel = function() {
+
+ if ( $('div#panel').hasClass('panel-hidden') )
+ return showPanel();
+
+ return hidePanel();
+
+ },
+
+
+ hidePanel = function() {
+
+ //If the panel is already hidden, don't go through any trouble.
+ if ( $('div#panel').hasClass('panel-hidden') )
+ return false;
+
+ var panelCSS = {bottom: -$('div#panel').height()};
+ var iframeCSS = {bottom: $('ul#panel-top').outerHeight()};
+
+ $('div#panel').css(panelCSS).addClass('panel-hidden');
+ $('div#iframe-container').css(iframeCSS);
+
+ setTimeout(repositionTooltips, 400);
+
+ $('body').addClass('panel-hidden');
+
+ /* Change arrow to pointing up arrow */
+ $('ul#panel-top-right li#minimize span').text('^');
+
+ /* De-select the selected block while the panel is hidden */
+ if ( typeof $i == 'function' ) {
+ $i('.block-selected').removeClass('block-selected block-hover');
+ }
+
+ $.cookie('hide-panel', true);
+
+ return true;
+
+ },
+
+
+ showPanel = function() {
+
+ //If the panel is already visible, don't go through any trouble.
+ if ( !$('div#panel').hasClass('panel-hidden') )
+ return false;
+
+ var panelCSS = {bottom: 0};
+ var iframeCSS = {bottom: $('div#panel').outerHeight()};
+
+ $('div#panel').css(panelCSS).removeClass('panel-hidden');
+ $('div#iframe-container').css(iframeCSS);
+
+ setTimeout(repositionTooltips, 400);
+
+ $('body').removeClass('panel-hidden');
+
+ /* Change arrow to pointing down arrow */
+ $('ul#panel-top-right li#minimize span').text('g');
+
+ /* Re-select the the block if a block options panel tab is open. */
+ if ( $('ul#panel-top > li.ui-state-active a').length )
+ $i('#' + $('ul#panel-top > li.ui-state-active a').attr('href').replace('#', '').replace('-tab', '')).addClass('block-selected block-hover');
+
+ $.cookie('hide-panel', false);
+
+ return true;
+
+ }
+
+
+ var panel = {
+ init: function() {
+
+ panelInputs.delegate();
+ panelInputs.bind();
+
+ },
+
+ getPanelMaxHeight: function() {
+ return $(window).height() - 275;
+ },
+
+ resizePanel: function(panelHeight, resizingWindow) {
+
+ var $panel = $('div#panel');
+ var $panelTop = $panel.find('ul#panel-top');
+
+ if ( typeof panelHeight == 'undefined' || panelHeight == false )
+ panelHeight = $('div#panel').height();
+
+ if ( panelHeight > panel.getPanelMaxHeight() )
+ panelHeight = (panel.getPanelMaxHeight() > panelMinHeight) ? panel.getPanelMaxHeight() : panelMinHeight;
+
+ if ( panelHeight < panelMinHeight )
+ panelHeight = panelMinHeight;
+
+ if ( typeof resizingWindow != 'undefined' && resizingWindow && panelHeight < panel.getPanelMaxHeight() )
+ return;
+
+ $panel.height(panelHeight);
+
+ var iframeBottomPadding = $panel.hasClass('panel-hidden') ? $panelTop.outerHeight() : $panel.outerHeight();
+ var layoutSelectorBottomPadding = $panel.hasClass('panel-hidden') ? $panelTop.outerHeight() + $('div#layout-selector-tabs').height() : $panel.outerHeight() + $('div#layout-selector-tabs').height();
+
+ $('div#iframe-container').css({bottom: iframeBottomPadding});
+
+ if ( $panel.hasClass('panel-hidden') )
+ $('div#panel').css({'bottom': -$('div#panel').height()});
+
+ $.cookie('panel-height', $panel.height());
+
+ }
+
+ }
+
+ /* If panel is empty then add body class */
+ if ( !$('ul#panel-top').find('li').length )
+ $('body').addClass('panel-empty');
+
+ /* PANEL */
+ /* Tab Functions */
+ $('ul#panel-top').delegate('span.close', 'click', function(){
+
+ var tab = $(this).siblings('a').attr('href').replace('#', '').replace('-tab', '');
+
+ return removePanelTab(tab);
+
+ });
+
+ $('div#panel').tabs({
+ tabTemplate: "<li><a href='#{href}'>#{label}</a></li>",
+ add: function(event, ui, content) {
+
+ $(ui.panel).append(content);
+
+ },
+ activate: function(event, ui) {
+
+ var tabID = $(ui.newTab).children('a').attr('href').replace('#', '').replace('-tab', '');
+
+ $i('.block-selected').removeClass('block-selected block-hover');
+
+ if ( tabID.indexOf('block-') === 0 )
+ $i('#' + tabID).addClass('block-selected block-hover');
+
+ }
+ });
+
+ $('ul#panel-top li a').on('click', showPanel);
+
+ $('div.sub-tab').tabs();
+
+ /* PANEL RESIZING */
+ var panelMinHeight = 120;
+
+ /* Resize the panel according to the cookie right on VE load */
+ $(document).ready(function() {
+
+ if ( $.cookie('panel-height') )
+ panel.resizePanel($.cookie('panel-height'));
+
+ });
+
+ /* Make the resizing handle actually work */
+ $('div#panel').resizable({
+ maxHeight: panel.getPanelMaxHeight(),
+ minHeight: 120,
+ handles: 'n',
+ resize: function(event, ui) {
+
+ $(this).css({
+ width: '100%',
+ position: 'fixed',
+ bottom: 0,
+ top: ''
+ });
+
+ /* Adjust Padding */
+ $('div#iframe-container').css({bottom: $('div#panel').outerHeight()});
+
+ /* Refresh iframe overlay size so it continues to cover iframe */
+ showIframeOverlay();
+
+ },
+ start: function() {
+
+ showIframeOverlay();
+
+ },
+ stop: function() {
+
+ $.cookie('panel-height', $(this).height());
+
+ hideIframeOverlay();
+
+ },
+ });
+
+ /* The max height option on the resizable must be updated if the window is resized. */
+ $(window).bind('resize', function(event) {
+
+ /* For some reason jQuery UI resizable triggers window resize so only fire if window is truly the target. */
+ if ( event.target != window )
+ return;
+
+ $('div#panel').resizable('option', {maxHeight: panel.getPanelMaxHeight()});
+
+ panel.resizePanel(false, true);
+
+ });
+ /* END PANEL RESIZING */
+
+ /* PANEL TOGGLE */
+ $('div#panel-top-container').bind('dblclick', function(event) {
+
+ if ( event.target.id != 'panel-top-container' )
+ return false;
+
+ togglePanel();
+
+ });
+
+ $('ul#panel-top-right li#minimize').bind('click', function(event) {
+
+ togglePanel();
+
+ return false;
+
+ });
+
+ /* Check for cookie */
+ if ( $.cookie('hide-panel') === 'true' ) {
+
+ hidePanel(true);
+
+ }
+ /* END PANEL TOGGLE */
+ /* END PANEL */
+
+ return panel;
+
+});
\ No newline at end of file
--- /dev/null
+define(['jquery', 'ko'], function($, ko) {
+
+ var snapshots = {
+ init: function() {
+
+ snapshots.bind();
+ snapshots.setupViewModel();
+
+ },
+
+ setupViewModel: function() {
+
+ Headway.viewModels.snapshots = {
+ snapshots: ko.observableArray(Headway.snapshots),
+ formatSnapshotDatetime: function(datetime) {
+
+ var datetimeFrags = datetime.split(/[- :]/);
+
+ return new Date(Date.UTC(datetimeFrags[0], datetimeFrags[1] - 1, datetimeFrags[2], datetimeFrags[3], datetimeFrags[4], datetimeFrags[5])).toLocaleString();
+
+ },
+ rollbackToSnapshot: function(data, event) {
+
+ if ( !confirm("Are you sure you wish to rollback?\n\nYou will lose all between this snapshot and now unless you save another snapshot.") )
+ return false;
+
+ var button = $(event.target);
+
+ if ( button.attr('disabled') )
+ return false;
+
+ /* Disable button temporarily */
+ button.attr('disabled', true);
+ button.addClass('button-depressed');
+ button.text('Rolling Back..');
+
+ /* Rollback */
+ $.post(Headway.ajaxURL, {
+ security: Headway.security,
+ action: 'headway_visual_editor',
+ method: 'rollback_to_snapshot',
+ layout: Headway.currentLayout,
+ snapshot_id: data.id,
+ mode: Headway.mode
+ }, function(response) {
+
+ if ( typeof response.error != 'undefined' )
+ return;
+
+ showNotification({
+ id: 'rolled-back-successfully',
+ message: 'Successfully rolled back to snapshot.<br /><br /><strong>Refreshing Visual Editor in 3 seconds</strong>.',
+ success: true
+ });
+
+ button.text('Rolled Back!');
+
+ /* Reload the Visual Editor */
+ setTimeout(function() {
+ allowVEClose();
+ document.location.reload(true);
+ }, 1000);
+
+ });
+
+ },
+ deleteSnapshot: function(data, event) {
+
+ if ( !confirm("Are you sure you wish to delete this snapshot?\n\nYou cannot undo this or restore another snapshot to bring this snapshot back.") )
+ return false;
+
+ var button = $(event.target);
+
+ if ( button.hasClass('deletion-in-progress') )
+ return false;
+
+ /* Disable button temporarily */
+ button.addClass('deletion-in-progress');
+
+ /* Delete snapshot */
+ $.post(Headway.ajaxURL, {
+ security: Headway.security,
+ action: 'headway_visual_editor',
+ method: 'delete_snapshot',
+ layout: Headway.currentLayout,
+ snapshot_id: data.id,
+ mode: Headway.mode
+ }, function (response) {
+
+ if ( typeof response.error != 'undefined' )
+ return;
+
+ showNotification({
+ id: 'deleted-snapshot-successfully',
+ message: 'Successfully deleted snapshot.',
+ success: true
+ });
+
+ Headway.viewModels.snapshots.snapshots.remove(data);
+
+ });
+
+
+ },
+ saveSnapshot: function(data, event) {
+
+ var button = $(event.target);
+
+ if ( button.attr('disabled') )
+ return false;
+
+ /* Disable button temporarily */
+ button.attr('disabled', true);
+ button.text('Saving Snapshot...');
+
+ /* Add the snapshot */
+ button.siblings('.spinner').show();
+
+ /* Prompt for comments about snapshot */
+ var snapshotComments = prompt("(Optional)\n\nEnter name or description of the changes in this snapshot.");
+
+ $.post(Headway.ajaxURL, {
+ security: Headway.security,
+ action: 'headway_visual_editor',
+ method: 'save_snapshot',
+ layout: Headway.currentLayout,
+ mode: Headway.mode,
+ snapshot_comments: snapshotComments
+ }, function(response) {
+
+ if ( typeof response.timestamp == 'undefined' )
+ return;
+
+ showNotification({
+ id: 'snapshot-saved',
+ message: 'Snapshot saved.',
+ success: true
+ });
+
+ Headway.viewModels.snapshots.snapshots.unshift({
+ id: response.id,
+ timestamp: response.timestamp,
+ comments: response.comments
+ });
+
+ button.text('Save Snapshot');
+ button.removeAttr('disabled');
+ button.siblings('.spinner').hide();
+
+ });
+
+ }
+ }
+
+ $(document).ready(function() {
+ ko.applyBindings(Headway.viewModels.snapshots, $('#box-snapshots').get(0));
+ });
+
+ },
+
+ bind: function() {
+
+
+ }
+ }
+
+
+ return snapshots;
+
+});
\ No newline at end of file
--- /dev/null
+define(['jquery', 'jqueryUI'], function($) {
+
+ $.widget('ui.custommouse', $.ui.mouse, {
+ options: {
+ mouseStart: function(e) {},
+ mouseDrag: function(e) {},
+ mouseStop: function(e) {},
+ mouseCapture: function(e) { return true; }
+ },
+ // Forward events to custom handlers
+ _mouseStart: function(e) { return this.options.mouseStart(e); },
+ _mouseDrag: function(e) { return this.options.mouseDrag(e); },
+ _mouseStop: function(e) { return this.options.mouseStop(e); },
+ _mouseCapture: function(e) { return this.options.mouseCapture(e); },
+
+ // Bookkeeping, inspired by Draggable
+ widgetEventPrefix: 'custommouse',
+
+ _init: function() {
+ return this._mouseInit();
+ },
+
+ _create: function() {
+ return this.element.addClass('ui-custommouse');
+ },
+
+ _destroy: function() {
+ this._mouseDestroy();
+ return this.element.removeClass('ui-custommouse');
+ }
+ });
+
+});
\ No newline at end of file
--- /dev/null
+(function($) {
+
+/*!
+jQuery quicksearch
+*/
+(function($,window,document,undefined){$.fn.quicksearch=function(target,opt){var timeout,cache,rowcache,jq_results,val="",e=this,options=$.extend({delay:100,selector:null,stripeRows:null,loader:null,noResults:"",matchedResultsCount:0,bind:"keyup",onBefore:function(){return},onAfter:function(){return},show:function(){this.style.display=""},hide:function(){this.style.display="none"},prepareQuery:function(val){return val.toLowerCase().split(" ")},testQuery:function(query,txt,_row){for(var i=0;i<query.length;i+=
+1)if(txt.indexOf(query[i])===-1)return false;return true}},opt);this.go=function(){var i=0,numMatchedRows=0,noresults=true,query=options.prepareQuery(val),val_empty=val.replace(" ","").length===0;for(var i=0,len=rowcache.length;i<len;i++)if(val_empty||options.testQuery(query,cache[i],rowcache[i])){options.show.apply(rowcache[i]);noresults=false;numMatchedRows++}else options.hide.apply(rowcache[i]);if(noresults)this.results(false);else{this.results(true);this.stripe()}this.matchedResultsCount=numMatchedRows;
+this.loader(false);options.onAfter();return this};this.search=function(submittedVal){val=submittedVal;e.trigger()};this.currentMatchedResults=function(){return this.matchedResultsCount};this.stripe=function(){if(typeof options.stripeRows==="object"&&options.stripeRows!==null){var joined=options.stripeRows.join(" ");var stripeRows_length=options.stripeRows.length;jq_results.not(":hidden").each(function(i){$(this).removeClass(joined).addClass(options.stripeRows[i%stripeRows_length])})}return this};
+this.strip_html=function(input){var output=input.replace(new RegExp("<[^<]+>","g"),"");output=$.trim(output.toLowerCase());return output};this.results=function(bool){if(typeof options.noResults==="string"&&options.noResults!=="")if(bool)$(options.noResults).hide();else $(options.noResults).show();return this};this.loader=function(bool){if(typeof options.loader==="string"&&options.loader!=="")bool?$(options.loader).show():$(options.loader).hide();return this};this.cache=function(){jq_results=$(target);
+if(typeof options.noResults==="string"&&options.noResults!=="")jq_results=jq_results.not(options.noResults);var t=typeof options.selector==="string"?jq_results.find(options.selector):$(target).not(options.noResults);cache=t.map(function(){return e.strip_html(this.innerHTML)});rowcache=jq_results.map(function(){return this});val=val||this.val()||"";return true};this.trigger=function(){this.loader(true);options.onBefore();window.clearTimeout(timeout);timeout=window.setTimeout(function(){e.go()},
+options.delay);return this};this.cache();this.results(true);this.stripe();this.loader(false);return this.each(function(){$(this).bind(options.bind,function(){val=$(this).val();e.trigger()})})}})(jQuery,this,document);
+
+
+/* Fonts input object */
+ function fontBrowserObj(browser) {
+
+ this.browser = browser;
+
+ this.propertyInput = browser.parents('.property-font-family-select');
+
+ this.hiddenInput = this.propertyInput.find('input.property-hidden-input');
+
+ this.setup = function() {
+
+ var self = this;
+
+ this.browser.find('.tab-content').each(function() {
+
+ var fontsList = $(this).find('.fonts-list ul');
+
+ var scrollWebFontLoaderDebounced = _.debounce(function() {
+ self.scrollWebFontLoader(fontsList);
+ }, 100);
+
+ fontsList.bind('scroll', scrollWebFontLoaderDebounced);
+
+ self.initQuickSearch($(this));
+ self.initPreview($(this));
+ self.initSorting($(this));
+
+ fontsList.delegate('.use-font', 'click', function() {
+
+ var li = $(this).parents('li').first();
+
+ /* Determine value to save to DB */
+ var webfontProvider = $(this).parents('.tab-content').data('font-webfont-provider');
+ var fontID = li.data('value');
+
+ var fontName = $(this).siblings('.font-family').text();
+ var fontFamily = li.css('font-family');
+ var fontVariants = li.data('variants');
+
+ var variantsStr = '';
+
+ if ( fontVariants && fontVariants.indexOf('regular') === -1 )
+ variantsStr = '|' + fontVariants.join(',');
+
+ var value = webfontProvider != false ? webfontProvider + '|' + fontID + variantsStr : fontID;
+
+ /* Change readout */
+ var fontNameReadout = self.propertyInput.find('.font-name');
+
+ fontNameReadout.css('font-family', fontFamily);
+ fontNameReadout.text(fontName);
+
+ /* Change selected font */
+ self.browser.find('.selected-font').removeClass('selected-font');
+ li.addClass('selected-font');
+
+ /* Close font panel */
+ fontBrowserClose({
+ data: {
+ fontBrowser: self.browser
+ }
+ });
+
+ /* Save value */
+ dataHandleDesignEditorInput({hiddenInput: self.hiddenInput, value: value, stack: fontFamily});
+
+ });
+
+ });
+
+ this.browser.tabs({
+ selected: 0,
+ activate: function(event, ui) {
+
+ var $newPanel = $(ui.newPanel);
+
+ if ( $newPanel.data('fonts-loaded') )
+ return;
+
+ self.retrieveRemoteFonts($newPanel, 'popularity', true, true);
+
+ }
+ });
+
+ this.changeToSelectedFontProviderTab();
+
+ }
+
+ this.retrieveRemoteFonts = function(context, sortBy, resetTransient, firstLoad) {
+
+ if ( !context.data('font-load-with-ajax') )
+ return;
+
+ var self = this;
+
+ createCog(context.find('.fonts-loading'), true);
+
+ context.find('.fonts-list ul').fadeOut(300);
+ context.find('.fonts-loading').fadeIn(300);
+
+ /* Lock search until it has finished loading */
+ context.find('.fonts-filter').attr('disabled', 'disabled');
+
+ $.post(Headway.ajaxURL, {
+ security: Headway.security,
+ action: 'headway_visual_editor',
+ method: 'fonts_list',
+ sortby: sortBy,
+ provider: context.data('font-webfont-provider')
+ }, function(response) {
+
+ context.find('.fonts-loading').fadeOut(300);
+ context.find('ul').hide().html(response).fadeIn(300, function() {
+
+ /* Force fonts to load before user scrolls */
+ self.scrollWebFontLoader(context.find('ul'));
+
+ });
+
+ /* Refresh quick search cache */
+ context.find('.fonts-filter').val('');
+ context.data('quicksearch').cache();
+
+ /* Allow quick search again */
+ context.find('.fonts-filter').removeAttr('disabled');
+
+ /* Scroll to selected item if first time loading tab otherwise scroll to top */
+ if ( typeof firstLoad != 'undefined' && firstLoad && self.hiddenInput.val().match(/\|/g) ) {
+
+ var selectedFont = context.find('li[data-value="' + self.hiddenInput.val().split('|')[1] + '"]');
+
+ if ( selectedFont.length ) {
+
+ selectedFont.addClass('selected-font');
+ context.find('.fonts-list ul').scrollTop(selectedFont.position().top);
+
+ }
+
+ } else {
+
+ context.find('.fonts-list ul').scrollTop(0);
+
+ }
+
+ context.data('fonts-loaded', true);
+
+ });
+
+ }
+
+ this.scrollWebFontLoader = function(fontList) {
+
+ var fontListContainer = $(fontList.parents('.tab-content').get(0));
+ var fontListProvider = fontListContainer.data('font-webfont-provider');
+
+ if ( fontList.parents('.font-provider-tab-content.ui-tabs-hide').length || !fontListProvider )
+ return;
+
+ var fontsToLoad = [];
+
+ /* Find Visible Fonts that need to be loaded */
+ var viewportTop = fontList.scrollTop();
+ var viewportBottom = viewportTop + fontList.outerHeight();
+
+ fontList.find('li').each(function() {
+
+ var fontTop = $(this).position().top + fontList.scrollTop();
+ var fontBottom = fontTop + $(this).outerHeight();
+
+ if ( !$(this).is(':visible') || $(this).data('loadedFont') )
+ return;
+
+ if ( !(fontTop <= viewportBottom) )
+ return;
+
+ if ( !(fontBottom >= viewportTop) )
+ return;
+
+ if ( fontBottom > viewportBottom )
+ return false;
+
+ var variants = '';
+
+ if ( $(this).data('variants').indexOf('regular') === -1 )
+ variants = ':' + $(this).data('variants').join(',');
+
+ fontsToLoad.push($(this).data('value') + variants);
+
+ });
+
+ /* Load fonts via WebFont API */
+ if ( fontsToLoad.length ) {
+
+ var args = {};
+ var googleFontsQueryString = '';
+
+ _.each(fontsToLoad, function(fontToLoad) {
+
+ var fontNode = fontList.find('li[data-value="' + fontToLoad + '"]');
+ fontNode.data('loadedFont', true);
+
+ googleFontsQueryString += fontToLoad.replace(' ', '+') + '|';
+
+ });
+
+ $('<link>')
+ .attr('type', 'text/css')
+ .attr('rel', 'stylesheet')
+ .attr('href', 'http://fonts.googleapis.com/css?family=' + googleFontsQueryString.substr(0, googleFontsQueryString.length-1))
+ .appendTo('head')
+ .bind('load', function() {
+
+ _.each(fontsToLoad, function(fontToLoad) {
+
+ var fontNode = fontList.find('li[data-value="' + fontToLoad.split(':')[0] + '"]');
+ fontNode.find('span.font-family, span.font-preview-text').show().css('opacity', 1);
+
+ });
+
+ });
+
+ }
+
+ }
+
+ this.initQuickSearch = function(context) {
+
+ var id = context.attr('id');
+
+ var quicksearch = context.find('.fonts-filter').quicksearch('#' + id + ' .fonts-list ul li', {
+ delay: 750,
+ noResults: '#' + id + ' .fonts-list .fonts-noresults',
+ loader: '#' + id + ' .fonts-list .fonts-loading',
+ bind: 'keyup',
+ onBefore: function() {
+ context.find('.fonts-list ul').fadeOut(100);
+ },
+ onAfter: function() {
+ /* Force fonts to be loaded */
+ context.find('.fonts-list ul')
+ .trigger('scroll')
+ .fadeIn(100);
+ },
+ prepareQuery: function (val) {
+ return new RegExp(val, "i");
+ },
+ testQuery: function (query, txt, _row) {
+ return query.test(jQuery.trim(txt.replace('the quick brown fox jumps over the lazy dog.', '')));
+ }
+ });
+
+ /* Attach quicksearch object to element that way the cache can be refreshed */
+ context.data('quicksearch', quicksearch);
+
+ }
+
+ this.initPreview = function(context) {
+
+ var self = this;
+
+ /* fonts preview overlay */
+ previewHtml = $('<div class="font-preview-overlay" style="display:none;">' +
+ '<span class="close-preview"></span>' +
+ '<header>' +
+ '<h4></h4>' +
+ '<p><i class="icon-edit"> </i><strong>click anywhere</strong> in preview text to edit and add your own</p>' +
+ '</header>' +
+ '<div class="editable allow-backspace-key" contenteditable="true"></div>' +
+ '<footer>' +
+ '<div class="tools">' +
+ '<span title="Reset Preview Text" class="reset-preview"></span>' +
+ '<span title="Decrease Preview Size" class="size-down"></span>' +
+ '<span title="Increase Preview Size" class="size-up"></span>' +
+ '<span title="Use This Font" class="use-font"></span>' +
+ '</div>' +
+ '</footer>' +
+ '</div>');
+
+ context.find('.fonts-list').after(previewHtml);
+
+ /* preview functions */
+ this.defaultPreviewText = 'The quick brown fox jumps over the lazy dog.';
+ this.defaultPreviewSize = '24px';
+
+ this.previewResize = function(preview, resizeBy) {
+
+ var editable = preview.find('.editable');
+
+ var originalSize = editable.css('font-size');
+ var newSize = parseFloat(originalSize, 10) * resizeBy;
+
+ editable.css('font-size', newSize);
+
+ localStorage.fontPreviewSize = editable.css('font-size');
+
+ }
+
+ this.previewLoadFromStorage = function(preview) {
+
+ var editable = preview.find('.editable');
+
+ /* set preview text */
+ if ( !localStorage.getItem('fontPreviewText') ) {
+ editable.html(self.defaultPreviewText);
+ } else {
+ editable.html(localStorage.fontPreviewText);
+ }
+
+ /* set font size */
+ if ( localStorage.getItem('fontPreviewSize') ) {
+ editable.css('font-size', localStorage.fontPreviewSize);
+ }
+
+ }
+
+ this.previewSaveText = function() {
+
+ localStorage.fontPreviewText = $(this).text();
+
+ }
+
+ this.previewReset = function(preview) {
+
+ preview.find('.editable').html(self.defaultPreviewText);
+ preview.find('.editable').css('font-size', self.defaultPreviewSize);
+
+ localStorage.fontPreviewText = self.defaultPreviewText;
+ localStorage.fontPreviewSize = self.defaultPreviewSize;
+
+ }
+
+ /* Bind the preview buttons to the preview can be opened */
+ context.find('.fonts-list ul').delegate('li .preview-font', 'click', function() {
+
+ var fontID = $(this).parents('li').data('value');
+ var fontFamily = $(this).parents('li').css('font-family');
+ var fontPreview = $(this).parents('.fonts-list').siblings('.font-preview-overlay');
+
+ fontPreview.data('font-value', fontID);
+ fontPreview.data('font-name', $(this).parent().find('.font-family').text());
+ fontPreview.data('font-variants', $(this).parents('li').data('variants'));
+
+ fontPreview.fadeIn(750);
+ fontPreview.css('font-family', fontFamily);
+ fontPreview.find('h4').html($(this).parent().find('.font-family').text() + ' <span>(Preview)</span>');
+
+ self.previewLoadFromStorage(fontPreview);
+
+ });
+
+ /* increase */
+ context.find('.font-preview-overlay .size-up').on('click', function() {
+ self.previewResize($(this).parents('.font-preview-overlay'), 1.1);
+ });
+
+ /* decrease */
+ context.find('.font-preview-overlay .size-down').on('click', function() {
+ self.previewResize($(this).parents('.font-preview-overlay'), 0.9);
+ });
+
+ /* reset preview text */
+ context.find('.font-preview-overlay .reset-preview').on('click', function() {
+ self.previewReset($(this).parents('.font-preview-overlay'));
+ });
+
+ /* close preview */
+ context.find('.font-preview-overlay .close-preview').on('click', function() {
+ $(this).parents('.font-preview-overlay').fadeOut(750);
+ });
+
+ /* save changes to local storage */
+ context.find('.font-preview-overlay .editable').on('blur', this.previewSaveText);
+
+ /* bind use font button */
+ context.find('.font-preview-overlay .use-font').on('click', function() {
+
+ /* Determine value to save to DB */
+ var webfontProvider = $(this).parents('.tab-content').data('font-webfont-provider');
+ var fontID = $(this).parents('.font-preview-overlay').data('font-value');
+
+ var fontName = $(this).parents('.font-preview-overlay').data('font-name');
+ var fontFamily = $(this).parents('.font-preview-overlay').css('font-family');
+
+ var variants = $(this).parents('.font-preview-overlay').data('font-variants');
+ var variantsStr = '';
+
+ if ( variants && variants.indexOf('regular') === -1 )
+ variantsStr = '|' + variants.join(',');
+
+ var value = webfontProvider != false ? webfontProvider + '|' + fontID + variantsStr : fontID;
+
+ /* Change readout */
+ var fontNameReadout = self.propertyInput.find('.font-name');
+
+ fontNameReadout.css('font-family', fontFamily);
+ fontNameReadout.text(fontName);
+
+ /* Change selected font */
+ self.browser.find('.selected-font').removeClass('selected-font');
+ self.browser.find('li[data-value="' + fontID + '"]').addClass('selected-font');
+
+ /* Close font panel */
+ fontBrowserClose({
+ data: {
+ fontBrowser: self.browser
+ }
+ });
+
+ /* Save value */
+ dataHandleDesignEditorInput({hiddenInput: self.hiddenInput, value: value, stack: fontFamily});
+
+ });
+
+ }
+
+ this.initSorting = function(context) {
+
+ var self = this;
+
+ context.find('.fonts-search select').bind('change', function() {
+
+ var sortBy = $(this).val();
+ self.retrieveRemoteFonts($(this).parents('.tab-content'), sortBy, true);
+
+ });
+
+ }
+
+ this.changeToSelectedFontProviderTab = function() {
+
+ var value = this.hiddenInput.val();
+
+ /* Traditional font */
+ if ( !value || !value.match(/\|/g) ) {
+
+ var tab = this.browser.find('#traditional-fonts');
+ var selectedFont = tab.find('li[data-value="' + value + '"]');
+
+ if ( selectedFont.length ) {
+
+ selectedFont.addClass('selected-font');
+
+ /* For some reason the selectedFont element isn't visible immediately so the position is wrong thus the use of timeout */
+ setTimeout(function() {
+ tab.find('.fonts-list ul').scrollTop(selectedFont.position().top);
+ }, 100);
+
+ }
+
+ /* Web Font */
+ } else {
+
+ var fragments = value.split('|');
+
+ selectTab(+ fragments[0] + '-fonts', this.browser);
+
+ }
+
+ }
+
+ }
+/* End fonts input object */
+
+/* Opening and closing */
+ fontBrowserOpen = function(event) {
+
+ var fontBrowser = $(this).siblings('.font-browser');
+ var inputContainerOffset = $(this).parents('.design-editor-property-font-family').offset();
+
+ fontBrowser.css({
+ top: inputContainerOffset.top - fontBrowser.outerHeight(true),
+ left: inputContainerOffset.left
+ });
+
+ /* Check that font browser isn't bleeding over right--if it is, fix it */
+ var fontBrowserLeftOffset = parseInt(fontBrowser.css('left').replace('px', ''));
+ var fontBrowserRightPos = fontBrowserLeftOffset + fontBrowser.outerWidth(true);
+
+ if ( fontBrowserRightPos > $(window).width() ) {
+
+ var fontBrowserRightOverflow = $(window).width() - fontBrowserRightPos;
+
+ fontBrowser.css({
+ left: fontBrowserLeftOffset + fontBrowserRightOverflow - 20
+ });
+
+ }
+
+ /* Keep the sub tabs content container from scrolling */
+ $('div.sub-tabs-content-container').css('overflow-y', 'hidden');
+
+ /* Setup browser */
+ if ( fontBrowser.data('setup') !== true ) {
+
+ fontBrowser.data('obj', new fontBrowserObj(fontBrowser));
+ fontBrowser.data('obj').setup();
+
+ fontBrowser.data('setup', true);
+
+ }
+
+ /* Show browser */
+ if ( fontBrowser.data('visible') !== true ) {
+
+ /* Show the font browser */
+ fontBrowser.fadeIn(150);
+ fontBrowser.data('visible', true);
+
+ /* Bind the document close */
+ $(document).bind('mousedown', {fontBrowser: fontBrowser}, fontBrowserClose);
+ Headway.iframe.contents().bind('mousedown', {fontBrowser: fontBrowser}, fontBrowserClose);
+
+ $(window).bind('resize', {fontBrowser: fontBrowser}, fontBrowserClose);
+
+ /* Hide browser */
+ } else {
+
+ /* Hide the font browser */
+ fontBrowser.fadeOut(150);
+ fontBrowser.data('visible', false);
+
+ /* Allow sub tabs content container to scroll again */
+ $('div.sub-tabs-content-container').css('overflow-y', 'auto');
+
+ /* Remove the events */
+ $(document).unbind('mousedown', fontBrowserClose);
+ Headway.iframe.contents().unbind('mousedown', fontBrowserClose);
+
+ $(window).unbind('resize', fontBrowserClose);
+
+ }
+
+ }
+
+ fontBrowserClose = function(event) {
+
+ /* Do not trigger this if they're clicking the same button that they used to open the multi-select */
+ if ( $(event.target).parents('.design-editor-property-font-family').length === 1 )
+ return;
+
+ var fontBrowser = event.data.fontBrowser;
+
+ /* Hide the font browser */
+ fontBrowser.fadeOut(150);
+ fontBrowser.data('visible', false);
+
+ /* Allow sub tabs content container to scroll again */
+ $('div.sub-tabs-content-container').css('overflow-y', 'auto');
+
+ /* Remove the events */
+ $(document).unbind('mousedown', fontBrowserClose);
+ Headway.iframe.contents().unbind('mousedown', fontBrowserClose);
+
+ $(window).unbind('resize', fontBrowserClose);
+
+ }
+/* End opening and closing functions */
+
+/* Web Font Quick load for loading just one font */
+ webFontQuickLoad = function(font) {
+
+ /* Not a web font */
+ if ( !font.match(/\|/g) )
+ return;
+
+ var fragments = font.split('|');
+ var fontOriginal = font;
+
+ var provider = fragments[0];
+ var font = fragments[1];
+ var variants = '';
+
+ if ( typeof fragments[2] != 'undefined' && fragments[2] )
+ var variants = ':' + fragments[2];
+
+ var args = {
+ fontactive: function(fontFamily, fontDescription) {
+ jQuery("span.font-name[data-webfont-value='" + fontOriginal + "']").animate({opacity: 1});
+ }
+ };
+
+ args[provider] = {
+ families: [font + variants]
+ };
+
+ return WebFont.load(args);
+
+ }
+/* End quick load */
+
+
+})(jQuery);
\ No newline at end of file
--- /dev/null
+define(['jquery', 'underscore'], function($, _) {
+
+ openImageUploader = function(callback) {
+
+ if ( !boxExists('input-image') ) {
+
+ if ( isNaN(Headway.currentLayout) )
+ iframePostID = 0;
+
+ var settings = {
+ id: 'input-image',
+ title: 'Select an image',
+ description: 'Upload or select an image',
+ src: Headway.homeURL + '/?headway-trigger=media-uploader',
+ load: function() {
+ initiateImageUploader(callback);
+ },
+ width: $(window).width() - 200,
+ height: $(window).height() - 200,
+ center: true,
+ draggable: false,
+ deleteWhenClosed: true,
+ blackOverlay: true
+ };
+
+ var box = createBox(settings);
+
+ $('#box-input-image').css({
+ width: 'auto',
+ height: 'auto',
+ top: '70px',
+ left: '70px',
+ right: '70px',
+ bottom: '70px',
+ margin: 0
+ });
+
+ }
+
+ openBox('input-image');
+
+ }
+
+ initiateImageUploader = function(callback) {
+
+ /* Check if iframe body has iframe-loaded class which is added via inline script in the footer of the iframe */
+ if (
+ !$('#box-input-image iframe').length
+ || typeof $('#box-input-image iframe')[0].contentWindow.wp == 'undefined'
+ || typeof $('#box-input-image iframe')[0].contentWindow.wp.media == 'undefined'
+ || typeof $('#box-input-image iframe')[0].contentWindow.wp.media() == 'undefined'
+ ) {
+
+ return setTimeout(function() {
+ initiateImageUploader(callback);
+ }, 100);
+
+ }
+
+ wpMedia = $('#box-input-image iframe')[0].contentWindow.wp.media;
+ var currentLayoutFragments = parent.Headway.currentLayout.split('-');
+
+ /* If the current layout is a WordPress "post" then associate all attachments uploaded with the post */
+ if (_.first(currentLayoutFragments) == 'single' && !isNaN(_.last(currentLayoutFragments)) ) {
+ wpMedia.model.settings.post.id = _.last(currentLayoutFragments);
+ }
+
+ wpMedia.frames = {
+ file_frame: wpMedia({
+ title: '',
+ button: {
+ text: 'Use Image'
+ },
+ multiple: false
+ })
+ };
+
+ wpMedia.frames.file_frame.on( 'select', function() {
+ // We set multiple to false so only get one image from the uploader
+ attachment = wpMedia.frames.file_frame.state().get('selection').first().toJSON();
+
+ if ( typeof url == 'undefined' )
+ var url = attachment.url;
+
+ var filename = url.split('/')[url.split('/').length-1];
+
+ callback(url, filename);
+
+ parent.closeBox('input-image', true);
+ });
+
+ wpMedia.frames.file_frame.on('escape', function() {
+ parent.closeBox('input-image', true);
+ });
+
+ return wpMedia.frames.file_frame.open();
+
+ }
+
+});
\ No newline at end of file
--- /dev/null
+define(['jquery', 'util.misc'], function($) {
+
+ createCog = function(element, deprecatedAnimate, append, context, opacity) {
+
+ if ( $(element).length === 0 || $(element).find('.cog-container:visible').length )
+ return false;
+
+ var append = typeof append == 'undefined' ? false : append;
+
+ var cogString = '<div class="cog-container"><div class="cog-bottom-left"></div><div class="cog-top-right"></div></div>';
+
+ if ( append ) {
+
+ element.append(cogString);
+
+ } else {
+
+ element.html(cogString);
+
+ }
+
+ if ( typeof opacity != 'undefined' )
+ element.find('.cog-container').css({opacity: opacity});
+
+ return true;
+
+ }
+
+ /* Title Functions */
+ changeTitle = function(title) {
+
+ return $('title').text(title);
+
+ }
+
+ startTitleActivityIndicator = function() {
+
+ //If the title activity indicator has already been started, don't try to again.
+ if ( typeof titleActivityIndicatorInstance === 'number' )
+ return false;
+
+ titleActivityIndicatorInstance = window.setInterval(titleActivityIndicator, 500);
+ titleActivityIndicatorSavedTitle = $('title').text();
+
+ return true;
+
+ }
+
+ stopTitleActivityIndicator = function() {
+
+ if ( typeof titleActivityIndicatorInstance !== 'number' ) {
+
+ return false;
+
+ }
+
+ window.clearInterval(titleActivityIndicatorInstance);
+
+ changeTitle(titleActivityIndicatorSavedTitle);
+
+ delete titleActivityIndicatorCounter;
+ delete titleActivityIndicatorSavedTitle;
+ delete titleActivityIndicatorInstance;
+
+ return true;
+
+ }
+
+ titleActivityIndicator = function() {
+
+ /* Set up variables */
+ if ( typeof titleActivityIndicatorCounter == 'undefined' ) {
+ titleActivityIndicatorCounter = 0;
+ titleActivityIndicatorCounterPos = true;
+ }
+
+
+ /* Increase/decrease periods */
+ if ( titleActivityIndicatorCounterPos === true ) {
+ ++titleActivityIndicatorCounter;
+ } else {
+ --titleActivityIndicatorCounter;
+ }
+
+ /* Flippy da switch */
+ if ( titleActivityIndicatorCounter === 3) {
+ titleActivityIndicatorCounterPos = false;
+ } else if ( titleActivityIndicatorCounter === 0) {
+ titleActivityIndicatorCounterPos = true;
+ }
+
+ var title = titleActivityIndicatorSavedTitle + '.'.repeatStr(titleActivityIndicatorCounter);
+
+ changeTitle(title);
+
+ }
+
+});
\ No newline at end of file
--- /dev/null
+define(['jquery'], function($) {
+
+ /* MISCELLANEOUS FUNCTIONS */
+ /* Add query string parameter :: http://stackoverflow.com/a/6021027 */
+ updateQueryStringParameter = function(uri, key, value) {
+
+ var re = new RegExp("([?|&])" + key + "=.*?(&|$)", "i");
+ var separator = uri.indexOf('?') !== -1 ? "&" : "?";
+
+ if (uri.match(re)) {
+ return uri.replace(re, '$1' + key + "=" + value + '$2');
+ } else {
+ return uri + separator + key + "=" + value;
+ }
+
+ }
+
+ /* Reversing jQuery results */
+ jQuery.fn.reverse = [].reverse;
+
+ /* Simple rounding function */
+ Number.prototype.toNearest = function(num){
+ return Math.round(this/num)*num;
+ }
+
+ /* Add precision to Math.round */
+ Math._round = Math.round;
+
+ Math.round = function(number, precision) {
+
+ precision = Math.abs(parseInt(precision)) || 0;
+
+ var coefficient = Math.pow(10, precision);
+
+ return Math._round(number * coefficient) / coefficient;
+
+ }
+
+
+
+ /* Nifty little function to repeat a string n times */
+ String.prototype.repeatStr = function(n) {
+ if ( n <= 0 ) {
+ return '';
+ }
+
+ return Array.prototype.join.call({length:n+1}, this);
+ };
+
+
+ /* Function to capitalize every word in string */
+ String.prototype.capitalize = function(){
+ return this.replace( /(^|\s)([a-z])/g , function(m,p1,p2){ return p1+p2.toUpperCase(); } );
+ }
+
+
+ hwBoolean = function(value) {
+
+ /* boolean to boolean */
+ if ( typeof value == 'boolean' ) {
+
+ return value;
+
+ /* Undefined to boolean */
+ } else if ( typeof value == 'undefined' ) {
+
+ return false;
+
+ /* number to boolean */
+ } else if ( typeof value == 'number' ) {
+
+ if ( value === 1 ) {
+
+ return true;
+
+ } else if ( value === 0 ) {
+
+ return false;
+
+ } else {
+
+ return null;
+
+ }
+
+ /* everything else: null to boolean and string to boolean */
+ } else {
+
+ if ( value === null ) {
+
+ return false;
+
+ } else if ( typeof value == 'string' ) {
+
+ var string = value.split(/\b/g);
+
+ if ( string[0] === '1' || string[0] === 'true' ) {
+
+ return true;
+
+ } else if ( string[0] === '0' || string[0] === 'false' ) {
+
+ return false;
+
+ } else {
+
+ return null;
+
+ }
+
+ } else {
+
+ return null;
+
+ }
+
+ }
+
+ }
+
+
+ /* Change integer 1 and integer 0 to boolean values */
+ Number.prototype.toBool = function(){
+
+ if ( this === 1 ) {
+
+ return true;
+
+ } else if ( this === 0 ) {
+
+ return false;
+
+ } else {
+
+ return null;
+
+ }
+
+ }
+
+
+ /* Change string 1, 0, true, and false to boolean values */
+ String.prototype.toBool = function(){
+
+ /* I'm still confused about this, but this changes the weird object of letters into an array of words */
+ var string = this.split(/\b/g);
+
+ if ( string[0] === '1' || string[0] === 'true' ) {
+
+ return true;
+
+ } else if ( string[0] === '0' || string[0] === 'false' ) {
+
+ return false;
+
+ } else {
+
+ return null;
+
+ }
+
+ }
+
+ /* Escape HTMl */
+ String.prototype.escapeHTML = function() {
+
+ return this
+ .replace(/&/g, '&')
+ .replace(/</g, '<')
+ .replace(/>/g, '>')
+ .replace(/"/g, '"')
+ .replace(/'/g, ''');
+
+ }
+ /* END MISCELLANEOUS FUNCTIONS */
+
+});
\ No newline at end of file
--- /dev/null
+define(['jquery', 'util.loader'], function($, loader) {
+
+ save = function() {
+
+ /* If saving isn't allowed, don't try to save. */
+ if ( typeof isSavingAllowed === 'undefined' || isSavingAllowed === false ) {
+ return false;
+ }
+
+ /* If currently saving, do not do it again. */
+ if ( typeof currentlySaving !== 'undefined' && currentlySaving === true ) {
+ return false;
+ }
+
+ currentlySaving = true;
+
+ savedTitle = $('title').text();
+ saveButton = $('span#save-button');
+
+ saveButton
+ .text('Saving...')
+ .addClass('active')
+ .css('cursor', 'wait');
+
+ /* Change the title */
+ changeTitle('Visual Editor: Saving');
+ startTitleActivityIndicator();
+
+ /* Build and serialize options */
+ var optionsSerialized = $.param(GLOBALunsavedValues);
+
+ /* Do the stuff */
+ $.post(Headway.ajaxURL, {
+ security: Headway.security,
+ action: 'headway_visual_editor',
+ method: 'save_options',
+ options: optionsSerialized,
+ layout: Headway.currentLayout,
+ mode: Headway.mode
+ }, function(response) {
+
+ delete currentlySaving;
+
+ /* If the AJAX response is '0' then show a log in alert */
+ if ( response === '0' ) {
+
+ saveButton.stop(true);
+
+ saveButton.text('Save');
+ saveButton.removeClass('active');
+
+ saveButton.css('cursor', 'pointer');
+
+ return showErrorNotification({
+ id: 'error-wordpress-authentication',
+ message: '<strong>Notice!</strong><br /><br />Your WordPress authentication has expired and you must log in before you can save.<br /><br /><a href="' + Headway.adminURL + '" target="_blank">Click Here to log in</a>, then switch back to the window/tab the Visual Editor is in.',
+ closeTimer: false,
+ closable: true
+ });
+
+ /* If it's not a successful save, revert the save button to normal and display an alert. */
+ } else if ( typeof response.errors !== 'undefined' || (typeof response != 'object' && response != 'success') ) {
+
+ saveButton.stop(true);
+
+ saveButton.text('Save');
+ saveButton.removeClass('active');
+
+ saveButton.css('cursor', 'pointer');
+
+ var errorMessage = 'There was an error while saving. Please try again';
+
+ if ( typeof response.errors != 'undefined' ) {
+
+ errorMessage += '<br /><ul>';
+
+ $.each(response.errors, function(errorIndex, errorValue) {
+ errorMessage += '<li>' + errorValue + '</li>';
+ });
+
+ errorMessage += '</ul>';
+
+ }
+
+ return showErrorNotification({
+ id: 'error-invalid-save-response',
+ message: errorMessage,
+ closeTimer: false,
+ closable: true
+ });
+
+ /* Successful Save */
+ } else {
+
+ /* Hide any previous save errors */
+ hideNotification('error-wordpress-authentication');
+ hideNotification('error-invalid-save-response');
+
+ saveButton.animate({boxShadow: '0 0 0 #7dd1e2'}, 350);
+
+ setTimeout(function() {
+
+ saveButton.css('boxShadow', '');
+ saveButton.stop(true);
+
+ saveButton.text('Save');
+ saveButton.removeClass('active');
+
+ saveButton.css('cursor', 'pointer');
+
+ /* Replace temporary IDs on new blocks with the new ID */
+ if ( typeof response['block-id-mapping'] !== 'undefined' ) {
+
+ $.each(response['block-id-mapping'], function(tempID, id) {
+
+ var block = $i('.block[data-temp-id="' + tempID + '"]');
+
+ block.attr('id', 'block-' + id)
+ .data('id', id)
+ .attr('data-id', id)
+ .removeAttr('data-temp-id')
+ .removeAttr('data-desired-id')
+ .removeData('temp-id')
+ .removeData('desired-id');
+
+ updateBlockContentCover(block);
+
+ /* Reload options with proper ID */
+ if ( $('#block-' + tempID + '-tab').length ) {
+
+ var currentSubTab = $('#block-' + tempID + '-tab').find('.sub-tabs .ui-tabs-active').attr('aria-controls');
+
+ removePanelTab('block-' + tempID);
+ openBlockOptions(block, currentSubTab)
+
+ }
+
+ });
+
+ }
+
+ /* Replace temporary IDs on new wrapper with the new ID */
+ if ( typeof response['wrapper-id-mapping'] !== 'undefined' ) {
+
+ $.each(response['wrapper-id-mapping'], function(tempID, id) {
+
+ var wrapper = $i('.wrapper[data-temp-id="' + tempID + '"]');
+
+ wrapper.attr('id', 'wrapper-' + id)
+ .data('id', id)
+ .attr('data-id', id)
+ .removeData('temp-id')
+ .removeData('desired-id');
+
+ /* Reload options with proper ID */
+ if ( $('#wrapper-' + tempID + '-tab').length ) {
+
+ removePanelTab('wrapper-' + tempID);
+ openWrapperOptions(id);
+
+ }
+
+ });
+
+ }
+
+ /* Clear out hidden inputs */
+ clearUnsavedValues();
+
+ /* Output information about snapshot */
+ if ( typeof response['snapshot'] !== 'undefined' && typeof response['snapshot'].timestamp !== 'undefined' ) {
+
+ showNotification({
+ id: 'snapshot-saved',
+ message: 'Snapshot automatically saved.',
+ success: true
+ });
+
+ Headway.viewModels.snapshots.snapshots.unshift({
+ id: response['snapshot'].id,
+ timestamp: response['snapshot'].timestamp,
+ comments: response['snapshot'].comments
+ });
+
+ }
+
+ /* Set the current layout to customized after save */
+ $('li.layout-selected').addClass('layout-item-customized');
+
+ /* Fade back to inactive save button. */
+ disallowSaving();
+
+ /* Reset the title and show the saving complete notification */
+ setTimeout(function() {
+
+ stopTitleActivityIndicator();
+ changeTitle(savedTitle);
+
+ showNotification({
+ id: 'saving-complete',
+ message: 'Saving Complete!',
+ closeTimer: 3500,
+ success: true
+ });
+
+ }, 150);
+
+ }, 350);
+
+ allowVEClose(); //Do this here in case we have some speedy folks who want to close VE ultra-early after a save.
+
+ }
+
+ });
+
+ }
+
+ clearUnsavedValues = function() {
+
+ delete GLOBALunsavedValues;
+
+ }
+
+ allowSaving = function() {
+
+ /* If it's the layout mode and there no blocks on the page, then do not allow saving. Also do not allow saving if there are overlapping blocks */
+ if ( (Headway.mode == 'grid' && $i('.block').length === 0) || (typeof Headway.overlappingBlocks != 'undefined' && Headway.overlappingBlocks) )
+ return disallowSaving();
+
+ /* If saving is already allowed, don't do anything else */
+ if ( typeof isSavingAllowed !== 'undefined' && isSavingAllowed === true )
+ return;
+
+ $('body').addClass('allow-saving');
+ isSavingAllowed = true;
+
+ /* Set reminder when trying to leave that there are changes. */
+ prohibitVEClose();
+
+ return true;
+
+ }
+
+ disallowSaving = function() {
+
+ isSavingAllowed = false;
+
+ $('body').removeClass('allow-saving');
+
+ /* User can safely leave VE now--changes are saved. As long as there are no overlapping blocks */
+ if ( typeof Headway.overlappingBlocks == 'undefined' || !Headway.overlappingBlocks )
+ allowVEClose();
+
+ return true;
+
+ }
+
+});
\ No newline at end of file
--- /dev/null
+define(['jquery', 'qtip'], function($) {
+
+ setupTooltips = function(location) {
+
+ if ( typeof location === 'undefined' )
+ location = false;
+
+ if ( Headway.disableTooltips == 1 || Headway.touch ) {
+
+ $('div.tooltip-button').hide();
+
+ return false;
+
+ }
+
+ var tooltipOptions = {
+ style: {
+ classes: 'qtip-headway'
+ },
+ show: {
+ delay: 10,
+ solo: true,
+ event: 'mouseenter'
+ },
+ position: {
+ my: 'bottom left',
+ at: 'top center',
+ viewport: $(window),
+ effect: false
+ },
+ hide: {
+ effect: false
+ }
+ }
+
+ if ( location == 'iframe' ) {
+
+ tooltipOptions.position.container = Headway.iframe.contents().find('body');
+ tooltipOptions.position.viewport = $('#iframe-container');
+
+ var tooltipElement = $i;
+
+ } else {
+
+ var tooltipElement = $;
+
+ }
+
+ tooltipElement('div.tooltip-button:not([data-hasqtip]), .tooltip:not([data-hasqtip])').qtip(tooltipOptions);
+
+ tooltipElement('.tooltip-bottom-right:not([data-hasqtip])').qtip($.extend(true, {}, tooltipOptions, {
+ position: {
+ my: 'bottom right',
+ at: 'top center'
+ }
+ }));
+
+ tooltipElement('.tooltip-top-right:not([data-hasqtip])').qtip($.extend(true, {}, tooltipOptions, {
+ position: {
+ my: 'top right',
+ at: 'bottom center'
+ }
+ }));
+
+ tooltipElement('.tooltip-top-left:not([data-hasqtip])').qtip($.extend(true, {}, tooltipOptions, {
+ position: {
+ my: 'top left',
+ at: 'bottom center'
+ },
+ show: {
+ delay: 750
+ }
+ }));
+
+ tooltipElement('.tooltip-left:not([data-hasqtip])').qtip($.extend(true, {}, tooltipOptions, {
+ position: {
+ my: 'left center',
+ at: 'right center'
+ }
+ }));
+
+ tooltipElement('.tooltip-right:not([data-hasqtip])').qtip($.extend(true, {}, tooltipOptions, {
+ position: {
+ my: 'right center',
+ at: 'left center'
+ }
+ }));
+
+ tooltipElement('.tooltip-top:not([data-hasqtip])').qtip($.extend(true, {}, tooltipOptions, {
+ position: {
+ my: 'top center',
+ at: 'bottom center'
+ }
+ }));
+
+
+ var iframeScrollTooltipReposition = function() {
+
+ /* Flood Control */
+ if ( $i('.qtip:visible').length === 0 || typeof iframeScrollTooltipRepositionFloodTimeout != 'undefined' )
+ return;
+
+ iframeScrollTooltipRepositionFloodTimeout = setTimeout(function() {
+
+ $i('.qtip:visible').qtip('reposition');
+
+ delete iframeScrollTooltipRepositionFloodTimeout;
+
+ }, 400);
+
+ }
+
+ Headway.iframe.contents().unbind('scroll', iframeScrollTooltipReposition);
+ Headway.iframe.contents().bind('scroll', iframeScrollTooltipReposition);
+
+ }
+
+
+ repositionTooltips = function() {
+
+ $i('.qtip:visible').qtip('reposition');
+
+ }
+
+});
\ No newline at end of file
--- /dev/null
+
+/* TOUCH OPTIMIZATION */
+ /* Keep Menu From Making the Whole VE From Bouncing on iPad */
+ $('#menu').bind('touchmove', function(event) {
+ event.preventDefault();
+ })
+/* END TOUCH OPTIMIZATION */
\ No newline at end of file
--- /dev/null
+define(['jquery', 'util.tooltips', 'helper.boxes', 'modules/panel'], function($, tooltips, panel) {
+
+ /* Grid */
+ tourStepsGrid = [
+ {
+ beginning: true,
+ title: 'Welcome to the Headway Visual Editor!',
+ content: '<p>If this is your first time in the Headway Visual Editor, <strong>we recommend following this tour so you can get the most out of Headway</strong>.</p><p>Or, if you\'re experienced or want to dive in right away, just click the close button in the top right at any time.</p>'
+ },
+
+ {
+ target: $('li#mode-grid'),
+ title: 'Mode Selector',
+ content: '<p>The Headway Visual Editor is split up into 2 modes.</p><p><ul><li><strong>Grid</strong> – Build your layouts</li><li><strong>Design</strong> – Add colors, customize fonts, and more!</li></ul></p>',
+ position: {
+ my: 'top left',
+ at: 'bottom center'
+ }
+ },
+
+ {
+ target: $('#layout-selector-select-content'),
+ title: 'Layout Selector',
+ content: '<p style="font-size:12px;">Since you may not want every page to be the same, you may use the Layout Selector to select which page, post, or archive to edit.</p><p style="font-size:12px;">The Layout Selector is based off of inheritance. For example, you can customize the "Page" layout and all pages will follow that layout. Plus, you can customize a specific page and it\'ll be different than all other pages.</p><p style="font-size:12px;">The layout selector will allow you to be as precise or broad as you wish. It\'s completely up to you!</p>',
+ position: {
+ my: 'top center',
+ at: 'bottom center'
+ }
+ },
+
+ {
+ target: $('div#box-grid-wizard'),
+ title: 'The Headway Grid',
+ content: '<p>Now we\'re ready to get started with the Headway Grid. In other words, the good stuff.</p><p>To build your first layout, please select a preset to the right to pre-populate the grid. Or, you may select "Use Empty Grid" to start with a completely blank grid.</p><p>Once you have a preset selected, click "Finish".</p>',
+ position: {
+ my: 'right top',
+ at: 'left center'
+ },
+ nextHandler: {
+ showButton: false,
+ clickElement: '#grid-wizard-button-preset-use-preset, span.grid-wizard-use-empty-grid',
+ message: 'Please click <strong>"Finish"</strong> or <strong>"Use Empty Grid"</strong> to continue.'
+ }
+ },
+
+ {
+ iframeTarget: 'div.grid-container',
+ title: 'Adding Blocks',
+ content: '<p>To add a block, simply place your mouse into the grid then click at where you\'d like the top-left point of the block to be.</p><p>Drag your mouse and the block will appear! Once the block appears, you may choose the block type.</p><p>Hint: Don\'t worry about being precise, you may always move or resize the block.</p>',
+ position: {
+ my: 'right top',
+ at: 'left top',
+ adjustY: 100
+ },
+ maxWidth: 280
+ },
+
+ {
+ iframeTarget: 'div.grid-container',
+ title: 'Modifying Blocks',
+ content: '\
+ <p style="font-size:12px;">After you\'ve added the desired blocks to your layout, you may move, resize, delete, or change the options of the block at any time.</p>\
+ <ul style="font-size:12px;">\
+ <li><strong>Moving Blocks</strong> – Click and drag the block. If you wish to move multiple blocks simultaneously, double-click on a block to enter <em>Mass Block Selection Mode</em>.</li>\
+ <li><strong>Resizing Blocks</strong> – Grab the border or corner of the block and drag your mouse.</li>\
+ <li><strong>Block Options (e.g. header image)</strong> – Hover over the block then click the block options icon in the top-right.</li>\
+ <li><strong>Deleting Blocks</strong> – Move your mouse over the desired block, then click the <em>X</em> icon in the top-right.</li>\
+ </ul>',
+ position: {
+ my: 'right top',
+ at: 'left top',
+ adjustY: 100
+ },
+ maxWidth: 280
+ },
+
+ {
+ target: $('#save-button-container'),
+ title: 'Saving',
+ content: '<p>Now that you hopefully have a few changes to be saved, you can save using this spiffy Save button.</p><p>For those of you who like hotkeys, use <strong>Ctrl + S</strong> to save.</p>',
+ position: {
+ my: 'top right',
+ at: 'bottom center'
+ },
+ tip: 'top right'
+ },
+
+ {
+ target: $('li#mode-design a'),
+ title: 'Design Mode',
+ content: '<p>Thanks for sticking with us!</p><p>Now that you have an understanding of the Grid Mode, we hope you stick with us and head on over to the Design Mode.</p>',
+ position: {
+ my: 'top left',
+ at: 'bottom center',
+ adjustY: 5
+ },
+ tip: 'top left',
+ buttonText: 'Continue to Design Mode',
+ buttonCallback: function () {
+
+ $.post(Headway.ajaxURL, {
+ security: Headway.security,
+ action: 'headway_visual_editor',
+ method: 'ran_tour',
+ mode: 'grid',
+ complete: function () {
+
+ Headway.ranTour['grid'] = true;
+
+ /* Advance to Design Editor */
+ $('li#mode-design a').trigger('click');
+ window.location = $('li#mode-design a').attr('href');
+
+ }
+ });
+
+ }
+ }
+ ];
+
+ /* Design */
+ tourStepsDesign = [
+ {
+ beginning: true,
+ title: 'Welcome to the Headway Design Editor!',
+ content: "<p>In the <strong>Design Editor</strong>, you can style your elements however you'd like.</p><p>Whether it's fonts, colors, padding, borders, shadows, or rounded corners, you can use the design editor.</p><p>Stick around to learn more!</p>"
+ },
+
+ {
+ target: '#side-panel-top',
+ title: 'Element Selector',
+ content: '<p>The element selector allows you choose which element to edit.</p>',
+ position: {
+ my: 'right top',
+ at: 'left center'
+ },
+ callback: function () {
+ $('li#element-block-header > span.element-name').trigger('click');
+ }
+ },
+
+ {
+ target: '#toggle-inspector',
+ title: 'Inspector',
+ content: "\
+ <p>Instead of using the <em>Element Selector</em>, let the Inspector do the work for you.</p>\
+ <p><strong>Try it out!</strong> Point and right-click on the element you wish to edit and it will become selected!</p>\
+ ",
+ position: {
+ my: 'top right',
+ at: 'bottom center',
+ adjustX: 10,
+ adjustY: 5
+ }
+ },
+
+ {
+ target: 'window',
+ title: 'Have fun building with Headway!',
+ content: '<p>We hope you find Headway to the most powerful and easy-to-use WordPress framework around.</p><p>If you have any questions, please don\'t hesitate to visit the <a href="http://support.headwaythemes.com/?utm_source=visualeditor&utm_medium=headway&utm_campaign=tour" target="_blank">support forums</a>.</p>',
+ end: true
+ }
+ ];
+
+ return {
+ start: function () {
+
+ if ( Headway.mode == 'grid' ) {
+
+ var steps = tourStepsGrid;
+
+ hidePanel();
+ openBox('grid-wizard');
+
+ } else if ( Headway.mode == 'design' ) {
+
+ var steps = tourStepsDesign;
+
+ showPanel();
+
+ require(['modules/design/mode-design'], function() {
+ showDesignEditor();
+ });
+
+ if ( typeof $('div#panel').data('ui-tabs') != 'undefined' )
+ selectTab('editor-tab', $('div#panel'));
+
+ } else {
+
+ return;
+
+ }
+
+ $('<div class="black-overlay"></div>')
+ .hide()
+ .attr('id', 'black-overlay-tour')
+ .css('zIndex', 15)
+ .appendTo('body')
+ .fadeIn(500);
+
+ $(document.body).qtip({
+ id: 'tour', // Give it an ID of qtip-tour so we an identify it easily
+ content: {
+ text: steps[0].content + '<div id="tour-next-container"><span id="tour-next" class="tour-button button button-blue">Continue Tour <span class="arrow">›</span></span></div>',
+ title: {
+ text: steps[0].title, // ...and title
+ button: 'Skip Tour'
+ }
+ },
+ style: {
+ classes: 'qtip-tour',
+ tip: {
+ width: 18,
+ height: 10,
+ mimic: 'center',
+ offset: 10
+ }
+ },
+ position: {
+ my: 'center',
+ at: 'center',
+ target: $(window), // Also use first steps position target...
+ viewport: $(window), // ...and make sure it stays on-screen if possible
+ adjust: {
+ y: 5,
+ method: 'shift shift'
+ }
+ },
+ show: {
+ event: false, // Only show when show() is called manually
+ ready: true, // Also show on page load,
+ effect: function () {
+ $(this).fadeIn(500);
+ }
+ },
+ hide: false, // Don't hide unless we call hide()
+ events: {
+ render: function (event, api) {
+
+ // Grab tooltip element
+ var tooltip = api.elements.tooltip;
+
+ // Track the current step in the API
+ api.step = 0;
+
+ // Bind custom custom events we can fire to step forward/back
+ tooltip.bind('next', function (event) {
+
+ /* For some reason trigger window resizing helps tooltip positioning */
+ $(window).trigger('resize');
+
+ // Increase/decrease step depending on the event fired
+ api.step += 1;
+ api.step = Math.min(steps.length - 1, Math.max(0, api.step));
+
+ // Set new step properties
+ currentTourStep = steps[api.step];
+
+ $('div#black-overlay-tour').fadeOut(100, function () {
+ $(this).remove();
+ });
+
+ //Run the callback if it exists
+ if ( typeof currentTourStep.callback === 'function' ) {
+ currentTourStep.callback.apply(api);
+ }
+
+ if ( currentTourStep.target == 'window' ) {
+ currentTourStep.target = $(window);
+ } else if ( typeof currentTourStep.target == 'string' ) {
+ currentTourStep.target = $(currentTourStep.target);
+ } else if ( typeof currentTourStep.iframeTarget == 'string' ) {
+ currentTourStep.target = $i(currentTourStep.iframeTarget).first();
+ }
+
+ api.set('position.target', currentTourStep.target);
+
+ if ( typeof currentTourStep.maxWidth !== 'undefined' && window.innerWidth < 1440 ) {
+ $('.qtip-tour').css('maxWidth', currentTourStep.maxWidth);
+ } else {
+ $('.qtip-tour').css('maxWidth', 350);
+ }
+
+ /* Set up button */
+ var buttonText = 'Next';
+
+ if ( typeof currentTourStep.buttonText == 'string' )
+ var buttonText = currentTourStep.buttonText;
+
+ if ( typeof currentTourStep.end !== 'undefined' && currentTourStep.end === true ) {
+ var button = '<div id="tour-next-container"><span id="tour-finish" class="tour-button button button-blue">Close Tour <span class="arrow">›</span></div>';
+ } else if ( typeof currentTourStep.nextHandler === 'undefined' || currentTourStep.nextHandler.showButton ) {
+ var button = '<div id="tour-next-container"><span id="tour-next" class="tour-button button button-blue">' + buttonText + ' <span class="arrow">›</span></div>';
+ } else {
+ var button = '<div id="tour-next-container"><p>' + currentTourStep.nextHandler.message + '</p></div>';
+ }
+
+ /* Next Handler Callback... Be able to use something other than the button */
+ if ( typeof currentTourStep.nextHandler !== 'undefined' && $(currentTourStep.nextHandler.clickElement) ) {
+
+ var nextHandlerCallback = function (event) {
+
+ $('.qtip-tour').triggerHandler('next');
+ event.preventDefault();
+
+ $(this).unbind('click', nextHandlerCallback);
+
+ }
+
+ $(currentTourStep.nextHandler.clickElement).bind('click', nextHandlerCallback);
+
+ }
+
+ /* Set the Content */
+ api.set('content.text', currentTourStep.content + button);
+ api.set('content.title', currentTourStep.title);
+
+ if ( typeof currentTourStep.end === 'undefined' ) {
+
+ /* Position */
+ if ( typeof currentTourStep.position !== 'undefined' ) {
+
+ api.set('position.my', currentTourStep.position.my);
+ api.set('position.at', currentTourStep.position.at);
+
+ /* Offset/Adjust */
+ if ( typeof currentTourStep.position.adjustX !== 'undefined' ) {
+ api.set('position.adjust.x', currentTourStep.position.adjustX);
+ } else {
+ api.set('position.adjust.x', 0);
+ }
+
+ if ( typeof currentTourStep.position.adjustY !== 'undefined' ) {
+ api.set('position.adjust.y', currentTourStep.position.adjustY);
+ } else {
+ api.set('position.adjust.y', 0);
+ }
+
+ } else {
+
+ api.set('position.my', 'top center');
+ api.set('position.at', 'bottom center');
+
+ }
+
+ if ( typeof currentTourStep.tip !== 'undefined' )
+ api.set('style.tip.corner', currentTourStep.tip);
+
+ } else {
+
+ api.set('position.my', 'center');
+ api.set('position.at', 'center');
+
+ }
+
+
+ });
+
+ /* Tour Button Bindings */
+ $('div.qtip-tour').on('click', 'span#tour-next', function (event) {
+
+ /* Callback that fires upon button click... Used for advancing to Design Editor */
+ if ( typeof currentTourStep == 'object' && typeof currentTourStep.buttonCallback == 'function' )
+ currentTourStep.buttonCallback.call();
+
+ $('.qtip-tour').triggerHandler('next');
+ event.preventDefault();
+
+ });
+
+ $('div.qtip-tour').on('click', 'span#tour-finish', function (event) {
+
+ $('.qtip-tour').qtip('hide');
+
+ });
+
+
+ },
+
+ // Destroy the tooltip after it hides as its no longer needed
+ hide: function (event, api) {
+
+ $('div#tour-overlay').remove();
+
+ $('div#black-overlay-tour').fadeOut(100, function () {
+ $(this).remove();
+ });
+
+ $('.qtip-tour').fadeOut(100, function () {
+ $(this).qtip('destroy');
+ });
+
+ //Tell the DB that the tour has been ran
+ if ( Headway.ranTour[Headway.mode] == false && Headway.ranTour.legacy != true ) {
+
+ $.post(Headway.ajaxURL, {
+ security: Headway.security,
+ action: 'headway_visual_editor',
+ method: 'ran_tour',
+ mode: Headway.mode
+ });
+
+ Headway.ranTour[Headway.mode] = true;
+
+ }
+
+ }
+ }
+ });
+
+ }
+ }
+
+});
\ No newline at end of file
--- /dev/null
+define(['jquery', 'deps/mousetrap'], function($, mousetrap) {
+
+ /* ANNOYANCE FIXER FUNCTIONS */
+ prohibitVEClose = function () {
+
+ window.onbeforeunload = function(){
+ return 'You have unsaved changes. Are you sure you wish to leave the Visual Editor?';
+ }
+
+ allowVECloseSwitch = false;
+
+ }
+
+
+ allowVEClose = function() {
+
+ window.onbeforeunload = function(){
+ return null;
+ }
+
+ allowVECloseSwitch = true;
+
+ }
+
+
+ disableBadKeys = function() {
+
+ var disableBadKeysCallback = function(event) {
+
+ //8 = Backspace
+ //9 = Tab
+ //13 = Enter
+
+ var element = $(event.target);
+
+ if ( event.which === 8 && !element.is('input') && !element.is('textarea') && !element.hasClass('allow-backspace-key') && !element.parents('.wysiwyg-container').length ) {
+ event.preventDefault();
+
+ return false;
+ }
+
+ if ( event.which === 9 && !element.is('input') && !element.is('textarea') && !element.hasClass('allow-tab-key') && !element.parents('.wysiwyg-container').length ) {
+ event.preventDefault();
+
+ return false;
+ }
+
+ if ( event.which == 13 && !element.is('textarea') && !element.hasClass('allow-enter-key') && !element.parents('.wysiwyg-container').length ) {
+ event.preventDefault();
+
+ return false;
+ }
+
+ }
+
+ //Disable backspace for normal frame but still keep backspace functionality in inputs. Also disable enter.
+ $(document).bind('keypress', disableBadKeysCallback);
+ $(document).bind('keydown', disableBadKeysCallback);
+
+ //Disable backspace and enter for iframe
+ $i('html').bind('keypress', disableBadKeysCallback);
+ $i('html').bind('keydown', disableBadKeysCallback);
+
+ }
+ /* END ANNOYANCE FIXER FUNCTIONS */
+
+
+ /* KEY SHORTCUTS */
+ bindKeyShortcuts = function() {
+
+ mousetrap.bindEventsTo($i('body').get(0));
+
+ /* Close Tour */
+ var keyBindingEscCloseTour = function(event) {
+
+ if ( !$('.qtip-tour').is(':visible') )
+ return;
+
+ $(document.body).qtip('hide');
+
+ }
+
+ mousetrap.bind('esc', keyBindingEscCloseTour);
+
+ /* Bindings with modifier */
+ /* Save */
+ mousetrap.bind(['ctrl+s', 'command+s'], function(event) {
+ save();
+
+ /* cancel browser default */
+ return false;
+ });
+
+ /* Panel Toggle */
+ mousetrap.bind(['ctrl+p', 'command+p'], function(event) {
+ togglePanel();
+
+ /* cancel browser default */
+ return false;
+ });
+
+ /* Layout Selector Toggle */
+ mousetrap.bind('ctrl+l', toggleLayoutSelector);
+
+ /* Design Editor Stuff */
+ if ( typeof designEditor != 'undefined' && typeof designEditor.processElementCopy == 'function' ) {
+
+ /* Copy and Paste */
+ mousetrap.bind(['ctrl+c', 'command+c'], designEditor.processElementCopy);
+ mousetrap.bind(['ctrl+v', 'command+v'], designEditor.processElementPaste);
+
+ /* Live CSS Toggle */
+ mousetrap.bind('ctrl+e', function() { if ( !boxOpen('live-css') ) { $('#open-live-css').trigger('click'); } else { closeBox('live-css'); } });
+
+ /* Inspector Toggle */
+ mousetrap.bind('ctrl+i', toggleInspector);
+
+ /* Design Editor Toggle */
+ mousetrap.bind('tab', toggleDesignEditor);
+
+ }
+ /* End bindings with modifier */
+
+ }
+ /* END KEY SHORTCUTS */
+
+ if ( Headway.touch ) {
+
+ require(['deps/jquery.ui.touchpunch', 'deps/jquery.taphold'], function() {});
+
+ }
+
+});
\ No newline at end of file
--- /dev/null
+<!DOCTYPE HTML>
+<html lang="en" style="background: #eee;">
+
+<head>
+
+ <meta charset="<?php bloginfo('charset'); ?>" />
+ <link rel="profile" href="http://gmpg.org/xfn/11" />
+
+ <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1" />
+ <meta http-equiv="cache-control" content="no-cache" />
+ <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1" />
+
+ <title>Visual Editor: Loading</title>
+
+ <?php do_action('headway_visual_editor_head'); ?>
+
+</head><!-- /head -->
+
+<!-- This background color has been inlined to reduce the white flicker during loading. -->
+<body class="wp-core-ui visual-editor-open visual-editor-mode-<?php echo HeadwayVisualEditor::get_current_mode() . ' ' . join(' ', get_body_class()); ?>" style="background: #1c1c1c;">
+
+ <?php do_action('headway_visual_editor_body_open'); ?>
+
+ <div id="ve-loading-overlay">
+ <div class="cog-container"><div class="cog-bottom-left"></div><div class="cog-top-right"></div></div>
+ </div><!-- #ve-loading-overlay -->
+
+ <div id="menu">
+ <span id="logo"></span>
+
+ <ul id="modes" class="top-menu-nav">
+ <?php do_action('headway_visual_editor_modes'); ?>
+ </ul>
+
+ <?php do_action('headway_visual_editor_menu'); ?>
+
+ <div id="menu-right">
+
+ <?php do_action('headway_visual_editor_menu_mode_buttons'); ?>
+
+ <ul class="top-menu-nav">
+ <li id="snapshots-button">
+ <span>Snapshots</span>
+ </li>
+
+ <?php do_action('headway_visual_editor_menu_links'); ?>
+ </ul>
+
+ <div id="save-button-container" class="save-button-container" style="margin-right:-76px;">
+ <span id="save-button" class="save-button">Save</span>
+ </div>
+
+ </div><!-- #menu-right -->
+ </div><!-- #menu -->
+
+
+ <!-- Big Boy iframe -->
+ <div id="iframe-container">
+ <?php
+ $layout_url = HeadwayVisualEditor::get_current_mode() == 'grid' ? home_url() : HeadwayLayout::get_url(HeadwayLayout::get_current());
+
+ $iframe_url = add_query_arg(array(
+ 've-iframe' => 'true',
+ 've-layout' => HeadwayLayout::get_current(),
+ 've-iframe-mode' => HeadwayVisualEditor::get_current_mode(),
+ 'rand' => rand(1, 999999)
+ ), $layout_url);
+
+ echo '<iframe id="content" class="content" src="' . $iframe_url . '" scrolling="yes"></iframe>';
+
+ ?>
+
+ <div id="iframe-overlay"></div>
+ <div id="iframe-loading-overlay"><div class="cog-container"><div class="cog-bottom-left"></div><div class="cog-top-right"></div></div></div>
+ </div>
+ <!-- #iframe#content -->
+
+ <div id="panel">
+
+ <div id="panel-top-container">
+
+ <ul id="panel-top">
+
+ <?php do_action('headway_visual_editor_panel_top_tabs'); ?>
+
+ </ul><!-- #ul#panel-top -->
+
+ <ul id="panel-top-right">
+
+ <?php do_action('headway_visual_editor_panel_top_right'); ?>
+
+ </ul><!-- #ul#panel-top -->
+
+ </div><!-- #div#panel-top-container -->
+
+ <?php do_action('headway_visual_editor_content'); ?>
+
+ </div><!-- div#panel -->
+
+
+ <?php
+ if ( has_action('headway_visual_editor_side_panel') ) {
+
+ echo '<div id="side-panel-container">
+
+ <div id="side-panel">';
+
+ do_action('headway_visual_editor_side_panel');
+
+ echo '</div><!-- #side-panel -->
+
+ </div><!-- #side-panel-container -->';
+
+ }
+ ?>
+
+
+ <div id="boxes">
+ <?php do_action('headway_visual_editor_boxes'); ?>
+ </div><!-- div#boxes -->
+
+ <?php do_action('headway_visual_editor_footer'); ?>
+
+ <div id="notification-center"></div>
+
+</body>
+</html>
\ No newline at end of file
--- /dev/null
+<?php
+class HeadwayVisualEditorAJAX {
+
+
+ private static function json_encode($data) {
+
+ header('content-type:application/json');
+
+ if ( headway_get('callback') )
+ echo headway_get('callback') . '(';
+
+ echo json_encode($data);
+
+ if ( headway_get('callback') )
+ echo ')';
+
+ }
+
+
+ /* Skin methods */
+ public static function secure_method_switch_skin() {
+
+ global $wpdb;
+
+ if ( HeadwayTemplates::get(headway_post('skin')) && HeadwayOption::set('current-skin', headway_post('skin')) ) {
+
+ do_action('headway_switch_skin');
+
+ /* Turn autoload off for Headway options then back on for the current template options as well as the headway_option_group_general option */
+ $wpdb->query( "UPDATE $wpdb->options SET autoload = 'no' WHERE option_name LIKE 'headway_%'" );
+
+ $wpdb->update( $wpdb->options, array(
+ 'autoload' => 'yes'
+ ), array(
+ 'option_name' => 'headway_option_group_general'
+ ) );
+
+ $wpdb->query( "UPDATE $wpdb->options SET autoload = 'yes' WHERE option_name LIKE 'headway_|template=" . headway_post( 'skin' ) . "|%'" );
+
+ echo 'success';
+
+ }
+
+ }
+
+ public static function secure_method_delete_skin() {
+
+ $skin_to_delete = headway_post('skin');
+
+ if ( $skin_to_delete == HeadwayOption::get('current-skin') || $skin_to_delete == 'base' ) {
+ echo 'error: cannot delete current template';
+ return;
+ }
+
+ /* Loop through WordPress options and delete the skin options */
+ foreach ( wp_load_alloptions() as $option => $option_value ) {
+
+ if ( strpos($option, 'headway_|template=' . $skin_to_delete . '|_') !== 0 )
+ continue;
+
+ delete_option($option);
+
+ }
+
+ HeadwayLayoutOption::delete_by_template($skin_to_delete);
+
+ /* Delete blocks and wrappers */
+ HeadwayBlocksData::delete_by_template($skin_to_delete);
+ HeadwayWrappersData::delete_by_template($skin_to_delete);
+
+ /* Delete snapshots */
+ HeadwayDataSnapshots::delete_by_template($skin_to_delete);
+
+ /* Remove the skin from the Headway skins catalog */
+ HeadwayOption::delete($skin_to_delete, 'skins');
+
+ echo 'success';
+
+ }
+
+ public static function secure_method_add_blank_skin() {
+
+ $blank_skin_name = headway_post('skinName');
+
+ if ( empty($blank_skin_name) )
+ return;
+
+ $original_skin_id = strtolower(str_replace(' ', '-', $blank_skin_name));
+
+ $skin_id = $original_skin_id;
+ $skin_name = $blank_skin_name;
+
+ $skin_unique_id_counter = 0;
+
+ /* Check if skin already exists. If it does, change ID and skin name */
+ while ( HeadwayOption::get($skin_id, 'skins') ) {
+
+ $skin_unique_id_counter++;
+ $skin_id = $original_skin_id . '-' . $skin_unique_id_counter;
+ $skin_name = $blank_skin_name . ' ' . $skin_unique_id_counter;
+
+ }
+
+ $skin['id'] = $skin_id;
+ $skin['name'] = $skin_name;
+
+ /* Send skin to DB */
+ HeadwayOption::set($skin['id'], $skin, 'skins');
+
+ self::json_encode($skin);
+
+ }
+
+
+ /* Snapshot methods */
+ public static function secure_method_save_snapshot() {
+
+ self::json_encode(HeadwayDataSnapshots::save_snapshot());
+
+ }
+
+ public static function secure_method_rollback_to_snapshot() {
+
+ self::json_encode(HeadwayDataSnapshots::rollback(headway_post('snapshot_id')));
+
+ }
+
+ public static function secure_method_delete_snapshot() {
+
+ self::json_encode( HeadwayDataSnapshots::delete( headway_post( 'snapshot_id' ) ) );
+
+ }
+
+
+ /* Saving methods */
+ public static function secure_method_save_options() {
+
+ //Set up options
+ parse_str(headway_post('options'), $options);
+
+ self::json_encode(HeadwayVisualEditor::save($options));
+
+ }
+
+
+ /* Layout Selector */
+ public static function method_get_layout_selector_pages() {
+
+ $pages = HeadwayVisualEditorDisplay::list_pages();
+
+ echo trim(str_replace(array("\n", "\t"), '', $pages));
+
+ }
+
+
+ public static function method_get_layout_selector_templates() {
+
+ $templates = HeadwayVisualEditorDisplay::list_templates();
+
+ echo trim(str_replace(array("\n", "\t"), '', $templates));
+
+ }
+
+
+ /* Block methods */
+ public static function method_get_layout_blocks_in_json() {
+
+ $layout = headway_post('layout', false);
+ $layout_status = HeadwayLayout::get_status($layout);
+
+ if ( $layout_status['customized'] != true )
+ return false;
+
+ self::json_encode(array(
+ 'blocks' => HeadwayBlocksData::get_blocks_by_layout($layout, false, true),
+ 'wrappers' => HeadwayWrappersData::get_wrappers_by_layout($layout, true)
+ ));
+
+ }
+
+
+ public static function method_load_block_content() {
+
+ /* Check for grid safe mode */
+ if ( HeadwayOption::get('grid-safe-mode', false, false) ) {
+
+ echo '<div class="alert alert-red block-safe-mode"><p>Grid Safe mode enabled. Block content not outputted.</p></div>';
+
+ return;
+
+ }
+
+ /* Go */
+ $layout = headway_post('layout');
+ $block_origin = headway_post('block_origin');
+ $block_default = headway_post('block_default', false);
+
+ $unsaved_block_settings = headway_post('unsaved_block_settings', false);
+
+ /* If the block origin is a string or ID, then get the object from DB. */
+ if ( is_numeric($block_origin) || is_string($block_origin) )
+ $block = HeadwayBlocksData::get_block($block_origin);
+
+ /* Otherwise use the object */
+ else
+ $block = $block_origin;
+
+ /* If the block doesn't exist, then use the default as the origin. If the default doesn't exist... We're screwed. */
+ if ( !$block && $block_default )
+ $block = $block_default;
+
+ /* If the block settings is an array, merge that into the origin. But first, make sure the settings exists for the origin. */
+ if ( !isset($block['settings']) )
+ $block['settings'] = array();
+
+ if ( is_array($unsaved_block_settings) && count($unsaved_block_settings) && isset($unsaved_block_settings['settings']) ) {
+
+ $block = headway_array_merge_recursive_simple($block, $unsaved_block_settings);
+
+ }
+
+ /* If the block is set to mirror, then get that block. */
+ if ( $mirrored_block = HeadwayBlocksData::get_block_mirror($block) ) {
+
+ $original_block = $block;
+
+ $block = $mirrored_block;
+ $block['original'] = $original_block;
+
+ }
+
+ /* Add a flag into the block so we can check if this is coming from the visual editor. */
+ $block['ve-live-content-query'] = true;
+
+ /* Show the content */
+ do_action('headway_block_content_' . $block['type'], $block);
+
+ /* Output dynamic JS and CSS */
+ if ( headway_post('mode') != 'grid' ) {
+
+ $block_types = HeadwayBlocks::get_block_types();
+
+ /* Dynamic CSS */
+ if ( method_exists($block_types[$block['type']]['class'], 'dynamic_css') ) {
+
+ echo '<style type="text/css">';
+ echo call_user_func(array($block_types[$block['type']]['class'], 'dynamic_css'), $block['id'], $block);
+ echo '</style><!-- AJAX Block Content Dynamic CSS -->';
+
+ }
+
+ /* Run enqueue action and print right away */
+ if ( method_exists($block_types[$block['type']]['class'], 'enqueue_action') ) {
+
+ /* Remove all other enqueued scripts to reduce conflicts */
+ global $wp_scripts;
+ $wp_scripts = null;
+ remove_all_actions('wp_print_scripts');
+
+ /* Remove all other enqueued styles to reduce conflicts */
+ global $wp_styles;
+ $wp_styles = null;
+ remove_all_actions('wp_print_styles');
+
+ echo call_user_func(array($block_types[$block['type']]['class'], 'enqueue_action'), $block['id'], $block);
+ wp_print_scripts();
+ wp_print_footer_scripts(); /* This isn't really needed, but it's here for juju power */
+
+ }
+
+ /* Output dynamic JS */
+ if ( method_exists($block_types[$block['type']]['class'], 'dynamic_js') ) {
+
+ echo '<script type="text/javascript">';
+ echo call_user_func(array($block_types[$block['type']]['class'], 'dynamic_js'), $block['id'], $block);
+ echo '</script><!-- AJAX Block Content Dynamic JS -->';
+
+ }
+
+ }
+ /* End outputting dynamic JS and CSS */
+
+ }
+
+
+ public static function method_load_block_options() {
+
+ $layout = headway_post('layout');
+ $block_id = headway_post('block_id');
+ $unsaved_options = headway_post('unsaved_block_options', array());
+
+ $block = HeadwayBlocksData::get_block($block_id);
+
+ //If block is new, set the bare basics up
+ if ( !$block ) {
+
+ $block = array(
+ 'type' => headway_post('block_type'),
+ 'new' => true,
+ 'id' => $block_id,
+ 'layout' => $layout
+ );
+
+ }
+
+ /* Merge unsaved options in */
+ if ( is_array($unsaved_options) )
+ $block['settings'] = is_array(headway_get('settings', $block)) ? array_merge($block['settings'], $unsaved_options) : $unsaved_options;
+
+ do_action('headway_block_options_' . $block['type'], $block, $layout);
+
+ }
+
+
+ /* Wrapper Methods */
+ public static function method_load_wrapper_options() {
+
+ $layout_id = headway_post('layout');
+ $wrapper_id = headway_post('wrapper_id');
+ $unsaved_options = headway_post('unsaved_wrapper_options', array());
+
+ $wrapper = HeadwayWrappersData::get_wrapper($wrapper_id);
+
+ if ( !$wrapper ) {
+
+ $wrapper = array(
+ 'id' => $wrapper_id,
+ 'layout' => $layout_id,
+ 'new' => true
+ );
+
+ }
+
+ /* Merge unsaved options in */
+ if ( is_array($unsaved_options) )
+ $wrapper = array_merge($wrapper, $unsaved_options);
+
+ do_action('headway_wrapper_options', $wrapper, $layout_id);
+
+ }
+
+
+ /* Box methods */
+ public static function method_load_box_ajax_content() {
+
+ $layout = headway_post('layout');
+ $box_id = headway_post('box_id');
+
+ do_action('headway_visual_editor_ajax_box_content_' . $box_id);
+
+ }
+
+
+ /* Layout methods */
+ public static function method_get_layout_name() {
+
+ $layout = headway_post('layout');
+
+ echo HeadwayLayout::get_name($layout);
+
+ }
+
+
+ public static function secure_method_revert_layout() {
+
+ $layout = headway_post('layout_to_revert');
+
+ //Delete wrappers, blocks, design settings
+ HeadwayLayout::delete_layout($layout);
+
+ do_action('headway_visual_editor_reset_layout');
+
+ echo 'success';
+
+ }
+
+
+ /* Design editor methods */
+ public static function method_get_element_inputs() {
+
+ $element = headway_post('element');
+ $special_element_type = headway_post('specialElementType', false);
+ $special_element_meta = headway_post('specialElementMeta', false);
+ $group = $element['group'];
+
+ $unsaved_values = headway_post('unsavedValues', false);
+
+ /* Make sure that the library is loaded */
+ Headway::load('visual-editor/panels/design/property-inputs');
+
+ /* Get values */
+ if ( !$special_element_type && !$special_element_meta ) {
+
+ $property_values = HeadwayElementsData::get_element_properties($element['id']);
+ $property_values_excluding_defaults = HeadwayElementsData::get_element_properties($element['id'], true);
+
+ } else {
+
+ $property_values_args = array(
+ 'element' => $element['id'],
+ 'se_type' => $special_element_type,
+ 'se_meta' => $special_element_meta
+ );
+
+ $property_values = HeadwayElementsData::get_special_element_properties($property_values_args);
+ $property_values_excluding_defaults = HeadwayElementsData::get_special_element_properties(array_merge($property_values_args, array('exclude_default_data' => true)));
+
+ }
+
+ /* Merge in the unsaved values */
+ $property_values = is_array($unsaved_values) ? array_merge($property_values, $unsaved_values) : $property_values;
+ $property_values_excluding_defaults = is_array($unsaved_values) ? array_merge($property_values_excluding_defaults, $unsaved_values) : $property_values_excluding_defaults;
+
+ /* Display the appropriate inputs and values depending on the element */
+ HeadwayPropertyInputs::display($element, $special_element_type, $special_element_meta, $property_values, $property_values_excluding_defaults);
+
+ }
+
+
+ public static function method_get_design_editor_elements() {
+
+ $current_layout = headway_post('layout');
+ $all_elements = HeadwayElementAPI::get_all_elements();
+ $groups = HeadwayElementAPI::get_groups();
+
+ $customized_element_data = HeadwayElementsData::get_all_elements();
+
+ $elements = array('groups' => $groups);
+
+ /* Assemble the arrays */
+ foreach ( $all_elements as $element_id => $element_settings ) {
+
+ $elements[$element_id] = array(
+ 'selector' => $element_settings['selector'],
+ 'id' => $element_settings['id'],
+ 'parent' => headway_get('parent', $element_settings),
+ 'name' => $element_settings['name'],
+ 'description' => headway_get('description', $element_settings),
+ 'properties' => $element_settings['properties'],
+ 'group' => $element_settings['group'],
+ 'states' => headway_get('states', $element_settings, array()),
+ 'instances' => headway_get('instances', $element_settings, array()),
+ 'disallow-nudging' => headway_get('disallow-nudging', $element_settings, false),
+ 'inspectable' => headway_get('inspectable', $element_settings),
+ 'customized' => count( headway_get('properties', headway_get( $element_settings['id'], $customized_element_data), array()) ) ? true : false
+ );
+
+ /* Loop through main element instances and add customized flag if necessary */
+ foreach ( $elements[$element_id]['instances'] as $element_instance_id => $element_instance_settings ) {
+
+ if ( isset($customized_element_data[$element_settings['id']]['special-element-instance'][$element_instance_id]) )
+ $elements[$element_id]['instances'][$element_instance_id]['customized'] = true;
+
+ }
+
+ }
+
+ /* Spit it all out */
+ self::json_encode($elements);
+
+ }
+
+
+ public static function method_get_design_editor_element_data() {
+
+ self::json_encode(HeadwayElementsData::get_all_elements(true));
+
+ }
+
+
+ /* Template methods */
+ public static function secure_method_add_template() {
+
+ //Send the template ID back to JavaScript so it can be added to the list
+ self::json_encode(HeadwayLayout::add_template(headway_post('template_name')));
+
+ }
+
+
+ public static function secure_method_rename_layout_template() {
+
+ //Get templates
+ $templates = HeadwaySkinOption::get( 'list', 'templates', array() );
+
+ //Get template to rename
+ $id = str_replace('template-', '', headway_post( 'layout' ));
+
+ //Rename
+ if ( isset( $templates[ $id ] ) ) {
+
+ $templates[ $id ] = headway_post( 'newName' );
+
+ //Send back to database
+ HeadwaySkinOption::set( 'list', $templates, 'templates' );
+
+ do_action( 'headway_visual_editor_rename_template' );
+
+ echo 'success';
+
+ } else {
+
+ echo 'failure';
+
+ }
+
+ }
+
+
+ public static function secure_method_delete_template() {
+
+ //Retreive templates
+ $templates = HeadwaySkinOption::get('list', 'templates', array());
+
+ //Unset the deleted ID
+ $id = headway_post('template_to_delete');
+
+ //Delete template if it exists and send array back to DB
+ if ( isset($templates[$id]) ) {
+
+ unset($templates[$id]);
+
+ //Delete blocks, wrappers, DE settings for current skin
+ HeadwayLayout::delete_layout('template-' . $id);
+
+ //Delete template from templates list
+ HeadwaySkinOption::set('list', $templates, 'templates');
+
+ do_action('headway_visual_editor_delete_template');
+
+ echo 'success';
+
+ } else {
+
+ echo 'failure';
+
+ }
+
+ }
+
+
+ public static function secure_method_assign_template() {
+
+ $layout = headway_post('layout');
+ $template = str_replace('template-', '', headway_post('template'));
+
+ //Add the template flag
+ HeadwayLayoutOption::set($layout, 'template', $template);
+
+ //Add template flag to global template assignments for easier skin import/export
+ $template_assignments = HeadwaySkinOption::get('assignments', 'templates', array());
+ $template_assignments[$layout] = $template;
+
+ HeadwaySkinOption::set('assignments', $template_assignments, 'templates');
+
+ do_action('headway_visual_editor_assign_template');
+
+ echo HeadwayLayout::get_name('template-' . $template);
+
+ }
+
+
+ public static function secure_method_remove_template_from_layout() {
+
+ $layout = headway_post('layout');
+
+ //Remove the template flag
+ if ( !HeadwayLayoutOption::set($layout, 'template', false) ) {
+ echo 'failure';
+
+ return;
+ }
+
+ //Remove template flag from global template assignments for easier skin import/export
+ $template_assignments = HeadwaySkinOption::get('assignments', 'templates', array());
+ unset($template_assignments[$layout]);
+
+ HeadwaySkinOption::set('assignments', $template_assignments, 'templates');
+
+ do_action('headway_visual_editor_unassign_template');
+
+ echo 'success';
+
+ }
+
+
+ /* Micellaneous methods */
+ public static function method_clear_cache() {
+
+ if ( HeadwayCompiler::flush_cache(true) && HeadwayBlocks::clear_block_actions_cache() )
+ echo 'success';
+ else
+ echo 'failure';
+
+ }
+
+
+ public static function method_ran_tour() {
+
+ $mode = headway_post('mode');
+
+ HeadwayOption::set('ran-tour-' . $mode, true);
+
+ }
+
+
+ public static function method_fonts_list() {
+
+ return do_action('headway_fonts_ajax_list_fonts_' . headway_post('provider'));
+
+ }
+
+
+ public static function secure_method_redactor_upload_image() {
+
+ /* Insure that file is image */
+ if ( strpos($_FILES['file']['type'], 'image') !== 0 )
+ return false;
+
+ /* Use wp_handle_upload() */
+ /* Add this in to make wp_handle_upload pass validation */
+ $_POST['action'] = 'headway_visual_editor';
+
+ $upload = wp_handle_upload($_FILES['file'], array(
+ 'action' => 'headway_visual_editor'
+ ));
+
+ if ( isset($upload['error']) ) {
+ return false;
+ }
+
+ $attachment = array(
+ 'post_title' => $_FILES['file']['name'],
+ 'post_content' => '',
+ 'post_type' => 'attachment',
+ 'post_parent' => 0,
+ 'post_mime_type' => $upload['type'],
+ 'guid' => $upload['url']
+ );
+
+ // Create an Attachment in WordPress
+ $attachment_id = wp_insert_attachment( $attachment, $upload['file'], 0 );
+ wp_update_attachment_metadata( $attachment_id, wp_generate_attachment_metadata( $attachment_id, $upload['file'] ));
+
+ /* Send URL back to VE */
+ self::json_encode(array(
+ 'filelink' => $upload['url']
+ ));
+
+ }
+
+
+ /* Data Portability */
+ /* General Data Portability */
+ public static function method_import_image() {
+
+ Headway::load('data/data-portability');
+
+ /* Set up variables */
+ $image_id = headway_post('imageID');
+ $image_contents = headway_post('imageContents');
+
+ /* Sideload image */
+ self::json_encode(HeadwayDataPortability::decode_image_to_uploads($image_contents['base64_contents']));
+
+ }
+
+ public static function method_import_images() {
+
+ Headway::load('data/data-portability');
+
+ /* Set up variables */
+ $import_file = headway_post('importFile');
+ $image_definitions = headway_get('image-definitions', $import_file, array());
+
+ $imported_images = array();
+
+ /* Loop through base64'd images and move them to uploads directory */
+ foreach ( $image_definitions as $image_id => $image )
+ $imported_images[$image_id] = HeadwayDataPortability::decode_image_to_uploads($image['base64_contents']);
+
+ /* Replace image variables in the import file */
+ foreach ( $imported_images as $imported_image_id => $imported_image ) {
+
+ /* Handle sideloading errors */
+ if ( headway_get('error', $imported_image) ) {
+
+ /* Replace entire array with error to stop import of settings */
+ $import_file = array(
+ 'error' => headway_get('error', $imported_image)
+ );
+
+ } else if ( headway_get('url', $imported_image) ) {
+
+ $import_file = self::import_images_recursive_replace($imported_image_id, $imported_image['url'], $import_file);
+
+ }
+
+ }
+
+ /* Remove giant image definitions from import file */
+ unset($import_file['image-definitions']);
+
+ /* Send import file with images replaced back to Visual Editor */
+ self::json_encode($import_file);
+
+ }
+
+
+ public static function replace_imported_images_variables($import_array) {
+
+ /* Check for imported images */
+ if ( empty($import_array['imported-images']) || !is_array($import_array['imported-images']) )
+ return $import_array;
+
+ /* Replace image variables in the import file */
+ foreach ( $import_array['imported-images'] as $imported_image_id => $imported_image ) {
+
+ if ( headway_get('url', $imported_image) ) {
+
+ $import_array = self::import_images_recursive_replace($imported_image_id, $imported_image['url'], $import_array);
+
+ /* Change erred image variable to point to a 404 image */
+ } else {
+
+ $import_array = self::import_images_recursive_replace($imported_image_id, 'IMAGE_NOT_UPLOADED', $import_array);
+
+ }
+
+ }
+
+ return $import_array;
+
+ }
+
+
+ public static function import_images_recursive_replace($variable, $replace, $array) {
+
+ if ( !is_array($array) )
+ return str_replace($variable, $replace, $array);
+
+ $processed_array = array();
+
+ foreach ( $array as $key => $value )
+ $processed_array[$key] = self::import_images_recursive_replace($variable, $replace, $value);
+
+ return $processed_array;
+
+ }
+
+
+ /* Skin Portability */
+ public static function method_export_skin() {
+
+ Headway::load('data/data-portability');
+
+ parse_str(headway_get('skin-info'), $skin_info);
+
+ return HeadwayDataPortability::export_skin($skin_info['skin-export-info']);
+
+ }
+
+
+ public static function method_install_skin() {
+
+ Headway::load('data/data-portability');
+
+ $skin_data = json_decode(stripslashes(headway_post('skin')), true);
+
+ if ( !is_array($skin_data) ) {
+ return self::json_encode(array(
+ 'error' => 'Could not install template.'
+ ));
+ }
+
+ $skin = self::replace_imported_images_variables($skin_data);
+
+ return self::json_encode(HeadwayDataPortability::install_skin($skin));
+
+ }
+
+
+ /* Layout Portability */
+ public static function method_export_layout() {
+
+ Headway::load('data/data-portability');
+
+ $layout = headway_get('layout', false);
+
+ return HeadwayDataPortability::export_layout($layout);
+
+ }
+
+
+ /* Block Settings Portability */
+ public static function method_export_block_settings() {
+
+ Headway::load('data/data-portability');
+
+ return HeadwayDataPortability::export_block_settings(headway_get('block-id'));
+
+ }
+
+
+}
\ No newline at end of file
--- /dev/null
+<?php
+class HeadwayVisualEditor {
+
+
+ protected static $modes = array();
+
+
+ protected static $default_mode = 'grid';
+
+
+ protected static $default_layout = 'index';
+
+
+ public static function init() {
+
+ if ( !HeadwayCapabilities::can_user_visually_edit() )
+ return;
+
+ //If no child theme is active or if a child theme IS active and the grid is supported, use the grid mode.
+ if ( current_theme_supports('headway-grid') )
+ self::$modes['Grid'] = 'Add blocks and arrange your website structure';
+
+ self::$modes['Design'] = 'Choose fonts, colors, and other styles';
+
+ //If the grid is disabled, set Design as the default mode.
+ if ( !current_theme_supports('headway-grid') )
+ self::$default_mode = 'design';
+
+ //Attempt to raise memory limit to max
+ @ini_set('memory_limit', apply_filters('headway_memory_limit', WP_MAX_MEMORY_LIMIT));
+
+ //Put in action so we can run top level functions
+ do_action('headway_visual_editor_init');
+
+ //Visual Editor AJAX
+ add_action('wp_ajax_headway_visual_editor', array(__CLASS__, 'ajax'));
+
+ if ( HeadwayOption::get('debug-mode') )
+ add_action('wp_ajax_nopriv_headway_visual_editor', array(__CLASS__, 'ajax'));
+
+ //Iframe handling
+ add_action('headway_body_close', array(__CLASS__, 'iframe_load_flag'));
+ add_action('headway_grid_iframe_footer', array(__CLASS__, 'iframe_load_flag'));
+
+ }
+
+
+ public static function ajax() {
+
+ Headway::load('visual-editor/display', 'VisualEditorDisplay');
+ Headway::load('visual-editor/visual-editor-ajax');
+
+ //Authenticate nonce
+ check_ajax_referer('headway-visual-editor-ajax', 'security');
+
+ $method = headway_post('method') ? headway_post('method') : headway_get('method');
+
+ //Check for a non-secure (something that doesn't save data) AJAX request first (let debug mode authentication pass through)
+ if ( method_exists('HeadwayVisualEditorAJAX', 'method_' . $method) && HeadwayCapabilities::can_user_visually_edit() ) {
+ do_action('headway_visual_editor_ajax_pre_' . $method);
+ call_user_func(array('HeadwayVisualEditorAJAX', 'method_' . $method));
+ do_action('headway_visual_editor_ajax_post_' . $method);
+ }
+
+ //Check for a secure (something that saves data) AJAX request and require genuine authentication
+ elseif ( method_exists('HeadwayVisualEditorAJAX', 'secure_method_' . $method) && HeadwayCapabilities::can_user_visually_edit(true) ) {
+ do_action('headway_visual_editor_ajax_pre_' . $method);
+ call_user_func(array('HeadwayVisualEditorAJAX', 'secure_method_' . $method));
+ do_action('headway_visual_editor_ajax_post_' . $method);
+ }
+
+ die();
+
+ }
+
+
+ public static function ajax_error_handler($errno, $errstr, $errfile, $errline) {
+
+ if ( !defined( 'E_STRICT' ) )
+ define( 'E_STRICT', 2048 );
+
+ if ( !defined( 'E_RECOVERABLE_ERROR' ) )
+ define( 'E_RECOVERABLE_ERROR', 4096 );
+
+ if ( !defined( 'E_DEPRECATED' ) )
+ define( 'E_DEPRECATED', 8192 );
+
+ if ( !defined( 'E_USER_DEPRECATED' ) )
+ define( 'E_USER_DEPRECATED', 16384 );
+
+ $severity =
+ 1 * E_ERROR |
+ 1 * E_WARNING |
+ 0 * E_PARSE |
+ 0 * E_NOTICE |
+ 0 * E_CORE_ERROR |
+ 0 * E_CORE_WARNING |
+ 0 * E_COMPILE_ERROR |
+ 0 * E_COMPILE_WARNING |
+ 0 * E_USER_ERROR |
+ 0 * E_USER_WARNING |
+ 0 * E_USER_NOTICE |
+ 0 * E_STRICT |
+ 0 * E_RECOVERABLE_ERROR |
+ 0 * E_DEPRECATED |
+ 0 * E_USER_DEPRECATED;
+
+ $error_ex = new ErrorException( $errstr, 0, $errno, $errfile, $errline );
+
+ if ( ( $error_ex->getSeverity() & $severity ) != 0 ) {
+ throw $error_ex;
+ }
+
+ }
+
+
+ public static function save($options, $current_layout = false, $mode = false) {
+
+ set_error_handler(array(__CLASS__, "ajax_error_handler"));
+
+ $output = array(
+ 'errors' => array()
+ );
+
+ if ( !$current_layout )
+ $current_layout = headway_post('layout');
+
+ if ( !$mode )
+ $mode = headway_post('mode');
+
+ //Handle triple slash bullshit
+ if ( get_magic_quotes_gpc() === 1 )
+ $options = array_map('stripslashes_deep', $options);
+
+ $blocks = isset($options['blocks']) ? $options['blocks'] : null;
+ $wrappers = isset($options['wrappers']) ? $options['wrappers'] : null;
+ $layout_options = isset($options['layout-options']) ? $options['layout-options'] : null;
+ $options_inputs = isset($options['options']) ? $options['options'] : null;
+ $design_editor_inputs = isset($options['design-editor']) ? $options['design-editor'] : null;
+
+ try {
+
+ /* Add wrappers */
+ if ( $wrappers ) {
+
+ foreach ( $wrappers as $id => $methods ) {
+
+ foreach ( $methods as $method => $value ) {
+
+ switch ( $method ) {
+
+ case 'new':
+
+ if ( HeadwayWrappersData::get_wrapper($id) )
+ continue;
+
+ if ( isset($wrappers[$id]['delete']) )
+ continue;
+
+ $args = array(
+ 'position' => headway_get('position', $wrappers[$id], 9999),
+ 'settings' => headway_get('settings', $wrappers[$id], array())
+ );
+
+ if ( $wrappers[$id]['insert_id'] ) {
+ $args['id'] = $wrappers[$id]['insert_id'];
+ }
+
+ $new_wrapper = HeadwayWrappersData::add_wrapper($current_layout, $args);
+
+ if ( is_wp_error($new_wrapper) ) {
+ $output['errors'][] = $new_wrapper->get_error_code() . ($new_wrapper->get_error_message() ? ' - ' . $new_wrapper->get_error_code() : '');
+ } else {
+ $output['wrapper-id-mapping'][$id] = $new_wrapper;
+ }
+
+ break;
+
+ }
+
+ }
+
+ }
+
+ }
+ /* End Adding wrappers */
+
+
+ /* Blocks */
+ if ( $blocks ) {
+
+ foreach ( $blocks as $id => $methods ) {
+
+ foreach ( $methods as $method => $value ) {
+
+ switch ( $method ) {
+
+ case 'new':
+
+ if ( HeadwayBlocksData::get_block($id) )
+ continue;
+
+ if ( isset($blocks[$id]['delete']) )
+ continue;
+
+ $dimensions = explode(',', $blocks[$id]['dimensions']);
+ $position = explode(',', $blocks[$id]['position']);
+
+ $settings = isset($blocks[$id]['settings']) ? $blocks[$id]['settings'] : array();
+
+ /* Check if the wrapper ID for the block is temporary, if it is get the real block ID */
+ if ( isset($output['wrapper-id-mapping']) && $added_wrapper_id = headway_get(HeadwayWrappers::format_wrapper_id($blocks[$id]['wrapper']), $output['wrapper-id-mapping']) ) {
+ $blocks[$id]['wrapper'] = $added_wrapper_id;
+ }
+
+ $args = array(
+ 'type' => $value,
+ 'wrapper' => $blocks[$id]['wrapper'],
+ 'position' => array(
+ 'left' => $position[0],
+ 'top' => $position[1]
+ ),
+ 'dimensions' => array(
+ 'width' => $dimensions[0],
+ 'height' => $dimensions[1]
+ ),
+ 'settings' => $settings
+ );
+
+ if ( $blocks[$id]['insert_id'] ) {
+ $args['id'] = $blocks[$id]['insert_id'];
+ }
+
+ $new_block = HeadwayBlocksData::add_block($current_layout, $args);
+
+ if ( is_wp_error($new_block) ) {
+ $output['errors'][] = $new_block->get_error_code() . ($new_block->get_error_message() ? ' - ' . $new_block->get_error_code() : '');
+ } else {
+ $output['block-id-mapping'][$id] = $new_block;
+ }
+
+ break;
+
+ case 'delete':
+
+ if ( isset($blocks[$id]['new']) )
+ continue;
+
+ HeadwayBlocksData::delete_block($id);
+
+ break;
+
+ case 'dimensions':
+
+ if ( isset($blocks[$id]['new']) )
+ continue;
+
+ $dimensions = explode(',', $value);
+
+ $args = array(
+ 'dimensions' => array(
+ 'width' => $dimensions[0],
+ 'height' => $dimensions[1]
+ )
+ );
+
+ HeadwayBlocksData::update_block($id, $args);
+
+ break;
+
+ case 'position':
+
+ if ( isset($blocks[$id]['new']) )
+ continue;
+
+ $position = explode(',', $value);
+
+ $args = array(
+ 'position' => array(
+ 'left' => $position[0],
+ 'top' => $position[1]
+ )
+ );
+
+ HeadwayBlocksData::update_block($id, $args);
+
+ break;
+
+ case 'wrapper':
+
+ if ( isset($blocks[$id]['new']) )
+ continue;
+
+ /* Check if the wrapper ID for the block is temporary, if it is get the real wrapper ID */
+ if ( isset($output['wrapper-id-mapping']) && headway_get($value, $output['wrapper-id-mapping']) )
+ $value = headway_get($value, $output['wrapper-id-mapping']);
+
+ $args = array(
+ 'wrapper' => $value
+ );
+
+
+ HeadwayBlocksData::update_block($id, $args);
+
+ break;
+
+ case 'settings':
+
+ if ( isset($blocks[$id]['new']) )
+ continue;
+
+ //Get the block from the layout
+ $block = HeadwayBlocksData::get_block($id);
+
+ //If block doesn't exist, we can't do anything.
+ if ( !$block || !is_array(headway_get('settings', $block)) )
+ continue;
+
+ //If there aren't any options, then don't do anything either
+ if ( !is_array($value) || count($value) === 0 )
+ continue;
+
+ $block['settings'] = array_merge($block['settings'], $value);
+
+ HeadwayBlocksData::update_block($id, $block);
+
+ break;
+
+ }
+
+ }
+
+ }
+
+ }
+ /* End Blocks */
+
+
+ /* Do everything else with wrappers. Reason being the wrapper IDs need to be established for adding blocks, but if we move a block from a wrapper then delete that wrapper, we don't want those blocks to be deleted. */
+ if ( $wrappers ) {
+
+ foreach ( $wrappers as $id => $methods ) {
+
+ foreach ( $methods as $method => $value ) {
+
+ switch ( $method ) {
+
+ case 'delete':
+
+ if ( isset($wrappers[$id]['new']) )
+ continue;
+
+ HeadwayWrappersData::delete_wrapper($current_layout, $id);
+
+ break;
+
+ case 'position':
+
+ if ( isset($wrappers[$id]['new']) )
+ continue;
+
+ $args = array(
+ 'position' => $value
+ );
+
+ HeadwayWrappersData::update_wrapper($id, $args);
+
+ break;
+
+ case 'settings':
+
+ if ( isset($wrappers[$id]['new']) )
+ continue;
+
+ //Get the wrapper from the layout so we can merge settings
+ $wrapper = HeadwayWrappersData::get_wrapper($id);
+
+ //If wrapper doesn't exist, we can't do anything.
+ if ( !$wrapper )
+ continue;
+
+ //If there aren't any options, then don't do anything either
+ if ( !is_array($value) || count($value) === 0 )
+ continue;
+
+ $wrapper['settings'] = array_merge($wrapper['settings'], $value);
+
+ HeadwayWrappersData::update_wrapper($id, $wrapper);
+
+ break;
+
+ }
+
+ }
+
+ }
+
+ }
+ /* End everything else wrappers (delete and options) */
+
+
+ /* Layout Options */
+ if ( $layout_options ) {
+
+ foreach ( $layout_options as $group => $options ) {
+
+ foreach ( $options as $option => $value ) {
+ HeadwayLayoutOption::set($current_layout, $option, $value, $group);
+ }
+
+ }
+
+ }
+ /* End Layout Options */
+
+ /* Options */
+ if ( $options_inputs ) {
+
+ foreach ( $options_inputs as $group => $options ) {
+
+ foreach ( $options as $option => $value ) {
+ HeadwaySkinOption::set($option, $value, $group);
+ }
+
+ }
+
+ }
+ /* End Options */
+
+ /* Design Editor Inputs */
+ if ( $design_editor_inputs ) {
+
+ /* Loop through to get every element and its properties */
+ foreach ( $design_editor_inputs as $element_id => $element_data ) {
+
+ if ( !is_array($element_data) )
+ continue;
+
+ //Dispatch depending on type of element data
+ foreach ( $element_data as $element_data_node => $element_data_node_data ) {
+
+ //Handle different nodes depending on what they are
+ if ( $element_data_node == 'properties' ) {
+
+ //Set each property for the regular element
+ foreach ( $element_data_node_data as $property_id => $property_value )
+ HeadwayElementsData::set_property(null, $element_id, $property_id, $property_value);
+
+ //Handle instances, states, etc.
+ } else if ( strpos($element_data_node, 'special-element-') === 0 ) {
+
+ $special_element_type = str_replace('special-element-', '', $element_data_node);
+
+ //Loop through the special elements
+ foreach ( $element_data_node_data as $special_element => $special_element_properties ) {
+
+ /* If block ID mapping exists, make sure that none of the temporary IDs are being a saved as instances. This is mainly to make block settimgs import work if they do it on a block that hasn't been saved yet. */
+ if ( isset($output['block-id-mapping']) && count($output['block-id-mapping']) ) {
+
+ foreach ( $output['block-id-mapping'] as $old_block_id => $new_block_id ) {
+ $special_element = str_replace('block-' . $old_block_id, 'block-' . $new_block_id, $special_element);
+ }
+
+ }
+
+ /* If wrapper ID mapping exists, do same thing as block ID mapping */
+ if ( isset( $output['wrapper-id-mapping'] ) && count( $output['wrapper-id-mapping'] ) ) {
+
+ foreach ( $output['wrapper-id-mapping'] as $old_wrapper_id => $new_wrapper_id ) {
+ $special_element = str_replace( 'wrapper-' . HeadwayWrappers::format_wrapper_id($old_wrapper_id), 'wrapper-' . HeadwayWrappers::format_wrapper_id( $new_wrapper_id ), $special_element );
+ }
+
+ }
+
+ //Set the special element properties now
+ foreach ( $special_element_properties as $special_element_property => $special_element_property_value ) {
+ HeadwayElementsData::set_special_element_property(null, $element_id, $special_element_type, $special_element, $special_element_property, $special_element_property_value);
+ }
+ }
+
+ }
+
+ }
+
+ }
+ /* End loop */
+
+ }
+ /* End Design Editor Inputs */
+
+ //This hook is used by cache flushing, plugins, etc. Do not fire on preview save because it'll flush preview options
+ if ( !headway_get('ve-preview') )
+ do_action('headway_visual_editor_save');
+
+ /* Save snapshot if allowed */
+ if ( !defined('HEADWAY_DISABLE_AUTO_SNAPSHOT') || HEADWAY_DISABLE_AUTO_SNAPSHOT !== true ) {
+ $output['snapshot'] = HeadwayDataSnapshots::save_snapshot(true);
+ }
+
+ } catch (Exception $e) {
+
+ /* Disable error output on saving right now */
+
+ /*
+ if ( !isset($output['errors']) || !is_array($output['errors']) )
+ $output['errors'] = array();
+
+ $output['errors'][] = $e->getMessage() . '<br /><br/><pre style="overflow: scroll;user-select: all;max-width: 220px;-webkit-user-select: all;-moz-user-select:all;border: 1px solid rgba(255, 255, 255, 0.2);">' . $e->getTraceAsString() . '</pre>';
+ */
+
+ }
+
+ if ( !count($output['errors']) )
+ unset($output['errors']);
+
+ return $output;
+
+ }
+
+
+ public static function display() {
+
+ self::check_if_ie();
+
+ Headway::load('visual-editor/display', 'VisualEditorDisplay');
+ HeadwayVisualEditorDisplay::display();
+
+ }
+
+
+ public static function check_if_ie() {
+
+ /* Only show this on IE versions less than 9 */
+ if ( !headway_is_ie() || (headway_is_ie(9) || headway_is_ie(10) || headway_is_ie(11)) )
+ return false;
+
+ $message = '
+ <span style="text-align: center;font-size: 26px;width: 100%;display: block;margin-bottom: 20px;">Error</span>
+
+ Unfortunately, the Headway Visual Editor does not work with Internet Explorer due to its lack of modern features.<br /><br />
+
+ Please upgrade to a modern browser such as <a href="http://www.google.com/chrome" target="_blank">Google Chrome</a> or <a href="http://firefox.com" target="_blank">Mozilla Firefox</a>.<br /><br />
+
+ If this message persists after upgrading to a modern browser, please visit <a href="http://support.headwaythemes.com" target="_blank">Headway Support</a>.
+ ';
+
+ return wp_die($message);
+
+ }
+
+
+ public static function get_modes() {
+
+ return apply_filters('headway_visual_editor_get_modes', self::$modes);
+
+ }
+
+
+ public static function get_current_mode() {
+
+ $mode = headway_get('visual-editor-mode');
+
+ if ( $mode ) {
+
+ if ( array_search(strtolower($mode), array_map('strtolower', array_keys(self::$modes))) ) {
+
+ return strtolower($mode);
+
+ }
+
+ }
+
+ return strtolower(self::$default_mode);
+
+ }
+
+
+ public static function is_mode($mode) {
+
+ if ( self::get_current_mode() === strtolower($mode) )
+ return true;
+
+ if ( !headway_get('visual-editor-mode') && strtolower($mode) === strtolower(self::$default_mode) )
+ return true;
+
+ return false;
+
+ }
+
+
+ ////////////////// iframe handling ///////////////////////
+ public static function iframe_load_flag() {
+
+ echo '<script type="text/javascript">
+ /* Set the iframe as loaded for the iframe load checker */
+ document.getElementsByTagName("body")[0].className += " iframe-loaded";
+ </script>';
+
+ }
+
+
+}
\ No newline at end of file
--- /dev/null
+<?php
+class HeadwayWidgets {
+
+
+ public static function init() {
+
+ add_filter('get_search_form', array(__CLASS__, 'search_form'));
+
+ add_filter('widget_title', array(__CLASS__, 'remove_unnecessary_nbsp_from_titles'));
+
+ }
+
+
+ public static function search_form() {
+
+ return headway_get_search_form();
+
+ }
+
+
+ public static function remove_unnecessary_nbsp_from_titles($title) {
+
+ if ( $title == ' ' )
+ return null;
+
+ return $title;
+
+ }
+
+
+}
\ No newline at end of file
--- /dev/null
+<?php
+class HeadwayWrapperOptions extends HeadwayVisualEditorPanelAPI {
+
+
+ public function register() {
+
+ return true;
+
+ }
+
+
+ public function display($wrapper, $layout) {
+
+ //Set block properties
+ $this->wrapper = $wrapper;
+
+ //Set up arguments
+ $args = array(
+ 'wrapper' => $this->wrapper,
+ 'layoutID' => $layout
+ );
+
+ //Get and display panel
+ $this->modify_arguments($args);
+ $this->panel_content($args);
+
+ }
+
+
+ public $id = 'wrapper-options';
+ public $name = 'Wrapper Options';
+ public $mode = 'grid';
+
+ public $tabs = array(
+ 'setup' => 'Grid & Margins',
+ 'config' => 'Mirroring & Config',
+ 'responsive' => 'Responsive'
+ );
+
+ public $inputs = array(
+ 'setup' => array(
+ 'grid-setup-heading' => array(
+ 'type' => 'heading',
+ 'name' => 'grid-setup-heading',
+ 'label' => 'Grid'
+ ),
+
+ 'column-count' => array(
+ 'type' => 'slider',
+ 'name' => 'columns',
+ 'label' => 'Columns',
+ 'default' => 24,
+ 'tooltip' => 'Number of columns in the Grid. Suggested values 9, 12, 16, and 24.<br /><br /><strong>Note:</strong> The wrapper must be empty of all blocks prior to changing the column count. Either move the blocks to another wrapper or delete them if they are not needed.',
+ 'slider-min' => 6,
+ 'slider-max' => 24,
+ 'slider-interval' => 1,
+ 'callback' => 'wrapperOptionCallbackColumnCount(input, value);'
+ ),
+
+ 'use-independent-grid' => array(
+ 'type' => 'checkbox',
+ 'name' => 'use-independent-grid',
+ 'label' => 'Use Independent Grid',
+ 'tooltip' => 'Check this if you would like this wrapper to have different Grid settings than the Global Grid settings.',
+ 'callback' => 'wrapperOptionCallbackIndependentGrid(input, value);',
+ 'toggle' => array(
+ 'true' => array(
+ 'show' => array(
+ '#input-column-width',
+ '#input-gutter-width',
+ '#input-grid-width'
+ )
+ ),
+ 'false' => array(
+ 'hide' => array(
+ '#input-column-width',
+ '#input-gutter-width',
+ '#input-grid-width'
+ )
+ )
+ )
+ ),
+
+ 'column-width' => array(
+ 'type' => 'slider',
+ 'name' => 'column-width',
+ 'label' => 'Column Width',
+ 'default' => 20,
+ 'tooltip' => 'The column width is the amount of space inside of each column. This is represented by the grey regions on the grid.',
+ 'unit' => 'px',
+ 'slider-min' => 10,
+ 'slider-max' => 80,
+ 'slider-interval' => 1,
+ 'callback' => 'wrapperOptionCallbackColumnWidth(input, value);'
+ ),
+
+ 'gutter-width' => array(
+ 'type' => 'slider',
+ 'name' => 'gutter-width',
+ 'label' => 'Gutter Width',
+ 'default' => 20,
+ 'tooltip' => 'The gutter width is the amount of space between each column. This is the space between each of the grey regions on the grid.',
+ 'unit' => 'px',
+ 'slider-min' => 0,
+ 'slider-max' => 40,
+ 'slider-interval' => 1,
+ 'callback' => 'wrapperOptionCallbackGutterWidth(input, value);'
+ ),
+
+ 'grid-width' => array(
+ 'type' => 'integer',
+ 'unit' => 'px',
+ 'default' => 940,
+ 'name' => 'grid-width',
+ 'label' => 'Grid Width',
+ 'readonly' => true
+ ),
+
+ 'wrapper-margins-heading' => array(
+ 'type' => 'heading',
+ 'name' => 'wrapper-margins-heading',
+ 'label' => 'Wrapper Margins'
+ ),
+
+ 'wrapper-margin-top' => array(
+ 'type' => 'slider',
+ 'name' => 'wrapper-margin-top',
+ 'label' => 'Top Margin',
+ 'default' => 30,
+ 'tooltip' => 'Space in between the top of this wrapper and the top of the page or the wrapper above it.',
+ 'unit' => 'px',
+ 'slider-min' => 0,
+ 'slider-max' => 200,
+ 'slider-interval' => 1,
+ 'callback' => 'wrapperOptionCallbackMarginTop(input, value);',
+ 'data-handler-callback' => 'dataSetDesignEditorProperty({
+ element: "wrapper",
+ property: "margin-top",
+ value: args.value.toString(),
+ specialElementType: "instance",
+ specialElementMeta: "wrapper-" + args.wrapper.id
+ });'
+ ),
+
+ 'wrapper-margin-bottom' => array(
+ 'type' => 'slider',
+ 'name' => 'wrapper-margin-bottom',
+ 'label' => 'Bottom Margin',
+ 'default' => 0,
+ 'tooltip' => 'Space in between this wrapper and the bottom of the page.',
+ 'unit' => 'px',
+ 'slider-min' => 0,
+ 'slider-max' => 200,
+ 'slider-interval' => 1,
+ 'callback' => 'wrapperOptionCallbackMarginBottom(input, value);',
+ 'data-handler-callback' => 'dataSetDesignEditorProperty({
+ element: "wrapper",
+ property: "margin-bottom",
+ value: args.value.toString(),
+ specialElementType: "instance",
+ specialElementMeta: "wrapper-" + args.wrapper.id
+ });'
+ )
+ ),
+
+ 'config' => array(
+ 'mirror-wrapper' => array(
+ 'type' => 'select',
+ 'name' => 'mirror-wrapper',
+ 'label' => 'Mirror Blocks From Another Wrapper',
+ 'default' => '',
+ 'tooltip' => 'By using this option, you can tell a wrapper to "mirror" another wrapper and all of its blocks. This option is useful if you are wanting to share a wrapper—such as a header—across layouts on your site. Select the wrapper you wish to mirror the content from in the select box to the right.',
+ 'options' => 'get_wrappers_select_options_for_mirroring()',
+ 'callback' => 'updateWrapperMirrorStatus(args.wrapper.id, value, input);'
+ ),
+
+ 'alias' => array(
+ 'type' => 'text',
+ 'name' => 'alias',
+ 'label' => 'Wrapper Alias',
+ 'default' => '',
+ 'tooltip' => 'Enter an easily recognizable name for the wrapper alias and it will be used throughout your site admin. Aliases are used in the Design Editor, mirroring menu, and are a great way of keeping track of a specific wrapper.'
+ ),
+
+ 'css-classes' => array(
+ 'type' => 'text',
+ 'name' => 'css-classes',
+ 'label' => 'Custom CSS Class(es)',
+ 'default' => '',
+ 'tooltip' => 'Need more finite control? Enter the custom CSS class selectors here and they will be added to the wrappers\'s class attribute. <strong>DO NOT</strong> put regular CSS in here. Use the Live CSS editor for that.'
+ )
+ ),
+
+ 'responsive' => array(
+
+ array(
+ 'type' => 'repeater',
+ 'name' => 'responsive-wrapper-options',
+ 'label' => 'Configure Breakpoints.',
+ 'inputs' => array(
+
+ array(
+ 'type' => 'select',
+ 'name' => 'breakpoint',
+ 'label' => 'Set Breakpoint',
+ 'options' => array(
+ '' => 'Off - No Breakpoint',
+ 'custom' => 'Custom Width',
+ '1824px' => '1824px - Very Large Screens',
+ '1224px' => '1224px - Desktop and Laptop',
+ '1024px' => '1024px - Popular Tablet Landscape',
+ '768px' => '768px - Popular Tablet Portrait',
+ '600px' => '600px - Popular Breakpoint in Headway',
+ '568px' => '568px - iPhone 5 Landscape',
+ '480px' => '480px - iPhone 3 & 4 Landscape',
+ '320px' => '320px - iPhone 3 & 4 & 5 & Android Portrait'
+ ),
+ 'toggle' => array(
+ '' => array(
+ 'hide' => array(
+ '#input-max-width'
+ ),
+ ),
+ 'custom' => array(
+ 'show' => array(
+ '#input-max-width'
+ ),
+ ),
+ '1824px' => array(
+ 'hide' => array(
+ '#input-max-width'
+ ),
+ ),
+ '1224px' => array(
+ 'hide' => array(
+ '#input-max-width'
+ ),
+ ),
+ '1024px' => array(
+ 'hide' => array(
+ '#input-max-width'
+ ),
+ ),
+ '768px' => array(
+ 'hide' => array(
+ '#input-max-width'
+ ),
+ ),
+ '600px' => array(
+ 'hide' => array(
+ '#input-max-width'
+ ),
+ ),
+ '568px' => array(
+ 'hide' => array(
+ '#input-max-width'
+ ),
+ ),
+ '480px' => array(
+ 'hide' => array(
+ '#input-max-width'
+ ),
+ ),
+ '320px' => array(
+ 'hide' => array(
+ '#input-max-width'
+ ),
+ )
+ ),
+ 'tooltip' => 'Select a screen width for these change to take effect.',
+ 'default' => ''
+ ),
+
+ array(
+ 'type' => 'text',
+ 'name' => 'max-width',
+ 'label' => 'Custom Width',
+ 'tooltip' => 'Add px value as well. eg: 600px'
+ ),
+
+ array(
+ 'type' => 'select',
+ 'name' => 'breakpoint-min-or-max',
+ 'label' => 'Min or Max width',
+ 'options' => array(
+ 'min' => 'Min Width (applies to screens that are wider than breakpoint)',
+ 'max' => 'Max Width (applies to screens that are narrower than breakpoint)'
+ ),
+ 'default' => 'max'
+ ),
+
+ array(
+ 'name' => 'adaptive-heading',
+ 'type' => 'heading',
+ 'label' => 'Adaptive Options'
+ ),
+
+ array(
+ 'type' => 'checkbox',
+ 'name' => 'stretch',
+ 'label' => 'Stretch blocks for mobile',
+ 'default' => false,
+ 'tooltip' => 'Enable this option to make all blocks in this wrapper stretch the full wrapper width on smaller screens. Blocks placed side by side may not look good on smaller screens as they fight for the horizontal space. Setting this option makes each block go full width at the set break point.'
+ ),
+
+ array(
+ 'type' => 'checkbox',
+ 'name' => 'auto-center',
+ 'label' => 'Attempt to Center items',
+ 'default' => false,
+ 'tooltip' => 'This will attempt to center the elements in this block at the set breakpoint. NOTE: This will not work for all elements but give it a try and if it works for you then great. More complex html like menus will require custom code.'
+ ),
+
+ array(
+ 'type' => 'checkbox',
+ 'name' => 'hide-wrapper',
+ 'label' => 'Hide this wrapper',
+ 'default' => false,
+ 'tooltip' => 'This will hide this wrapper for the set breakpoint.'
+ )
+
+ ),
+ 'sortable' => true,
+ 'limit' => false,
+ 'callback' => ''
+ )
+
+ )
+ );
+
+
+ function modify_arguments($args = false) {
+
+ /* Grid Settings Defaults */
+ $this->inputs['setup']['column-width']['default'] = HeadwayWrappers::$default_column_width;
+ $this->inputs['setup']['gutter-width']['default'] = HeadwayWrappers::$default_gutter_width;
+ /* End Grid Settings Defaults */
+
+ /* Margins */
+ $wrapper_instance_id = 'wrapper-' . $args['wrapper']['id'];
+
+ $this->inputs['setup']['wrapper-margin-top']['value'] = HeadwayElementsData::get_special_element_property('wrapper', 'instance', $wrapper_instance_id, 'margin-top', HeadwayWrappers::$default_wrapper_margin_top, 'structure');
+ $this->inputs['setup']['wrapper-margin-bottom']['value'] = HeadwayElementsData::get_special_element_property('wrapper', 'instance', $wrapper_instance_id, 'margin-bottom', HeadwayWrappers::$default_wrapper_margin_bottom, 'structure');
+ /* End Margins */
+
+ /* Wrapper Mirror Value */
+ $this->inputs['config']['mirror-wrapper']['value'] = HeadwayWrappersData::is_wrapper_mirrored($args['wrapper']);
+
+ }
+
+
+ public function get_wrappers_select_options_for_mirroring() {
+
+ $wrappers = HeadwayWrappersData::get_all_wrappers();
+
+ $options = array('' => '– Do Not Mirror –');
+
+ //If there are no wrappers to mirror, then just return the Do Not Mirror option.
+ if ( empty($wrappers) || !is_array($wrappers) )
+ return $options;
+
+ foreach ( $wrappers as $wrapper_id => $wrapper ) {
+
+ /* If we can't get a name for the layout, then things probably aren't looking good. Just skip this wrapper. */
+ if ( !($layout_name = HeadwayLayout::get_name($wrapper['layout'])) )
+ continue;
+
+ /* Check for mirroring here */
+ if ( HeadwayWrappersData::is_wrapper_mirrored($wrapper) )
+ continue;
+
+ $current_layout_suffix = ( $this->wrapper['layout'] == $wrapper['layout'] ) ? ' (Warning: Same Layout)' : null;
+ $wrapper_alias = headway_get('alias', $wrapper['settings']) ? ' – ' . headway_get('alias', $wrapper['settings']) : null;
+
+ /* Build info that shows if wrapper is fixed or fluid since a wrapper may not have alias and that can be confusing if it just says "Wrapper - Some Layout" over and over */
+ $wrapper_info = array();
+
+ if ( headway_fix_data_type($wrapper['settings']['fluid']) )
+ $wrapper_info[] = 'Fluid';
+
+ if ( headway_fix_data_type($wrapper['settings']['fluid-grid']) )
+ $wrapper_info[] = 'Fluid Grid';
+
+ $wrapper_info_str = $wrapper_info ? ' (' . implode( ', ', $wrapper_info ) . ')' : '';
+
+ //Get alias if it exists, otherwise use the default name
+ $options[$wrapper_id] = 'Wrapper' . $wrapper_alias . ' – ' . $layout_name . $wrapper_info_str . $current_layout_suffix;
+
+ }
+
+ //Remove the current wrapper from the list
+ if ( isset($this->wrapper['id']) && $this->wrapper['id'] )
+ unset($options[$this->wrapper['id']]);
+
+ return $options;
+
+ }
+
+
+}
\ No newline at end of file
--- /dev/null
+<?php
+class HeadwayWrappers {
+
+
+ public static $default_wrappers = array(
+ 'default' => array(
+ 'id' => 'default',
+ 'position' => 0,
+ 'settings' => array(
+ 'fluid' => false,
+ 'fluid-grid' => false,
+ 'columns' => null,
+ 'column-width' => null,
+ 'gutter-width' => null
+ )
+ )
+ );
+
+ public static $default_wrapper_id = 'default';
+
+ public static $default_columns = 24;
+
+ public static $default_column_width = 20;
+
+ public static $default_gutter_width = 20;
+
+ public static $default_wrapper_margin_top = 30;
+
+ public static $default_wrapper_margin_bottom = 30;
+
+
+ public static $global_grid_column_width = null;
+
+ public static $global_grid_gutter_width = null;
+
+
+ public static function init() {
+
+ /* Set defaults */
+ self::$default_columns = HeadwaySkinOption::get('columns', false, self::$default_columns);
+ self::$global_grid_column_width = HeadwaySkinOption::get('column-width', false, self::$default_column_width);
+ self::$global_grid_gutter_width = HeadwaySkinOption::get('gutter-width', false, self::$default_gutter_width);
+
+ self::$default_wrappers['default']['settings']['use-independent-grid'] = false;
+ self::$default_wrappers['default']['settings']['columns'] = self::$default_columns;
+ self::$default_wrappers['default']['settings']['column-width'] = self::$default_column_width;
+ self::$default_wrappers['default']['settings']['gutter-width'] = self::$default_gutter_width;
+
+ /* Setup hooks */
+ add_action('headway_register_elements_instances', array(__CLASS__, 'register_wrapper_instances'), 11);
+ add_action('headway_wrapper_options', array(__CLASS__, 'options_panel'), 10, 2);
+
+ }
+
+
+ public static function format_wrapper_id($wrapper_id) {
+
+ return str_replace('wrapper-', '', $wrapper_id);
+
+ }
+
+
+ public static function register_wrapper_instances() {
+
+ $all_wrappers = HeadwayWrappersData::get_all_wrappers();
+
+ if ( !$all_wrappers )
+ return false;
+
+ foreach ( $all_wrappers as $wrapper_id => $wrapper_options ) {
+
+ /* Do NOT register the default wrapper instance */
+ if ( $wrapper_id == 'default' )
+ continue;
+
+ /* Do not register instance for mirrored wrapper */
+ if ( HeadwayWrappersData::is_wrapper_mirrored($wrapper_options) )
+ continue;
+
+ $wrapper_id_for_selector = HeadwayWrappersData::get_legacy_id( $wrapper_options );
+
+ $wrapper_name = headway_get('alias', headway_get('settings', $wrapper_options, array())) ? 'Wrapper: ' . headway_get( 'alias', headway_get( 'settings', $wrapper_options, array() ) ) : 'Wrapper (Unnamed)';
+
+ HeadwayElementAPI::register_element_instance(array(
+ 'group' => 'structure',
+ 'element' => 'wrapper',
+ 'id' => 'wrapper-' . HeadwayWrappers::format_wrapper_id($wrapper_id),
+ 'name' => $wrapper_name,
+ 'selector' => '#wrapper-' . self::format_wrapper_id( $wrapper_id_for_selector) . ', div.wrapper-mirroring-' . self::format_wrapper_id($wrapper_id_for_selector),
+ 'layout' => $wrapper_options['layout']
+ ));
+
+ }
+
+ }
+
+
+ public static function is_fluid($wrapper) {
+
+ return headway_get('fluid', headway_get('settings', $wrapper, array()), false, true);
+
+ }
+
+
+ public static function is_grid_fluid($wrapper) {
+
+ $wrapper_settings = headway_get('settings', $wrapper, array());
+
+ return headway_get('fluid', $wrapper_settings, false, true) && headway_get('fluid-grid', $wrapper_settings, false, true);
+
+ }
+
+
+ public static function is_independent_grid($wrapper) {
+
+ return headway_get('use-independent-grid', headway_get('settings', $wrapper, array()), false, true);
+
+ }
+
+
+ public static function get_columns($wrapper) {
+
+ return headway_get('columns', headway_get('settings', $wrapper, array()), false, true);
+
+ }
+
+
+ public static function get_column_width($wrapper) {
+
+ $wrapper_settings = headway_get('settings', $wrapper, array());
+
+ return headway_get('use-independent-grid', $wrapper_settings, false, true) ? headway_get('column-width', $wrapper_settings, false, true) : HeadwayWrappers::$global_grid_column_width;
+
+ }
+
+
+ public static function get_gutter_width($wrapper) {
+
+ $wrapper_settings = headway_get('settings', $wrapper, array());
+
+ return headway_get('use-independent-grid', $wrapper_settings, false, true) ? headway_get('gutter-width', $wrapper_settings, false, true) : HeadwayWrappers::$global_grid_gutter_width;
+
+ }
+
+
+ public static function get_grid_width($wrapper) {
+
+ if ( !is_array($wrapper) )
+ return false;
+
+ /* If wrapper is mirrored then use settings from it for the grid */
+ if ( $potential_wrapper_mirror = HeadwayWrappersData::get_wrapper_mirror($wrapper) )
+ $wrapper = $potential_wrapper_mirror;
+
+ $columns = self::get_columns($wrapper);
+
+ $column_width = self::get_column_width($wrapper);
+ $gutter_width = self::get_gutter_width($wrapper);
+
+ return ($column_width * $columns) + (($columns - 1) * $gutter_width);
+
+ }
+
+
+ public static function options_panel($wrapper, $layout) {
+
+ require_once HEADWAY_LIBRARY_DIR . '/wrappers/wrapper-options.php';
+
+ //Initiate options class
+ $options = new HeadwayWrapperOptions;
+ $options->display($wrapper, $layout);
+
+ }
+
+
+ public static function get_layout_wrappers( $layout ) {
+
+ _deprecated_function( __FUNCTION__, '3.7', 'HeadwayDataWrappers::get_wrappers_by_layout()' );
+
+ $wrappers = HeadwayWrappersData::get_wrappers_by_layout( $layout );
+
+ if ( ! $wrappers )
+ return $wrappers;
+
+ /* Merge settings array with each wrapper so it's single dimension */
+ foreach ( $wrappers as $wrapper_id => $wrapper ) {
+
+ $wrappers[ $wrapper_id ]['mirror-wrapper'] = headway_get( 'mirror_id', $wrapper );
+
+ $wrappers[ $wrapper_id ] = array_merge( $wrappers[ $wrapper_id ], headway_get( 'settings', $wrappers[ $wrapper_id ], array() ) );
+
+ }
+
+ return $wrappers;
+
+ }
+
+
+ public static function get_all_wrappers() {
+
+ _deprecated_function( __FUNCTION__, '3.7', 'HeadwayWrappersData::get_all_wrappers()' );
+
+ $wrappers = HeadwayWrappersData::get_all_wrappers();
+
+ return $wrappers;
+
+ }
+
+
+ public static function get_wrapper($wrapper_id, $deprecated = null) {
+
+ _deprecated_function( __FUNCTION__, '3.7', 'HeadwayWrappersData::get_wrapper()' );
+
+ return HeadwayWrappersData::get_wrapper($wrapper_id);
+
+ }
+
+
+}
\ No newline at end of file
--- /dev/null
+<?php
+/* Silence is golden. */
\ No newline at end of file
--- /dev/null
+/*
+THEME NAME:Headway Base
+THEME URI:http://www.headwaythemes.com
+VERSION:3.7.8
+AUTHOR:Headway Themes
+AUTHOR URI:http://www.headwaythemes.com
+DESCRIPTION:Headway is a feature-packed theme with drag and drop layout editing, point and click design capabilities, powerful search engine optimization and much more. For help, you can <a href="http://support.headwaythemes.com" target="_blank">access our support</a> or go to the <a href="http://docs.headwaythemes.com/" target="_blank">Headway documentation</a>.
+LICENSE: Terms of Service
+LICENSE URI: http://headwaythemes.com/terms-of-service
+
+------------------------------------------------------------------------
+Copyright 2009-2014 Vesped Inc.
+
+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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+*/
\ No newline at end of file