diff --git a/.travis.yml b/.travis.yml index 737689c3..e69de29b 100644 --- a/.travis.yml +++ b/.travis.yml @@ -1,24 +0,0 @@ -language: android -jdk: oraclejdk8 - -android: - components: - - extra-android-m2repository - - extra-android-support - - platform-tools - - tools - - build-tools-25.0.1 - - android-25 - -env: - global: - - GRADLE_OPTS="-XX:MaxPermSize=4g -Xmx4g" - - ANDROID_SDKS=android-16 - - ANDROID_TARGET=android-16 - -before_install: - # TODO: Remove the following line when Travis' platform-tools are updated to v24+ - - echo yes | android update sdk -a --filter platform-tools --no-ui --force - -script: - - ./gradlew build diff --git a/README.md b/README.md index 75379491..7c66a06a 100644 --- a/README.md +++ b/README.md @@ -1,7 +1,5 @@ # WordPress-Editor-Android # -[![Build Status](https://travis-ci.org/wordpress-mobile/WordPress-Editor-Android.svg?branch=develop)](https://travis-ci.org/wordpress-mobile/WordPress-Editor-Android) - ## Introduction ## WordPress-Editor-Android is the text editor used in the [WordPress Android app](https://github.com/wordpress-mobile/WordPress-Android) to create and edit pages & posts. In short it's a simple, straightforward way to visually edit HTML. diff --git a/WordPressEditor/build.gradle b/WordPressEditor/build.gradle index 6ad0e825..fa188d40 100644 --- a/WordPressEditor/build.gradle +++ b/WordPressEditor/build.gradle @@ -1,31 +1,49 @@ buildscript { repositories { + google() jcenter() } + + ext { + aztecVersion = 'v1.3.44' + } + dependencies { - classpath 'com.android.tools.build:gradle:2.2.3' + classpath 'com.android.tools.build:gradle:4.0.1' + classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlinVersion" } } +repositories { + google() + jcenter() + maven { url "https://www.jitpack.io" } + maven { url "https://dl.bintray.com/wordpress-mobile/react-native-mirror/" } +} + apply plugin: 'com.android.library' apply plugin: 'maven' apply plugin: 'signing' +apply plugin: 'kotlin-android' +apply plugin: 'kotlin-android-extensions' -repositories { - jcenter() -} -android { - publishNonDefault true +// import the `submoduleGitHash()` function +apply from: 'https://gist.githubusercontent.com/hypest/e06f6097065728b6db7b7c462f8fef1a/raw/3b91756fca76e4c2a9b573313e186c47842e1f7d/submoduleGitHash.gradle' - compileSdkVersion 25 - buildToolsVersion "25.0.1" +android { + compileSdkVersion 29 defaultConfig { versionCode 13 versionName "1.3" - minSdkVersion 16 - targetSdkVersion 25 + minSdkVersion 21 + targetSdkVersion 29 + buildConfigField "boolean", "BUILD_GUTENBERG_FROM_SOURCE", (rootProject.ext.has("buildGutenbergFromSource") ? rootProject.ext.buildGutenbergFromSource : false).toString() + } + compileOptions { + sourceCompatibility 1.8 + targetCompatibility 1.8 } buildTypes { release { @@ -45,10 +63,35 @@ android { } dependencies { - compile 'com.android.support:appcompat-v7:25.0.1' - compile 'com.android.support:support-v4:25.0.1' - compile 'com.android.support:design:25.0.1' - compile 'org.wordpress:utils:1.11.0' + implementation 'androidx.appcompat:appcompat:1.1.0' + implementation 'androidx.vectordrawable:vectordrawable-animated:1.0.0' + implementation 'androidx.gridlayout:gridlayout:1.0.0' + implementation 'androidx.legacy:legacy-support-v4:1.0.0' + implementation 'com.google.android.material:material:1.1.0' + implementation 'org.apache.commons:commons-lang3:3.5' + implementation 'com.android.volley:volley:1.1.1' + implementation 'org.wordpress:utils:1.25' + implementation "org.jetbrains.kotlin:kotlin-stdlib-jdk7:$kotlinVersion" + + api ("com.github.wordpress-mobile.WordPress-Aztec-Android:aztec:$aztecVersion") { + exclude group: "com.android.volley" + } + api ("com.github.wordpress-mobile.WordPress-Aztec-Android:wordpress-shortcodes:$aztecVersion") + api ("com.github.wordpress-mobile.WordPress-Aztec-Android:wordpress-comments:$aztecVersion") + + implementation (project(':@wordpress_react-native-bridge')) { + exclude group: 'com.squareup.okhttp3' + exclude group: "com.android.volley" + exclude group: 'com.google.code.findbugs' + } + + // Required Aztec dependencies (they should be included but Jitpack seems to be stripping these out) + implementation "org.jetbrains.kotlin:kotlin-stdlib:1.1.4" + implementation "org.jsoup:jsoup:1.10.3" + + implementation 'com.google.code.gson:gson:2.6.2' + + lintChecks 'org.wordpress:lint:1.0.1' } signing { diff --git a/WordPressEditor/lint.xml b/WordPressEditor/lint.xml index d377d1d0..fff68c3f 100644 --- a/WordPressEditor/lint.xml +++ b/WordPressEditor/lint.xml @@ -7,4 +7,13 @@ + + + + + + + + + \ No newline at end of file diff --git a/WordPressEditor/src/androidTest/AndroidManifest.xml b/WordPressEditor/src/androidTest/AndroidManifest.xml index eeef377f..9cdaeb41 100644 --- a/WordPressEditor/src/androidTest/AndroidManifest.xml +++ b/WordPressEditor/src/androidTest/AndroidManifest.xml @@ -1,12 +1,4 @@ - - - - > diff --git a/WordPressEditor/src/androidTest/java/org.wordpress.android.editor/EditorFragmentForTests.java b/WordPressEditor/src/androidTest/java/org.wordpress.android.editor/EditorFragmentForTests.java deleted file mode 100644 index 1babaa3d..00000000 --- a/WordPressEditor/src/androidTest/java/org.wordpress.android.editor/EditorFragmentForTests.java +++ /dev/null @@ -1,41 +0,0 @@ -package org.wordpress.android.editor; - -import android.os.Bundle; -import android.view.LayoutInflater; -import android.view.View; -import android.view.ViewGroup; - -import java.util.Map; - -public class EditorFragmentForTests extends EditorFragment { - protected EditorWebViewAbstract mWebView; - - protected boolean mInitCalled = false; - protected boolean mDomLoaded = false; - protected boolean mOnSelectionStyleChangedCalled = false; - - @Override - public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { - View view = super.onCreateView(inflater, container, savedInstanceState); - mWebView = (EditorWebViewAbstract) view.findViewById(R.id.webview); - return view; - } - - @Override - protected void initJsEditor() { - super.initJsEditor(); - mInitCalled = true; - } - - @Override - public void onDomLoaded() { - super.onDomLoaded(); - mDomLoaded = true; - } - - @Override - public void onSelectionStyleChanged(final Map changeMap) { - super.onSelectionStyleChanged(changeMap); - mOnSelectionStyleChangedCalled = true; - } -} diff --git a/WordPressEditor/src/androidTest/java/org.wordpress.android.editor/EditorFragmentTest.java b/WordPressEditor/src/androidTest/java/org.wordpress.android.editor/EditorFragmentTest.java deleted file mode 100644 index 54c1f831..00000000 --- a/WordPressEditor/src/androidTest/java/org.wordpress.android.editor/EditorFragmentTest.java +++ /dev/null @@ -1,183 +0,0 @@ -package org.wordpress.android.editor; - -import android.app.Activity; -import android.test.ActivityInstrumentationTestCase2; -import android.view.View; -import android.widget.ToggleButton; - -import org.wordpress.android.editor.EditorFragment.IllegalEditorStateException; - -import java.util.HashMap; -import java.util.Map; -import java.util.concurrent.CountDownLatch; - -import static org.wordpress.android.editor.TestingUtils.waitFor; - -public class EditorFragmentTest extends ActivityInstrumentationTestCase2 { - private Activity mActivity; - private EditorFragmentForTests mFragment; - - public EditorFragmentTest() { - super(MockEditorActivity.class); - } - - @Override - protected void setUp() throws Exception { - super.setUp(); - mActivity = getActivity(); - mFragment = (EditorFragmentForTests) mActivity.getFragmentManager().findFragmentByTag("editorFragment"); - } - - public void testDomLoadedCallbackReceived() { - // initJsEditor() should have been called on setup - assertTrue(mFragment.mInitCalled); - - waitForOnDomLoaded(); - - // The JS editor should have sent out a callback when the DOM loaded, triggering onDomLoaded() - assertTrue(mFragment.mDomLoaded); - } - - public void testFormatBarToggledOnSelectedFieldChanged() { - Map selectionArgs = new HashMap<>(); - - selectionArgs.put("id", "zss_field_title"); - mFragment.onSelectionChanged(selectionArgs); - - waitFor(100); - - View view = mFragment.getView(); - - if (view == null) { - throw(new IllegalStateException("Fragment view is empty")); - } - - // The formatting buttons should be disabled while the title field is selected - ToggleButton mediaButton = (ToggleButton) view.findViewById(R.id.format_bar_button_media); - ToggleButton boldButton = (ToggleButton) view.findViewById(R.id.format_bar_button_bold); - ToggleButton italicButton = (ToggleButton) view.findViewById(R.id.format_bar_button_italic); - ToggleButton quoteButton = (ToggleButton) view.findViewById(R.id.format_bar_button_quote); - ToggleButton ulButton = (ToggleButton) view.findViewById(R.id.format_bar_button_ul); - ToggleButton olButton = (ToggleButton) view.findViewById(R.id.format_bar_button_ol); - ToggleButton linkButton = (ToggleButton) view.findViewById(R.id.format_bar_button_link); - ToggleButton strikethroughButton = (ToggleButton) view.findViewById(R.id.format_bar_button_strikethrough); - - assertFalse(mediaButton.isEnabled()); - assertFalse(boldButton.isEnabled()); - assertFalse(italicButton.isEnabled()); - assertFalse(quoteButton.isEnabled()); - assertFalse(ulButton.isEnabled()); - assertFalse(olButton.isEnabled()); - assertFalse(linkButton.isEnabled()); - - if (strikethroughButton != null) { - assertFalse(strikethroughButton.isEnabled()); - } - - // The HTML button should always be enabled - ToggleButton htmlButton = (ToggleButton) view.findViewById(R.id.format_bar_button_html); - assertTrue(htmlButton.isEnabled()); - - selectionArgs.clear(); - selectionArgs.put("id", "zss_field_content"); - mFragment.onSelectionChanged(selectionArgs); - - waitFor(500); - - // The formatting buttons should be enabled while the content field is selected - assertTrue(mediaButton.isEnabled()); - assertTrue(boldButton.isEnabled()); - assertTrue(italicButton.isEnabled()); - assertTrue(quoteButton.isEnabled()); - assertTrue(ulButton.isEnabled()); - assertTrue(olButton.isEnabled()); - assertTrue(linkButton.isEnabled()); - - if (strikethroughButton != null) { - assertTrue(strikethroughButton.isEnabled()); - } - - // The HTML button should always be enabled - assertTrue(htmlButton.isEnabled()); - } - - public void testHtmlModeToggleTextTransfer() throws InterruptedException, IllegalEditorStateException { - waitForOnDomLoaded(); - - final View view = mFragment.getView(); - - if (view == null) { - throw (new IllegalStateException("Fragment view is empty")); - } - - final ToggleButton htmlButton = (ToggleButton) view.findViewById(R.id.format_bar_button_html); - - String content = mFragment.getContent().toString(); - - final SourceViewEditText titleText = (SourceViewEditText) view.findViewById(R.id.sourceview_title); - final SourceViewEditText contentText = (SourceViewEditText) view.findViewById(R.id.sourceview_content); - - // -- Check that title and content text is properly loaded into the EditTexts when switching to HTML mode - - final CountDownLatch uiThreadLatch1 = new CountDownLatch(1); - - mActivity.runOnUiThread(new Runnable() { - @Override - public void run() { - htmlButton.performClick(); // Turn on HTML mode - - uiThreadLatch1.countDown(); - } - }); - - uiThreadLatch1.await(); - - waitFor(500); - - // The HTML mode fields should be populated with the raw HTML loaded into the WebView on load - // (see MockEditorActivity) - assertEquals("A title", titleText.getText().toString()); - assertEquals(content, contentText.getText().toString()); - - // -- Check that the title and content text is updated in the WebView when switching back from HTML mode - - final CountDownLatch uiThreadLatch2 = new CountDownLatch(1); - - mActivity.runOnUiThread(new Runnable() { - @Override - public void run() { - titleText.setText("new title"); - contentText.setText("new content"); - - // Check that getTitle() and getContent() return latest version even in HTML mode - try { - assertEquals("new title", mFragment.getTitle()); - assertEquals("new content", mFragment.getContent()); - } catch (IllegalEditorStateException e) { - throw new RuntimeException(); - } - - htmlButton.performClick(); // Turn off HTML mode - - uiThreadLatch2.countDown(); - } - }); - - uiThreadLatch2.await(); - - waitFor(300); // Wait for JS to update the title/content - - assertEquals("new title", mFragment.getTitle()); - assertEquals("new content", mFragment.getContent()); - } - - private void waitForOnDomLoaded() { - long start = System.currentTimeMillis(); - while(!mFragment.mDomLoaded) { - waitFor(10); - if (System.currentTimeMillis() - start > 5000) { - throw(new RuntimeException("Callback wait timed out")); - } - } - } -} diff --git a/WordPressEditor/src/androidTest/java/org.wordpress.android.editor/MockActivity.java b/WordPressEditor/src/androidTest/java/org.wordpress.android.editor/MockActivity.java deleted file mode 100644 index 580ea2de..00000000 --- a/WordPressEditor/src/androidTest/java/org.wordpress.android.editor/MockActivity.java +++ /dev/null @@ -1,7 +0,0 @@ -package org.wordpress.android.editor; - -import android.support.v7.app.AppCompatActivity; - -public class MockActivity extends AppCompatActivity { - -} diff --git a/WordPressEditor/src/androidTest/java/org.wordpress.android.editor/MockEditorActivity.java b/WordPressEditor/src/androidTest/java/org.wordpress.android.editor/MockEditorActivity.java deleted file mode 100644 index ecd51515..00000000 --- a/WordPressEditor/src/androidTest/java/org.wordpress.android.editor/MockEditorActivity.java +++ /dev/null @@ -1,102 +0,0 @@ -package org.wordpress.android.editor; - -import android.app.FragmentManager; -import android.app.FragmentTransaction; -import android.net.Uri; -import android.os.Bundle; -import android.support.v7.app.AppCompatActivity; -import android.view.DragEvent; -import android.widget.LinearLayout; - -import org.wordpress.android.editor.EditorFragmentAbstract.EditorDragAndDropListener; -import org.wordpress.android.editor.EditorFragmentAbstract.EditorFragmentListener; -import org.wordpress.android.editor.EditorFragmentAbstract.TrackableEvent; -import org.wordpress.android.util.helpers.MediaFile; - -import java.util.ArrayList; - -public class MockEditorActivity extends AppCompatActivity implements EditorFragmentListener, - EditorDragAndDropListener { - public static final int LAYOUT_ID = 999; - - EditorFragment mEditorFragment; - - @SuppressWarnings("ResourceType") - @Override - protected void onCreate(Bundle savedInstanceState) { - super.onCreate(savedInstanceState); - - LinearLayout linearLayout = new LinearLayout(this); - linearLayout.setId(LAYOUT_ID); - setContentView(linearLayout); - - FragmentManager fragmentManager = getFragmentManager(); - FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction(); - - mEditorFragment = new EditorFragmentForTests(); - fragmentTransaction.add(linearLayout.getId(), mEditorFragment, "editorFragment"); - fragmentTransaction.commit(); - } - - @Override - public void onEditorFragmentInitialized() { - mEditorFragment.setTitle("A title"); - mEditorFragment.setContent("

Example content

"); - } - - @Override - public void onSettingsClicked() { - - } - - @Override - public void onAddMediaClicked() { - - } - - @Override - public void onMediaRetryClicked(String mediaId) { - - } - - @Override - public void onMediaUploadCancelClicked(String mediaId, boolean delete) { - - } - - @Override - public void onFeaturedImageChanged(long mediaId) { - - } - - @Override - public void onVideoPressInfoRequested(String videoId) { - - } - - @Override - public String onAuthHeaderRequested(String url) { - return ""; - } - - @Override - public void saveMediaFile(MediaFile mediaFile) { - - } - - @Override - public void onTrackableEvent(TrackableEvent event) { - - } - - @Override - public void onMediaDropped(ArrayList mediaUri) { - - } - - @Override - public void onRequestDragAndDropPermissions(DragEvent dragEvent) { - - } -} - diff --git a/WordPressEditor/src/androidTest/java/org.wordpress.android.editor/TestingUtils.java b/WordPressEditor/src/androidTest/java/org.wordpress.android.editor/TestingUtils.java deleted file mode 100644 index e51cba6b..00000000 --- a/WordPressEditor/src/androidTest/java/org.wordpress.android.editor/TestingUtils.java +++ /dev/null @@ -1,14 +0,0 @@ -package org.wordpress.android.editor; - -import org.wordpress.android.util.AppLog; - -public class TestingUtils { - - static public void waitFor(long milliseconds) { - try { - Thread.sleep(milliseconds); - } catch(InterruptedException e) { - AppLog.e(AppLog.T.EDITOR, "Thread interrupted"); - } - } -} diff --git a/WordPressEditor/src/androidTest/java/org.wordpress.android.editor/ZssEditorTest.java b/WordPressEditor/src/androidTest/java/org.wordpress.android.editor/ZssEditorTest.java deleted file mode 100644 index 9989cbd6..00000000 --- a/WordPressEditor/src/androidTest/java/org.wordpress.android.editor/ZssEditorTest.java +++ /dev/null @@ -1,128 +0,0 @@ -package org.wordpress.android.editor; - -import android.annotation.SuppressLint; -import android.app.Activity; -import android.app.Instrumentation; -import android.os.Build; -import android.test.ActivityInstrumentationTestCase2; -import android.webkit.JavascriptInterface; - -import java.util.HashSet; -import java.util.Set; -import java.util.concurrent.CountDownLatch; -import java.util.concurrent.TimeUnit; - -/** - * Tests for the ZSSEditor inside an EditorWebViewAbstract, with no UI. - */ -public class ZssEditorTest extends ActivityInstrumentationTestCase2 { - private static final String JS_CALLBACK_HANDLER = "nativeCallbackHandler"; - - private Instrumentation mInstrumentation; - private EditorWebViewAbstract mWebView; - - private CountDownLatch mSetUpLatch; - - private TestMethod mTestMethod; - private CountDownLatch mCallbackLatch; - private CountDownLatch mDomLoadedCallbackLatch; - private Set mCallbackSet; - - private enum TestMethod { - INIT - } - - public ZssEditorTest() { - super(MockActivity.class); - } - - @SuppressLint("AddJavascriptInterface") - @Override - protected void setUp() throws Exception { - super.setUp(); - mInstrumentation = getInstrumentation(); - Activity activity = getActivity(); - mSetUpLatch = new CountDownLatch(1); - mDomLoadedCallbackLatch = new CountDownLatch(1); - - mSetUpLatch.countDown(); - - String htmlEditor = Utils.getHtmlFromFile(activity, "android-editor.html"); - - if (htmlEditor != null) { - htmlEditor = htmlEditor.replace("%%TITLE%%", getActivity().getString(R.string.visual_editor)); - htmlEditor = htmlEditor.replace("%%ANDROID_API_LEVEL%%", String.valueOf(Build.VERSION.SDK_INT)); - htmlEditor = htmlEditor.replace("%%LOCALIZED_STRING_INIT%%", - "nativeState.localizedStringEdit = '" + getActivity().getString(R.string.edit) + "';\n" + - "nativeState.localizedStringUploading = '" + getActivity().getString(R.string.uploading) + "';\n" + - "nativeState.localizedStringUploadingGallery = '" + - getActivity().getString(R.string.uploading_gallery_placeholder) + "';\n"); - } - - final String finalHtmlEditor = htmlEditor; - - activity.runOnUiThread(new Runnable() { - @Override - public void run() { - mWebView = new EditorWebView(mInstrumentation.getContext(), null); - if (Build.VERSION.SDK_INT < 17) { - mWebView.setJsCallbackReceiver(new MockJsCallbackReceiver(new EditorFragmentForTests())); - } else { - mWebView.addJavascriptInterface(new MockJsCallbackReceiver(new EditorFragmentForTests()), - JS_CALLBACK_HANDLER); - } - mWebView.loadDataWithBaseURL("file:///android_asset/", finalHtmlEditor, "text/html", "utf-8", ""); - mSetUpLatch.countDown(); - } - }); - } - - public void testInitialization() throws InterruptedException { - // Wait for setUp() to finish initializing the WebView - mSetUpLatch.await(); - - // Identify this method to the MockJsCallbackReceiver - mTestMethod = TestMethod.INIT; - - // Expecting three startup callbacks from the ZSS editor - mCallbackLatch = new CountDownLatch(3); - mCallbackSet = new HashSet<>(); - boolean callbacksReceived = mCallbackLatch.await(5, TimeUnit.SECONDS); - assertTrue(callbacksReceived); - - Set expectedSet = new HashSet<>(); - expectedSet.add("callback-new-field:id=zss_field_title"); - expectedSet.add("callback-new-field:id=zss_field_content"); - expectedSet.add("callback-dom-loaded:"); - - assertEquals(expectedSet, mCallbackSet); - } - - private class MockJsCallbackReceiver extends JsCallbackReceiver { - public MockJsCallbackReceiver(EditorFragmentAbstract editorFragmentAbstract) { - super(editorFragmentAbstract); - } - - @JavascriptInterface - public void executeCallback(String callbackId, String params) { - if (callbackId.equals("callback-dom-loaded")) { - // Notify test methods that the dom has loaded - mDomLoadedCallbackLatch.countDown(); - } - - // Handle callbacks and count down latches according to the currently running test - switch(mTestMethod) { - case INIT: - if (callbackId.equals("callback-dom-loaded")) { - mCallbackSet.add(callbackId + ":"); - } else if (callbackId.equals("callback-new-field")) { - mCallbackSet.add(callbackId + ":" + params); - } - mCallbackLatch.countDown(); - break; - default: - throw(new RuntimeException("Unknown calling method")); - } - } - } -} diff --git a/WordPressEditor/src/main/AndroidManifest.xml b/WordPressEditor/src/main/AndroidManifest.xml index fcade320..b42a780d 100644 --- a/WordPressEditor/src/main/AndroidManifest.xml +++ b/WordPressEditor/src/main/AndroidManifest.xml @@ -1,7 +1,12 @@ - + + - - > + + + diff --git a/WordPressEditor/src/main/assets/ZSSRichTextEditor.js b/WordPressEditor/src/main/assets/ZSSRichTextEditor.js deleted file mode 100755 index 52dabe1e..00000000 --- a/WordPressEditor/src/main/assets/ZSSRichTextEditor.js +++ /dev/null @@ -1,3847 +0,0 @@ -/*! - * - * ZSSRichTextEditor v1.0 - * http://www.zedsaid.com - * - * Copyright 2013 Zed Said Studio - * - */ - -// If we are using iOS or desktop -var isUsingiOS = false; -var isUsingAndroid = true; - -// THe default callback parameter separator -var defaultCallbackSeparator = '~'; - -const NodeName = { - BLOCKQUOTE: "BLOCKQUOTE", - PARAGRAPH: "P", - STRONG: "STRONG", - DEL: "DEL", - EM: "EM", - A: "A", - OL: "OL", - UL: "UL", - LI: "LI", - CODE: "CODE", - SPAN: "SPAN", - BR: "BR", - DIV: "DIV", - BODY: "BODY" -}; - -// The editor object -var ZSSEditor = {}; - -// These variables exist to reduce garbage (as in memory garbage) generation when typing real fast -// in the editor. -// -ZSSEditor.caretArguments = ['yOffset=' + 0, 'height=' + 0]; -ZSSEditor.caretInfo = { y: 0, height: 0 }; - -// Is this device an iPad -ZSSEditor.isiPad; - -// The current selection -ZSSEditor.currentSelection; - -// The current editing image -ZSSEditor.currentEditingImage; - -// The current editing video -ZSSEditor.currentEditingVideo; - -// The current editing link -ZSSEditor.currentEditingLink; - -ZSSEditor.focusedField = null; - -// The objects that are enabled -ZSSEditor.enabledItems = {}; - -ZSSEditor.editableFields = {}; - -ZSSEditor.lastTappedNode = null; - -// The default paragraph separator -ZSSEditor.defaultParagraphSeparator = 'div'; - -// We use a MutationObserver to catch user deletions of uploading or failed media -// This is only officially supported on API>18; when the WebView doesn't recognize the MutationObserver, -// we fall back to the deprecated DOMNodeRemoved event -ZSSEditor.mutationObserver; - -ZSSEditor.defaultMutationObserverConfig = { attributes: false, childList: true, characterData: false }; - -/** - * The initializer function that must be called onLoad - */ -ZSSEditor.init = function() { - - rangy.init(); - - // Change a few CSS values if the device is an iPad - ZSSEditor.isiPad = (navigator.userAgent.match(/iPad/i) != null); - if (ZSSEditor.isiPad) { - $(document.body).addClass('ipad_body'); - $('#zss_field_title').addClass('ipad_field_title'); - $('#zss_field_content').addClass('ipad_field_content'); - } - - document.execCommand('insertBrOnReturn', false, false); - - var editor = $('div.field').each(function() { - var editableField = new ZSSField($(this)); - var editableFieldId = editableField.getNodeId(); - - ZSSEditor.editableFields[editableFieldId] = editableField; - ZSSEditor.callback("callback-new-field", "id=" + editableFieldId); - }); - - document.addEventListener("selectionchange", function(e) { - ZSSEditor.currentEditingLink = null; - // DRM: only do something here if the editor has focus. The reason is that when the - // selection changes due to the editor loosing focus, the focusout event will not be - // sent if we try to load a callback here. - // - if (editor.is(":focus")) { - ZSSEditor.selectionChangedCallback(); - ZSSEditor.sendEnabledStyles(e); - var clicked = $(e.target); - if (!clicked.hasClass('zs_active')) { - $('img').removeClass('zs_active'); - } - } - }, false); - - // Attempt to instantiate a MutationObserver. This should fail for API<19, unless the OEM of the device has - // modified the WebView. If it fails, the editor will fall back to DOMNodeRemoved events. - try { - ZSSEditor.mutationObserver = new MutationObserver(function(mutations) { - ZSSEditor.onMutationObserved(mutations);} ); - } catch(e) { - // no op - } - -}; //end - -// MARK: - Debugging logs - -ZSSEditor.logMainElementSizes = function() { - msg = 'Window [w:' + $(window).width() + '|h:' + $(window).height() + ']'; - this.log(msg); - - var msg = encodeURIComponent('Viewport [w:' + window.innerWidth + '|h:' + window.innerHeight + ']'); - this.log(msg); - - msg = encodeURIComponent('Body [w:' + $(document.body).width() + '|h:' + $(document.body).height() + ']'); - this.log(msg); - - msg = encodeURIComponent('HTML [w:' + $('html').width() + '|h:' + $('html').height() + ']'); - this.log(msg); - - msg = encodeURIComponent('Document [w:' + $(document).width() + '|h:' + $(document).height() + ']'); - this.log(msg); -}; - -// MARK: - Viewport Refreshing - -ZSSEditor.refreshVisibleViewportSize = function() { - $(document.body).css('min-height', window.innerHeight + 'px'); - $('#zss_field_content').css('min-height', (window.innerHeight - $('#zss_field_content').position().top) + 'px'); -}; - -// MARK: - Fields - -ZSSEditor.focusFirstEditableField = function() { - $('div[contenteditable=true]:first').focus(); -}; - -ZSSEditor.formatNewLine = function(e) { - - var currentField = this.getFocusedField(); - - if (currentField.isMultiline()) { - var parentBlockQuoteNode = ZSSEditor.closerParentNodeWithName('blockquote'); - - if (parentBlockQuoteNode) { - this.formatNewLineInsideBlockquote(e); - } else if (!ZSSEditor.isCommandEnabled('insertOrderedList') - && !ZSSEditor.isCommandEnabled('insertUnorderedList')) { - document.execCommand('formatBlock', false, 'div'); - } - } else { - e.preventDefault(); - } -}; - -ZSSEditor.formatNewLineInsideBlockquote = function(e) { - this.insertBreakTagAtCaretPosition(); - e.preventDefault(); -}; - -ZSSEditor.getField = function(fieldId) { - - var field = this.editableFields[fieldId]; - - return field; -}; - -ZSSEditor.moveCaretToCoords = function(x, y) { - if (document.caretRangeFromPoint) { - var range = document.caretRangeFromPoint(x, y); - - var selection = window.getSelection(); - - if (range && selection.rangeCount) { - selection.removeAllRanges(); - selection.addRange(range); - } - } -}; - -ZSSEditor.getFocusedField = function() { - var currentField = $(this.findParentContenteditableDiv()); - var currentFieldId; - - if (currentField) { - currentFieldId = currentField.attr('id'); - } - - if (!currentFieldId) { - ZSSEditor.resetSelectionOnField('zss_field_content'); - currentFieldId = 'zss_field_content'; - } - - return this.editableFields[currentFieldId]; -}; - -ZSSEditor.execFunctionForResult = function(methodName) { - var functionArgument = "function=" + methodName; - var resultArgument = "result=" + window["ZSSEditor"][methodName].apply(); - ZSSEditor.callback('callback-response-string', functionArgument + defaultCallbackSeparator + resultArgument); -}; - -// MARK: - Mutation observing - -/** - * @brief Register a node to be tracked for modifications - */ -ZSSEditor.trackNodeForMutation = function(target) { - if (ZSSEditor.mutationObserver != undefined) { - ZSSEditor.mutationObserver.observe(target[0], ZSSEditor.defaultMutationObserverConfig); - } else { - // The WebView doesn't support MutationObservers - fall back to DOMNodeRemoved events - target.bind("DOMNodeRemoved", function(event) { ZSSEditor.onDomNodeRemoved(event); }); - } -}; - -/** - * @brief Called when the MutationObserver registers a mutation to a node it's listening to - */ -ZSSEditor.onMutationObserved = function(mutations) { - mutations.forEach(function(mutation) { - for (var i = 0; i < mutation.removedNodes.length; i++) { - var removedNode = mutation.removedNodes[i]; - if (!removedNode.attributes) { - // Fix for https://github.com/wordpress-mobile/WordPress-Editor-Android/issues/394 - // If removedNode doesn't have an attributes property, it's not of type Node and we shouldn't proceed - continue; - } - if (ZSSEditor.isMediaContainerNode(removedNode)) { - // An uploading or failed container node was deleted manually - notify native - var mediaIdentifier = ZSSEditor.extractMediaIdentifier(removedNode); - ZSSEditor.sendMediaRemovedCallback(mediaIdentifier); - } else if (removedNode.attributes.getNamedItem("data-wpid")) { - // An uploading or failed image was deleted manually - remove its container and send the callback - var mediaIdentifier = removedNode.attributes.getNamedItem("data-wpid").value; - var parentRange = ZSSEditor.getParentRangeOfFocusedNode(); - ZSSEditor.removeImage(mediaIdentifier); - if (parentRange != null) { - ZSSEditor.setRange(parentRange); - } - ZSSEditor.sendMediaRemovedCallback(mediaIdentifier); - } else if (removedNode.attributes.getNamedItem("data-video_wpid")) { - // An uploading or failed video was deleted manually - remove its container and send the callback - var mediaIdentifier = removedNode.attributes.getNamedItem("data-video_wpid").value; - var parentRange = ZSSEditor.getParentRangeOfFocusedNode(); - ZSSEditor.removeVideo(mediaIdentifier); - if (parentRange != null) { - ZSSEditor.setRange(parentRange); - } - ZSSEditor.sendMediaRemovedCallback(mediaIdentifier); - } else if (mutation.target.className == "edit-container") { - // A media item wrapped in an edit container was deleted manually - remove its container - // No callback in this case since it's not an uploading or failed media item - var parentRange = ZSSEditor.getParentRangeOfFocusedNode(); - - mutation.target.remove(); - - if (parentRange != null) { - ZSSEditor.setRange(parentRange); - } - - ZSSEditor.getFocusedField().emptyFieldIfNoContents(); - } - } - }); -}; - -/** - * @brief Called when a DOMNodeRemoved event is triggered for an element we're tracking - * (only used when MutationObserver is unsupported by the WebView) - */ -ZSSEditor.onDomNodeRemoved = function(event) { - if (event.target.id.length > 0) { - var mediaId = ZSSEditor.extractMediaIdentifier(event.target); - } else if (event.target.parentNode.id.length > 0) { - var mediaId = ZSSEditor.extractMediaIdentifier(event.target.parentNode); - } else { - return; - } - ZSSEditor.sendMediaRemovedCallback(mediaId); -}; - -// MARK: - Logging - -ZSSEditor.log = function(msg) { - ZSSEditor.callback('callback-log', 'msg=' + msg); -}; - -// MARK: - Callbacks - -ZSSEditor.domLoadedCallback = function() { - - ZSSEditor.callback("callback-dom-loaded"); -}; - -ZSSEditor.selectionChangedCallback = function () { - - var joinedArguments = ZSSEditor.getJoinedFocusedFieldIdAndCaretArguments(); - - ZSSEditor.callback('callback-selection-changed', joinedArguments); - this.callback("callback-input", joinedArguments); -}; - -ZSSEditor.callback = function(callbackScheme, callbackPath) { - - var url = callbackScheme + ":"; - - if (callbackPath) { - url = url + callbackPath; - } - - if (isUsingiOS) { - ZSSEditor.callbackThroughIFrame(url); - } else if (isUsingAndroid) { - if (nativeState.androidApiLevel < 17) { - ZSSEditor.callbackThroughIFrame(url); - } else { - nativeCallbackHandler.executeCallback(callbackScheme, callbackPath); - } - } else { - console.log(url); - } -}; - -/** - * @brief Executes a callback by loading it into an IFrame. - * @details The reason why we're using this instead of window.location is that window.location - * can sometimes fail silently when called multiple times in rapid succession. - * Found here: - * http://stackoverflow.com/questions/10010342/clicking-on-a-link-inside-a-webview-that-will-trigger-a-native-ios-screen-with/10080969#10080969 - * - * @param url The callback URL. - */ -ZSSEditor.callbackThroughIFrame = function(url) { - var iframe = document.createElement("IFRAME"); - iframe.setAttribute('sandbox', ''); - iframe.setAttribute("src", url); - - // IMPORTANT: the IFrame was showing up as a black box below our text. By setting its borders - // to be 0px transparent we make sure it's not shown at all. - // - // REF BUG: https://github.com/wordpress-mobile/WordPress-iOS-Editor/issues/318 - // - iframe.style.cssText = "border: 0px transparent;"; - - document.documentElement.appendChild(iframe); - iframe.parentNode.removeChild(iframe); - iframe = null; -}; - -ZSSEditor.stylesCallback = function(stylesArray) { - - var stylesString = ''; - - if (stylesArray.length > 0) { - stylesString = stylesArray.join(defaultCallbackSeparator); - } - - ZSSEditor.callback("callback-selection-style", stylesString); -}; - -// MARK: - Selection - -ZSSEditor.backupRange = function(){ - var selection = window.getSelection(); - if (selection.rangeCount < 1) { - return; - } - var range = selection.getRangeAt(0); - - ZSSEditor.currentSelection = - { - "startContainer": range.startContainer, - "startOffset": range.startOffset, - "endContainer": range.endContainer, - "endOffset": range.endOffset - }; -}; - -ZSSEditor.restoreRange = function(){ - if (this.currentSelection) { - var selection = window.getSelection(); - selection.removeAllRanges(); - - var range = document.createRange(); - range.setStart(this.currentSelection.startContainer, this.currentSelection.startOffset); - range.setEnd(this.currentSelection.endContainer, this.currentSelection.endOffset); - selection.addRange(range); - } -}; - -ZSSEditor.resetSelectionOnField = function(fieldId, offset) { - var query = "div#" + fieldId; - var field = document.querySelector(query); - - this.giveFocusToElement(field, offset); -}; - -ZSSEditor.giveFocusToElement = function(element, offset) { - offset = typeof offset !== 'undefined' ? offset : 0; - - var range = document.createRange(); - range.setStart(element, offset); - range.setEnd(element, offset); - - var selection = document.getSelection(); - selection.removeAllRanges(); - selection.addRange(range); -}; - -ZSSEditor.setFocusAfterElement = function(element) { - var selection = window.getSelection(); - - if (selection.rangeCount) { - var range = document.createRange(); - - range.setStartAfter(element); - range.setEndAfter(element); - selection.removeAllRanges(); - selection.addRange(range); - } -}; - -ZSSEditor.getSelectedText = function() { - var selection = window.getSelection(); - return selection.toString(); -}; - -ZSSEditor.selectWordAroundCursor = function() { - var selection = window.getSelection(); - // If there is no text selected, try to expand it to the word under the cursor - if (selection.rangeCount == 1) { - var range = selection.getRangeAt(0); - if (range.startOffset == range.endOffset) { - while (ZSSEditor.canExpandBackward(range)) { - range.setStart(range.startContainer, range.startOffset - 1); - } - while (ZSSEditor.canExpandForward(range)) { - range.setEnd(range.endContainer, range.endOffset + 1); - } - selection.removeAllRanges(); - selection.addRange(range); - } - } - return selection; -}; - -ZSSEditor.canExpandBackward = function(range) { - // Can't expand if focus is not a text node - if (!range.endContainer.nodeType == 3) { - return false; - } - var caretRange = range.cloneRange(); - if (range.startOffset == 0) { - return false; - } - caretRange.setStart(range.startContainer, range.startOffset - 1); - caretRange.setEnd(range.startContainer, range.startOffset); - if (!caretRange.toString().match(/\w/)) { - return false; - } - return true; -}; - -ZSSEditor.canExpandForward = function(range) { - // Can't expand if focus is not a text node - if (!range.endContainer.nodeType == 3) { - return false; - } - var caretRange = range.cloneRange(); - if (range.endOffset == range.endContainer.length) { - return false; - } - caretRange.setStart(range.endContainer, range.endOffset); - if (range.endOffset) { - caretRange.setEnd(range.endContainer, range.endOffset + 1); - } - if (!caretRange.toString().match(/\w/)) { - return false; - } - return true; -}; - -ZSSEditor.getSelectedTextToLinkify = function() { - ZSSEditor.selectWordAroundCursor(); - return document.getSelection().toString(); -}; - -ZSSEditor.getCaretArguments = function() { - var caretInfo = this.getYCaretInfo(); - - if (caretInfo == null) { - return null; - } else { - this.caretArguments[0] = 'yOffset=' + caretInfo.y; - this.caretArguments[1] = 'height=' + caretInfo.height; - return this.caretArguments; - } -}; - -ZSSEditor.getJoinedFocusedFieldIdAndCaretArguments = function() { - var joinedArguments = ZSSEditor.getJoinedCaretArguments(); - var idArgument = "id=" + ZSSEditor.getFocusedField().getNodeId(); - - joinedArguments = idArgument + defaultCallbackSeparator + joinedArguments; - - return joinedArguments; -}; - -ZSSEditor.getJoinedCaretArguments = function() { - - var caretArguments = this.getCaretArguments(); - var joinedArguments = this.caretArguments.join(defaultCallbackSeparator); - - return joinedArguments; -}; - -ZSSEditor.getCaretYPosition = function() { - var selection = window.getSelection(); - if (selection.rangeCount == 0) { - return 0; - } - var range = selection.getRangeAt(0); - var span = document.createElement("span"); - // Ensure span has dimensions and position by - // adding a zero-width space character - span.appendChild( document.createTextNode("\u200b") ); - range.insertNode(span); - var y = span.offsetTop; - var spanParent = span.parentNode; - spanParent.removeChild(span); - - // Glue any broken text nodes back together - spanParent.normalize(); - - return y; -} - -ZSSEditor.getYCaretInfo = function() { - var selection = window.getSelection(); - var noSelectionAvailable = selection.rangeCount == 0; - - if (noSelectionAvailable) { - return null; - } - - var y = 0; - var height = 0; - var range = selection.getRangeAt(0); - var needsToWorkAroundNewlineBug = (range.getClientRects().length == 0); - - // PROBLEM: iOS seems to have problems getting the offset for some empty nodes and return - // 0 (zero) as the selection range top offset. - // - // WORKAROUND: To fix this problem we use a different method to obtain the Y position instead. - // - if (needsToWorkAroundNewlineBug) { - var closerParentNode = ZSSEditor.closerParentNode(); - var closerDiv = ZSSEditor.findParentContenteditableDiv(); - - var fontSize = $(closerParentNode).css('font-size'); - var lineHeight = Math.floor(parseInt(fontSize.replace('px','')) * 1.5); - - y = this.getCaretYPosition(); - height = lineHeight; - } else { - if (range.getClientRects) { - var rects = range.getClientRects(); - if (rects.length > 0) { - // PROBLEM: some iOS versions differ in what is returned by getClientRects() - // Some versions return the offset from the page's top, some other return the - // offset from the visible viewport's top. - // - // WORKAROUND: see if the offset of the body's top is ever negative. If it is - // then it means that the offset we have is relative to the body's top, and we - // should add the scroll offset. - // - var addsScrollOffset = document.body.getClientRects()[0].top < 0; - - if (addsScrollOffset) { - y = document.body.scrollTop; - } - - y += rects[0].top; - height = rects[0].height; - } - } - } - - this.caretInfo.y = y; - this.caretInfo.height = height; - - return this.caretInfo; -}; - -// MARK: - Styles - -ZSSEditor.setBold = function() { - ZSSEditor.selectWordAroundCursor(); - document.execCommand('bold', false, null); - ZSSEditor.sendEnabledStyles(); -}; - -ZSSEditor.setItalic = function() { - ZSSEditor.selectWordAroundCursor(); - document.execCommand('italic', false, null); - ZSSEditor.sendEnabledStyles(); -}; - -ZSSEditor.setSubscript = function() { - ZSSEditor.selectWordAroundCursor(); - document.execCommand('subscript', false, null); - ZSSEditor.sendEnabledStyles(); -}; - -ZSSEditor.setSuperscript = function() { - ZSSEditor.selectWordAroundCursor(); - document.execCommand('superscript', false, null); - ZSSEditor.sendEnabledStyles(); -}; - -ZSSEditor.setStrikeThrough = function() { - ZSSEditor.selectWordAroundCursor(); - var commandName = 'strikeThrough'; - var isDisablingStrikeThrough = ZSSEditor.isCommandEnabled(commandName); - - document.execCommand(commandName, false, null); - - // DRM: WebKit has a problem disabling strikeThrough when the tag is used instead of - // . The code below serves as a way to fix this issue. - // - var mustHandleWebKitIssue = (isDisablingStrikeThrough - && ZSSEditor.isCommandEnabled(commandName)); - - if (mustHandleWebKitIssue && window.getSelection().rangeCount > 0) { - var troublesomeNodeNames = ['del']; - - var selection = window.getSelection(); - var range = selection.getRangeAt(0).cloneRange(); - - var container = range.commonAncestorContainer; - var nodeFound = false; - var textNode = null; - - while (container && !nodeFound) { - nodeFound = (container - && container.nodeType == document.ELEMENT_NODE - && troublesomeNodeNames.indexOf(container.nodeName.toLowerCase()) > -1); - - if (!nodeFound) { - container = container.parentElement; - } - } - - if (container) { - var newObject = $(container).replaceWith(container.innerHTML); - - var finalSelection = window.getSelection(); - var finalRange = selection.getRangeAt(0).cloneRange(); - - finalRange.setEnd(finalRange.startContainer, finalRange.startOffset + 1); - - selection.removeAllRanges(); - selection.addRange(finalRange); - } - } - - ZSSEditor.sendEnabledStyles(); -}; - -ZSSEditor.setUnderline = function() { - ZSSEditor.selectWordAroundCursor(); - document.execCommand('underline', false, null); - ZSSEditor.sendEnabledStyles(); -}; - -/** - * @brief Turns blockquote ON or OFF for the current selection. - * @details This method makes sure that the contents of the blockquotes are surrounded by the - * defaultParagraphSeparator tag (by default '

'). This ensures parity with the web - * editor. - */ -ZSSEditor.setBlockquote = function() { - - var savedSelection = rangy.saveSelection(); - var selection = document.getSelection(); - var range = selection.getRangeAt(0).cloneRange(); - var sendStyles = false; - - // Make sure text being wrapped in blockquotes is inside paragraph tags - // (should be

contents
) - var currentHtml = ZSSEditor.focusedField.getWrappedDomNode().innerHTML; - if (currentHtml.search('<' + ZSSEditor.defaultParagraphSeparator) == -1) { - ZSSEditor.focusedField.setHTML(Util.wrapHTMLInTag(currentHtml, ZSSEditor.defaultParagraphSeparator)); - } - - var ancestorElement = this.getAncestorElementForSettingBlockquote(range); - - if (ancestorElement) { - sendStyles = true; - - var childNodes = this.getChildNodesIntersectingRange(ancestorElement, range); - - // On older APIs, the rangy selection node is targeted when turning off empty blockquotes at the start of a post - // In that case, add the empty DIV element next to the rangy selection to the childNodes array to correctly - // turn the blockquote off - // https://github.com/wordpress-mobile/WordPress-Editor-Android/issues/401 - var nextChildNode = childNodes[childNodes.length-1].nextSibling; - if (nextChildNode && nextChildNode.nodeName == NodeName.DIV && nextChildNode.innerHTML == "") { - childNodes.push(nextChildNode); - } - - if (childNodes && childNodes.length) { - this.toggleBlockquoteForSpecificChildNodes(ancestorElement, childNodes); - } - } - - rangy.restoreSelection(savedSelection); - - // When turning off an empty blockquote in an empty post, ensure there aren't any leftover empty paragraph tags - // https://github.com/wordpress-mobile/WordPress-Editor-Android/issues/401 - var currentContenteditableDiv = ZSSEditor.focusedField.getWrappedDomNode(); - if (currentContenteditableDiv.children.length == 1 && currentContenteditableDiv.firstChild.innerHTML == "") { - ZSSEditor.focusedField.emptyFieldIfNoContents(); - } - - if (sendStyles) { - ZSSEditor.sendEnabledStyles(); - } -}; - -ZSSEditor.removeFormating = function() { - document.execCommand('removeFormat', false, null); - ZSSEditor.sendEnabledStyles(); -}; - -ZSSEditor.setHorizontalRule = function() { - document.execCommand('insertHorizontalRule', false, null); - ZSSEditor.sendEnabledStyles(); -}; - -ZSSEditor.setHeading = function(heading) { - var formatTag = heading; - var formatBlock = document.queryCommandValue('formatBlock'); - - if (formatBlock.length > 0 && formatBlock.toLowerCase() == formatTag) { - document.execCommand('formatBlock', false, Util.buildOpeningTag(this.defaultParagraphSeparator)); - } else { - document.execCommand('formatBlock', false, Util.buildOpeningTag(formatTag)); - } - - ZSSEditor.sendEnabledStyles(); -}; - -ZSSEditor.setParagraph = function() { - var formatTag = "div"; - var formatBlock = document.queryCommandValue('formatBlock'); - - if (formatBlock.length > 0 && formatBlock.toLowerCase() == formatTag) { - document.execCommand('formatBlock', false, Util.buildOpeningTag(this.defaultParagraphSeparator)); - } else { - document.execCommand('formatBlock', false, Util.buildOpeningTag(formatTag)); - } - - ZSSEditor.sendEnabledStyles(); -}; - -ZSSEditor.undo = function() { - document.execCommand('undo', false, null); - ZSSEditor.sendEnabledStyles(); -}; - -ZSSEditor.redo = function() { - document.execCommand('redo', false, null); - ZSSEditor.sendEnabledStyles(); -}; - -ZSSEditor.setOrderedList = function() { - document.execCommand('insertOrderedList', false, null); - - // If the insertOrderedList is no longer enabled after running execCommand, - // we can assume the user is turning it off. - if (!ZSSEditor.isCommandEnabled('insertOrderedList')) { - ZSSEditor.completeListEditing(); - } - ZSSEditor.sendEnabledStyles(); -}; - -ZSSEditor.setUnorderedList = function() { - document.execCommand('insertUnorderedList', false, null); - - // If the insertUnorderedList is no longer enabled after running execCommand, - // we can assume the user is turning it off. - if (!ZSSEditor.isCommandEnabled('insertUnorderedList')) { - ZSSEditor.completeListEditing(); - } - ZSSEditor.sendEnabledStyles(); -}; - -ZSSEditor.setJustifyCenter = function() { - document.execCommand('justifyCenter', false, null); - ZSSEditor.sendEnabledStyles(); -}; - -ZSSEditor.setJustifyFull = function() { - document.execCommand('justifyFull', false, null); - ZSSEditor.sendEnabledStyles(); -}; - -ZSSEditor.setJustifyLeft = function() { - document.execCommand('justifyLeft', false, null); - ZSSEditor.sendEnabledStyles(); -}; - -ZSSEditor.setJustifyRight = function() { - document.execCommand('justifyRight', false, null); - ZSSEditor.sendEnabledStyles(); -}; - -ZSSEditor.setIndent = function() { - document.execCommand('indent', false, null); - ZSSEditor.sendEnabledStyles(); -}; - -ZSSEditor.setOutdent = function() { - document.execCommand('outdent', false, null); - ZSSEditor.sendEnabledStyles(); -}; - -ZSSEditor.setTextColor = function(color) { - ZSSEditor.selectWordAroundCursor(); - ZSSEditor.restoreRange(); - document.execCommand("styleWithCSS", null, true); - document.execCommand('foreColor', false, color); - document.execCommand("styleWithCSS", null, false); - ZSSEditor.sendEnabledStyles(); - // document.execCommand("removeFormat", false, "foreColor"); // Removes just foreColor -}; - -ZSSEditor.setBackgroundColor = function(color) { - ZSSEditor.selectWordAroundCursor(); - ZSSEditor.restoreRange(); - document.execCommand("styleWithCSS", null, true); - document.execCommand('hiliteColor', false, color); - document.execCommand("styleWithCSS", null, false); - ZSSEditor.sendEnabledStyles(); -}; - -/** - * @brief Wraps given HTML in paragraph tags, appends a new line, and inserts it into the field - * @details This method makes sure that passed HTML is wrapped in a separate paragraph. - * It also appends a new opening paragraph tag and a space. This step is necessary to keep any spans or - * divs in the HTML from being read by the WebView as a style and applied to all future paragraphs. - */ -ZSSEditor.insertHTMLWrappedInParagraphTags = function(html) { - var space = '
'; - var paragraphOpenTag = Util.buildOpeningTag(this.defaultParagraphSeparator); - var paragraphCloseTag = Util.buildClosingTag(this.defaultParagraphSeparator); - - if (this.getFocusedField().getHTML().length == 0) { - html = paragraphOpenTag + html; - } - - // Without this line, API<19 WebView will reset the caret to the start of the document, inserting the new line - // there instead of under the newly added media item - if (nativeState.androidApiLevel < 19) { - html = html + '​'; - } - - // Due to the way the WebView handles divs, we need to add a new paragraph in a separate insertion - otherwise, - // the new paragraph will be nested within the existing paragraph. - this.insertHTML(html); - - this.insertHTML(paragraphOpenTag + space + paragraphCloseTag); -}; - -ZSSEditor.insertLink = function(url, title) { - var html = '' + title + ""; - - var parentBlockQuoteNode = ZSSEditor.closerParentNodeWithName('blockquote'); - - var currentRange = document.getSelection().getRangeAt(0); - var currentNode = currentRange.startContainer; - var currentNodeIsEmpty = (currentNode.innerHTML == '' || currentNode.innerHTML == '
'); - - var selectionIsAtStartOrEnd = Util.rangeIsAtStartOfParent(currentRange) || Util.rangeIsAtEndOfParent(currentRange); - - if (this.getFocusedField().getHTML().length == 0 - || (parentBlockQuoteNode && !currentNodeIsEmpty && selectionIsAtStartOrEnd)) { - // Wrap the link tag in paragraph tags when the post is empty, and also when inside a blockquote - // The latter is to fix a bug with document.execCommand('insertHTML') inside a blockquote, where the div inside - // the blockquote is ignored and the link tag is inserted outside it, on a new line with no wrapping div - // Wrapping the link in paragraph tags makes insertHTML join it to the existing div, for some reason - // We exclude being on an empty line inside a blockquote and when the selection isn't at the beginning or end - // of the line, as the fix is unnecessary in both those cases and causes paragraph formatting issues - html = Util.buildOpeningTag(this.defaultParagraphSeparator) + html; - } - - this.insertHTML(html); -}; - -ZSSEditor.updateLink = function(url, title) { - - ZSSEditor.restoreRange(); - - var currentLinkNode = ZSSEditor.lastTappedNode; - - if (currentLinkNode) { - currentLinkNode.setAttribute("href", url); - currentLinkNode.innerHTML = title; - } - ZSSEditor.sendEnabledStyles(); -}; - -ZSSEditor.unlink = function() { - var savedSelection = rangy.saveSelection(); - - var currentLinkNode = ZSSEditor.closerParentNodeWithName('a'); - - if (currentLinkNode) { - ZSSEditor.unwrapNode(currentLinkNode); - } - - rangy.restoreSelection(savedSelection); - - ZSSEditor.sendEnabledStyles(); -}; - -ZSSEditor.unwrapNode = function(node) { - $(node).contents().unwrap(); -}; - -ZSSEditor.quickLink = function() { - - var sel = document.getSelection(); - var link_url = ""; - var test = new String(sel); - var mailregexp = new RegExp("^(.+)(\@)(.+)$", "gi"); - if (test.search(mailregexp) == -1) { - checkhttplink = new RegExp("^http\:\/\/", "gi"); - if (test.search(checkhttplink) == -1) { - checkanchorlink = new RegExp("^\#", "gi"); - if (test.search(checkanchorlink) == -1) { - link_url = "http://" + sel; - } else { - link_url = sel; - } - } else { - link_url = sel; - } - } else { - checkmaillink = new RegExp("^mailto\:", "gi"); - if (test.search(checkmaillink) == -1) { - link_url = "mailto:" + sel; - } else { - link_url = sel; - } - } - - var html_code = '' + sel + ''; - ZSSEditor.insertHTML(html_code); -}; - -// MARK: - Blockquotes - -/** - * @brief This method toggles blockquote for the specified child nodes. This is useful since - * we can toggle blockquote either for some or ALL of the child nodes, depending on - * what we need to achieve. - * @details CASE 1: If the parent node is a blockquote node, the child nodes will be extracted - * from it leaving the remaining siblings untouched (by splitting the parent blockquote - * node in two if necessary). - * CASE 2: If the parent node is NOT a blockquote node, but the first child is, the - * method will make sure all child nodes that are blockquote nodes will be toggled to - * non-blockquote nodes. - * CASE 3: If both the parent node and the first node are non-blockquote nodes, this - * method will turn all child nodes into blockquote nodes. - * - * @param parentNode The parent node. Can be either a blockquote or non-blockquote node. - * Cannot be null. - * @param nodes The child nodes. Can be any combination of blockquote and - * non-blockquote nodes. Cannot be null. - */ -ZSSEditor.toggleBlockquoteForSpecificChildNodes = function(parentNode, nodes) { - - if (nodes && nodes.length > 0) { - if (parentNode.nodeName == NodeName.BLOCKQUOTE) { - for (var counter = 0; counter < nodes.length; counter++) { - this.turnBlockquoteOffForNode(nodes[counter]); - } - } else { - - var turnOn = (nodes[0].nodeName != NodeName.BLOCKQUOTE); - - for (var counter = 0; counter < nodes.length; counter++) { - if (turnOn) { - this.turnBlockquoteOnForNode(nodes[counter]); - } else { - this.turnBlockquoteOffForNode(nodes[counter]); - } - } - } - } -}; - - -/** - * @brief Turns blockquote off for the specified node. - * - * @param node The node to turn the blockquote off for. It can either be a blockquote - * node (in which case it will be removed and all child nodes extracted) or - * have a parent blockquote node (in which case the node will be extracted - * from its parent). - */ -ZSSEditor.turnBlockquoteOffForNode = function(node) { - - if (node.nodeName == NodeName.BLOCKQUOTE) { - for (var i = 0; i < node.childNodes.length; i++) { - this.extractNodeFromAncestorNode(node.childNodes[i], node); - } - } else { - if (node.parentNode.nodeName == NodeName.BLOCKQUOTE) { - this.extractNodeFromAncestorNode(node, node.parentNode); - } - } -}; - -/** - * @brief Turns blockquote on for the specified node. - * - * @param node The node to turn blockquote on for. Will attempt to attach the newly - * created blockquote to sibling or uncle blockquote nodes. If the node is - * null or it's parent is null, this method will exit without affecting it - * (this can actually be caused by this method modifying the surrounding - * nodes, if those nodes are stored in an array - and thus are not notified - * of DOM hierarchy changes). - */ -ZSSEditor.turnBlockquoteOnForNode = function(node) { - - if (!node || !node.parentNode) { - return; - } - - var couldJoinBlockquotes = this.joinAdjacentSiblingsOrAncestorBlockquotes(node); - - if (!couldJoinBlockquotes) { - var blockquote = document.createElement(NodeName.BLOCKQUOTE); - - node.parentNode.insertBefore(blockquote, node); - blockquote.appendChild(node); - } -}; - -// MARK: - Generic media - -ZSSEditor.isMediaContainerNode = function(node) { - if (node.id === undefined) { - return false; - } - return (node.id.search("img_container_") == 0) || (node.id.search("video_container_") == 0); -}; - -ZSSEditor.extractMediaIdentifier = function(node) { - if (node.id.search("img_container_") == 0) { - return node.id.replace("img_container_", ""); - } else if (node.id.search("video_container_") == 0) { - return node.id.replace("video_container_", ""); - } - return ""; -}; - -ZSSEditor.getMediaNodeWithIdentifier = function(mediaNodeIdentifier) { - var imageNode = ZSSEditor.getImageNodeWithIdentifier(mediaNodeIdentifier); - if (imageNode.length > 0) { - return imageNode; - } else { - return ZSSEditor.getVideoNodeWithIdentifier(mediaNodeIdentifier); - } -}; - -ZSSEditor.getMediaProgressNodeWithIdentifier = function(mediaNodeIdentifier) { - var imageProgressNode = ZSSEditor.getImageProgressNodeWithIdentifier(mediaNodeIdentifier); - if (imageProgressNode.length > 0) { - return imageProgressNode; - } else { - return ZSSEditor.getVideoProgressNodeWithIdentifier(mediaNodeIdentifier); - } -}; - -ZSSEditor.getMediaContainerNodeWithIdentifier = function(mediaNodeIdentifier) { - var imageContainerNode = ZSSEditor.getImageContainerNodeWithIdentifier(mediaNodeIdentifier); - if (imageContainerNode.length > 0) { - return imageContainerNode; - } else { - return ZSSEditor.getVideoContainerNodeWithIdentifier(mediaNodeIdentifier); - } -}; - -/** - * @brief Update the progress indicator for the media item identified with the value in progress. - * - * @param mediaNodeIdentifier This is a unique ID provided by the caller. - * @param progress A value between 0 and 1 indicating the progress on the media upload. - */ -ZSSEditor.setProgressOnMedia = function(mediaNodeIdentifier, progress) { - var mediaNode = this.getMediaNodeWithIdentifier(mediaNodeIdentifier); - var mediaProgressNode = this.getMediaProgressNodeWithIdentifier(mediaNodeIdentifier); - - if (progress == 0) { - mediaNode.addClass("uploading"); - } - - // Don't allow the progress bar to move backward - if (mediaNode.length == 0 || mediaProgressNode.length == 0 || mediaProgressNode.attr("value") > progress) { - return; - } - - // Revert to non-compatibility image container once image upload has begun. This centers the overlays on the image - // (instead of the screen), while still circumventing the small container bug the compat class was added to fix - if (progress > 0) { - this.getMediaContainerNodeWithIdentifier(mediaNodeIdentifier).removeClass("compat"); - } - - // Sometimes the progress bar can be stuck at 100% for a long time while further processing happens - // From a UX perspective, it's better to just keep the progress bars at 90% until the upload is really complete - // and the progress bar is removed entirely - if (progress > 0.9) { - return; - } - - mediaProgressNode.attr("value", progress); -}; - -ZSSEditor.setupOptimisticProgressUpdate = function(mediaNodeIdentifier, nCall) { - setTimeout(ZSSEditor.sendOptimisticProgressUpdate, nCall * 100, mediaNodeIdentifier, nCall); -}; - -ZSSEditor.sendOptimisticProgressUpdate = function(mediaNodeIdentifier, nCall) { - if (nCall > 15) { - return; - } - - var mediaNode = ZSSEditor.getMediaNodeWithIdentifier(mediaNodeIdentifier); - - // Don't send progress updates to failed media - if (mediaNode.length != 0 && mediaNode[0].classList.contains("failed")) { - return; - } - - ZSSEditor.setProgressOnMedia(mediaNodeIdentifier, nCall / 100); - ZSSEditor.setupOptimisticProgressUpdate(mediaNodeIdentifier, nCall + 1); -}; - -ZSSEditor.removeAllFailedMediaUploads = function() { - console.log("Remove all failed media"); - var failedMediaArray = ZSSEditor.getFailedMediaIdArray(); - for (var i = 0; i < failedMediaArray.length; i++) { - ZSSEditor.removeMedia(failedMediaArray[i]); - } -}; - -ZSSEditor.removeMedia = function(mediaNodeIdentifier) { - if (this.getImageNodeWithIdentifier(mediaNodeIdentifier).length != 0) { - this.removeImage(mediaNodeIdentifier); - } else if (this.getVideoNodeWithIdentifier(mediaNodeIdentifier).length != 0) { - this.removeVideo(mediaNodeIdentifier); - } -}; - -ZSSEditor.sendMediaRemovedCallback = function(mediaNodeIdentifier) { - var arguments = ['id=' + encodeURIComponent(mediaNodeIdentifier)]; - var joinedArguments = arguments.join(defaultCallbackSeparator); - this.callback("callback-media-removed", joinedArguments); -}; - -/** - * @brief Marks all in-progress images as failed to upload - */ -ZSSEditor.markAllUploadingMediaAsFailed = function(message) { - var html = ZSSEditor.getField("zss_field_content").getHTML(); - var tmp = document.createElement( "div" ); - var tmpDom = $( tmp ).html( html ); - var matches = tmpDom.find("img.uploading"); - - for(var i = 0; i < matches.size(); i++) { - if (matches[i].hasAttribute('data-wpid')) { - var mediaId = matches[i].getAttribute('data-wpid'); - ZSSEditor.markImageUploadFailed(mediaId, message); - } else if (matches[i].hasAttribute('data-video_wpid')) { - var videoId = matches[i].getAttribute('data-video_wpid'); - ZSSEditor.markVideoUploadFailed(videoId, message); - } - } -}; - -ZSSEditor.getFailedMediaIdArray = function() { - var html = ZSSEditor.getField("zss_field_content").getHTML(); - var tmp = document.createElement( "div" ); - var tmpDom = $( tmp ).html( html ); - var matches = tmpDom.find("img.failed"); - - var mediaIdArray = []; - - for (var i = 0; i < matches.size(); i++) { - var mediaId = null; - if (matches[i].hasAttribute("data-wpid")) { - mediaId = matches[i].getAttribute("data-wpid"); - } else if (matches[i].hasAttribute("data-video_wpid")) { - mediaId = matches[i].getAttribute("data-video_wpid"); - } - if (mediaId !== null) { - mediaIdArray.push(mediaId); - } - } - return mediaIdArray; -}; - -/** - * @brief Sends a callback with a list of failed images - */ -ZSSEditor.getFailedMedia = function() { - var mediaIdArray = ZSSEditor.getFailedMediaIdArray(); - for (var i = 0; i < mediaIdArray.length; i++) { - // Track pre-existing failed media nodes for manual deletion events - ZSSEditor.trackNodeForMutation(this.getMediaContainerNodeWithIdentifier(mediaIdArray[i])); - } - - var functionArgument = "function=getFailedMedia"; - var joinedArguments = functionArgument + defaultCallbackSeparator + "ids=" + mediaIdArray.toString(); - ZSSEditor.callback('callback-response-string', joinedArguments); -}; - -// MARK: - Images - -ZSSEditor.updateImage = function(url, alt) { - - ZSSEditor.restoreRange(); - - if (ZSSEditor.currentEditingImage) { - var c = ZSSEditor.currentEditingImage; - c.attr('src', url); - c.attr('alt', alt); - } - ZSSEditor.sendEnabledStyles(); - -}; - -ZSSEditor.insertImage = function(url, remoteId, alt) { - var html = '' + alt;
-    }
-    html += ''; - - this.insertHTMLWrappedInParagraphTags(html); - - this.sendEnabledStyles(); - this.callback("callback-action-finished"); -}; - -/** - * @brief Inserts a local image URL. Useful for images that need to be uploaded. - * @details By inserting a local image URL, we can make sure the image is shown to the user - * as soon as it's selected for uploading. Once the image is successfully uploaded - * the application should call replaceLocalImageWithRemoteImage(). - * - * @param imageNodeIdentifier This is a unique ID provided by the caller. It exists as - * a mechanism to update the image node with the remote URL - * when replaceLocalImageWithRemoteImage() is called. - * @param localImageUrl The URL of the local image to display. Please keep in mind - * that a remote URL can be used here too, since this method - * does not check for that. It would be a mistake. - */ -ZSSEditor.insertLocalImage = function(imageNodeIdentifier, localImageUrl) { - var progressIdentifier = this.getImageProgressIdentifier(imageNodeIdentifier); - var imageContainerIdentifier = this.getImageContainerIdentifier(imageNodeIdentifier); - - if (nativeState.androidApiLevel > 18) { - var imgContainerClass = 'img_container'; - var progressElement = ''; - } else { - // Before API 19, the WebView didn't support progress tags. Use an upload overlay instead of a progress bar - var imgContainerClass = 'img_container compat'; - var progressElement = '' + nativeState.localizedStringUploading - + ''; - } - - var imgContainerStart = ''; - var imgContainerEnd = ''; - var image = ''; - var html = imgContainerStart + progressElement + image + imgContainerEnd; - - this.insertHTMLWrappedInParagraphTags(html); - - ZSSEditor.trackNodeForMutation(this.getImageContainerNodeWithIdentifier(imageNodeIdentifier)); - - this.setProgressOnMedia(imageNodeIdentifier, 0); - - if (nativeState.androidApiLevel > 18) { - setTimeout(ZSSEditor.setupOptimisticProgressUpdate, 300, imageNodeIdentifier, 1); - } - - this.sendEnabledStyles(); -}; - -ZSSEditor.getImageNodeWithIdentifier = function(imageNodeIdentifier) { - return $('img[data-wpid="' + imageNodeIdentifier+'"]'); -}; - -ZSSEditor.getImageProgressIdentifier = function(imageNodeIdentifier) { - return 'progress_' + imageNodeIdentifier; -}; - -ZSSEditor.getImageProgressNodeWithIdentifier = function(imageNodeIdentifier) { - return $('#'+this.getImageProgressIdentifier(imageNodeIdentifier)); -}; - -ZSSEditor.getImageContainerIdentifier = function(imageNodeIdentifier) { - return 'img_container_' + imageNodeIdentifier; -}; - -ZSSEditor.getImageContainerNodeWithIdentifier = function(imageNodeIdentifier) { - return $('#'+this.getImageContainerIdentifier(imageNodeIdentifier)); -}; - -/** - * @brief Replaces a local image URL with a remote image URL. Useful for images that have - * just finished uploading. - * @details The remote image can be available after a while, when uploading images. This method - * allows for the remote URL to be loaded once the upload completes. - * - * @param imageNodeIdentifier This is a unique ID provided by the caller. It exists as - * a mechanism to update the image node with the remote URL - * when replaceLocalImageWithRemoteImage() is called. - * @param remoteImageUrl The URL of the remote image to display. - */ -ZSSEditor.replaceLocalImageWithRemoteImage = function(imageNodeIdentifier, remoteImageId, remoteImageUrl) { - var imageNode = this.getImageNodeWithIdentifier(imageNodeIdentifier); - - if (imageNode.length == 0) { - // even if the image is not present anymore we must do callback - this.markImageUploadDone(imageNodeIdentifier); - return; - } - - var image = new Image; - - image.onload = function () { - ZSSEditor.finishLocalImageSwap(image, imageNode, imageNodeIdentifier, remoteImageId) - image.classList.add("image-loaded"); - console.log("Image Loaded!"); - } - - image.onerror = function () { - // Add a remoteUrl attribute, remoteUrl and src must be swapped before publishing. - image.setAttribute('remoteurl', image.src); - // Try to reload the image on error. - ZSSEditor.tryToReload(image, imageNode, imageNodeIdentifier, remoteImageId, 1); - } - - image.src = remoteImageUrl; -}; - -ZSSEditor.finishLocalImageSwap = function(image, imageNode, imageNodeIdentifier, remoteImageId) { - imageNode.addClass("wp-image-" + remoteImageId); - if (image.getAttribute("remoteurl")) { - imageNode.attr('remoteurl', image.getAttribute("remoteurl")); - } - imageNode.attr('src', image.src); - // Set extra attributes and classes used by WordPress - imageNode.attr({'width': image.width, 'height': image.height}); - imageNode.addClass("alignnone size-full"); - ZSSEditor.markImageUploadDone(imageNodeIdentifier); - var joinedArguments = ZSSEditor.getJoinedFocusedFieldIdAndCaretArguments(); - ZSSEditor.callback("callback-input", joinedArguments); - image.onerror = null; -} - -ZSSEditor.reloadImage = function(image, imageNode, imageNodeIdentifier, remoteImageId, nCall) { - if (image.classList.contains("image-loaded")) { - return; - } - image.onerror = ZSSEditor.tryToReload(image, imageNode, imageNodeIdentifier, remoteImageId, nCall + 1); - // Force reloading by updating image src - image.src = image.getAttribute("remoteurl") + "?retry=" + nCall; - console.log("Reloading image:" + nCall + " - " + image.src); -} - -ZSSEditor.tryToReload = function (image, imageNode, imageNodeIdentifier, remoteImageId, nCall) { - if (nCall > 8) { // 7 tries: 22500 ms total - ZSSEditor.finishLocalImageSwap(image, imageNode, imageNodeIdentifier, remoteImageId); - return; - } - image.onerror = null; - console.log("Image not loaded"); - // reload the image with a variable delay: 500ms, 1000ms, 1500ms, 2000ms, etc. - setTimeout(ZSSEditor.reloadImage, nCall * 500, image, imageNode, imageNodeIdentifier, remoteImageId, nCall); -} - -/** - * @brief Notifies that the image upload as finished - * - * @param imageNodeIdentifier The unique image ID for the uploaded image - */ -ZSSEditor.markImageUploadDone = function(imageNodeIdentifier) { - var imageNode = this.getImageNodeWithIdentifier(imageNodeIdentifier); - if (imageNode.length == 0){ - return; - } - - // remove identifier attributed from image - imageNode.removeAttr('data-wpid'); - - // remove uploading style - imageNode.removeClass("uploading"); - - // Remove all extra formatting nodes for progress - if (imageNode.parent().attr("id") == this.getImageContainerIdentifier(imageNodeIdentifier)) { - // Reset id before removal to avoid triggering the manual media removal callback - imageNode.parent().attr("id", ""); - imageNode.parent().replaceWith(imageNode); - } - // Wrap link around image - var link = $('', { href: imageNode.attr("src") } ); - imageNode.wrap(link); - // We invoke the sendImageReplacedCallback with a delay to avoid for - // it to be ignored by the webview because of the previous callback being done. - var thisObj = this; - setTimeout(function() { thisObj.sendImageReplacedCallback(imageNodeIdentifier);}, 500); -}; - -/** - * @brief Callbacks to native that the image upload as finished and the local url was replaced by the remote url - * - * @param imageNodeIdentifier The unique image ID for the uploaded image - */ -ZSSEditor.sendImageReplacedCallback = function( imageNodeIdentifier ) { - var arguments = ['id=' + encodeURIComponent( imageNodeIdentifier )]; - - var joinedArguments = arguments.join( defaultCallbackSeparator ); - - this.callback("callback-image-replaced", joinedArguments); -}; - -/** - * @brief Marks the image as failed to upload - * - * @param imageNodeIdentifier This is a unique ID provided by the caller. - * @param message A message to show to the user, overlayed on the image - */ -ZSSEditor.markImageUploadFailed = function(imageNodeIdentifier, message) { - var imageNode = this.getImageNodeWithIdentifier(imageNodeIdentifier); - if (imageNode.length == 0){ - return; - } - - var sizeClass = ''; - if ( imageNode[0].width > 480 && imageNode[0].height > 240 ) { - sizeClass = "largeFail"; - } else if ( imageNode[0].width < 100 || imageNode[0].height < 100 ) { - sizeClass = "smallFail"; - } - - imageNode.addClass('failed'); - - var imageContainerNode = this.getImageContainerNodeWithIdentifier(imageNodeIdentifier); - if(imageContainerNode.length != 0){ - imageContainerNode.attr("data-failed", message); - imageNode.removeClass("uploading"); - imageContainerNode.addClass('failed'); - imageContainerNode.addClass(sizeClass); - } - - var imageProgressNode = this.getImageProgressNodeWithIdentifier(imageNodeIdentifier); - if (imageProgressNode.length != 0){ - imageProgressNode.addClass('failed'); - imageProgressNode.attr("value", 0); - } - - // Delete the compatibility overlay if present - imageContainerNode.find("span.upload-overlay").addClass("failed"); -}; - -/** - * @brief Unmarks the image as failed to upload - * - * @param imageNodeIdentifier This is a unique ID provided by the caller. - */ -ZSSEditor.unmarkImageUploadFailed = function(imageNodeIdentifier) { - var imageNode = this.getImageNodeWithIdentifier(imageNodeIdentifier); - if (imageNode.length != 0){ - imageNode.removeClass('failed'); - } - - var imageContainerNode = this.getImageContainerNodeWithIdentifier(imageNodeIdentifier); - if(imageContainerNode.length != 0){ - imageContainerNode.removeAttr("data-failed"); - imageContainerNode.removeClass('failed'); - } - - var imageProgressNode = this.getImageProgressNodeWithIdentifier(imageNodeIdentifier); - if (imageProgressNode.length != 0){ - imageProgressNode.removeClass('failed'); - } - - // Display the compatibility overlay again if present - imageContainerNode.find("span.upload-overlay").removeClass("failed"); - - this.setProgressOnMedia(imageNodeIdentifier, 0); - - if (nativeState.androidApiLevel > 18) { - setTimeout(ZSSEditor.setupOptimisticProgressUpdate, 300, imageNodeIdentifier, 1); - } -}; - -/** - * @brief Remove the image from the DOM. - * - * @param imageNodeIdentifier This is a unique ID provided by the caller. - */ -ZSSEditor.removeImage = function(imageNodeIdentifier) { - var imageNode = this.getImageNodeWithIdentifier(imageNodeIdentifier); - if (imageNode.length != 0){ - // Reset id before removal to avoid triggering the manual media removal callback - imageNode.attr("id",""); - imageNode.remove(); - } - - // if image is inside options container we need to remove the container - var imageContainerNode = this.getImageContainerNodeWithIdentifier(imageNodeIdentifier); - if (imageContainerNode.length != 0){ - imageContainerNode.remove(); - } -}; - -/** - * @brief Inserts a video tag using the videoURL as source and posterURL as the - * image to show while video is loading. - * - * @param videoURL the url of the video - * @param posterURL the url of an image to show while the video is loading - * @param videoPressID the VideoPress ID of the video, when applicable - * - */ -ZSSEditor.insertVideo = function(videoURL, posterURL, videopressID) { - var videoId = Date.now(); - var html = '
') == null) { - // Blockquote at start of post was removed - var newParagraphMatch = afterHTML.match('^
(.*?)

'); - - if (newParagraphMatch != null) { - // The blockquote was removed in a newline operation - var originalText = blockquoteMatch[1]; - var newText = newParagraphMatch[1]; - - if (originalText != newText) { - // Blockquote was removed and its inner text changed - this points to autocorrect removing the - // blockquote when changing the text in the previous paragraph, so we replace the blockquote - ZSSEditor.turnBlockquoteOnForNode(focusedNode.parentNode.firstChild); - } - } else if (afterHTML.match('^
(.*?)
') != null) { - // The blockquote was removed in a backspace operation - ZSSEditor.turnBlockquoteOnForNode(focusedNode.parentNode); - ZSSEditor.setFocusAfterElement(focusedNode); - } - } - } - - var focusedNodeIsEmpty = (focusedNode.innerHTML != undefined - && (focusedNode.innerHTML.length == 0 || focusedNode.innerHTML == '
')); - - // Blockquote handling - if (focusedNode.nodeName == NodeName.BLOCKQUOTE && focusedNodeIsEmpty) { - if (!htmlWasModified) { - // We only want to handle this if the last character inside a blockquote was just deleted - if the HTML - // is unchanged, it might be that afterKeyDownEvent was called too soon, and we should avoid doing anything - return; - } - - // When using backspace to delete the contents of a blockquote, the div within the blockquote is deleted - // This makes the blockquote unable to be deleted using backspace, and also causes autocorrect issues on API19+ - range.startContainer.innerHTML = Util.wrapHTMLInTag('
', ZSSEditor.defaultParagraphSeparator); - - // Give focus to new div - var newFocusElement = focusedNode.firstChild; - ZSSEditor.giveFocusToElement(newFocusElement, 1); - } else if (focusedNode.nodeName == NodeName.DIV && focusedNode.parentNode.nodeName == NodeName.BLOCKQUOTE) { - if (focusedNode.parentNode.previousSibling == null && focusedNode.parentNode.childNodes.length == 1 - && focusedNodeIsEmpty) { - // When a post begins with a blockquote, and there's content after that blockquote, backspacing inside that - // blockquote will work until the blockquote is empty. After that, backspace will have no effect - // This fix identifies that situation and makes the call to setBlockquote() to toggle off the blockquote - ZSSEditor.setBlockquote(); - } else { - // Remove extraneous break tags sometimes added to blockquotes by autocorrect actions - // https://github.com/wordpress-mobile/WordPress-Editor-Android/issues/385 - var blockquoteChildNodes = focusedNode.parentNode.childNodes; - - for (var i = 0; i < blockquoteChildNodes.length; i++) { - var childNode = blockquoteChildNodes[i]; - if (childNode.nodeName == NodeName.BR) { - childNode.parentNode.removeChild(childNode); - } - } - } - } -}; - -ZSSField.prototype.sendImageTappedCallback = function(imageNode) { - var meta = JSON.stringify(ZSSEditor.extractImageMeta(imageNode)); - var imageId = "", mediaType = "image"; - if (imageNode.hasAttribute('data-wpid')){ - imageId = imageNode.getAttribute('data-wpid'); - } else if (imageNode.hasAttribute('data-video_wpid')){ - imageId = imageNode.getAttribute('data-video_wpid'); - mediaType = "video"; - } - var arguments = ['id=' + encodeURIComponent(imageId), - 'url=' + encodeURIComponent(imageNode.src), - 'meta=' + encodeURIComponent(meta), - 'type=' + mediaType]; - - var joinedArguments = arguments.join(defaultCallbackSeparator); - - var thisObj = this; - - // WORKAROUND: force the event to become sort of "after-tap" through setTimeout() - // - setTimeout(function() { thisObj.callback('callback-image-tap', joinedArguments);}, 500); -} - -ZSSField.prototype.sendVideoTappedCallback = function( videoNode ) { - var videoId = ""; - if ( videoNode.hasAttribute( 'data-wpid' ) ){ - videoId = videoNode.getAttribute( 'data-wpid' ) - } - var arguments = ['id=' + encodeURIComponent( videoId ), - 'url=' + encodeURIComponent( videoNode.src )]; - - var joinedArguments = arguments.join( defaultCallbackSeparator ); - - ZSSEditor.callback('callback-video-tap', joinedArguments); -} - -// MARK: - Callback Execution - -ZSSField.prototype.callback = function(callbackScheme, callbackPath) { - var url = callbackScheme + ":"; - - url = url + "id=" + this.getNodeId(); - - if (callbackPath) { - url = url + defaultCallbackSeparator + callbackPath; - } - - if (isUsingiOS) { - ZSSEditor.callbackThroughIFrame(url); - } else if (isUsingAndroid) { - if (nativeState.androidApiLevel < 17) { - ZSSEditor.callbackThroughIFrame(url); - } else { - nativeCallbackHandler.executeCallback(callbackScheme, callbackPath); - } - } else { - console.log(url); - } -}; - -// MARK: - Focus - -ZSSField.prototype.isFocused = function() { - - return this.wrappedObject.is(':focus'); -}; - -ZSSField.prototype.focus = function() { - - if (!this.isFocused()) { - this.wrappedObject.focus(); - } -}; - -ZSSField.prototype.blur = function() { - if (this.isFocused()) { - this.wrappedObject.blur(); - } -}; - -// MARK: - Multiline support - -ZSSField.prototype.isMultiline = function() { - return this.multiline; -}; - -ZSSField.prototype.setMultiline = function(multiline) { - this.multiline = multiline; -}; - -// MARK: - NodeId - -ZSSField.prototype.getNodeId = function() { - return this.wrappedObject.attr('id'); -}; - -// MARK: - Editing - -ZSSField.prototype.enableEditing = function () { - - this.wrappedObject.attr('contenteditable', true); - - if (!ZSSEditor.focusedField) { - ZSSEditor.focusFirstEditableField(); - } -}; - -ZSSField.prototype.disableEditing = function () { - // IMPORTANT: we're blurring the field before making it non-editable since that ensures - // that the iOS keyboard is dismissed through an animation, as opposed to being immediately - // removed from the screen. - // - this.blur(); - - this.wrappedObject.attr('contenteditable', false); -}; - -// MARK: - Caret - -/** - * @brief Whenever this method is called, a check will be performed on the caret position - * to figure out if it needs to be wrapped in a paragraph node. - * @details A parent paragraph node should be added if the current parent is either the field - * node itself, or a blockquote node. - */ -ZSSField.prototype.wrapCaretInParagraphIfNecessary = function() { - var closerParentNode = ZSSEditor.closerParentNode(); - - if (closerParentNode == null) { - return; - } - - var parentNodeShouldBeParagraph = (closerParentNode == this.getWrappedDomNode() - || closerParentNode.nodeName == NodeName.BLOCKQUOTE); - - // When starting a post with a blockquote (before any text is entered), the paragraph tags inside the blockquote - // won't properly wrap the text once it's entered - // In that case, remove the paragraph tags and re-apply them, wrapping around the newly entered text - var fixNewPostBlockquoteBug = (closerParentNode.nodeName == NodeName.DIV - && closerParentNode.parentNode.nodeName == NodeName.BLOCKQUOTE - && closerParentNode.innerHTML.length == 0); - - // On API 19 and below, identifying the situation where the blockquote bug for new posts occurs works a little - // differently than above, with the focused node being the parent blockquote rather than the empty div inside it. - // We still remove the empty div so it can be re-applied correctly to the newly entered text, but we select it - // differently - // https://github.com/wordpress-mobile/WordPress-Editor-Android/issues/398 - var fixNewPostBlockquoteBugOldApi = (closerParentNode.nodeName == NodeName.BLOCKQUOTE - && closerParentNode.parentNode.nodeName == NodeName.DIV - && closerParentNode.innerHTML == '
'); - - if (parentNodeShouldBeParagraph || fixNewPostBlockquoteBug || fixNewPostBlockquoteBugOldApi) { - var selection = window.getSelection(); - - if (selection && selection.rangeCount > 0) { - var range = selection.getRangeAt(0); - - if (range.startContainer == range.endContainer) { - if (fixNewPostBlockquoteBug) { - closerParentNode.parentNode.removeChild(closerParentNode); - } else if (fixNewPostBlockquoteBugOldApi) { - closerParentNode.removeChild(closerParentNode.firstChild); - } - - var storedStyles = []; - if (this.getWrappedDomNode().innerHTML.length == 0) { - // If the post is empty, store any active in-line formatting so it can be re-applied after the - // DOM manipulations are completed - // (Fix for https://github.com/wordpress-mobile/WordPress-Editor-Android/issues/204) - storedStyles = ZSSEditor.storeInlineStylesAsFunctions(); - } - - var paragraph = document.createElement("div"); - var textNode = document.createTextNode("​"); - - paragraph.appendChild(textNode); - - range.insertNode(paragraph); - range.selectNode(textNode); - - selection.removeAllRanges(); - selection.addRange(range); - - // Re-apply inline styles that were cleared - storedStyles.map(function(styleFunction) { - styleFunction(); - }); - } - } - } -}; - -/** - * @brief Called when enter is pressed inside an image caption. Clears away the span and label tags the new line - * inherits from the caption styling. - */ -ZSSField.prototype.handleCaptionNewLine = function() { - var selectedNode = document.getSelection().baseNode; - - var contentsNode; - if (selectedNode.firstChild != null) { - contentsNode = selectedNode.firstChild.cloneNode(); - } else { - contentsNode = selectedNode.cloneNode(); - } - - var parentSpan = selectedNode.parentNode.parentNode; - var parentDiv = parentSpan.parentNode; - - var paragraph = document.createElement("div"); - paragraph.appendChild(contentsNode); - - parentDiv.insertBefore(paragraph, parentSpan); - parentDiv.removeChild(parentSpan); - - ZSSEditor.giveFocusToElement(contentsNode); -}; - -// MARK: - i18n - -ZSSField.prototype.isRightToLeftTextEnabled = function() { - var textDir = this.wrappedObject.attr('dir'); - var isRTL = (textDir != "undefined" && textDir == 'rtl'); - return isRTL; -}; - -ZSSField.prototype.enableRightToLeftText = function(isRTL) { - var textDirectionString = isRTL ? "rtl" : "ltr"; - this.wrappedObject.attr('dir', textDirectionString); - this.wrappedObject.css('direction', textDirectionString); -}; - -// MARK: - HTML contents - -ZSSField.prototype.isEmpty = function() { - var html = this.getHTML(); - var isEmpty = (html.length == 0 || html == "
"); - - return isEmpty; -}; - -ZSSField.prototype.getHTML = function() { - var html = this.wrappedObject.html(); - if (ZSSEditor.defaultParagraphSeparator == 'div') { - html = Formatter.convertDivToP(html); - } - html = Formatter.visualToHtml(html); - html = ZSSEditor.removeVisualFormatting( html ); - return html; -}; - -ZSSField.prototype.getHTMLForCallback = function() { - var functionArgument = "function=getHTMLForCallback"; - var idArgument = "id=" + this.getNodeId(); - var contentsArgument; - - if (this.hasNoStyle) { - contentsArgument = "contents=" + this.strippedHTML(); - } else { - var html; - if (nativeState.androidApiLevel < 17) { - // URI Encode HTML on API < 17 because of the use of WebViewClient.shouldOverrideUrlLoading. Data must - // be decoded in shouldOverrideUrlLoading. - html = encodeURIComponent(this.getHTML()); - } else { - html = this.getHTML(); - } - contentsArgument = "contents=" + html; - } - var joinedArguments = functionArgument + defaultCallbackSeparator + idArgument + defaultCallbackSeparator + - contentsArgument; - ZSSEditor.callback('callback-response-string', joinedArguments); -}; - -ZSSField.prototype.strippedHTML = function() { - return this.wrappedObject.text(); -}; - -ZSSField.prototype.setPlainText = function(text) { - ZSSEditor.currentEditingImage = null; - this.wrappedObject.text(text); -}; - -ZSSField.prototype.setHTML = function(html) { - ZSSEditor.currentEditingImage = null; - var mutatedHTML = Formatter.htmlToVisual(html); - - if (ZSSEditor.defaultParagraphSeparator == 'div') { - mutatedHTML = Formatter.convertPToDiv(mutatedHTML); - } - - this.wrappedObject.html(mutatedHTML); - - // Track video container nodes for mutation - var videoNodes = $('span.edit-container > video'); - for (var i = 0; i < videoNodes.length; i++) { - ZSSEditor.trackNodeForMutation($(videoNodes[i].parentNode)); - } -}; - -// MARK: - Placeholder - -ZSSField.prototype.hasPlaceholderText = function() { - return this.wrappedObject.attr('placeholderText') != null; -}; - -ZSSField.prototype.setPlaceholderText = function(placeholder) { - this.wrappedObject.attr('placeholderText', placeholder); -}; - -// MARK: - Wrapped Object - -ZSSField.prototype.getWrappedDomNode = function() { - return this.wrappedObject[0]; -}; diff --git a/WordPressEditor/src/main/assets/android-editor.html b/WordPressEditor/src/main/assets/android-editor.html deleted file mode 100755 index d70c11fa..00000000 --- a/WordPressEditor/src/main/assets/android-editor.html +++ /dev/null @@ -1,48 +0,0 @@ - - - - %%TITLE%% - - - - - - - - - - - - - - - - - - - - - - - -
-
-
-
-
-
-
- - diff --git a/WordPressEditor/src/main/assets/editor-android.css b/WordPressEditor/src/main/assets/editor-android.css deleted file mode 100644 index cd57c242..00000000 --- a/WordPressEditor/src/main/assets/editor-android.css +++ /dev/null @@ -1,95 +0,0 @@ -@media screen and (min-width: 720px) and (max-width: 1279px) { - body { - padding-left:90px; - padding-right:90px; - } -} - -@media screen and (min-width: 1280px){ - body { - padding-left:170px; - padding-right:170px; - } -} - -video::-webkit-media-controls-fullscreen-button { - display: none; -} - -/* Duplicates paragraph tag formatting for div tags, which are needed on Android API 19+ due to autocorrect issues: -https://bugs.chromium.org/p/chromium/issues/detail?id=599890 -*/ -div:not(.field):not(#separatorDiv) { - line-height: 24px; - margin-top: 0px; - margin-bottom: 24px; -} - -/* --- API<19 workarounds --- */ - -/* Used only on older APIs (API<19), which don't support CSS filter effects (specifically, blur). */ -.edit-container .edit-overlay-bg { - position: absolute; - top: -6px; - left: 0; - width: 100%; - height: 100%; - display: block; - background-color: rgba(0, 0, 0, 0.5); -} - -/* Used only on older APIs (API<19), where using inline-block is buggy and sometimes displays a very small container */ -span.img_container.compat, -span.video_container.compat { - display: block; -} - -/* Used on API<19 to darken the image so that the 'uploading' and 'retry' overlays can still be seen when the image is -light */ -.img_container .upload-overlay-bg, -.video_container .upload-overlay-bg { - position: absolute; - width: 100%; - height: 100%; - display: block; - background-color: rgba(0, 0, 0, 0.5); -} - -/* When the upload-overlay-bg element is present (API<19), a bug is exposed where the img_container is slightly larger -than its containing image. The upload-overlay-bg is larger as well, leaving a dark line below the image. By setting -display:block on the image and setting a width limit we get around this issue. */ - -.img_container .upload-overlay-bg ~ img.uploading, -.video_container .upload-overlay-bg ~ img.uploading { - display:block; - max-width:100%; -} - -.img_container .upload-overlay-bg ~ img.failed, -.video_container .upload-overlay-bg ~ img.failed{ - display:block; - max-width:100%; -} - -/* Used only on older APIs (API<19) instead of a progress bar for uploading images, since the WebView at those API - levels does not support the progress tag */ -.img_container .upload-overlay, -.video_container .upload-overlay{ - position: absolute; - top: 50%; - -webkit-transform: translateY(-50%); - width:100%; - z-index: 100; - min-width: 60px; - font-family: sans-serif; - font-size:20px; - font-weight:600; - text-align: center; - text-shadow: 0px 1px 2px rgba(0,0,0,.06); - color: white; -} - -.img_container .upload-overlay.failed, -.video_container .upload-overlay.failed{ - visibility: hidden; -} diff --git a/WordPressEditor/src/main/assets/editor-utils-formatter.js b/WordPressEditor/src/main/assets/editor-utils-formatter.js deleted file mode 100644 index 69b0254c..00000000 --- a/WordPressEditor/src/main/assets/editor-utils-formatter.js +++ /dev/null @@ -1,158 +0,0 @@ -function Formatter () {} - -// Video format tags supported by the [video] shortcode: https://codex.wordpress.org/Video_Shortcode -// mp4, m4v and webm prioritized since they're supported by the stock player as of Android API 23 -Formatter.videoShortcodeFormats = ["mp4", "m4v", "webm", "ogv", "wmv", "flv"]; - -Formatter.htmlToVisual = function(html) { - var mutatedHTML = wp.loadText(html); - - // Perform extra transformations to properly wrap captioned images in paragraphs - mutatedHTML = mutatedHTML.replace(/^\[caption([^\]]*\])/igm, '

[caption$1'); - mutatedHTML = mutatedHTML.replace(/([^\n>])\[caption/igm, '$1
\n[caption'); - mutatedHTML = mutatedHTML.replace(/\[\/caption\]\n(?=<|$)/igm, '[/caption]

\n'); - mutatedHTML = mutatedHTML.replace(/\[\/caption\]\n(?=[^<])/igm, '[/caption]
\n'); - - return Formatter.applyVisualFormatting(mutatedHTML); -} - -Formatter.convertPToDiv = function(html) { - // Replace the paragraph tags we get from wpload with divs - var mutatedHTML = html.replace(/(\s]))/igm, '/igm, ''); - - // Replace break tags around media items with paragraphs - // The break tags appear when text and media are separated by only a line break rather than a paragraph break, - // which can happen when inserting media inline and switching to HTML mode and back, or by deleting line breaks - // in HTML mode - mutatedHTML = mutatedHTML.replace(/
(?=\s*(
'); - mutatedHTML = mutatedHTML.replace(/(]*>|<\/a>|<\/label>|<\/video>|<\/span>)
/igm, - function replaceBrWithDivs(match) { return match.substr(0, match.length - 6) + '
'; }); - - // Append paragraph-wrapped break tag under media at the end of a post - mutatedHTML = mutatedHTML.replace(/(]*>|<\/a>|<\/label>|<\/video>|<\/span>)[^<>]*<\/div>\s$/igm, - function replaceBrWithDivs(match) { return match + '

'; }); - - return mutatedHTML; -} - -Formatter.visualToHtml = function(html) { - return wp.saveText(html); - return Formatter.removeVisualFormatting(mutatedHTML); -} - -Formatter.convertDivToP = function(html) { - return html.replace(/(\s]))/igm, '/igm, '

'); -} - -/** - * @brief Applies editor specific visual formatting. - * - * @param html The markup to format - * - * @return Returns the string with the visual formatting applied. - */ -Formatter.applyVisualFormatting = function(html) { - var str = wp.shortcode.replace('caption', html, Formatter.applyCaptionFormatting); - str = wp.shortcode.replace('wpvideo', str, Formatter.applyVideoPressFormattingCallback); - str = wp.shortcode.replace('video', str, Formatter.applyVideoFormattingCallback); - - // More tag - str = str.replace(//igm, "
") - str = str.replace(//igm, "
") - return str; -} - -/** - * @brief Adds visual formatting to a caption shortcodes. - * - * @param html The markup containing caption shortcodes to process. - * - * @return The html with caption shortcodes replaced with editor specific markup. - * See shortcode.js::next or details - */ -Formatter.applyCaptionFormatting = function(match) { - var attrs = match.attrs.named; - // The empty 'onclick' is important. It prevents the cursor jumping to the end - // of the content body when `-webkit-user-select: none` is set and the caption is tapped. - var out = '
",a.querySelectorAll("[msallowcapture^='']").length&&q.push("[*^$]="+L+"*(?:''|\"\")"),a.querySelectorAll("[selected]").length||q.push("\\["+L+"*(?:value|"+K+")"),a.querySelectorAll("[id~="+u+"-]").length||q.push("~="),a.querySelectorAll(":checked").length||q.push(":checked"),a.querySelectorAll("a#"+u+"+*").length||q.push(".#.+[+~]")}),jb(function(a){var b=g.createElement("input");b.setAttribute("type","hidden"),a.appendChild(b).setAttribute("name","D"),a.querySelectorAll("[name=d]").length&&q.push("name"+L+"*[*^$|!~]?="),a.querySelectorAll(":enabled").length||q.push(":enabled",":disabled"),a.querySelectorAll("*,:x"),q.push(",.*:")})),(c.matchesSelector=$.test(s=o.matches||o.webkitMatchesSelector||o.mozMatchesSelector||o.oMatchesSelector||o.msMatchesSelector))&&jb(function(a){c.disconnectedMatch=s.call(a,"div"),s.call(a,"[s!='']:x"),r.push("!=",P)}),q=q.length&&new RegExp(q.join("|")),r=r.length&&new RegExp(r.join("|")),b=$.test(o.compareDocumentPosition),t=b||$.test(o.contains)?function(a,b){var c=9===a.nodeType?a.documentElement:a,d=b&&b.parentNode;return a===d||!(!d||1!==d.nodeType||!(c.contains?c.contains(d):a.compareDocumentPosition&&16&a.compareDocumentPosition(d)))}:function(a,b){if(b)while(b=b.parentNode)if(b===a)return!0;return!1},B=b?function(a,b){if(a===b)return l=!0,0;var d=!a.compareDocumentPosition-!b.compareDocumentPosition;return d?d:(d=(a.ownerDocument||a)===(b.ownerDocument||b)?a.compareDocumentPosition(b):1,1&d||!c.sortDetached&&b.compareDocumentPosition(a)===d?a===g||a.ownerDocument===v&&t(v,a)?-1:b===g||b.ownerDocument===v&&t(v,b)?1:k?J(k,a)-J(k,b):0:4&d?-1:1)}:function(a,b){if(a===b)return l=!0,0;var c,d=0,e=a.parentNode,f=b.parentNode,h=[a],i=[b];if(!e||!f)return a===g?-1:b===g?1:e?-1:f?1:k?J(k,a)-J(k,b):0;if(e===f)return lb(a,b);c=a;while(c=c.parentNode)h.unshift(c);c=b;while(c=c.parentNode)i.unshift(c);while(h[d]===i[d])d++;return d?lb(h[d],i[d]):h[d]===v?-1:i[d]===v?1:0},g):n},gb.matches=function(a,b){return gb(a,null,null,b)},gb.matchesSelector=function(a,b){if((a.ownerDocument||a)!==n&&m(a),b=b.replace(U,"='$1']"),!(!c.matchesSelector||!p||r&&r.test(b)||q&&q.test(b)))try{var d=s.call(a,b);if(d||c.disconnectedMatch||a.document&&11!==a.document.nodeType)return d}catch(e){}return gb(b,n,null,[a]).length>0},gb.contains=function(a,b){return(a.ownerDocument||a)!==n&&m(a),t(a,b)},gb.attr=function(a,b){(a.ownerDocument||a)!==n&&m(a);var e=d.attrHandle[b.toLowerCase()],f=e&&D.call(d.attrHandle,b.toLowerCase())?e(a,b,!p):void 0;return void 0!==f?f:c.attributes||!p?a.getAttribute(b):(f=a.getAttributeNode(b))&&f.specified?f.value:null},gb.error=function(a){throw new Error("Syntax error, unrecognized expression: "+a)},gb.uniqueSort=function(a){var b,d=[],e=0,f=0;if(l=!c.detectDuplicates,k=!c.sortStable&&a.slice(0),a.sort(B),l){while(b=a[f++])b===a[f]&&(e=d.push(f));while(e--)a.splice(d[e],1)}return k=null,a},e=gb.getText=function(a){var b,c="",d=0,f=a.nodeType;if(f){if(1===f||9===f||11===f){if("string"==typeof a.textContent)return a.textContent;for(a=a.firstChild;a;a=a.nextSibling)c+=e(a)}else if(3===f||4===f)return a.nodeValue}else while(b=a[d++])c+=e(b);return c},d=gb.selectors={cacheLength:50,createPseudo:ib,match:X,attrHandle:{},find:{},relative:{">":{dir:"parentNode",first:!0}," ":{dir:"parentNode"},"+":{dir:"previousSibling",first:!0},"~":{dir:"previousSibling"}},preFilter:{ATTR:function(a){return a[1]=a[1].replace(cb,db),a[3]=(a[3]||a[4]||a[5]||"").replace(cb,db),"~="===a[2]&&(a[3]=" "+a[3]+" "),a.slice(0,4)},CHILD:function(a){return a[1]=a[1].toLowerCase(),"nth"===a[1].slice(0,3)?(a[3]||gb.error(a[0]),a[4]=+(a[4]?a[5]+(a[6]||1):2*("even"===a[3]||"odd"===a[3])),a[5]=+(a[7]+a[8]||"odd"===a[3])):a[3]&&gb.error(a[0]),a},PSEUDO:function(a){var b,c=!a[6]&&a[2];return X.CHILD.test(a[0])?null:(a[3]?a[2]=a[4]||a[5]||"":c&&V.test(c)&&(b=g(c,!0))&&(b=c.indexOf(")",c.length-b)-c.length)&&(a[0]=a[0].slice(0,b),a[2]=c.slice(0,b)),a.slice(0,3))}},filter:{TAG:function(a){var b=a.replace(cb,db).toLowerCase();return"*"===a?function(){return!0}:function(a){return a.nodeName&&a.nodeName.toLowerCase()===b}},CLASS:function(a){var b=y[a+" "];return b||(b=new RegExp("(^|"+L+")"+a+"("+L+"|$)"))&&y(a,function(a){return b.test("string"==typeof a.className&&a.className||"undefined"!=typeof a.getAttribute&&a.getAttribute("class")||"")})},ATTR:function(a,b,c){return function(d){var e=gb.attr(d,a);return null==e?"!="===b:b?(e+="","="===b?e===c:"!="===b?e!==c:"^="===b?c&&0===e.indexOf(c):"*="===b?c&&e.indexOf(c)>-1:"$="===b?c&&e.slice(-c.length)===c:"~="===b?(" "+e.replace(Q," ")+" ").indexOf(c)>-1:"|="===b?e===c||e.slice(0,c.length+1)===c+"-":!1):!0}},CHILD:function(a,b,c,d,e){var f="nth"!==a.slice(0,3),g="last"!==a.slice(-4),h="of-type"===b;return 1===d&&0===e?function(a){return!!a.parentNode}:function(b,c,i){var j,k,l,m,n,o,p=f!==g?"nextSibling":"previousSibling",q=b.parentNode,r=h&&b.nodeName.toLowerCase(),s=!i&&!h;if(q){if(f){while(p){l=b;while(l=l[p])if(h?l.nodeName.toLowerCase()===r:1===l.nodeType)return!1;o=p="only"===a&&!o&&"nextSibling"}return!0}if(o=[g?q.firstChild:q.lastChild],g&&s){k=q[u]||(q[u]={}),j=k[a]||[],n=j[0]===w&&j[1],m=j[0]===w&&j[2],l=n&&q.childNodes[n];while(l=++n&&l&&l[p]||(m=n=0)||o.pop())if(1===l.nodeType&&++m&&l===b){k[a]=[w,n,m];break}}else if(s&&(j=(b[u]||(b[u]={}))[a])&&j[0]===w)m=j[1];else while(l=++n&&l&&l[p]||(m=n=0)||o.pop())if((h?l.nodeName.toLowerCase()===r:1===l.nodeType)&&++m&&(s&&((l[u]||(l[u]={}))[a]=[w,m]),l===b))break;return m-=e,m===d||m%d===0&&m/d>=0}}},PSEUDO:function(a,b){var c,e=d.pseudos[a]||d.setFilters[a.toLowerCase()]||gb.error("unsupported pseudo: "+a);return e[u]?e(b):e.length>1?(c=[a,a,"",b],d.setFilters.hasOwnProperty(a.toLowerCase())?ib(function(a,c){var d,f=e(a,b),g=f.length;while(g--)d=J(a,f[g]),a[d]=!(c[d]=f[g])}):function(a){return e(a,0,c)}):e}},pseudos:{not:ib(function(a){var b=[],c=[],d=h(a.replace(R,"$1"));return d[u]?ib(function(a,b,c,e){var f,g=d(a,null,e,[]),h=a.length;while(h--)(f=g[h])&&(a[h]=!(b[h]=f))}):function(a,e,f){return b[0]=a,d(b,null,f,c),b[0]=null,!c.pop()}}),has:ib(function(a){return function(b){return gb(a,b).length>0}}),contains:ib(function(a){return a=a.replace(cb,db),function(b){return(b.textContent||b.innerText||e(b)).indexOf(a)>-1}}),lang:ib(function(a){return W.test(a||"")||gb.error("unsupported lang: "+a),a=a.replace(cb,db).toLowerCase(),function(b){var c;do if(c=p?b.lang:b.getAttribute("xml:lang")||b.getAttribute("lang"))return c=c.toLowerCase(),c===a||0===c.indexOf(a+"-");while((b=b.parentNode)&&1===b.nodeType);return!1}}),target:function(b){var c=a.location&&a.location.hash;return c&&c.slice(1)===b.id},root:function(a){return a===o},focus:function(a){return a===n.activeElement&&(!n.hasFocus||n.hasFocus())&&!!(a.type||a.href||~a.tabIndex)},enabled:function(a){return a.disabled===!1},disabled:function(a){return a.disabled===!0},checked:function(a){var b=a.nodeName.toLowerCase();return"input"===b&&!!a.checked||"option"===b&&!!a.selected},selected:function(a){return a.parentNode&&a.parentNode.selectedIndex,a.selected===!0},empty:function(a){for(a=a.firstChild;a;a=a.nextSibling)if(a.nodeType<6)return!1;return!0},parent:function(a){return!d.pseudos.empty(a)},header:function(a){return Z.test(a.nodeName)},input:function(a){return Y.test(a.nodeName)},button:function(a){var b=a.nodeName.toLowerCase();return"input"===b&&"button"===a.type||"button"===b},text:function(a){var b;return"input"===a.nodeName.toLowerCase()&&"text"===a.type&&(null==(b=a.getAttribute("type"))||"text"===b.toLowerCase())},first:ob(function(){return[0]}),last:ob(function(a,b){return[b-1]}),eq:ob(function(a,b,c){return[0>c?c+b:c]}),even:ob(function(a,b){for(var c=0;b>c;c+=2)a.push(c);return a}),odd:ob(function(a,b){for(var c=1;b>c;c+=2)a.push(c);return a}),lt:ob(function(a,b,c){for(var d=0>c?c+b:c;--d>=0;)a.push(d);return a}),gt:ob(function(a,b,c){for(var d=0>c?c+b:c;++db;b++)d+=a[b].value;return d}function sb(a,b,c){var d=b.dir,e=c&&"parentNode"===d,f=x++;return b.first?function(b,c,f){while(b=b[d])if(1===b.nodeType||e)return a(b,c,f)}:function(b,c,g){var h,i,j=[w,f];if(g){while(b=b[d])if((1===b.nodeType||e)&&a(b,c,g))return!0}else while(b=b[d])if(1===b.nodeType||e){if(i=b[u]||(b[u]={}),(h=i[d])&&h[0]===w&&h[1]===f)return j[2]=h[2];if(i[d]=j,j[2]=a(b,c,g))return!0}}}function tb(a){return a.length>1?function(b,c,d){var e=a.length;while(e--)if(!a[e](b,c,d))return!1;return!0}:a[0]}function ub(a,b,c){for(var d=0,e=b.length;e>d;d++)gb(a,b[d],c);return c}function vb(a,b,c,d,e){for(var f,g=[],h=0,i=a.length,j=null!=b;i>h;h++)(f=a[h])&&(!c||c(f,d,e))&&(g.push(f),j&&b.push(h));return g}function wb(a,b,c,d,e,f){return d&&!d[u]&&(d=wb(d)),e&&!e[u]&&(e=wb(e,f)),ib(function(f,g,h,i){var j,k,l,m=[],n=[],o=g.length,p=f||ub(b||"*",h.nodeType?[h]:h,[]),q=!a||!f&&b?p:vb(p,m,a,h,i),r=c?e||(f?a:o||d)?[]:g:q;if(c&&c(q,r,h,i),d){j=vb(r,n),d(j,[],h,i),k=j.length;while(k--)(l=j[k])&&(r[n[k]]=!(q[n[k]]=l))}if(f){if(e||a){if(e){j=[],k=r.length;while(k--)(l=r[k])&&j.push(q[k]=l);e(null,r=[],j,i)}k=r.length;while(k--)(l=r[k])&&(j=e?J(f,l):m[k])>-1&&(f[j]=!(g[j]=l))}}else r=vb(r===g?r.splice(o,r.length):r),e?e(null,g,r,i):H.apply(g,r)})}function xb(a){for(var b,c,e,f=a.length,g=d.relative[a[0].type],h=g||d.relative[" "],i=g?1:0,k=sb(function(a){return a===b},h,!0),l=sb(function(a){return J(b,a)>-1},h,!0),m=[function(a,c,d){var e=!g&&(d||c!==j)||((b=c).nodeType?k(a,c,d):l(a,c,d));return b=null,e}];f>i;i++)if(c=d.relative[a[i].type])m=[sb(tb(m),c)];else{if(c=d.filter[a[i].type].apply(null,a[i].matches),c[u]){for(e=++i;f>e;e++)if(d.relative[a[e].type])break;return wb(i>1&&tb(m),i>1&&rb(a.slice(0,i-1).concat({value:" "===a[i-2].type?"*":""})).replace(R,"$1"),c,e>i&&xb(a.slice(i,e)),f>e&&xb(a=a.slice(e)),f>e&&rb(a))}m.push(c)}return tb(m)}function yb(a,b){var c=b.length>0,e=a.length>0,f=function(f,g,h,i,k){var l,m,o,p=0,q="0",r=f&&[],s=[],t=j,u=f||e&&d.find.TAG("*",k),v=w+=null==t?1:Math.random()||.1,x=u.length;for(k&&(j=g!==n&&g);q!==x&&null!=(l=u[q]);q++){if(e&&l){m=0;while(o=a[m++])if(o(l,g,h)){i.push(l);break}k&&(w=v)}c&&((l=!o&&l)&&p--,f&&r.push(l))}if(p+=q,c&&q!==p){m=0;while(o=b[m++])o(r,s,g,h);if(f){if(p>0)while(q--)r[q]||s[q]||(s[q]=F.call(i));s=vb(s)}H.apply(i,s),k&&!f&&s.length>0&&p+b.length>1&&gb.uniqueSort(i)}return k&&(w=v,j=t),r};return c?ib(f):f}return h=gb.compile=function(a,b){var c,d=[],e=[],f=A[a+" "];if(!f){b||(b=g(a)),c=b.length;while(c--)f=xb(b[c]),f[u]?d.push(f):e.push(f);f=A(a,yb(e,d)),f.selector=a}return f},i=gb.select=function(a,b,e,f){var i,j,k,l,m,n="function"==typeof a&&a,o=!f&&g(a=n.selector||a);if(e=e||[],1===o.length){if(j=o[0]=o[0].slice(0),j.length>2&&"ID"===(k=j[0]).type&&c.getById&&9===b.nodeType&&p&&d.relative[j[1].type]){if(b=(d.find.ID(k.matches[0].replace(cb,db),b)||[])[0],!b)return e;n&&(b=b.parentNode),a=a.slice(j.shift().value.length)}i=X.needsContext.test(a)?0:j.length;while(i--){if(k=j[i],d.relative[l=k.type])break;if((m=d.find[l])&&(f=m(k.matches[0].replace(cb,db),ab.test(j[0].type)&&pb(b.parentNode)||b))){if(j.splice(i,1),a=f.length&&rb(j),!a)return H.apply(e,f),e;break}}}return(n||h(a,o))(f,b,!p,e,ab.test(a)&&pb(b.parentNode)||b),e},c.sortStable=u.split("").sort(B).join("")===u,c.detectDuplicates=!!l,m(),c.sortDetached=jb(function(a){return 1&a.compareDocumentPosition(n.createElement("div"))}),jb(function(a){return a.innerHTML="","#"===a.firstChild.getAttribute("href")})||kb("type|href|height|width",function(a,b,c){return c?void 0:a.getAttribute(b,"type"===b.toLowerCase()?1:2)}),c.attributes&&jb(function(a){return a.innerHTML="",a.firstChild.setAttribute("value",""),""===a.firstChild.getAttribute("value")})||kb("value",function(a,b,c){return c||"input"!==a.nodeName.toLowerCase()?void 0:a.defaultValue}),jb(function(a){return null==a.getAttribute("disabled")})||kb(K,function(a,b,c){var d;return c?void 0:a[b]===!0?b.toLowerCase():(d=a.getAttributeNode(b))&&d.specified?d.value:null}),gb}(a);n.find=t,n.expr=t.selectors,n.expr[":"]=n.expr.pseudos,n.unique=t.uniqueSort,n.text=t.getText,n.isXMLDoc=t.isXML,n.contains=t.contains;var u=n.expr.match.needsContext,v=/^<(\w+)\s*\/?>(?:<\/\1>|)$/,w=/^.[^:#\[\.,]*$/;function x(a,b,c){if(n.isFunction(b))return n.grep(a,function(a,d){return!!b.call(a,d,a)!==c});if(b.nodeType)return n.grep(a,function(a){return a===b!==c});if("string"==typeof b){if(w.test(b))return n.filter(b,a,c);b=n.filter(b,a)}return n.grep(a,function(a){return g.call(b,a)>=0!==c})}n.filter=function(a,b,c){var d=b[0];return c&&(a=":not("+a+")"),1===b.length&&1===d.nodeType?n.find.matchesSelector(d,a)?[d]:[]:n.find.matches(a,n.grep(b,function(a){return 1===a.nodeType}))},n.fn.extend({find:function(a){var b,c=this.length,d=[],e=this;if("string"!=typeof a)return this.pushStack(n(a).filter(function(){for(b=0;c>b;b++)if(n.contains(e[b],this))return!0}));for(b=0;c>b;b++)n.find(a,e[b],d);return d=this.pushStack(c>1?n.unique(d):d),d.selector=this.selector?this.selector+" "+a:a,d},filter:function(a){return this.pushStack(x(this,a||[],!1))},not:function(a){return this.pushStack(x(this,a||[],!0))},is:function(a){return!!x(this,"string"==typeof a&&u.test(a)?n(a):a||[],!1).length}});var y,z=/^(?:\s*(<[\w\W]+>)[^>]*|#([\w-]*))$/,A=n.fn.init=function(a,b){var c,d;if(!a)return this;if("string"==typeof a){if(c="<"===a[0]&&">"===a[a.length-1]&&a.length>=3?[null,a,null]:z.exec(a),!c||!c[1]&&b)return!b||b.jquery?(b||y).find(a):this.constructor(b).find(a);if(c[1]){if(b=b instanceof n?b[0]:b,n.merge(this,n.parseHTML(c[1],b&&b.nodeType?b.ownerDocument||b:l,!0)),v.test(c[1])&&n.isPlainObject(b))for(c in b)n.isFunction(this[c])?this[c](b[c]):this.attr(c,b[c]);return this}return d=l.getElementById(c[2]),d&&d.parentNode&&(this.length=1,this[0]=d),this.context=l,this.selector=a,this}return a.nodeType?(this.context=this[0]=a,this.length=1,this):n.isFunction(a)?"undefined"!=typeof y.ready?y.ready(a):a(n):(void 0!==a.selector&&(this.selector=a.selector,this.context=a.context),n.makeArray(a,this))};A.prototype=n.fn,y=n(l);var B=/^(?:parents|prev(?:Until|All))/,C={children:!0,contents:!0,next:!0,prev:!0};n.extend({dir:function(a,b,c){var d=[],e=void 0!==c;while((a=a[b])&&9!==a.nodeType)if(1===a.nodeType){if(e&&n(a).is(c))break;d.push(a)}return d},sibling:function(a,b){for(var c=[];a;a=a.nextSibling)1===a.nodeType&&a!==b&&c.push(a);return c}}),n.fn.extend({has:function(a){var b=n(a,this),c=b.length;return this.filter(function(){for(var a=0;c>a;a++)if(n.contains(this,b[a]))return!0})},closest:function(a,b){for(var c,d=0,e=this.length,f=[],g=u.test(a)||"string"!=typeof a?n(a,b||this.context):0;e>d;d++)for(c=this[d];c&&c!==b;c=c.parentNode)if(c.nodeType<11&&(g?g.index(c)>-1:1===c.nodeType&&n.find.matchesSelector(c,a))){f.push(c);break}return this.pushStack(f.length>1?n.unique(f):f)},index:function(a){return a?"string"==typeof a?g.call(n(a),this[0]):g.call(this,a.jquery?a[0]:a):this[0]&&this[0].parentNode?this.first().prevAll().length:-1},add:function(a,b){return this.pushStack(n.unique(n.merge(this.get(),n(a,b))))},addBack:function(a){return this.add(null==a?this.prevObject:this.prevObject.filter(a))}});function D(a,b){while((a=a[b])&&1!==a.nodeType);return a}n.each({parent:function(a){var b=a.parentNode;return b&&11!==b.nodeType?b:null},parents:function(a){return n.dir(a,"parentNode")},parentsUntil:function(a,b,c){return n.dir(a,"parentNode",c)},next:function(a){return D(a,"nextSibling")},prev:function(a){return D(a,"previousSibling")},nextAll:function(a){return n.dir(a,"nextSibling")},prevAll:function(a){return n.dir(a,"previousSibling")},nextUntil:function(a,b,c){return n.dir(a,"nextSibling",c)},prevUntil:function(a,b,c){return n.dir(a,"previousSibling",c)},siblings:function(a){return n.sibling((a.parentNode||{}).firstChild,a)},children:function(a){return n.sibling(a.firstChild)},contents:function(a){return a.contentDocument||n.merge([],a.childNodes)}},function(a,b){n.fn[a]=function(c,d){var e=n.map(this,b,c);return"Until"!==a.slice(-5)&&(d=c),d&&"string"==typeof d&&(e=n.filter(d,e)),this.length>1&&(C[a]||n.unique(e),B.test(a)&&e.reverse()),this.pushStack(e)}});var E=/\S+/g,F={};function G(a){var b=F[a]={};return n.each(a.match(E)||[],function(a,c){b[c]=!0}),b}n.Callbacks=function(a){a="string"==typeof a?F[a]||G(a):n.extend({},a);var b,c,d,e,f,g,h=[],i=!a.once&&[],j=function(l){for(b=a.memory&&l,c=!0,g=e||0,e=0,f=h.length,d=!0;h&&f>g;g++)if(h[g].apply(l[0],l[1])===!1&&a.stopOnFalse){b=!1;break}d=!1,h&&(i?i.length&&j(i.shift()):b?h=[]:k.disable())},k={add:function(){if(h){var c=h.length;!function g(b){n.each(b,function(b,c){var d=n.type(c);"function"===d?a.unique&&k.has(c)||h.push(c):c&&c.length&&"string"!==d&&g(c)})}(arguments),d?f=h.length:b&&(e=c,j(b))}return this},remove:function(){return h&&n.each(arguments,function(a,b){var c;while((c=n.inArray(b,h,c))>-1)h.splice(c,1),d&&(f>=c&&f--,g>=c&&g--)}),this},has:function(a){return a?n.inArray(a,h)>-1:!(!h||!h.length)},empty:function(){return h=[],f=0,this},disable:function(){return h=i=b=void 0,this},disabled:function(){return!h},lock:function(){return i=void 0,b||k.disable(),this},locked:function(){return!i},fireWith:function(a,b){return!h||c&&!i||(b=b||[],b=[a,b.slice?b.slice():b],d?i.push(b):j(b)),this},fire:function(){return k.fireWith(this,arguments),this},fired:function(){return!!c}};return k},n.extend({Deferred:function(a){var b=[["resolve","done",n.Callbacks("once memory"),"resolved"],["reject","fail",n.Callbacks("once memory"),"rejected"],["notify","progress",n.Callbacks("memory")]],c="pending",d={state:function(){return c},always:function(){return e.done(arguments).fail(arguments),this},then:function(){var a=arguments;return n.Deferred(function(c){n.each(b,function(b,f){var g=n.isFunction(a[b])&&a[b];e[f[1]](function(){var a=g&&g.apply(this,arguments);a&&n.isFunction(a.promise)?a.promise().done(c.resolve).fail(c.reject).progress(c.notify):c[f[0]+"With"](this===d?c.promise():this,g?[a]:arguments)})}),a=null}).promise()},promise:function(a){return null!=a?n.extend(a,d):d}},e={};return d.pipe=d.then,n.each(b,function(a,f){var g=f[2],h=f[3];d[f[1]]=g.add,h&&g.add(function(){c=h},b[1^a][2].disable,b[2][2].lock),e[f[0]]=function(){return e[f[0]+"With"](this===e?d:this,arguments),this},e[f[0]+"With"]=g.fireWith}),d.promise(e),a&&a.call(e,e),e},when:function(a){var b=0,c=d.call(arguments),e=c.length,f=1!==e||a&&n.isFunction(a.promise)?e:0,g=1===f?a:n.Deferred(),h=function(a,b,c){return function(e){b[a]=this,c[a]=arguments.length>1?d.call(arguments):e,c===i?g.notifyWith(b,c):--f||g.resolveWith(b,c)}},i,j,k;if(e>1)for(i=new Array(e),j=new Array(e),k=new Array(e);e>b;b++)c[b]&&n.isFunction(c[b].promise)?c[b].promise().done(h(b,k,c)).fail(g.reject).progress(h(b,j,i)):--f;return f||g.resolveWith(k,c),g.promise()}});var H;n.fn.ready=function(a){return n.ready.promise().done(a),this},n.extend({isReady:!1,readyWait:1,holdReady:function(a){a?n.readyWait++:n.ready(!0)},ready:function(a){(a===!0?--n.readyWait:n.isReady)||(n.isReady=!0,a!==!0&&--n.readyWait>0||(H.resolveWith(l,[n]),n.fn.triggerHandler&&(n(l).triggerHandler("ready"),n(l).off("ready"))))}});function I(){l.removeEventListener("DOMContentLoaded",I,!1),a.removeEventListener("load",I,!1),n.ready()}n.ready.promise=function(b){return H||(H=n.Deferred(),"complete"===l.readyState?setTimeout(n.ready):(l.addEventListener("DOMContentLoaded",I,!1),a.addEventListener("load",I,!1))),H.promise(b)},n.ready.promise();var J=n.access=function(a,b,c,d,e,f,g){var h=0,i=a.length,j=null==c;if("object"===n.type(c)){e=!0;for(h in c)n.access(a,b,h,c[h],!0,f,g)}else if(void 0!==d&&(e=!0,n.isFunction(d)||(g=!0),j&&(g?(b.call(a,d),b=null):(j=b,b=function(a,b,c){return j.call(n(a),c)})),b))for(;i>h;h++)b(a[h],c,g?d:d.call(a[h],h,b(a[h],c)));return e?a:j?b.call(a):i?b(a[0],c):f};n.acceptData=function(a){return 1===a.nodeType||9===a.nodeType||!+a.nodeType};function K(){Object.defineProperty(this.cache={},0,{get:function(){return{}}}),this.expando=n.expando+K.uid++}K.uid=1,K.accepts=n.acceptData,K.prototype={key:function(a){if(!K.accepts(a))return 0;var b={},c=a[this.expando];if(!c){c=K.uid++;try{b[this.expando]={value:c},Object.defineProperties(a,b)}catch(d){b[this.expando]=c,n.extend(a,b)}}return this.cache[c]||(this.cache[c]={}),c},set:function(a,b,c){var d,e=this.key(a),f=this.cache[e];if("string"==typeof b)f[b]=c;else if(n.isEmptyObject(f))n.extend(this.cache[e],b);else for(d in b)f[d]=b[d];return f},get:function(a,b){var c=this.cache[this.key(a)];return void 0===b?c:c[b]},access:function(a,b,c){var d;return void 0===b||b&&"string"==typeof b&&void 0===c?(d=this.get(a,b),void 0!==d?d:this.get(a,n.camelCase(b))):(this.set(a,b,c),void 0!==c?c:b)},remove:function(a,b){var c,d,e,f=this.key(a),g=this.cache[f];if(void 0===b)this.cache[f]={};else{n.isArray(b)?d=b.concat(b.map(n.camelCase)):(e=n.camelCase(b),b in g?d=[b,e]:(d=e,d=d in g?[d]:d.match(E)||[])),c=d.length;while(c--)delete g[d[c]]}},hasData:function(a){return!n.isEmptyObject(this.cache[a[this.expando]]||{})},discard:function(a){a[this.expando]&&delete this.cache[a[this.expando]]}};var L=new K,M=new K,N=/^(?:\{[\w\W]*\}|\[[\w\W]*\])$/,O=/([A-Z])/g;function P(a,b,c){var d;if(void 0===c&&1===a.nodeType)if(d="data-"+b.replace(O,"-$1").toLowerCase(),c=a.getAttribute(d),"string"==typeof c){try{c="true"===c?!0:"false"===c?!1:"null"===c?null:+c+""===c?+c:N.test(c)?n.parseJSON(c):c}catch(e){}M.set(a,b,c)}else c=void 0;return c}n.extend({hasData:function(a){return M.hasData(a)||L.hasData(a)},data:function(a,b,c){return M.access(a,b,c) -},removeData:function(a,b){M.remove(a,b)},_data:function(a,b,c){return L.access(a,b,c)},_removeData:function(a,b){L.remove(a,b)}}),n.fn.extend({data:function(a,b){var c,d,e,f=this[0],g=f&&f.attributes;if(void 0===a){if(this.length&&(e=M.get(f),1===f.nodeType&&!L.get(f,"hasDataAttrs"))){c=g.length;while(c--)g[c]&&(d=g[c].name,0===d.indexOf("data-")&&(d=n.camelCase(d.slice(5)),P(f,d,e[d])));L.set(f,"hasDataAttrs",!0)}return e}return"object"==typeof a?this.each(function(){M.set(this,a)}):J(this,function(b){var c,d=n.camelCase(a);if(f&&void 0===b){if(c=M.get(f,a),void 0!==c)return c;if(c=M.get(f,d),void 0!==c)return c;if(c=P(f,d,void 0),void 0!==c)return c}else this.each(function(){var c=M.get(this,d);M.set(this,d,b),-1!==a.indexOf("-")&&void 0!==c&&M.set(this,a,b)})},null,b,arguments.length>1,null,!0)},removeData:function(a){return this.each(function(){M.remove(this,a)})}}),n.extend({queue:function(a,b,c){var d;return a?(b=(b||"fx")+"queue",d=L.get(a,b),c&&(!d||n.isArray(c)?d=L.access(a,b,n.makeArray(c)):d.push(c)),d||[]):void 0},dequeue:function(a,b){b=b||"fx";var c=n.queue(a,b),d=c.length,e=c.shift(),f=n._queueHooks(a,b),g=function(){n.dequeue(a,b)};"inprogress"===e&&(e=c.shift(),d--),e&&("fx"===b&&c.unshift("inprogress"),delete f.stop,e.call(a,g,f)),!d&&f&&f.empty.fire()},_queueHooks:function(a,b){var c=b+"queueHooks";return L.get(a,c)||L.access(a,c,{empty:n.Callbacks("once memory").add(function(){L.remove(a,[b+"queue",c])})})}}),n.fn.extend({queue:function(a,b){var c=2;return"string"!=typeof a&&(b=a,a="fx",c--),arguments.lengthx",k.noCloneChecked=!!b.cloneNode(!0).lastChild.defaultValue}();var U="undefined";k.focusinBubbles="onfocusin"in a;var V=/^key/,W=/^(?:mouse|pointer|contextmenu)|click/,X=/^(?:focusinfocus|focusoutblur)$/,Y=/^([^.]*)(?:\.(.+)|)$/;function Z(){return!0}function $(){return!1}function _(){try{return l.activeElement}catch(a){}}n.event={global:{},add:function(a,b,c,d,e){var f,g,h,i,j,k,l,m,o,p,q,r=L.get(a);if(r){c.handler&&(f=c,c=f.handler,e=f.selector),c.guid||(c.guid=n.guid++),(i=r.events)||(i=r.events={}),(g=r.handle)||(g=r.handle=function(b){return typeof n!==U&&n.event.triggered!==b.type?n.event.dispatch.apply(a,arguments):void 0}),b=(b||"").match(E)||[""],j=b.length;while(j--)h=Y.exec(b[j])||[],o=q=h[1],p=(h[2]||"").split(".").sort(),o&&(l=n.event.special[o]||{},o=(e?l.delegateType:l.bindType)||o,l=n.event.special[o]||{},k=n.extend({type:o,origType:q,data:d,handler:c,guid:c.guid,selector:e,needsContext:e&&n.expr.match.needsContext.test(e),namespace:p.join(".")},f),(m=i[o])||(m=i[o]=[],m.delegateCount=0,l.setup&&l.setup.call(a,d,p,g)!==!1||a.addEventListener&&a.addEventListener(o,g,!1)),l.add&&(l.add.call(a,k),k.handler.guid||(k.handler.guid=c.guid)),e?m.splice(m.delegateCount++,0,k):m.push(k),n.event.global[o]=!0)}},remove:function(a,b,c,d,e){var f,g,h,i,j,k,l,m,o,p,q,r=L.hasData(a)&&L.get(a);if(r&&(i=r.events)){b=(b||"").match(E)||[""],j=b.length;while(j--)if(h=Y.exec(b[j])||[],o=q=h[1],p=(h[2]||"").split(".").sort(),o){l=n.event.special[o]||{},o=(d?l.delegateType:l.bindType)||o,m=i[o]||[],h=h[2]&&new RegExp("(^|\\.)"+p.join("\\.(?:.*\\.|)")+"(\\.|$)"),g=f=m.length;while(f--)k=m[f],!e&&q!==k.origType||c&&c.guid!==k.guid||h&&!h.test(k.namespace)||d&&d!==k.selector&&("**"!==d||!k.selector)||(m.splice(f,1),k.selector&&m.delegateCount--,l.remove&&l.remove.call(a,k));g&&!m.length&&(l.teardown&&l.teardown.call(a,p,r.handle)!==!1||n.removeEvent(a,o,r.handle),delete i[o])}else for(o in i)n.event.remove(a,o+b[j],c,d,!0);n.isEmptyObject(i)&&(delete r.handle,L.remove(a,"events"))}},trigger:function(b,c,d,e){var f,g,h,i,k,m,o,p=[d||l],q=j.call(b,"type")?b.type:b,r=j.call(b,"namespace")?b.namespace.split("."):[];if(g=h=d=d||l,3!==d.nodeType&&8!==d.nodeType&&!X.test(q+n.event.triggered)&&(q.indexOf(".")>=0&&(r=q.split("."),q=r.shift(),r.sort()),k=q.indexOf(":")<0&&"on"+q,b=b[n.expando]?b:new n.Event(q,"object"==typeof b&&b),b.isTrigger=e?2:3,b.namespace=r.join("."),b.namespace_re=b.namespace?new RegExp("(^|\\.)"+r.join("\\.(?:.*\\.|)")+"(\\.|$)"):null,b.result=void 0,b.target||(b.target=d),c=null==c?[b]:n.makeArray(c,[b]),o=n.event.special[q]||{},e||!o.trigger||o.trigger.apply(d,c)!==!1)){if(!e&&!o.noBubble&&!n.isWindow(d)){for(i=o.delegateType||q,X.test(i+q)||(g=g.parentNode);g;g=g.parentNode)p.push(g),h=g;h===(d.ownerDocument||l)&&p.push(h.defaultView||h.parentWindow||a)}f=0;while((g=p[f++])&&!b.isPropagationStopped())b.type=f>1?i:o.bindType||q,m=(L.get(g,"events")||{})[b.type]&&L.get(g,"handle"),m&&m.apply(g,c),m=k&&g[k],m&&m.apply&&n.acceptData(g)&&(b.result=m.apply(g,c),b.result===!1&&b.preventDefault());return b.type=q,e||b.isDefaultPrevented()||o._default&&o._default.apply(p.pop(),c)!==!1||!n.acceptData(d)||k&&n.isFunction(d[q])&&!n.isWindow(d)&&(h=d[k],h&&(d[k]=null),n.event.triggered=q,d[q](),n.event.triggered=void 0,h&&(d[k]=h)),b.result}},dispatch:function(a){a=n.event.fix(a);var b,c,e,f,g,h=[],i=d.call(arguments),j=(L.get(this,"events")||{})[a.type]||[],k=n.event.special[a.type]||{};if(i[0]=a,a.delegateTarget=this,!k.preDispatch||k.preDispatch.call(this,a)!==!1){h=n.event.handlers.call(this,a,j),b=0;while((f=h[b++])&&!a.isPropagationStopped()){a.currentTarget=f.elem,c=0;while((g=f.handlers[c++])&&!a.isImmediatePropagationStopped())(!a.namespace_re||a.namespace_re.test(g.namespace))&&(a.handleObj=g,a.data=g.data,e=((n.event.special[g.origType]||{}).handle||g.handler).apply(f.elem,i),void 0!==e&&(a.result=e)===!1&&(a.preventDefault(),a.stopPropagation()))}return k.postDispatch&&k.postDispatch.call(this,a),a.result}},handlers:function(a,b){var c,d,e,f,g=[],h=b.delegateCount,i=a.target;if(h&&i.nodeType&&(!a.button||"click"!==a.type))for(;i!==this;i=i.parentNode||this)if(i.disabled!==!0||"click"!==a.type){for(d=[],c=0;h>c;c++)f=b[c],e=f.selector+" ",void 0===d[e]&&(d[e]=f.needsContext?n(e,this).index(i)>=0:n.find(e,this,null,[i]).length),d[e]&&d.push(f);d.length&&g.push({elem:i,handlers:d})}return h]*)\/>/gi,bb=/<([\w:]+)/,cb=/<|&#?\w+;/,db=/<(?:script|style|link)/i,eb=/checked\s*(?:[^=]|=\s*.checked.)/i,fb=/^$|\/(?:java|ecma)script/i,gb=/^true\/(.*)/,hb=/^\s*\s*$/g,ib={option:[1,""],thead:[1,"","
"],col:[2,"","
"],tr:[2,"","
"],td:[3,"","
"],_default:[0,"",""]};ib.optgroup=ib.option,ib.tbody=ib.tfoot=ib.colgroup=ib.caption=ib.thead,ib.th=ib.td;function jb(a,b){return n.nodeName(a,"table")&&n.nodeName(11!==b.nodeType?b:b.firstChild,"tr")?a.getElementsByTagName("tbody")[0]||a.appendChild(a.ownerDocument.createElement("tbody")):a}function kb(a){return a.type=(null!==a.getAttribute("type"))+"/"+a.type,a}function lb(a){var b=gb.exec(a.type);return b?a.type=b[1]:a.removeAttribute("type"),a}function mb(a,b){for(var c=0,d=a.length;d>c;c++)L.set(a[c],"globalEval",!b||L.get(b[c],"globalEval"))}function nb(a,b){var c,d,e,f,g,h,i,j;if(1===b.nodeType){if(L.hasData(a)&&(f=L.access(a),g=L.set(b,f),j=f.events)){delete g.handle,g.events={};for(e in j)for(c=0,d=j[e].length;d>c;c++)n.event.add(b,e,j[e][c])}M.hasData(a)&&(h=M.access(a),i=n.extend({},h),M.set(b,i))}}function ob(a,b){var c=a.getElementsByTagName?a.getElementsByTagName(b||"*"):a.querySelectorAll?a.querySelectorAll(b||"*"):[];return void 0===b||b&&n.nodeName(a,b)?n.merge([a],c):c}function pb(a,b){var c=b.nodeName.toLowerCase();"input"===c&&T.test(a.type)?b.checked=a.checked:("input"===c||"textarea"===c)&&(b.defaultValue=a.defaultValue)}n.extend({clone:function(a,b,c){var d,e,f,g,h=a.cloneNode(!0),i=n.contains(a.ownerDocument,a);if(!(k.noCloneChecked||1!==a.nodeType&&11!==a.nodeType||n.isXMLDoc(a)))for(g=ob(h),f=ob(a),d=0,e=f.length;e>d;d++)pb(f[d],g[d]);if(b)if(c)for(f=f||ob(a),g=g||ob(h),d=0,e=f.length;e>d;d++)nb(f[d],g[d]);else nb(a,h);return g=ob(h,"script"),g.length>0&&mb(g,!i&&ob(a,"script")),h},buildFragment:function(a,b,c,d){for(var e,f,g,h,i,j,k=b.createDocumentFragment(),l=[],m=0,o=a.length;o>m;m++)if(e=a[m],e||0===e)if("object"===n.type(e))n.merge(l,e.nodeType?[e]:e);else if(cb.test(e)){f=f||k.appendChild(b.createElement("div")),g=(bb.exec(e)||["",""])[1].toLowerCase(),h=ib[g]||ib._default,f.innerHTML=h[1]+e.replace(ab,"<$1>")+h[2],j=h[0];while(j--)f=f.lastChild;n.merge(l,f.childNodes),f=k.firstChild,f.textContent=""}else l.push(b.createTextNode(e));k.textContent="",m=0;while(e=l[m++])if((!d||-1===n.inArray(e,d))&&(i=n.contains(e.ownerDocument,e),f=ob(k.appendChild(e),"script"),i&&mb(f),c)){j=0;while(e=f[j++])fb.test(e.type||"")&&c.push(e)}return k},cleanData:function(a){for(var b,c,d,e,f=n.event.special,g=0;void 0!==(c=a[g]);g++){if(n.acceptData(c)&&(e=c[L.expando],e&&(b=L.cache[e]))){if(b.events)for(d in b.events)f[d]?n.event.remove(c,d):n.removeEvent(c,d,b.handle);L.cache[e]&&delete L.cache[e]}delete M.cache[c[M.expando]]}}}),n.fn.extend({text:function(a){return J(this,function(a){return void 0===a?n.text(this):this.empty().each(function(){(1===this.nodeType||11===this.nodeType||9===this.nodeType)&&(this.textContent=a)})},null,a,arguments.length)},append:function(){return this.domManip(arguments,function(a){if(1===this.nodeType||11===this.nodeType||9===this.nodeType){var b=jb(this,a);b.appendChild(a)}})},prepend:function(){return this.domManip(arguments,function(a){if(1===this.nodeType||11===this.nodeType||9===this.nodeType){var b=jb(this,a);b.insertBefore(a,b.firstChild)}})},before:function(){return this.domManip(arguments,function(a){this.parentNode&&this.parentNode.insertBefore(a,this)})},after:function(){return this.domManip(arguments,function(a){this.parentNode&&this.parentNode.insertBefore(a,this.nextSibling)})},remove:function(a,b){for(var c,d=a?n.filter(a,this):this,e=0;null!=(c=d[e]);e++)b||1!==c.nodeType||n.cleanData(ob(c)),c.parentNode&&(b&&n.contains(c.ownerDocument,c)&&mb(ob(c,"script")),c.parentNode.removeChild(c));return this},empty:function(){for(var a,b=0;null!=(a=this[b]);b++)1===a.nodeType&&(n.cleanData(ob(a,!1)),a.textContent="");return this},clone:function(a,b){return a=null==a?!1:a,b=null==b?a:b,this.map(function(){return n.clone(this,a,b)})},html:function(a){return J(this,function(a){var b=this[0]||{},c=0,d=this.length;if(void 0===a&&1===b.nodeType)return b.innerHTML;if("string"==typeof a&&!db.test(a)&&!ib[(bb.exec(a)||["",""])[1].toLowerCase()]){a=a.replace(ab,"<$1>");try{for(;d>c;c++)b=this[c]||{},1===b.nodeType&&(n.cleanData(ob(b,!1)),b.innerHTML=a);b=0}catch(e){}}b&&this.empty().append(a)},null,a,arguments.length)},replaceWith:function(){var a=arguments[0];return this.domManip(arguments,function(b){a=this.parentNode,n.cleanData(ob(this)),a&&a.replaceChild(b,this)}),a&&(a.length||a.nodeType)?this:this.remove()},detach:function(a){return this.remove(a,!0)},domManip:function(a,b){a=e.apply([],a);var c,d,f,g,h,i,j=0,l=this.length,m=this,o=l-1,p=a[0],q=n.isFunction(p);if(q||l>1&&"string"==typeof p&&!k.checkClone&&eb.test(p))return this.each(function(c){var d=m.eq(c);q&&(a[0]=p.call(this,c,d.html())),d.domManip(a,b)});if(l&&(c=n.buildFragment(a,this[0].ownerDocument,!1,this),d=c.firstChild,1===c.childNodes.length&&(c=d),d)){for(f=n.map(ob(c,"script"),kb),g=f.length;l>j;j++)h=c,j!==o&&(h=n.clone(h,!0,!0),g&&n.merge(f,ob(h,"script"))),b.call(this[j],h,j);if(g)for(i=f[f.length-1].ownerDocument,n.map(f,lb),j=0;g>j;j++)h=f[j],fb.test(h.type||"")&&!L.access(h,"globalEval")&&n.contains(i,h)&&(h.src?n._evalUrl&&n._evalUrl(h.src):n.globalEval(h.textContent.replace(hb,"")))}return this}}),n.each({appendTo:"append",prependTo:"prepend",insertBefore:"before",insertAfter:"after",replaceAll:"replaceWith"},function(a,b){n.fn[a]=function(a){for(var c,d=[],e=n(a),g=e.length-1,h=0;g>=h;h++)c=h===g?this:this.clone(!0),n(e[h])[b](c),f.apply(d,c.get());return this.pushStack(d)}});var qb,rb={};function sb(b,c){var d,e=n(c.createElement(b)).appendTo(c.body),f=a.getDefaultComputedStyle&&(d=a.getDefaultComputedStyle(e[0]))?d.display:n.css(e[0],"display");return e.detach(),f}function tb(a){var b=l,c=rb[a];return c||(c=sb(a,b),"none"!==c&&c||(qb=(qb||n("